Akr*_*ifi 7 c# httpclient openai-api
通过使用会话,开发人员可以构建聊天应用程序,在与用户的多次交互中维护上下文,这可以带来更具吸引力和自然的对话。
问题:如何使用 c# http 与 gpt-3.5-turbo API 建立会话?
using Newtonsoft.Json;
using System.Text;
namespace MyChatGPT
{
internal class Program
{
static async Task Main(string[] args)
{
// Set up the HttpClient
var client = new HttpClient();
var baseUrl = "https://api.openai.com/v1/chat/completions";
// Set up the API key
var apiKey = "YOUR_API_KEY";
client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", apiKey);
while (true)
{
// Prompt the user for input
Console.Write("> ");
var userInput = Console.ReadLine();
// Set up the request parameters
var parameters = new
{
model = "gpt-3.5-turbo",
messages = new[] { new { role = "user", content = userInput }, },
max_tokens = 1024,
temperature = 0.2f,
};
// Send the HTTP request
var response = await client.PostAsync(baseUrl, new StringContent(JsonConvert.SerializeObject(parameters), Encoding.UTF8, "application/json"));// new StringContent(json));
// Read the response
var responseContent = await response.Content.ReadAsStringAsync();
// Extract the completed text from the response
dynamic responseObject = JsonConvert.DeserializeObject(responseContent);
string generatedText = responseObject.choices[0].message.content;
// Print the generated text
Console.WriteLine("Bot: " + generatedText);
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
这段代码工作正常,但问题是它没有保存对话的先前上下文。你能帮我创建多个会话吗?我可以根据要求选择会话吗?提前感谢您的帮助。
我搜索了很多并尝试了很多方法,原因是 ChatGPT 不依赖会话也不依赖 cookie,因为答案是通过 API 处理和发送的。
为了与 ChatGPT 保持上下文关系,我没有找到比使用以下代码将之前对话的一部分发送到 API 更好的方法:
messages = new[] {
new { role = "system", content = "You are a helpful assistant." },
new { role = "user", content = "Who won the world series in 2020?" },
new { role = "assistant", content = "The Los Angeles Dodgers won the World Series in 2020." },
new { role = "user", content = "Where was it played?" },
},
Run Code Online (Sandbox Code Playgroud)
或者
messages = new[] {
new { role = "user", content = "Who won the world series in 2020?" },
new { role = "assistant", content = "The Los Angeles Dodgers won the World Series in 2020." },
new { role = "user", content = "Where was it played?" },
},
Run Code Online (Sandbox Code Playgroud)
注:如果您不输入系统消息,系统会默认写入“您是一个有用的助手”。
据 ChatGPT 团队介绍,当前版本并不专业支持系统消息,但他们正在努力确保系统消息对对话产生影响。
您可以通过尝试OpenAI Playground了解更多信息