如何使用 C# 在 GPT API 中处理会话

问题描述 投票:0回答:0

通过使用会话,开发人员可以构建聊天应用程序,在与用户的多次交互中保持上下文,这可以带来更吸引人和更自然的对话。

问题:如何使用 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);
            }
        }
    }
}

这段代码工作正常,但问题是它没有保存之前的对话上下文。你能帮我创建多个session吗,我可以按要求选择session吗? 提前感谢您的帮助。

c# httpclient openai-api
© www.soinside.com 2019 - 2024. All rights reserved.