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<string> 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<dynamic>(){
                    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
        }
    ]
}
  • 3
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值