Net6 调用 chatGPT3.5-turbo

现在可以调用最新的GPT3.5模型了,响应速度很快,可以集成的自己的应用里面。

net6 控制台调用ChatGPT

using System.Text.Json;
using System.Text.Json.Nodes;

namespace ConsoleApp1
{
    internal class Program
    {
        private static readonly HttpClient http = new HttpClient();
        private static string apiKey = "xxxxxxxxx"; // 替换为你的OpenAI API密钥
        static async Task Main(string[] args)
        {
            Console.WriteLine("Enter your prompt:");
            string prompt = Console.ReadLine();
            string response = await GenerateText(prompt);
            Console.WriteLine(response);
        }
        static async Task GenerateText(string prompt)
        {
            string url = "https://api.openai.com/v1/chat/completions";
            string requestBody = JsonSerializer.Serialize(new
            {
                model = "gpt-3.5-turbo",
                messages = new List(){
                    new { role = "user", content = prompt }
                }
            });

            var request = new HttpRequestMessage(HttpMethod.Post, url);
            request.Headers.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", apiKey);
            request.Content = new StringContent(requestBody, System.Text.Encoding.UTF8, "application/json");

            var response = await http.SendAsync(request);
            response.EnsureSuccessStatusCode();
            var responseBody = await response.Content.ReadAsStringAsync();

            var result=JsonNode.Parse(responseBody);
            return result["choices"][0]["message"]["content"].ToString();
        }
    }
}

接口请求

{
    "model":"gpt-3.5-turbo",
    "messages":[
        {"role": "user", "content": "你好,请自我介绍一下?"}
    ]
}

返回的结果

{
    "id": "chatcmpl-6qHSMMDauvfcISM65K8m54TX3reKO",
    "object": "chat.completion",
    "created": 1677918178,
    "model": "gpt-3.5-turbo-0301",
    "usage": {
        "prompt_tokens": 18,
        "completion_tokens": 86,
        "total_tokens": 104
    },
    "choices": [
        {
            "message": {
                "role": "assistant",
                "content": "您好,我是一名AI语言模型,可以用自然语言处理技术与人类进行交互。我拥有丰富的知识库和语言处理能力,可以回答您的各种问题、提供帮助、解决疑问。感谢您的使用!"
            },
            "finish_reason": "stop",
            "index": 0
        }
    ]
}

你可能感兴趣的:(chatgpt,c#,gpt-3)