在.NET 中调用第三方 AI 大模型可以借助不同的类库来实现,以下为你介绍几个常见的第三方 AI 大模型类库,并给出部分示例代码。
 

1. OpenAI API(使用OpenAI-DotNet库)

介绍

OpenAI-DotNet 是一个用于与 OpenAI API 进行交互的.NET 库,它提供了简单易用的接口,方便开发者在.NET 应用程序中调用 OpenAI 的各种模型,如 GPT - 3、GPT - 3.5 Turbo、GPT - 4 等。

安装

可以通过 NuGet 包管理器安装 OpenAI-DotNet
Install-Package OpenAI.Net
using OpenAI.Net;
using OpenAI.Net.Models.Requests;
using OpenAI.Net.Models.Responses;

class Program
{
    static async Task Main()
    {
        // 设置OpenAI API密钥
        var apiKey = "YOUR_OPENAI_API_KEY";
        var openAIClient = new OpenAIClient(apiKey);

        // 创建聊天请求
        var chatRequest = new ChatCompletionRequest
        {
            Model = "gpt-3.5-turbo",
            Messages = new[]
            {
                new ChatMessage { Role = ChatMessageRole.System, Content = "You are a helpful assistant." },
                new ChatMessage { Role = ChatMessageRole.User, Content = "What is the capital of France?" }
            }
        };

        // 发送请求并获取响应
        var response = await openAIClient.ChatCompletions.Create(chatRequest);

        if (response.IsSuccess)
        {
            var answer = response.Result?.Choices?.FirstOrDefault()?.Message?.Content;
            Console.WriteLine($"Answer: {answer}");
        }
        else
        {
            Console.WriteLine($"Error: {response.Error?.Message}");
        }
    }
}

2. 百度文心一言(使用RestEase库调用 API)

介绍

百度文心一言是百度研发的知识增强大语言模型,开发者可以通过 HTTP 请求调用其 API。RestEase 是一个用于创建类型安全的 REST 客户端的.NET 库,可用于简化与文心一言 API 的交互。

安装

通过 NuGet 包管理器安装 RestEase
Install-Package RestEase
using RestEase;
using System.Net.Http;
using System.Threading.Tasks;

// 定义文心一言API接口
[BasePath("https://aip.baidubce.com")]
public interface IErnieBotApi
{
    [Post("/rpc/2.0/ai_custom/v1/wenxinworkshop/chat/completions")]
    Task<HttpResponseMessage> GetCompletion([Query("access_token")] string accessToken, [Body] object request);
}

class Program
{
    static async Task Main()
    {
        // 获取百度API的访问令牌
        var accessToken = "YOUR_BAIDU_ACCESS_TOKEN";

        // 创建RestEase客户端
        var api = RestClient.For<IErnieBotApi>("https://aip.baidubce.com");

        // 构建请求体
        var requestBody = new
        {
            messages = new[]
            {
                new { role = "user", content = "法国的首都是哪里?" }
            }
        };

        // 发送请求
        var response = await api.GetCompletion(accessToken, requestBody);

        if (response.IsSuccessStatusCode)
        {
            var responseContent = await response.Content.ReadAsStringAsync();
            Console.WriteLine($"Answer: {responseContent}");
        }
        else
        {
            Console.WriteLine($"Error: {response.StatusCode}");
        }
    }
}

 

3. 讯飞星火(使用HttpClient调用 API)

介绍

讯飞星火是科大讯飞研发的认知智能大模型,开发者可以通过 HTTP 请求调用其 API。使用 HttpClient 可以直接发送 HTTP 请求与讯飞星火 API 进行交互。
using System;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;

class Program
{
    static async Task Main()
    {
        var apiUrl = "YOUR_XINGHUO_API_URL";
        var appId = "YOUR_APP_ID";
        var apiKey = "YOUR_API_KEY";
        var apiSecret = "YOUR_API_SECRET";

        // 构建请求体
        var requestBody = new
        {
            header = new
            {
                app_id = appId
            },
            parameter = new
            {
                chat = new
                {
                    domain = "general",
                    temperature = 0.5,
                    max_tokens = 2048
                }
            },
            payload = new
            {
                message = new
                {
                    text = new[]
                    {
                        new { role = "user", content = "法国的首都是哪里?" }
                    }
                }
            }
        };

        var jsonBody = JsonConvert.SerializeObject(requestBody);
        var httpContent = new StringContent(jsonBody, Encoding.UTF8, "application/json");

        using (var httpClient = new HttpClient())
        {
            // 设置请求头和签名等信息(此处省略详细签名逻辑)
            var response = await httpClient.PostAsync(apiUrl, httpContent);

            if (response.IsSuccessStatusCode)
            {
                var responseContent = await response.Content.ReadAsStringAsync();
                Console.WriteLine($"Answer: {responseContent}");
            }
            else
            {
                Console.WriteLine($"Error: {response.StatusCode}");
            }
        }
    }
}