如何使用OPENAI API来通过程序生成回复,使用C#语言。

image_print阅读模式

通过openai的API程序化生成回复,使用C#语言。即输入一段文字,通过程序得到chatgpt的回复。代码如下,生成的速度有点慢,运行时还是得使用梯子:

    private async void button11_Click(object sender, EventArgs e)
    { string apiKey = "sk-xxxxxxxxx"; // 请替换为您的OpenAI API Key
        string originalString = textBox7.Text; // 替换为你的原始字符串
        string first2000Chars = originalString.Length > 2000
            ? originalString.Substring(0, 2000)
            : originalString;
        string organizedText = await OrganizeTextWithChatGPT(apiKey, first2000Chars);
            textBox7.Text= organizedText;

    }
    static async Task<string> OrganizeTextWithChatGPT(string apiKey, string textToOrganize)
    {        // 构造请求的JSON数据
        string apiUrl = "https://api.openai.com/v1/engines/text-davinci-003/completions";
        string prompt = "请校正并排版以下文字:\n" + textToOrganize + "\n整理结果:";
        string model = "text-davinci-003";
        int maxTokens = 2000;
        string data = JsonConvert.SerializeObject(new { prompt = prompt, max_tokens = maxTokens });
        // 发送HTTP请求到OpenAI API
        using (HttpClient client = new HttpClient())
        {
            client.DefaultRequestHeaders.Add("Authorization", $"Bearer {apiKey}");

            StringContent content = new StringContent(data, Encoding.UTF8, "application/json");

            HttpResponseMessage response = await client.PostAsync(apiUrl, content);
            string responseContent = await esponse.Content.ReadAsStringAsync();

            // 解析JSON字符串
            JObject jsonObject = JObject.Parse(responseContent);

            // 获取text字段的值
            string textValue = (string)jsonObject["choices"][0]["text"];
            return textValue;
        }
    }
0

评论0

请先
中建基础设施施工技术标准化系列图集-市政路桥分册-共6册
中建基础设施施工技术标准化系列图集-市政路桥分册-共6册
1分钟前 有人购买 去瞅瞅看
没有账号?注册  忘记密码?

社交账号快速登录

微信扫一扫关注
扫码关注后会自动登录网站