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

openai csharp 文章 2023-02-17 10:35 1599 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群

相关文章
为什么openai无法使用中国的visa卡支付
chatgpt喂数据以及知识库检索
OpenAI 今日开放新的模型
OpenAI(ChatGPT)又出幺蛾子了 Sorry, you have been blocked
CSharp.net调用chatGPT代码
随便看看
教育科技公司申请微信支付被拒绝? 4696
微信公众号免300认证教程 5777
小程序已经上线,作为管理员无法在小程序数据助手查看数据? 5188
小程序广告组件通过审核,但是小程序内没有显示广告? 4962
企业微信通讯录账号被管理员误/恶意删除,怎么办? 9391
问题? 8911
如何快速搭建抽奖助手小程序(无需代码知识) 6041
许涛 大哥在吗, 要解冻小程序的时候提示信息主体不一致, 能帮忙看下吗? 7345
小程序搜一搜全称搜索不显示 麻烦解决一下!谢谢 6671
我的小程序广告收款主体是个体工商户,每个月邮寄两次发票很是麻烦,我年底的时候打包邮寄一次可以么? 6000