Bitzsoft.Integrations.AI 1.0.0-alpha.7

This is a prerelease version of Bitzsoft.Integrations.AI.
dotnet add package Bitzsoft.Integrations.AI --version 1.0.0-alpha.7
                    
NuGet\Install-Package Bitzsoft.Integrations.AI -Version 1.0.0-alpha.7
                    
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="Bitzsoft.Integrations.AI" Version="1.0.0-alpha.7" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="Bitzsoft.Integrations.AI" Version="1.0.0-alpha.7" />
                    
Directory.Packages.props
<PackageReference Include="Bitzsoft.Integrations.AI" />
                    
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 Bitzsoft.Integrations.AI --version 1.0.0-alpha.7
                    
#r "nuget: Bitzsoft.Integrations.AI, 1.0.0-alpha.7"
                    
#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 Bitzsoft.Integrations.AI@1.0.0-alpha.7
                    
#: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=Bitzsoft.Integrations.AI&version=1.0.0-alpha.7&prerelease
                    
Install as a Cake Addin
#tool nuget:?package=Bitzsoft.Integrations.AI&version=1.0.0-alpha.7&prerelease
                    
Install as a Cake Tool

Bitzsoft.Integrations.AI

AI 服务集成 — 基于 Microsoft.Extensions.AIIChatClient 抽象,提供轻量 OpenAI 兼容客户端。

功能特性

  • 基于 Microsoft.Extensions.AI.IChatClient 标准抽象,Provider 无关
  • 兼容所有 OpenAI Chat Completions API 协议的服务商(OpenAI、DeepSeek、通义千问等)
  • 支持命名客户端(Keyed DI),满足多租户或多模型场景
  • 支持结构化输出(GetObjectAsync<T>),直接获取强类型对象
  • 内置 MEAI 中间件管道:OpenTelemetry 遥测、分布式缓存、日志记录
  • HttpClient 已接入 Bitzsoft.Integrations.RequestLogging 第三方请求日志

安装

dotnet add package Bitzsoft.Integrations.AI

配置

appsettings.json 中添加以下配置节:

