C# chatGPT API调用示例

# C# API

现在需要Verify your phone number to create an API key

using Newtonsoft.Json;
using System.Text;

class Program
{
    static readonly HttpClient client = new HttpClient();

    static async Task Main()
    {
        try
        {
            // 设置 API 密钥
            string apiKey = "your api";
            client.DefaultRequestHeaders.Add("Authorization", $"Bearer {apiKey}");

            // 构建请求体
            var requestData = new
            {
                model = "gpt-3.5-turbo-1106",
                messages = new[] { 
                    new { role = "system",content = "解释递归" }, 
                },
                
                // [{ role: "system", content: "You are a helpful assistant." }],
                temperature = 0.7,
                max_tokens = 60
            };
            string json = JsonConvert.SerializeObject(requestData);
            StringContent content = new StringContent(json, Encoding.UTF8, "application/json");

            // 发送请求
            HttpResponseMessage response = await client.PostAsync("https://api.openai.com//v1/chat/completions", content);

            // 获取响应
            string responseString = await response.Content.ReadAsStringAsync();
            Console.WriteLine(responseString);
        }
        catch (HttpRequestException e)
        {
            Console.WriteLine("\nException Caught!");
            Console.WriteLine("Message :{0} ", e.Message);
        }
    }
}

max_tokens = 60 我设的小了,内容就截断了。
C# chatGPT API调用示例_第1张图片

C# chatGPT API调用示例_第2张图片

你可能感兴趣的:(c#,开发语言)