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就可以运行了。

相关推荐
userkang13 分钟前
消失的前后端,崛起的智能体
前端·人工智能·后端·ai·硬件工程
契合qht53_shine13 分钟前
深度学习 视觉处理(CNN) day_01
人工智能·深度学习·cnn
新智元17 分钟前
100 年企业知识超 10 万文件,「内网版 ChatGPT」血洗最卷行业!全员 70% 和 AI 共事
人工智能·openai
新智元20 分钟前
AGI 幻灭,LeCun 观点得证?哈佛研究实锤 AI 不懂因果,世界模型神话破灭
人工智能·openai
量子位33 分钟前
图像编辑开源新 SOTA,来自多模态卷王阶跃!大模型行业正步入「多模态时间」
人工智能·llm
量子位34 分钟前
数学家们仍在追赶天才拉马努金
人工智能·数学
是瑶瑶子啦38 分钟前
【深度学习】多头注意力机制的实现|pytorch
人工智能·pytorch·深度学习
小和尚同志43 分钟前
热门 AI 编辑器(Cursor、v0、Manus、Windsurf 等)及工具的系统提示词
人工智能·aigc
量子位1 小时前
不用等R2了!第三方给新版DeepSeek V3添加深度思考,推理101秒破解7米甘蔗过2米门
人工智能·deepseek
沈建军_Juhani1 小时前
Function calling, 模态上下文协议(MCP),多步能力协议(MCP) 和 A2A的区别
aigc·openai·mcp