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

相关推荐
冬奇Lab31 分钟前
OpenClaw 源码精读(3):Agent 执行引擎——AI 如何「思考」并与真实世界交互?
人工智能·aigc
没事勤琢磨2 小时前
如何让 OpenClaw 控制使用浏览器:让 AI 像真人一样操控你的浏览器
人工智能
用户5191495848452 小时前
CrushFTP 认证绕过漏洞利用工具 (CVE-2024-4040)
人工智能·aigc
牛马摆渡人5283 小时前
OpenClaw实战--Day1: 本地化
人工智能
前端小豆3 小时前
玩转 OpenClaw:打造你的私有 AI 助手网关
人工智能
BugShare3 小时前
写一个你自己的Agent Skills
人工智能·程序员
机器之心3 小时前
英伟达护城河被AI攻破,字节清华CUDA Agent,让人人能搓CUDA内核
人工智能·openai
后端小肥肠4 小时前
公众号躺更神器!OpenClaw+Claude Skill 实现自动读对标 + 写文 + 配图 + 存入草稿箱
人工智能·aigc·agent
爱可生开源社区5 小时前
SCALE | 重构 AI 时代数据库能力的全新评估标准
人工智能
Jahzo5 小时前
openclaw本地化部署体验与踩坑记录--飞书机器人配置
人工智能·开源