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

相关推荐
白掰虾27 分钟前
STM32N6&AI资料汇总
人工智能·stm32·嵌入式硬件·stm32n6·stm32ai
爱思德学术1 小时前
中国计算机学会(CCF)推荐学术会议-C(软件工程/系统软件/程序设计语言):MSR 2026
人工智能·机器学习·软件工程·数据科学
小李独爱秋1 小时前
特征值优化:机器学习中的数学基石
人工智能·python·线性代数·机器学习·数学建模
科兴第一吴彦祖1 小时前
在线会议系统是一个基于Vue3 + Spring Boot的现代化在线会议管理平台,集成了视频会议、实时聊天、AI智能助手等多项先进技术。
java·vue.js·人工智能·spring boot·推荐算法
Lululaurel2 小时前
机器学习系统框架:核心分类、算法与应用全景解析
人工智能·算法·机器学习·ai·分类
居7然2 小时前
解锁AI智能体:上下文工程如何成为架构落地的“魔法钥匙”
人工智能·架构·大模型·智能体·上下文工程
二向箔reverse2 小时前
opencv基于SIFT特征匹配的简单指纹识别系统实现
人工智能·opencv·计算机视觉
啵啵鱼爱吃小猫咪2 小时前
机器人路径规划算法大全RRT,APF,DS,RL
人工智能
AI小书房2 小时前
【人工智能通识专栏】第十四讲:语音交互
人工智能
eqwaak02 小时前
Matplotlib 动画显示进阶:交互式控制、3D 动画与未来趋势
python·tcp/ip·3d·语言模型·matplotlib