C#判断openai的密钥是否有效

openai csharp 文章 2023-02-17 10:35 1598 0 全屏看文

AI助手支持GPT4.0

以下是一个使用WinForms和C#的示例代码,用于验证OpenAI API密钥的有效性:

using System;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace OpenAI_Key_Validation
{
    public partial class Form1 : Form
    {
        private const string API_KEY = "YOUR_API_KEY_HERE";
        private const string API_URL = "https://api.openai.com/v1/engines/davinci-codex/completions";

        public Form1()
        {
            InitializeComponent();
        }

        private async void button1_Click(object sender, EventArgs e)
        {
            // Disable the button while the validation is in progress
            button1.Enabled = false;

            bool keyIsValid = await ValidateApiKeyAsync();

            if (keyIsValid)
            {
                MessageBox.Show("API key is valid!");
            }
            else
            {
                MessageBox.Show("Invalid API key.");
            }

            // Re-enable the button
            button1.Enabled = true;
        }

        private async Task<bool> ValidateApiKeyAsync()
        {
            using (var client = new HttpClient())
            {
                // Set the API key in the Authorization header
                client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", API_KEY);

                // Send a test request to the OpenAI API to check if the key is valid
                try
                {
                    var response = await client.PostAsync(API_URL, new StringContent("test"));
                    if (response.StatusCode == HttpStatusCode.Unauthorized)
                    {
                        // The API key is invalid
                        return false;
                    }
                    else if (response.IsSuccessStatusCode)
                    {
                        // The API key is valid
                        return true;
                    }
                    else
                    {
                        // There was an error with the API request
                        throw new Exception($"API request failed with status code {response.StatusCode}");
                    }
                }
                catch (HttpRequestException ex)
                {
                    // There was an error with the HTTP request
                    throw new Exception("HTTP request failed", ex);
                }
            }
        }
    }
}

在代码中,将YOUR_API_KEY_HERE替换为您自己的OpenAI API密钥。然后,在窗体上添加一个按钮,并将其Click事件处理程序设置为button1_Click。当用户单击该按钮时,它将调用ValidateApiKeyAsync方法,该方法将尝试向OpenAI API发送一个测试请求来验证API密钥的有效性。如果API密钥有效,它将返回true,否则返回false。该方法使用HttpClient来进行HTTP请求,并使用Authorization标头将API密钥设置为Bearer令牌。


请注意,此代码仅在Windows操作系统上使用WinForms框架,如果您使用其他操作系统或UI框架,则可能需要进行适当的更改。


-EOF-

AI助手支持GPT4.0


国内超级便宜服务器

摸鱼人热门新闻聚合

钻级赞助商 我要加入

开发者在线工具

第三方支付技术请加QQ群

相关文章
C#判断openai的密钥是否有效
vue调用openai的代码
openAI首席执行官宣布:暂停注册新plus会员
目前市面上AI模型价格对比
发生如下错误都是你的科学工具有问题
随便看看
企业微信通讯录账号被管理员误/恶意删除,怎么办? 9389
问题? 8910
如何快速搭建抽奖助手小程序(无需代码知识) 6040
许涛 大哥在吗, 要解冻小程序的时候提示信息主体不一致, 能帮忙看下吗? 7344
小程序搜一搜全称搜索不显示 麻烦解决一下!谢谢 6671
我的小程序广告收款主体是个体工商户,每个月邮寄两次发票很是麻烦,我年底的时候打包邮寄一次可以么? 5999
如何解决渲染层网络错误Failed to load media? 17276
小程序找号找回 释放昵称? 3151
我的小程序广告主收入5301,实际进账4406,是怎么回事呀? 3014
删除部分微信用户个人数据的通知,怎么删除? 6262