CSharp OpenAI

微软有个开源框架,可以使用C#调用OpenAI接口。地址如下:

GitHub - microsoft/semantic-kernel: Integrate cutting-edge LLM technology quickly and easily into your apps

今天研究了下,看如果使用国内代理来使用OpenAI的API。

国内代理使用的是之前文章中的代理:

国内访问OpenAI API_openai代理-CSDN博客

微软这个框架也可以通过在Visual Studio中的NuGet来安装。

框架示例中有个Create_Kernel的代码,我改造了一下,就可以使用国内代理来运行了。

改造后的代码如下:

cs 复制代码
using Microsoft.SemanticKernel;
using Microsoft.SemanticKernel.Connectors.OpenAI;
using OpenAI;
using System.ClientModel;

public sealed class S01_Create_Kernel
{
    public async Task RunAsync()
    {
        OpenAIClientOptions options = new OpenAIClientOptions();
        options.Endpoint = new Uri("https://api.openai-proxy.org/v1");
        OpenAIClient client = new OpenAIClient(new ApiKeyCredential("sk-xxxxx"), options);
        Kernel kernel = Kernel.CreateBuilder().AddOpenAIChatCompletion(modelId: "gpt-4", client).Build();

        // 1.
        Console.WriteLine(await kernel.InvokePromptAsync("What color is the sky?"));
        Console.WriteLine();
        // 2.
        KernelArguments arguments = new() { { "topic", "sea" } };
        Console.WriteLine(await kernel.InvokePromptAsync("What color is the {{$topic}}?", arguments));
        Console.WriteLine();
        // 3.
        await foreach (var update in kernel.InvokePromptStreamingAsync("What color is the {{$topic}}? Provide a detailed explanation.", arguments))
        {
            Console.Write(update);
        }

        Console.WriteLine(string.Empty);

        // 4.
        arguments = new(new OpenAIPromptExecutionSettings { MaxTokens = 500, Temperature = 0.5 }) { { "topic", "dogs" } };
        Console.WriteLine(await kernel.InvokePromptAsync("Tell me a story about {{$topic}}?", arguments));

        // 5. 
#pragma warning disable SKEXP0010
        arguments = new(new OpenAIPromptExecutionSettings { ResponseFormat = "json_object" }) { { "topic", "chocolate" } };
        Console.WriteLine(await kernel.InvokePromptAsync("Create a recipe for a {{$topic}} cake in JSON format", arguments));
    }

    public static async Task Main()
    {
        await new S01_Create_Kernel().RunAsync();
    }
}

只需将代码中的sk-xxxxx替换为自己代理中的apikey就可以运行了。

相关推荐
边缘常驻民12 分钟前
PyTorch深度学习入门记录3
人工智能·pytorch·深度学习
阿里云大数据AI技术24 分钟前
[VLDB 2025]面向Flink集群巡检的交叉对比学习异常检测
大数据·人工智能·flink
a1504631 小时前
人工智能——图像梯度处理、边缘检测、绘制图像轮廓、凸包特征检测
人工智能·深度学习·计算机视觉
荼蘼1 小时前
基于 KNN 算法的手写数字识别项目实践
人工智能·算法·机器学习
wei_shuo1 小时前
亚马逊云科技 EC2 部署 Dify,集成 Amazon Bedrock 构建生成式 AI 应用
人工智能·amazon·amazon bedrock
ppo921 小时前
MCP简单应用:使用SpringAI + Cline + DeepSeek实现AI创建文件并写入内容
人工智能·后端
云卓SKYDROID2 小时前
无人机速度模块技术要点分析
人工智能·无人机·科普·高科技·云卓科技
vvandre2 小时前
ChatGPT桌面版深度解析
chatgpt
UQI-LIUWJ3 小时前
论文笔记:Tuning Language Models by Proxy
论文阅读·人工智能·语言模型
哪吒编程3 小时前
炸裂!OpenAI GPT-5提前泄露?最强模型诞生
openai