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

相关推荐
一只落魄的蜂鸟5 分钟前
【2026年-04期】Intelligent agent architecture
人工智能
咋吃都不胖lyh6 分钟前
GBDT 回归任务生成过程(逐步计算演示)
人工智能·数据挖掘·回归
幻云20107 分钟前
Next.js 之道:从入门到精通
前端·javascript·vue.js·人工智能·python
阿豪Jeremy7 分钟前
LlamaFactory微调Qwen3-0.6B大模型实验整理——调一个人物领域专属的模型
人工智能·深度学习·机器学习
培根芝士10 分钟前
把PP-OCRv5_server模型转换为OpenVINO格式
人工智能·openvino
方见华Richard12 分钟前
《认知纪元宪章》V1.0-人类智能与人工智能联合签署
人工智能·经验分享·交互·原型模式·空间计算
juhanishen13 分钟前
Agent skill 大白话,从零到1,范例解析
chatgpt·llm·agent·deepseek·agent skill
财经科技14 分钟前
安全测试观察:某类AI智能反诈通信业务的运行特征与潜在风险
大数据·人工智能·物联网
速易达网络15 分钟前
AI发展全景:从模型到硬件的多层演进
人工智能
Jouham19 分钟前
瞬维智能CEO刘哲先生受邀参加2025年火山引擎FORCE原动力大会
人工智能·火山引擎