NewLife.AI 1.3.2026.608

There is a newer prerelease version of this package available.
See the version list below for details.
dotnet add package NewLife.AI --version 1.3.2026.608
                    
NuGet\Install-Package NewLife.AI -Version 1.3.2026.608
                    
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="NewLife.AI" Version="1.3.2026.608" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="NewLife.AI" Version="1.3.2026.608" />
                    
Directory.Packages.props
<PackageReference Include="NewLife.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 NewLife.AI --version 1.3.2026.608
                    
#r "nuget: NewLife.AI, 1.3.2026.608"
                    
#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 NewLife.AI@1.3.2026.608
                    
#: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=NewLife.AI&version=1.3.2026.608
                    
Install as a Cake Addin
#tool nuget:?package=NewLife.AI&version=1.3.2026.608
                    
Install as a Cake Tool

NewLife.AI

<p align="center"> <a href="https://www.nuget.org/packages/NewLife.AI"><img src="https://img.shields.io/nuget/v/NewLife.AI.svg" alt="NuGet"></a> <a href="https://www.nuget.org/packages/NewLife.AI"><img src="https://img.shields.io/nuget/dt/NewLife.AI.svg" alt="Downloads"></a> <img src="https://img.shields.io/badge/.NET-netstandard2.1%20%7C%20net8.0%20%7C%20net10.0-blue" alt=".NET"> <a href="https://github.com/NewLifeX/NewLife.AI/blob/main/LICENSE"><img src="https://img.shields.io/github/license/NewLifeX/NewLife.AI.svg" alt="License"></a> </p>

项目介绍

NewLife.AI 是面向 .NET 生态的开源 AI 基础库,通过统一的 IChatClient 接口封装 46 个主流大模型服务商,内置函数调用、MCP 协议、流式输出、多模态、多智能体等能力,可作为 NuGet 包嵌入任意 .NET 项目(net45 / netstandard2.1)。

NewLife.ChatAI 是构建于 NewLife.AI 之上的完整 Web 对话应用(ASP.NET Core),提供即开即用的多模型对话前端、统一 AI 网关与自动记忆进化,既可独立部署,也可通过 NuGet 嵌入已有 ASP.NET Core 项目。


核心特性

  • 46 家 AI 服务商,6 种协议:OpenAI / Anthropic / Gemini / 通义 DashScope / Ollama / AWS Bedrock,一行代码任意切换
  • 统一 IChatClient 接口:对齐 MEAI 规范,单轮、流式、函数调用、多模态全部统一 API
  • 函数调用(工具)[ToolDescription] 特性自动生成 JSON Schema,ToolChatClient 多轮循环,内置搜索 / 天气 / 翻译 / 网页抓取 / IP 定位等工具
  • MCP 双向支持:客户端对接外部 MCP Server(stdio / HTTP SSE),服务端将本系统工具暴露为标准 MCP 服务
  • 完整对话内核IChatHandler 三段式处理链(OnBefore → Execute → OnAfter),内置 Handler(技能激活 / 记忆注入 / 持久化 / 用量统计 / 标题生成),可插拔 IChatFilter
  • 用户记忆进化:自动从对话中提取 10 类结构化记忆,越用越懂用户
  • 统一 AI 网关:兼容 OpenAI / Anthropic / Gemini 协议,snake_case/camelCase 自动适配,AppKey 多租户,上游 429 指数退避重试
  • 技能系统:Markdown 提示词复用,@ 递归引用,触发词自动激活
  • 多智能体ConversableAgent / GroupChat / ParallelGroupChat / FunctionCallingPlanner
  • React 19 Web 前端:SSE 流式 + 对话预设 + Artifact 实时预览(HTML/SVG/Mermaid)+ 对话分叉 + 工具调用可视化 + 推理计时 + 多模态
  • 知识进化层:自动从对话中提炼知识,构建可检索的知识库,支持 TOC 目录式浏览与向量语义检索
  • TTS 语音合成:支持 DashScope TTS 与 CosyVoice V3.5,流式语音合成,前端专用 TTS 接口
  • 嵌入/向量检索:内置 HashTextEmbedder v2 与向量存储,支持知识库文档向量化与语义搜索
  • 多智能体增强:新增反思代理(ReflectionAgent)、评审代理(ReviewAgent),支持复杂任务拆分与子代理并行聚合
  • 人机决策检查点:人类可在 AI 多路径中实时选择,支持多问题组模式的决策检查与人工干预
  • 工具调用增强:引入 ToolCallContext 上下文透传、工具 Provider 熔断器、会话级工具可见性过滤、结构化错误返回与三档权限体系
  • 记忆进化:记忆整合服务支持去重/合并/过期机制,学习记忆功能自动从对话中提取结构化知识

