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

相关推荐
kalvin_y_liu3 分钟前
【2026年经济周期关键节点案例分析】
人工智能
Wokoo710 分钟前
开发者AI大模型学习与接入指南
java·人工智能·学习·架构
骚戴14 分钟前
2025 n1n.ai 全栈国产大模型接入列表与实测报告
人工智能·大模型·llm·api·ai gateway
南山乐只16 分钟前
【Spring AI 开发指南】ChatClient 基础、原理与实战案例
人工智能·后端·spring ai
极客小云41 分钟前
【突发公共事件智能分析新范式:基于PERSIA框架与大模型的知识图谱构建实践】
大数据·人工智能·知识图谱
Fuly10241 小时前
如何评估LLM和Agent质量
人工智能
weisian1511 小时前
入门篇--知名企业-12-Stability AI:不止于“艺术”,这是一场开源AI的全面起义
人工智能·开源·stablility ai
五月君_1 小时前
Nuxt UI v4.3 发布:原生 AI 富文本编辑器来了,Vue 生态又添一员猛将!
前端·javascript·vue.js·人工智能·ui
wjykp2 小时前
109~111集成学习
人工智能·机器学习·集成学习
小程故事多_802 小时前
Spring AI 赋能 Java,Spring Boot 快速落地 LLM 的企业级解决方案
java·人工智能·spring·架构·aigc