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

相关推荐
自由能燃气设备3 分钟前
燃气容积式热水器厂家选购指南:2026年商用热水设备采购避坑手册
大数据·数据库·数据仓库·人工智能
Nomarsgo9 分钟前
3C电子智能制造产线嵌入式工控机解决方案——基于研华 MIC-770H 打造高性能、紧凑型智能制造边缘控制平台
人工智能·科技·视觉检测·电脑·制造
yinghuoAI20269 分钟前
电商卖货,本质上是“视觉的战争”
人工智能·ai·ai作画·ai作图·ai生视频
做前端的娜娜子16 分钟前
Embedding 向量模型:从语义表示到相似度计算
langchain·openai·掘金·金石计划
武汉星际互动23 分钟前
政务智能体进入大厅,需要理解哪些核心问题?
人工智能·政务
别动我齐刘海26 分钟前
机器学习基础2——C++、OpenCV、点云、Open3D
c++·人工智能·opencv·机器学习·计算机视觉·机器人·ros2
DeepIntelli34 分钟前
品牌内容AI友好化改造:从被搜索引擎收录到被AI引擎引用的技术路径
人工智能·chatgpt
测试_AI_一辰40 分钟前
AI Agent 评测最隐蔽的坑-记忆
人工智能·算法·ai·自动化·ai编程
Hotchip_MEMS1 小时前
TWS耳机微米级较量:超薄LGA封装如何助力MEMS麦克风小型化?
人工智能·笔记·物联网·电脑