支持的 AI 服务商

46 家服务商,9 个独立协议客户端 + 37 个 OpenAI 兼容适配

独立协议实现(9 个)

服务商 协议 特性
OpenAI ChatCompletions / Responses 视觉 / 函数调用 / 图像生成 / o3 推理
DeepSeek DeepSeek API reasoning_content / DeepSeek v4 专属参数
Anthropic Messages Claude 3.5 / Claude 4
Google Gemini Gemini 1.5 / 2.0 / 2.5
阿里云 DashScope qwen-plus / qwen-max / Omni 全模态 / Files API
Azure AI Azure OpenAI 部署名称 URL + api-key
Ollama Ollama API 本地 llama / deepseek / qwen
AWS Bedrock SigV4 签名 Claude / Llama / Titan / Mistral
NewLifeAI 级联代理 聚合多服务商
(其他) OpenAI 兼容 37 个兼容平台

OpenAI 兼容家族(37 个)

豆包(火山引擎)、智谱清言(GLM)、文心一言、月之暗面(Kimi)、MiniMax、阶跃星辰(StepFun)、百川、讯飞星火、零一万物、Moonshot、Mistral、Perplexity、Cohere、Together AI、Fireworks、OpenRouter、SiliconCloud、DeepInfra、Groq、Cerebras、Hyperbolic、Nebius、Novita、Lepton、302.AI、xAI(Grok)……以及其他 OpenAI 兼容平台。

所有服务商通过 [AiClient] 特性声明,AiClientRegistry 启动时自动扫描注册,新增服务商零配置。


快速开始

1. 仅使用 AI 基础库(SDK)

dotnet add package NewLife.AI
using NewLife.AI.Clients;

// 单轮问答
using var client = new DashScopeChatClient("your-api-key", "qwen-plus");
var reply = await client.ChatAsync("用三句话介绍一下大语言模型");
Console.WriteLine(reply);

// 多角色消息(元组数组,无需手动构造 ChatMessage)
var reply2 = await client.ChatAsync([
    ("system", "你是一名专业的 C# 开发助手"),
    ("user", "解释一下 ValueTask 和 Task 的区别"),
]);

// 流式输出
await foreach (var chunk in client.GetStreamingResponseAsync([
    new ChatMessage { Role = "user", Content = "写一首关于代码的短诗" }
], new ChatOptions()))
{
    Console.Write(chunk.Text);
}

2. ASP.NET Core 依赖注入

dotnet add package NewLife.AI.Extensions
// 注册服务
builder.Services.AddDashScope("your-api-key", "qwen-plus");

// Keyed 多服务商并存
builder.Services.AddOpenAI("openai-key", serviceKey: "openai");
builder.Services.AddAnthropic("anthropic-key", serviceKey: "anthropic");

// 注入使用
public class MyService(IChatClient chatClient)
{
    public Task<String> ChatAsync(String question)
        => chatClient.ChatAsync(question);
}

3. 函数调用(工具)

public class MyTools
{
    /// <summary>获取指定城市的天气</summary>
    [ToolDescription("get_weather")]
    public async Task<String> GetWeatherAsync(
        [Description("城市名")] String city)
        => $"{city} 今天晴,22°C";
}

// 注册工具
var registry = new ToolRegistry();
registry.AddTools<MyTools>(new MyTools());

// 挂入管道,自动多轮循环工具调用
var client = rawClient.AsBuilder()
    .UseTools(registry)
    .Build();

// 模型自动调用 get_weather("北京"),返回最终文本答案
var reply = await client.ChatAsync("北京今天天气怎么样?");

4. 约束推理路径(ReAct 模式)

当 AI 对复杂问题容易猜测或走弯路时,在 System Prompt 中使用 ReAct 格式强制逐步推理。 ToolChatClient 已内置 while 大循环(MaxIterations = 10),无需手写 Agent; 搭配 ReAct System Prompt 可进一步约束每步的推理方向,防止跳步猜测。

// UseTools 管道装配:ToolChatClient 自动循环至模型不再发起工具调用为止
var client = rawClient.AsBuilder()
    .UseTools(registry)
    .Build();

