ChatStream.OpenAi.Client.Net
8.0.5
dotnet add package ChatStream.OpenAi.Client.Net --version 8.0.5
NuGet\Install-Package ChatStream.OpenAi.Client.Net -Version 8.0.5
<PackageReference Include="ChatStream.OpenAi.Client.Net" Version="8.0.5" />
<PackageVersion Include="ChatStream.OpenAi.Client.Net" Version="8.0.5" />
<PackageReference Include="ChatStream.OpenAi.Client.Net" />
paket add ChatStream.OpenAi.Client.Net --version 8.0.5
#r "nuget: ChatStream.OpenAi.Client.Net, 8.0.5"
#:package ChatStream.OpenAi.Client.Net@8.0.5
#addin nuget:?package=ChatStream.OpenAi.Client.Net&version=8.0.5
#tool nuget:?package=ChatStream.OpenAi.Client.Net&version=8.0.5
ChatStream.OpenAi.Client.Net
ChatStream.OpenAi.Client 是一个轻量级 .NET 8 库,用于与 OpenAI 兼容的聊天 API 进行交互。它提供了流式响应、函数调用(Tool Calling) 的抽象,并支持通过 [Tool] 特性自动扫描业务服务中的方法作为工具。同时,该库还内置了与 RAGFlow 知识库 集成的能力,让您可以轻松构建具备内部知识检索能力的 AI 助手。
✨ 特性
- 🚀 异步流式输出:通过
IAsyncEnumerable<string>逐字返回模型生成的内容。 - 🔧 函数调用(Tool Calling):支持两种模式:
- 手动定义
ChatTool并传入回调 - 自动扫描
[Tool]特性标记的方法,零配置集成
- 手动定义
- 🧩 RAGFlow 集成:内置
IRagFlowClient和RagFlowClient,快速对接 RAGFlow 知识库 API。 - 📦 依赖注入友好:提供扩展方法
AddOpenAiClient、AddRagFlowClient,与 ASP.NET Core DI 无缝集成。 - 🎯 ASP.NET Core 支持:提供
StreamResult(需自行复制到 Web 项目中)以返回 SSE 流式响应。 - ⚡ 高性能:核心库仅依赖
OpenAI官方 SDK,无多余重量级依赖。
📦 安装
核心库(所有项目通用)
-- bash dotnet add package ChatStream.OpenAi.Client.Net
🚀 快速开始
核心库(所有项目通用)
- 注册 OpenAI 客户端
在 Program.cs 中配置 API Key 和模型: using ChatStream.OpenAi.Client.Extensions;
var builder = WebApplication.CreateBuilder(args);
string apiKey = builder.Configuration["OpenAI:ApiKey"]; string model = builder.Configuration["OpenAI:Model"] ?? "gpt-4o"; string? endpoint = builder.Configuration["OpenAI:Endpoint"]; // 可选,如阿里云地址
builder.Services.AddOpenAiClient(apiKey, model, endpoint);
- 定义业务工具(使用 [Tool] 特性)
using ChatStream.OpenAi.Client.Attributes; public class WeatherService { [Tool("GetCurrentTemperature", "获取指定城市的当前温度(摄氏度)。")] public async Task<string> GetCurrentTemperatureAsync(string city, CancellationToken ct) { // 调用真实天气 API... return $"{city} 当前温度 22°C"; } }
- 注册工具处理器并注入依赖
// 注册业务服务 builder.Services.AddScoped<WeatherService>();
// 注册 ToolCallHandler,将 WeatherService 实例传入 builder.Services.AddScoped<IToolCallHandler>(sp ⇒ { var weather = sp.GetRequiredService<WeatherService>(); return new ToolCallHandler(weather); // 可传入多个服务:new ToolCallHandler(weather, ragService, ...) });
- 在控制器中使用流式输出
[ApiController] [Route("api/chat")] public class ChatController : ControllerBase { private readonly IOpenAIService _ai;
public ChatController(IOpenAIService ai) => _ai = ai;
[HttpGet("ask")]
public IActionResult Ask([FromQuery] string prompt)
{
// 使用自动扫描的工具(通过 IToolCallHandler)
return new StreamResult(ct => _ai.StreamWithToolsAsync(prompt, null, ct));
}
}
线程安全与异步 OpenAiChatClient 和 OpenAIService 是线程安全的。
ToolCallHandler 基于反射,但设计为单例或 scoped 均可。
所有方法均支持 CancellationToken,且使用 ConfigureAwait(false) 避免死锁。
重试与超时策略 由于库内部使用 HttpClient,你可以通过依赖注入的 IHttpClientFactory 添加 Polly 策略。例如,对天气 API 调用自动重试: 天气工具调用助手 ToolCallHandler 会自动扫描带有 [Tool] 特性的方法(例如 GetWeatherAsync),生成符合 OpenAI 规范的 ChatTool 描述,并自动解析模型传入的城市参数,执行天气查询方法。
示例 API 参数 模型 支持 OpenAI 兼容的所有模型,常用示例:
C# 常数值 API 模型 "gpt-4o" gpt-4o "gpt-4" gpt-4 "gpt-3.5-turbo" gpt-3.5-turbo "glm-5.1" 智谱 AI "qwen-max" 通义千问 MaxTokens 限制生成的最大 token 数,默认为 64。可设置 null 表示使用模型默认值。
Temperature 采样温度,范围 0~2,默认 0.5。值越高输出越随机。
不使用 DI 的原始客户端 如果你不需要 DI 和工具处理器,可以直接使用 OpenAiChatClient 进行天气查询: ⚙️ 常用配置 参数 说明 apiKey OpenAI 或兼容服务的 API Key modelName 模型名称,如 gpt-4o、glm-5.1 endpoint 自定义端点(阿里云等需要) StreamFormat PlainText、StandardSSE、OpenAILike
📄 许可证
MIT License
Copyright (c) 2024 yuan
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
| Product | Versions Compatible and additional computed target framework versions. |
|---|---|
| .NET | net8.0 is compatible. net8.0-android was computed. net8.0-browser was computed. net8.0-ios was computed. net8.0-maccatalyst was computed. net8.0-macos was computed. net8.0-tvos was computed. net8.0-windows was computed. net9.0 was computed. net9.0-android was computed. net9.0-browser was computed. net9.0-ios was computed. net9.0-maccatalyst was computed. net9.0-macos was computed. net9.0-tvos was computed. net9.0-windows was computed. net10.0 was computed. net10.0-android was computed. net10.0-browser was computed. net10.0-ios was computed. net10.0-maccatalyst was computed. net10.0-macos was computed. net10.0-tvos was computed. net10.0-windows was computed. |
-
net8.0
- Microsoft.Extensions.Http (>= 8.0.0)
- OpenAI (>= 2.10.0)
- System.Text.Json (>= 10.0.7)
NuGet packages
This package is not used by any NuGet packages.
GitHub repositories
This package is not used by any popular GitHub repositories.