{
  "AI": {
    "Endpoint": "https://api.openai.com/v1",
    "ApiKey": "sk-your-api-key",
    "ModelId": "gpt-4o",
    "SystemPrompt": "你是一个有帮助的 AI 助手。"
  }
}
配置项 类型 默认值 说明
Endpoint string https://api.openai.com/v1 OpenAI 兼容端点地址
ApiKey string - API 密钥
ModelId string gpt-4o 默认模型名称
SystemPrompt string 你是一个有帮助的 AI 助手。 默认系统提示词
EnableTelemetry bool false 是否启用 OpenTelemetry 遥测中间件
EnableCaching bool false 是否启用分布式缓存中间件(需注册 IDistributedCache

兼容历史配置ApiUrl 映射到 EndpointDefaultModel 映射到 ModelId

注册服务

基础注册

using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.AI;

// Program.cs
services.AddBitzChatClient(options =>
{
    options.Endpoint = "https://api.openai.com/v1";
    options.ApiKey = "sk-your-api-key";
    options.ModelId = "gpt-4o";
});

多租户 / 多模型注册

// 注册 GPT-4o 客户端
services.AddBitzChatClient("GPT4", options =>
{
    options.Endpoint = "https://api.openai.com/v1";
    options.ApiKey = "sk-openai-key";
    options.ModelId = "gpt-4o";
});

// 注册 DeepSeek 客户端
services.AddBitzChatClient("DeepSeek", options =>
{
    options.Endpoint = "https://api.deepseek.com/v1";
    options.ApiKey = "sk-deepseek-key";
    options.ModelId = "deepseek-chat";
});

第三方请求日志

机制说明:本连接器基于 Microsoft.Extensions.AIIChatClient 抽象,HTTP 管道由 IChatClient 实现内部管理,无法DelegatingHandler 拦截(与 HttpClient 直连实现不同)。请求日志改由 RequestLoggingChatClient 包装层实现:它实现 IChatClient,在每次对话补全调用前后经 IRequestLogRecorder 钩子记录,汇入与 HttpClient 拦截同一个日志管道(IRequestLogStore),由宿主统一持久化。

记录内容(每次对话补全调用产生一条):

字段 取值
Provider AI
Endpoint OpenAI 兼容服务域名(如 api.openai.com / api.deepseek.com
Method SDK(非标准 HTTP 方法,标识为 IChatClient 管道调用)
ApiName 操作名,如 ChatCompletion(对话补全)
RequestBody / ResponseBody 请求/响应消息序列化(经 SensitiveFields 脱敏)
StatusCode 成功记 200,调用抛异常时为空(受限于 IChatClient 不暴露原始 HTTP 状态码)
Exception IChatClient 异常信息
DurationMs 本次调用耗时

局限

  • IChatClient 不暴露原始 HTTP 状态码与响应头,无法像 HttpClient 拦截那样记录真实 HTTP StatusCode/RequestHeadersStatusCode 在成功时记 200,异常时留空。
  • 仅本连接器实现的对话补全调用会被记录;IChatClient 管道的其他能力(如嵌入、音频等,本连接器未使用)不在记录范围。
// ① 默认:启用回调但不持久化(日志丢弃)
services.AddBitzChatClient(options => { /* ... */ });

// ② 持久化:宿主注册 IRequestLogStore 实现后,对话补全调用自动落库
//    AddBitzChatClient 内部已挂载 RequestLoggingChatClient,宿主无需再额外挂载 handler
services.AddRequestLogging<MyRequestLogStore>(opts =>
{
    opts.MaxBodyLength = 0;               // AI 补全响应可能很长,0=不截断完整保留
    opts.SensitiveFields.Add("mySecret"); // 额外脱敏字段
});
services.AddBitzChatClient(options => { /* ... */ });

自定义 IRequestLogStore 实现(SqlSugar / Dapper / MongoDB)详见 Bitzsoft.Integrations.RequestLogging

使用示例

注入并使用 IChatClient

using Microsoft.Extensions.AI;

public class DocumentService(IChatClient chatClient)
{
    /// <summary>
    /// 对文档内容进行摘要提取
    /// </summary>
    public async Task<string> SummarizeAsync(string documentContent, CancellationToken ct = default)
    {
        var messages = new List<ChatMessage>
        {
            new(ChatRole.System, "你是一个专业的文档摘要助手。"),
            new(ChatRole.User, $"请对以下文档内容进行摘要:\n\n{documentContent}")
        };

        var response = await chatClient.GetResponseAsync(messages, cancellationToken: ct);
        return response.Text;
    }

    /// <summary>
    /// 流式输出
    /// </summary>
    public async IAsyncEnumerable<string> SummarizeStreamAsync(
        string documentContent,
        [EnumeratorCancellation] CancellationToken ct = default)
    {
        var messages = new List<ChatMessage>
        {
            new(ChatRole.System, "你是一个专业的文档摘要助手。"),
            new(ChatRole.User, documentContent)
        };

        await foreach (var update in chatClient.GetStreamingResponseAsync(messages, cancellationToken: ct))
        {
            if (update.Text is not null)
            {
                yield return update.Text;
            }
        }
    }
}

结构化输出(Structured Output)

通过 GetObjectAsync<T> 直接获取强类型对象,无需手动 JSON 反序列化:

using Bitzsoft.Integrations.AI;

// 定义返回类型
public record SentimentResult(string Sentiment, double Confidence, string Summary);

public class AnalysisService(IChatClient chatClient)
{
    public async Task<SentimentResult?> AnalyzeAsync(string text, CancellationToken ct = default)
    {
        return await chatClient.GetObjectAsync<SentimentResult>(
            message: $"请分析以下文本的情感倾向:\n{text}",
            systemPrompt: "你是情感分析助手,返回 JSON 格式:sentiment(正面/负面/中性)、confidence(0-1)、summary");
    }
}

使用命名客户端(多模型场景)

public class MultiModelService(
    [FromKeyedServices("BitzChatClient_GPT4")] IChatClient gpt4Client,
    [FromKeyedServices("BitzChatClient_DeepSeek")] IChatClient deepseekClient)
{
    public Task<string> AskGptAsync(string question) =>
        gpt4Client.GetResponseAsync(question);

    public Task<string> AskDeepSeekAsync(string question) =>
        deepseekClient.GetResponseAsync(question);
}

相关包

包名 说明
Bitzsoft.Integrations.AI.Abstractions AI 共享抽象层(AiOptions、DI 扩展)
Bitzsoft.Integrations.SemanticKernel Semantic Kernel 编排层(插件、函数调用)
Bitzsoft.Integrations.RAG 检索增强生成(Qdrant + IEmbeddingGenerator)
Bitzsoft.Integrations.AgentFramework AI Agent 框架
Bitzsoft.Integrations.McpServer MCP Server 集成
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 is compatible.  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 (1)

Showing the top 1 NuGet packages that depend on Bitzsoft.Integrations.AI:

Package Downloads
Bitzsoft.Integrations.All

Bitzsoft 第三方集成聚合包 — 包含全部 Integration 模块

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last Updated
1.0.0-alpha.7 54 6/16/2026
1.0.0-alpha.6 58 6/16/2026
1.0.0-alpha.5 53 6/14/2026
1.0.0-alpha.4 60 6/14/2026
1.0.0-alpha.3 57 6/7/2026
1.0.0-alpha.2 59 5/29/2026
1.0.0-alpha.1 53 5/28/2026