// ReAct System Prompt:Thought → Action → Observation → Answer 强制逐步推理
var reply = await client.ChatAsync([
    ("system",
        "你必须按如下格式逐步推理,不允许跳过步骤或直接猜测:\n" +
        "Thought: <分析当前需要做什么>\n" +
        "Action: <调用哪个工具及参数>\n" +
        "Observation: <分析工具返回结果>\n" +
        "(重复 Thought/Action/Observation 直到信息充分)\n" +
        "Answer: <基于以上观测得出最终结论>\n\n" +
        "规则:禁止在未调用工具的情况下直接给出 Answer。"),
    ("user", "北京今天天气适合户外运动吗?"),
]);

5. 运行完整 Web 对话应用

git clone https://github.com/NewLifeX/NewLife.AI.git
cd NewLife.AI

# 构建前端(需要 Node.js + pnpm)
cd Web && pnpm install && pnpm build && cd ..

# 启动
cd NewLife.ChatAI
dotnet run --framework net8.0

浏览器访问 http://localhost:5000,默认 SQLite,开箱即用。首次启动通过 /Admin 配置服务商 API Key。

也可将 NewLife.ChatAI 通过 NuGet 嵌入已有项目:

dotnet add package NewLife.ChatAI
using NewLife.ChatAI;

var builder = WebApplication.CreateBuilder(args);
builder.Services.AddChatAI();

var app = builder.Build();
app.UseChatAI(redirectToChat: true);
app.Run();

API 网关

NewLife.ChatAI 内置多协议 AI 网关,第三方系统无需改造即可接入,全路径经过记忆注入与技能增强。

协议 路由 说明
OpenAI ChatCompletions POST /v1/chat/completions 流式 / 非流式 / 函数调用 / 视觉
OpenAI Responses POST /v1/responses o3 / gpt-5 推理模型
Anthropic Messages POST /v1/messages Claude 系列
Google Gemini POST /v1/gemini/... Gemini 系列
图像生成 POST /v1/images/generations Text-to-Image
图像编辑 POST /v1/images/edits Inpainting(multipart/form-data)
模型发现 GET /v1/models 可用模型列表

认证Authorization: Bearer sk-xxxx(AppKey)

特性:上游 429 指数退避重试(随机抖动,最多 5 次)、Token 用量自动记录、按 AppKey + 用户双维度统计


扩展开发

新增 AI 服务商

继承 OpenAIChatClient,添加 [AiClient] 特性,AiClientRegistry 启动自动扫描注册:

[AiClient("MyAI", "我的服务", "https://api.myai.com/v1",
    Description = "自定义 AI 服务")]
[AiClientModel("myai-latest", "MyAI Latest", Code = "MyAI",
    FunctionCalling = true, Vision = true)]
public class MyAiChatClient : OpenAIChatClient
{
    public MyAiChatClient() { }
    public MyAiChatClient(String apiKey, String? model = null, String? endpoint = null)
        : base(apiKey, model, endpoint) { }
}

新增工具

public class MyTools
{
    /// <summary>查询当前时间</summary>
    [ToolDescription("get_current_time")]
    public String GetCurrentTime()
        => DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
}

var registry = new ToolRegistry();
registry.AddTools<MyTools>(new MyTools());

// DI 场景
services.AddSingleton<IToolProvider>(_ =>
{
    var r = new ToolRegistry();
    r.AddTools<MyTools>(new MyTools());
    return r;
});

新增 IChatHandler

在对话事前(OnBefore)或事后(OnAfter)注入自定义逻辑(如上下文注入、审计、记录):

[ChatHandlerOrder(150)]
public class CurrentTimeHandler : ChatHandlerBase
{
    public override Task OnBefore(IChatContext context, CancellationToken cancellationToken)
    {
        context.ContextMessages.Insert(0,
            new ChatMessage { Role = "system", Content = $"当前时间:{DateTime.Now:yyyy-MM-dd HH:mm}" });
        return Task.CompletedTask;
    }
}

// DI 注册,MessageFlow 自动按 ChatHandlerOrderAttribute 排序调用
services.AddSingleton<IChatHandler, CurrentTimeHandler>();

新增过滤器

洋葱圈模型,可在对话前后插入日志、审计、内容审核等逻辑:

public class AuditFilter : IChatFilter
{
    public async Task OnChatAsync(
        ChatFilterContext ctx,
        Func<ChatFilterContext, CancellationToken, Task> next,
        CancellationToken ct)
    {
        // before:记录输入 / 敏感词过滤
        await next(ctx, ct);
        // after:记录输出 / 写审计日志
    }

