WebAgentLibrary 1.3.11
There is a newer version of this package available.
See the version list below for details.
See the version list below for details.
dotnet add package WebAgentLibrary --version 1.3.11
NuGet\Install-Package WebAgentLibrary -Version 1.3.11
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="WebAgentLibrary" Version="1.3.11" />
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="WebAgentLibrary" Version="1.3.11" />
<PackageReference Include="WebAgentLibrary" />
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 WebAgentLibrary --version 1.3.11
The NuGet Team does not provide support for this client. Please contact its maintainers for support.
#r "nuget: WebAgentLibrary, 1.3.11"
#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 WebAgentLibrary@1.3.11
#: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=WebAgentLibrary&version=1.3.11
#tool nuget:?package=WebAgentLibrary&version=1.3.11
The NuGet Team does not provide support for this client. Please contact its maintainers for support.
WebAgent Library
面向 .NET 10 的企业级 Agent 开发框架,基于 Microsoft.Extensions.AI 10.x 抽象层,提供开箱即用的会话管理、权限控制、限流防护、工具调用等完整能力栈。
✨ 功能特性
🧠 核心能力
- 会话记忆管理:支持 SQLite/Redis 等多种存储后端,自动历史消息压缩
- 上下文管道:统一的 Agent 请求上下文,支持 JWT/自定义身份认证
- 输入输出过滤:内置敏感词检测、长度限制、内容截断等过滤器,支持自定义扩展
- 限流防护:基于 IP、用户级别的分布式限流,防止恶意请求
- 工具调用框架:特性驱动的工具自动发现与注册,支持权限控制
- 意图分类:关键词 + LLM 混合意图识别,支持自定义规则
- 身份管理:静态/动态 Agent 身份配置,支持多租户隔离
🎯 设计优势
- 遵循 .NET 规范:完全兼容 Microsoft.Extensions.AI 抽象,无缝对接 OpenAI、Azure OpenAI、 Claude 等大模型
- 高度可扩展:所有核心组件均提供接口,支持自定义实现替换
- 配置驱动:统一的 Options 配置入口,链式 API 设计,使用简单
- 性能优先:无运行期反射开销,所有扫描在启动时一次性完成
- 生产就绪:内置完整的日志、监控、错误处理机制
🚀 快速开始
前置要求
- .NET 10.0 SDK
- 大模型 API 密钥(OpenAI、Azure OpenAI、Anthropic 等)
安装 NuGet 包
dotnet add package WebAgentLibrary
基础配置
在 Program.cs 中添加 Agent 框架服务:
using WebAgentLibrary.Configuration;
var builder = WebApplication.CreateBuilder(args);
// 1. 注册大模型客户端(以 OpenAI 为例)
builder.Services.AddOpenAIChatClient(
model: "gpt-3.5-turbo",
apiKey: builder.Configuration["OpenAI:ApiKey"]!);
// 2. 注册 Agent 框架
builder.Services.AddAgentFramework(opt =>
{
// 配置会话存储(SQLite 开箱即用)
opt.UseSqliteMemory("DataSource=agent_sessions.sqlite");
// 配置 Agent 身份
opt.UseStaticIdentity(
name: "智能助手",
systemPrompt: "你是一个友好的智能助手,负责回答用户的问题。",
maxOutputLength: 2000);
// 配置限流
opt.UseRateLimiting(ipPermitLimit: 100, userPermitLimit: 50);
// 注册自定义工具
opt.AddToolsFromAssembly<SampleAgentTools>();
});
// 3. 添加控制器支持
builder.Services.AddControllers();
var app = builder.Build();
// 4. 配置中间件
app.UseHttpsRedirection();
app.UseAuthorization();
app.MapControllers();
app.Run();
创建 Agent 控制器
[ApiController]
[Route("api/agent")]
public class AgentController : ControllerBase
{
private readonly IChatClient _chatClient;
private readonly IConversationMemory _memory;
private readonly IAgentIdentityProvider _identityProvider;
public AgentController(
IChatClient chatClient,
IConversationMemory memory,
IAgentIdentityProvider identityProvider)
{
_chatClient = chatClient;
_memory = memory;
_identityProvider = identityProvider;
}
[HttpPost("chat")]
public async Task<IActionResult> Chat([FromBody] ChatRequest request)
{
// 1. 获取系统提示词
var identity = await _identityProvider.GetIdentityAsync();
// 2. 获取会话历史
var history = await _memory.GetHistoryAsync(request.SessionId);
// 3. 构建消息列表
var messages = new List<ChatMessage>
{
new ChatMessage(ChatRole.System, identity.SystemPrompt)
};
messages.AddRange(history);
messages.Add(new ChatMessage(ChatRole.User, request.Message));
// 4. 调用大模型
var response = await _chatClient.CompleteAsync(messages);
// 5. 保存对话历史
await _memory.AppendAsync(request.SessionId, new ChatMessage(ChatRole.User, request.Message));
await _memory.AppendAsync(request.SessionId, response.Message);
return Ok(new { response.Message.Content });
}
}
public class ChatRequest
{
public string SessionId { get; set; } = string.Empty;
public string Message { get; set; } = string.Empty;
}
📚 详细文档
会话记忆管理
框架提供灵活的会话记忆存储方案:
// 使用 SQLite 存储(默认)
opt.UseSqliteMemory("DataSource=agent_sessions.sqlite");
// 使用自定义存储(如 Redis)
opt.UseMemoryStore<RedisConversationMemory>();
IConversationMemory 接口提供以下能力:
GetHistoryAsync(sessionId):获取会话历史AppendAsync(sessionId, message):追加消息CompressAsync(sessionId):自动压缩历史(Token 超过阈值时)ClearAsync(sessionId):清空会话DeleteMessageAsync(sessionId, messageId):删除单条消息
工具调用
通过 [AgentTool] 特性标记工具方法,框架会自动扫描注册:
public class OrderTools
{
[AgentTool("query_order", "根据订单号查询订单状态", RequiredClaim = "tools:order")]
public async Task<string> QueryOrder(string orderId)
{
// 实现订单查询逻辑
return $"订单 {orderId} 的状态是:已发货";
}
}
// 注册工具程序集
opt.AddToolsFromAssembly<OrderTools>();
输入输出过滤
内置多种过滤器,支持自定义扩展:
// 添加自定义输入过滤器
opt.AddInputFilter<CustomInputFilter>();
// 添加自定义输出过滤器
opt.AddOutputFilter<CustomOutputFilter>();
内置过滤器:
LengthLimitFilter:输入长度限制SensitiveWordFilter:敏感词检测与替换ToolPermissionFilter:工具调用权限验证OutputTruncationFilter:输出内容截断
限流配置
// 默认限流策略
opt.UseRateLimiting(
ipPermitLimit: 100, // IP 每分钟允许请求数
userPermitLimit: 50, // 每个用户每分钟允许请求数
window: TimeSpan.FromMinutes(1));
// 自定义限流策略
opt.UseRateLimitPolicy<CustomRateLimitPolicy>();
意图识别
// 添加意图规则
opt.AddIntentRule("查询订单", new[] { "订单", "物流", "发货" });
opt.AddIntentRule("查询余额", new[] { "余额", "账户", "钱" });
// 自定义意图分类器
opt.UseIntentClassifier<CustomIntentClassifier>();
🏗️ 项目结构
WebAgentLibrary/
├── Abstractions/ # 核心接口定义
├── Configuration/ # 服务注册扩展
├── Context/ # 请求上下文实现
├── Filtering/ # 输入输出过滤管道
├── Identity/ # Agent 身份管理
├── Intent/ # 意图分类实现
├── Memory/ # 会话记忆存储
├── Middleware/ # ASP.NET Core 中间件
├── RateLimiting/ # 限流策略实现
├── SensitiveWords/ # 敏感词检测
└── Tools/ # 工具调用框架
🧪 示例项目
查看 src/WebAgent.Host 目录,包含完整的示例实现:
- 完整的 Web API 项目
- 内置聊天界面单页应用
- 自定义工具示例
- 过滤器扩展示例
- Swagger API 文档
运行示例:
dotnet run --project src/WebAgent.Host
访问地址:
- 聊天界面:https://localhost:5001/
- Swagger 文档:https://localhost:5001/swagger
🔧 配置选项
| 配置方法 | 说明 |
|---|---|
UseSqliteMemory(connectionString) |
配置 SQLite 会话存储 |
UseMemoryStore<T>() |
配置自定义会话存储实现 |
UseContextProvider<T>() |
配置自定义上下文提供器 |
UseRateLimiting(ipPermitLimit, userPermitLimit) |
配置默认限流策略 |
UseRateLimitPolicy<T>() |
配置自定义限流策略 |
UseStaticIdentity(name, systemPrompt, maxOutputLength) |
配置静态 Agent 身份 |
UseIdentityProvider<T>() |
配置自定义身份提供器 |
AddToolsFromAssembly<T>() |
从指定程序集扫描注册工具 |
AddInputFilter<T>() |
添加自定义输入过滤器 |
AddOutputFilter<T>() |
添加自定义输出过滤器 |
AddIntentRule(name, keywords) |
添加意图识别规则 |
UseIntentClassifier<T>() |
配置自定义意图分类器 |
UseSensitiveWordStore(connectionString, refreshInterval) |
配置敏感词存储 |
🛡️ 生产环境建议
- 密钥安全:使用环境变量或密钥管理服务存储 API 密钥,不要硬编码
- 存储选择:生产环境使用 Redis 或分布式数据库代替 SQLite
- 身份验证:添加 JWT 或 OAuth2 身份验证,保护 API 接口
- HTTPS:强制使用 HTTPS 协议传输数据
- 限流策略:根据业务需求合理配置限流参数
- 日志监控:配置合适的日志级别和监控告警
- CORS 策略:严格配置跨域访问规则,不要使用 AllowAll
🤝 贡献指南
欢迎提交 Issue 和 Pull Request!
📄 许可证
本项目采用 MIT 许可证,详见 LICENSE 文件。
| Product | Versions Compatible and additional computed target framework versions. |
|---|---|
| .NET | 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.
-
net10.0
- AhoCorasick (>= 2.0.279)
- Microsoft.AspNetCore.Authentication.JwtBearer (>= 10.0.7)
- Microsoft.AspNetCore.OpenApi (>= 10.0.7)
- Microsoft.Extensions.AI (>= 10.5.1)
- Microsoft.Extensions.AI.Abstractions (>= 10.5.1)
- Microsoft.Extensions.AI.OpenAI (>= 10.5.1)
- ModelContextProtocol.Core (>= 1.2.0)
- OpenAI (>= 2.10.0)
- Polly.Core (>= 8.6.6)
- SqlSugarCore (>= 5.1.4.214)
- StackExchange.Redis (>= 2.12.14)
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 |
|---|---|---|
| 1.3.17 | 92 | 5/19/2026 |
| 1.3.16 | 100 | 5/11/2026 |
| 1.3.15 | 101 | 5/10/2026 |
| 1.3.14 | 94 | 5/10/2026 |
| 1.3.13 | 94 | 5/10/2026 |
| 1.3.12 | 89 | 5/10/2026 |
| 1.3.11 | 93 | 5/10/2026 |
| 1.3.10 | 95 | 5/10/2026 |
| 1.3.9 | 94 | 5/10/2026 |
| 1.3.8 | 98 | 5/10/2026 |
| 1.3.7 | 94 | 5/10/2026 |
| 1.3.6 | 93 | 5/10/2026 |
| 1.3.5 | 90 | 5/10/2026 |
| 1.3.4 | 97 | 5/10/2026 |
| 1.3.3 | 98 | 5/10/2026 |
| 1.3.2 | 94 | 5/10/2026 |
| 1.3.1 | 95 | 5/10/2026 |
| 1.3.0 | 97 | 5/10/2026 |
| 1.2.3 | 104 | 5/10/2026 |
| 1.2.2 | 95 | 5/10/2026 |
Loading failed