In the modern landscape of conversational AI, maintaining message context is vital for delivering relevant and coherent responses. This article will guide you in handling conversation history using the Gemini and OpenAI APIs in both PHP and Python.
Why Preserve Conversation History?
Engaging with language models like Gemini and OpenAI’s API necessitates having an extensive conversation history. This history enables the model to generate contextually appropriate responses based on prior exchanges.
Transmitting Conversation History to Gemini API
PHP Example
To transmit conversation history to the Gemini API in PHP, you can use the following code snippet:
Python Example
In Python, achieving similar functionality with the requests library can be done as follows:
“`python
import json
import requests
# Define the conversation history
conversation_history = [
{
“question”: “mi scrivi una descrizione di Roma?”,
“answer”: “Roma è una città ricca di storia e cultura…”
},
{
“question”: “ok traducila in inglese.”,
“answer”: “”Can you write me a description of Rome?…””
}
]
# Send the conversation history to Gemini API
api_url = ‘https://gemini1.5api.com/chat_history’
headers = {‘Content-Type’: ‘application/json’}
response = requests.post(api_url, headers=headers, data=json.dumps(conversation_history))
# Print the response from the API
print(response.json())
“`
Transmitting Conversation History to OpenAI API
PHP Example
To maintain conversation history with the OpenAI API in PHP, refer to the following example:
“`php
// Your OpenAI API key
$api_key = ‘your-api-key-here’;
// Example chat history
$chat_history = [
“User: What’s the weather like today?”,
“Assistant: The weather is sunny and warm.”,
“User: Should I take an umbrella?”
];
// Prepare the prompt
$prompt = implode(“n”, $chat_history) . “nAssistant:”;
// Send the request to OpenAI API
$response = file_get_contents(‘https://api.openai.com/v1/engines/text-davinci-003/completions’, false, stream_context_create([
‘http’ => [
‘header’ => “Content-Type: application/jsonrn” .
“Authorization: Bearer $api_keyrn”,
‘method’ => ‘POST’,
‘content’ => json_encode([
‘prompt’ => $prompt,
‘max_tokens’ => 150,
‘temperature’ => 0.7,
]),
],
]));
// Extract and print the assistant’s reply
echo “Assistant: ” . json_decode($response)->choices[0]->text;
“`
Python Example
Here’s how to manage conversation history with OpenAI’s API in Python:
“`python
import openai
# Your OpenAI API key
openai.api_key = ‘your-api-key-here’
# Example chat history
chat_history = [
“User: What’s the weather like today?”,
“Assistant: The weather is sunny and warm.”,
“User: Should I take an umbrella?”
]
# Prepare the prompt
prompt = “n”.join(chat_history) + “nAssistant:”
# Send the request to OpenAI API
response = openai.Completion.create(
engine=”text-davinci-003″,
prompt=prompt,
max_tokens=150,
temperature=0.7
)
# Extract and print the assistant’s reply
reply = response.choices[0].text.strip()
print(“Assistant:”, reply)
“`
Implementing in Other Languages
Conversation history management is achievable in various programming languages. Below are additional examples:
JavaScript (Node.js)
“`javascript
const axios = require(‘axios’);
const conversationHistory = [
{ question: “mi scrivi una descrizione di Roma?”, answer: “Roma è una città ricca di storia e cultura…” },
{ question: “ok traducila in inglese.”, answer: “”Can you write me a description of Rome?…”” }
];
const sendConversationHistory = async () => {
const apiUrl = ‘https://gemini1.5api.com/chat_history’;
const response = await axios.post(apiUrl, conversationHistory, {
headers: {
‘Content-Type’: ‘application/json’
}
});
console.log(response.data);
};
sendConversationHistory();
“`
C# Example
“`csharp
using System;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;
class Program
{
public static async Task Main(string[] args)
{
using var client = new HttpClient();
var conversationHistory = new []
{
new { question = “mi scrivi una descrizione di Roma?”, answer = “Roma è una città ricca di storia e cultura…” },
new { question = “ok traducila in inglese.”, answer = “”Can you write me a description of Rome?…”” }
};
var json = JsonConvert.SerializeObject(conversationHistory);
var content = new StringContent(json, Encoding.UTF8, “application/json”);
var response = await client.PostAsync(“https://gemini1.5api.com/chat_history”, content);
var responseString = await response.Content.ReadAsStringAsync();
Console.WriteLine(responseString);
}
}
“`
Final Thoughts
Retaining conversation history enhances the responsiveness and relevance of AI models. By utilizing the methods outlined above, you can effectively manage and convey conversation history to both Gemini and OpenAI APIs in your applications, whether in PHP, Python, or other programming languages. Always check the official documentation for the latest updates and best practices concerning API usage.
Further Improvements
For practical applications, consider:
– Storing conversation history in a database
– Implementing user sessions to manage multiple conversations
– Adding error handling and retry mechanisms for enhanced reliability
– Incorporating rate limiting to comply with API usage restrictions
Discover more about AI automation at 42rows.