    public Task OnStreamCompletedAsync(ChatFilterContext ctx, CancellationToken ct)
        => Task.CompletedTask;
}

文档

文档 说明
需求规格说明 产品目标、功能清单、非功能需求
架构设计 四层架构、各模块设计细节
AI 编排框架需求 工具 / 智能体 / 规划器设计
API 网关需求 网关协议适配详解
MCP 架构 MCP 客户端与服务端设计
技能管理需求 技能系统详细设计
自学习系统需求 对话分析 + 记忆提取
对话数据保存流程 MessageFlow 详细流程
功能模块清单 完整功能清单

许可证

MIT License

欢迎提交 Issue 与 Pull Request。

  • GitHub:https://github.com/NewLifeX/NewLife.AI
  • 官网:https://newlifex.com
  • QQ 群:1600800

相关项目

Product Compatible and additional computed target framework versions.
.NET net5.0 was computed.  net5.0-windows was computed.  net6.0 was computed.  net6.0-android was computed.  net6.0-ios was computed.  net6.0-maccatalyst was computed.  net6.0-macos was computed.  net6.0-tvos was computed.  net6.0-windows was computed.  net7.0 was computed.  net7.0-android was computed.  net7.0-ios was computed.  net7.0-maccatalyst was computed.  net7.0-macos was computed.  net7.0-tvos was computed.  net7.0-windows was computed.  net8.0 was computed.  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. 
.NET Core netcoreapp2.0 was computed.  netcoreapp2.1 was computed.  netcoreapp2.2 was computed.  netcoreapp3.0 was computed.  netcoreapp3.1 was computed. 
.NET Standard netstandard2.0 is compatible.  netstandard2.1 is compatible. 
.NET Framework net45 is compatible.  net451 was computed.  net452 was computed.  net46 was computed.  net461 was computed.  net462 was computed.  net463 was computed.  net47 was computed.  net471 was computed.  net472 was computed.  net48 was computed.  net481 was computed. 
MonoAndroid monoandroid was computed. 
MonoMac monomac was computed. 
MonoTouch monotouch was computed. 
Tizen tizen40 was computed.  tizen60 was computed. 
Xamarin.iOS xamarinios was computed. 
Xamarin.Mac xamarinmac was computed. 
Xamarin.TVOS xamarintvos was computed. 
Xamarin.WatchOS xamarinwatchos was computed. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.

NuGet packages (2)

Showing the top 2 NuGet packages that depend on NewLife.AI:

Package Downloads
NewLife.ChatAI

集对话前端、统一 AI 网关、Agent 平台于一身的完整 AI 应用。支持多轮对话、流式输出、函数调用、图像生成、会话管理与使用量统计

NewLife.StarChat

集对话前端、统一 AI 网关、Agent 平台于一身的完整 AI 应用。支持多轮对话、流式输出、函数调用、图像生成、会话管理与使用量统计

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last Updated
1.3.2026.610-beta0815 0 6/10/2026
1.3.2026.609-beta1557 26 6/9/2026
1.3.2026.608 63 6/8/2026
1.3.2026.608-beta0921 54 6/8/2026
1.2.2026.531-beta1644 107 5/31/2026
1.2.2026.529-beta0051 122 5/29/2026
1.2.2026.528-beta1609 113 5/28/2026
1.2.2026.528-beta0359 99 5/28/2026
1.2.2026.527-beta0103 82 5/27/2026
1.2.2026.526-beta0043 99 5/26/2026
1.2.2026.522-beta0457 111 5/22/2026
1.2.2026.521-beta1541 101 5/21/2026
1.2.2026.521-beta1221 106 5/21/2026
1.2.2026.521-beta0418 127 5/21/2026
1.2.2026.520-beta0906 108 5/20/2026
1.2.2026.520-beta0002 87 5/20/2026
1.2.2026.519-beta0420 110 5/19/2026
1.2.2026.517-beta1320 115 5/17/2026
1.2.2026.514-beta0653 115 5/14/2026
1.2.2026.509-beta1100 97 5/9/2026
Loading failed

知识进化层功能落地,支持知识库自动构建与向量语义检索;嵌入/向量检索能力内置,HashTextEmbedder v2;TTS 语音合成支持 DashScope/CosyVoice V3.5;新增反思代理与评审代理,复杂任务拆分与并行聚合;人机决策检查点功能,支持 AI 多路径人工选择;工具调用增强:ToolCallContext 透传、Provider 熔断器、三档权限体系;兼容 net45/net462