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
                    
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="ChatStream.OpenAi.Client.Net" Version="8.0.5" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="ChatStream.OpenAi.Client.Net" Version="8.0.5" />
                    
Directory.Packages.props
<PackageReference Include="ChatStream.OpenAi.Client.Net" />
                    
Project file
For projects that support Central Package Management (CPM), copy this XML node into the solution Directory.Packages.props file to version the package.
paket add ChatStream.OpenAi.Client.Net --version 8.0.5
                    
#r "nuget: ChatStream.OpenAi.Client.Net, 8.0.5"
                    
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
#:package ChatStream.OpenAi.Client.Net@8.0.5
                    
#:package directive can be used in C# file-based apps starting in .NET 10 preview 4. Copy this into a .cs file before any lines of code to reference the package.
#addin nuget:?package=ChatStream.OpenAi.Client.Net&version=8.0.5
                    
Install as a Cake Addin
#tool nuget:?package=ChatStream.OpenAi.Client.Net&version=8.0.5
                    
Install as a Cake Tool

ChatStream.OpenAi.Client.Net

NuGet Version License: MIT

ChatStream.OpenAi.Client 是一个轻量级 .NET 8 库,用于与 OpenAI 兼容的聊天 API 进行交互。它提供了流式响应函数调用(Tool Calling) 的抽象,并支持通过 [Tool] 特性自动扫描业务服务中的方法作为工具。同时,该库还内置了与 RAGFlow 知识库 集成的能力,让您可以轻松构建具备内部知识检索能力的 AI 助手。

✨ 特性

  • 🚀 异步流式输出:通过 IAsyncEnumerable<string> 逐字返回模型生成的内容。
  • 🔧 函数调用(Tool Calling):支持两种模式:
    • 手动定义 ChatTool 并传入回调
    • 自动扫描 [Tool] 特性标记的方法,零配置集成
  • 🧩 RAGFlow 集成:内置 IRagFlowClientRagFlowClient,快速对接 RAGFlow 知识库 API。
  • 📦 依赖注入友好:提供扩展方法 AddOpenAiClientAddRagFlowClient,与 ASP.NET Core DI 无缝集成。
  • 🎯 ASP.NET Core 支持:提供 StreamResult(需自行复制到 Web 项目中)以返回 SSE 流式响应。
  • 高性能:核心库仅依赖 OpenAI 官方 SDK,无多余重量级依赖。

📦 安装

核心库(所有项目通用)

-- bash dotnet add package ChatStream.OpenAi.Client.Net

🚀 快速开始

核心库(所有项目通用)

  1. 注册 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);

  1. 定义业务工具(使用 [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"; } }

  1. 注册工具处理器并注入依赖

// 注册业务服务 builder.Services.AddScoped<WeatherService>();

// 注册 ToolCallHandler,将 WeatherService 实例传入 builder.Services.AddScoped<IToolCallHandler>(sp ⇒ { var weather = sp.GetRequiredService<WeatherService>(); return new ToolCallHandler(weather); // 可传入多个服务:new ToolCallHandler(weather, ragService, ...) });

  1. 在控制器中使用流式输出

[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 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. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.

NuGet packages

This package is not used by any NuGet packages.

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last Updated
8.0.5 93 5/17/2026
8.0.4 105 4/28/2026
8.0.3 105 4/27/2026
8.0.2 104 4/26/2026
8.0.1 115 4/23/2026