大数跨境
0
0

.NET+AI | Agent | 自定义 Agent (19)

.NET+AI | Agent | 自定义 Agent (19) dotNET跨平台
2026-01-03
8
导读:自定义 Agent 实现:构建企业级智能体一句话简介通过继承 AIAgent 抽象类,实现 FAQ 自动回复

自定义 Agent 实现:构建企业级智能体

一句话简介

通过继承 AIAgent 抽象类,实现 FAQ 自动回复、审批工作流、数据查询等企业级自定义 Agent,实现成本优化和业务控制。

🎯 何时需要自定义 Agent

场景
说明
收益
FAQ 自动回复
高频问题用规则匹配
成本降低 90%,响应提升 60 倍
遗留系统集成
包装 ERP/CRM 为 Agent
无缝集成,数据安全可控
测试模拟
返回固定测试数据
零成本,确定性输出
混合模式
规则优先,AI 降级
平衡成本与效果

📝 AIAgent 核心接口

public abstract class AIAgent
{
    public abstract string? Name { get; }
    public abstract AgentThread GetNewThread();
    public abstract AgentThread DeserializeThread(JsonElement serializedThread, ...);
    public abstract Task<AgentRunResponse> RunAsync(
        IEnumerable<ChatMessage> messages, 
        AgentThread? thread = null, ...
)
;
    public abstract IAsyncEnumerable<AgentRunResponseUpdate> RunStreamingAsync(
        IEnumerable<ChatMessage> messages, ...
)
;
}

💻 实战 1:FAQ Agent

零成本、毫秒级响应的 FAQ 自动回复

public classFaqAgent : AIAgent
{
    privatereadonly Dictionary<stringstring> _faqDatabase = new()
    {
        ["营业时间"] = "周一至周五 9:00-18:00",
        ["退货"] = "请登录账户 → 订单详情 → 申请退货",
        ["配送"] = "同城 24 小时,省内 2-3 天",
    };

    publicoverridestring? Name => "FaqAgent";

    public override async Task<AgentRunResponse> RunAsync(
        IEnumerable<ChatMessage> messages, ...
)

    {
        var userText = messages.LastOrDefault()?.Text ?? "";
        
        // 关键词匹配
        var answer = _faqDatabase.FirstOrDefault(
            kvp => userText.Contains(kvp.Key)).Value;
        
        var responseText = answer ?? "抱歉,未找到相关 FAQ";
        
        var responseMessage = new ChatMessage(ChatRole.Assistant, responseText)
        {
            AuthorName = this.DisplayName,
            MessageId = Guid.NewGuid().ToString("N")
        };

        await thread.MessageStore.AddMessageAsync(messages.Concat([responseMessage]), ct);
        
        returnnew AgentRunResponse { Messages = [responseMessage] };
    }
}

效果对比:

指标
传统 AI Agent
FaqAgent
响应时间
1-3 秒
< 50 毫秒
单次成本
¥0.005
¥0
日处理 10 万次
¥500
¥0

💻 实战 2:审批工作流 Agent

多轮对话 + 规则引擎

public classApprovalAgent : AIAgent
{
    privatereadonly List<ApprovalRule> _rules = new()
    {
        new() { Type = "请假", MaxDays = 3, Result = "自动通过" },
        new() { Type = "请假", MaxDays = 7, Result = "需要主管审批" },
        new() { Type = "报销", MaxAmount = 1000, Result = "自动通过" },
    };
    
    // 自定义 Thread 存储对话状态
    public override AgentThread GetNewThread() => new ApprovalAgentThread();
    
    private string ProcessConversation(ApprovalAgentThread thread, string userInput)
    {
        var state = thread.State;
        
        // 步骤 1: 识别审批类型
        if (!state.HasType) { /* 询问类型 */ }
        
        // 步骤 2: 收集金额或天数
        if (!state.HasAmount) { /* 询问数值 */ }
        
        // 步骤 3: 执行规则匹配
        var rule = MatchRule(state.Type, state.Amount);
        return$"审批结果: {rule.Result}";
    }
}

💻 实战 3:混合模式 Agent

智能路由 + 降级策略

public classHybridAgent : AIAgent
{
    privatereadonly FaqAgent _faqAgent = new();
    privatereadonly DataQueryAgent _dataQueryAgent = new();
    privatereadonly IChatClient _aiClient;
    
    public override async Task<AgentRunResponse> RunAsync(...)
    {
        var intent = ClassifyIntent(userText);  // 意图识别
        
        if (intent == "faq")
        {
            var response = await _faqAgent.RunAsync(userText);
            if (IsSuccessful(response)) return response;
        }
        
        if (intent == "data")
        {
            var response = await _dataQueryAgent.RunAsync(userText);
            if (IsSuccessful(response)) return response;
        }
        
        // 降级到 AI
        returnawait CallAI(userText);
    }
}

成本优化效果:

  • 60% FAQ → ¥0
  • 30% 数据查询 → ¥0
  • 10% AI → 正常费用
  • 年度节省:¥16.2 万(日 10 万次)

🏢 RunAsync 实现检查清单

public override async Task<AgentRunResponse> RunAsync(...)
{
    // ✅ 1. 确保线程存在
    thread ??= GetNewThread();
    
    // ✅ 2. 提取用户消息
    var userText = messages.LastOrDefault()?.Text ?? "";
    
    // ✅ 3. 执行业务逻辑
    var responseText = ProcessLogic(userText);
    
    // ✅ 4. 设置消息属性
    var responseMessage = new ChatMessage(ChatRole.Assistant, responseText)
    {
        AuthorName = this.DisplayName,
        MessageId = Guid.NewGuid().ToString("N")
    };
    
    // ✅ 5. 通知线程(关键!)
    await thread.MessageStore.AddMessagesAsync(messages.Concat([responseMessage]), ct);
    
    // ✅ 6. 返回响应
    returnnew AgentRunResponse { Messages = [responseMessage] };
}

🎯 总结

  • ✅ 5 个必须实现的方法:Name、GetNewThread、DeserializeThread、RunAsync、RunStreamingAsync
  • ✅ FAQ Agent:成本降低 100%,响应提升 60 倍
  • ✅ 审批 Agent:多轮对话 + 规则引擎 + 状态持久化
  • ✅ 混合 Agent:智能路由 + 降级策略,年节省 16 万

【声明】内容源于网络
0
0
dotNET跨平台
专注于.NET Core的技术传播。在这里你可以谈微软.NET,Mono的跨平台开发技术。在这里可以让你的.NET项目有新的思路,不局限于微软的技术栈,横跨Windows,
内容 999
粉丝 0
dotNET跨平台 专注于.NET Core的技术传播。在这里你可以谈微软.NET,Mono的跨平台开发技术。在这里可以让你的.NET项目有新的思路,不局限于微软的技术栈,横跨Windows,
总阅读16.8k
粉丝0
内容999