jaythawme 首页

abp vnext 集成Microsoft agent framework

Dec 31, 2025 · 20min

背景

在人工智能技术迅猛发展的今天,微软顺势推出了集 Semantic Kernel 与 Auto Agent 于一体的智能代理开发框架 —— Microsoft Agent Framework。与此同时,ABP vNext 作为广受欢迎的 .NET 应用开发框架,以其模块化架构和开箱即用的企业级功能深受开发者青睐。本文将探索如何将 Microsoft Agent Framework 与 ABP vNext 深度融合,构建智能化、可扩展的 AI 驱动型 .NET 应用。

实现

1. 创建abp 项目

这里使用的是abp vnext pro 的集成项目 , 其在abp 的基础上进行了一些抽象和改造

安装CLI工具

dotnet tool install Lion.AbpPro.Cli -g

创建Vben2项目的nuget版本

lion.abp new -t pro-nuget -c 公司名称 -p 项目名称 -v 版本(默认LastRelease)

创建一个名为AiTry的项目

lion.abp new -t pro-nuget -c Personal -p AiTry

创建项目结构如下:

─service
│  ├─host
│  │  ├─Personal.AiTry.HttpApi.Host
│  │  │  ├─Controllers
│  │  │  ├─Logs
│  │  │  ├─Microsoft
│  │  │  │  └─Extensions
│  │  │  │      └─DependencyInjection
│  │  │  ├─Pages
│  │  │  ├─Properties
│  │  │  └─wwwroot
│  │  │      ├─images
│  │  │      └─libs
│  │  │          └─bootstrap
│  │  │              └─css
│  │  └─Personal.AiTry.WebGateway
│  │      └─Properties
│  ├─src
│  │  ├─Personal.AiTry.Application
│  │  │  ├─AiTry
│  │  │  ├─Jobs
│  │  │  ├─Properties
│  │  │  └─Tools
│  │  ├─Personal.AiTry.Application.Contracts
│  │  │  ├─AiTry
│  │  │  │  └─Dtos
│  │  │  ├─Jobs
│  │  │  └─Permissions
│  │  ├─Personal.AiTry.DbMigrator
│  │  ├─Personal.AiTry.Domain
│  │  │  ├─AiTry
│  │  │  ├─Data
│  │  │  ├─Properties
│  │  │  └─Settings
│  │  ├─Personal.AiTry.Domain.Shared
│  │  │  ├─AiTry
│  │  │  │  └─Dtos
│  │  │  ├─Localization
│  │  │  │  └─AiTry
│  │  │  ├─MultiTenancy
│  │  │  ├─Users
│  │  │  │  └─Dto
│  │  │  └─Utils
│  │  ├─Personal.AiTry.EntityFrameworkCore
│  │  │  └─Properties
│  │  ├─Personal.AiTry.FreeSqlRepository
│  │  ├─Personal.AiTry.HttpApi
│  │  │  ├─AiTry
│  │  │  └─Controllers
│  │  └─Personal.AiTry.HttpApi.Client
│  └─test
│      ├─Personal.AiTry.Application.Tests
│      │  └─Samples
│      ├─Personal.AiTry.Domain.Tests
│      │  ├─Localizations
│      │  └─Samples
│      ├─Personal.AiTry.EntityFrameworkCore.Tests
│      │  └─EntityFrameworkCore
│      ├─Personal.AiTry.FreeSqlReppsitory.Tests
│      │  └─Users
│      ├─Personal.AiTry.HttpApi.Client.ConsoleTestApp
│      └─Personal.AiTry.TestBase
│          └─Security

2. 引用相关nuge包

在Personal.AiTry.Domain.Shared 项目中引用如下nuget包:


    <PackageReference Include="Microsoft.Agents.AI.Hosting"  />
    <PackageReference Include="Microsoft.Agents.AI.Hosting.OpenAI" />
    <PackageReference Include="Microsoft.Agents.AI.DevUI" />
    <PackageReference Include="Microsoft.Agents.AI.OpenAI"  />
    <PackageReference Include="Microsoft.Extensions.AI.Abstractions"  />
    <PackageReference Include="Microsoft.Extensions.AI.Ollama" />
    <PackageReference Include="Microsoft.Extensions.AI.OpenAI"  />
    <PackageReference Include="Microsoft.SemanticKernel.Abstractions"  />
    <PackageReference Include="OllamaSharp" />
    <PackageReference Include="Microsoft.SemanticKernel.Connectors.Qdrant" />
    <PackageReference Include="AIDotNet.Toon"/>

同时在 Directory.Build.Microsoft.targets 文件中维护上述nuget包的版本号:

        <PackageReference Update="Microsoft.Agents.AI.DevUI" Version="1.0.0-preview.251125.1" />
        <PackageReference Update="Microsoft.Agents.AI.OpenAI" Version="1.0.0-preview.251125.1" />
        <PackageReference Update="Microsoft.Extensions.AI.Abstractions" Version="10.0.1" />
        <PackageReference Update="Microsoft.Extensions.AI.Ollama" Version="9.7.0-preview.1.25356.2" />
        <PackageReference Update="Microsoft.Extensions.AI.OpenAI" Version="10.0.1-preview.1.25571.5" />
        <PackageReference Update="Microsoft.SemanticKernel.Abstractions" Version="1.68.0" />
        <PackageReference Update="OllamaSharp" Version="5.4.11" />
        <PackageReference Update="Microsoft.SemanticKernel.Connectors.Qdrant" Version="1.68.0-preview" />
        <PackageReference Update="Microsoft.Agents.AI.Hosting" Version="1.0.0-preview.251204.1" />
        <PackageReference Update="Microsoft.Agents.AI.Hosting.OpenAI" Version="1.0.0-alpha.251204.1" />
        <PackageReference Update="Microsoft.SemanticKernel.Connectors.Qdrant" Version="1.68.0-preview" />
        <PackageReference Update="AIDotNet.Toon" Version="0.1.3" />

3. 依赖注入

a. 创建配置类

在 Personal.AiTry.HttpApi.Host 目录下创建一个配置类ChatClientInfo.cs ,用于从appsetting.json加载模型配置:

public class ChatClientInfo
{
    /// <summary>
    /// 名称
    /// </summary>
    public string Name { get; set; }

    /// <summary>
    /// 模型
    /// </summary>
    public string Model { get; set; }

    /// <summary>
    /// 地址
    /// </summary>
    public Uri Uri { get; set; }

    /// <summary>
    /// 职能
    /// </summary>
    public string? Instruction { get; set; }

    public string ApiKey { get; set; }
}

b. appsetting.json

appsetting.json 添加如下配置:

 "ChatClientInfos":[
    {
      "Name": "DefaultAgent",
      "ApiKey": "key",
      "Model": "Qwen/Qwen2.5-7B-Instruct", //这里选用的模型是Qwen/Qwen2.5-7B-Instruct
      "Uri": "http://xxxx.xxx.xxx.xxx:8000/v1",
      "Instruction": "你是一个乐于助人的 AI 助手,能够清晰、准确、有礼貌地回答用户的问题。  \n请用中文回答,语言简洁自然,避免冗长。  \n如果问题涉及你不了解的内容,请诚实说明,不要编造答案。"
    }
  ]

c. 创建服务扩展类

之后,在 Personal.AiTry.HttpApi.Host 目录下创建一个扩展类 ServiceExtension.cs :

public static class ServiceExtension
{

    //添加AIAgent
    public static IServiceCollection AddAIAgent(this IServiceCollection services, IConfiguration configuration)
    {
        var agents = configuration.GetSection("ChatClientInfos").Get<List<ChatClientInfo>>();
      var clients =   agents.DistinctBy(i => (i.Uri, i.Model)).ToList();
      foreach (var client in clients)
      {

          services.AddSingleton(new OpenAIClient(
              new ApiKeyCredential(client.ApiKey),
              new OpenAIClientOptions { Endpoint = client.Uri }
          ).GetChatClient(client.Model));
      }
      foreach (var agent in agents)
        {
            services.AddSingleton<AIAgent>(sp =>
            {
                return new ChatClientAgent(
                    chatClient: new OpenAIClient(
                        new ApiKeyCredential(agent.ApiKey),
                        new OpenAIClientOptions { Endpoint = agent.Uri }
                    ).GetChatClient(agent.Model).AsIChatClient(),
                    options: new ChatClientAgentOptions
                    {
                        Name = agent.Name,
                        ChatOptions = new ChatOptions() { Instructions = agent.Instruction,Tools = [..sp.GetRequiredService<GetWeatherTool>().AsAITools()]}
                    }
                );
            });
        }

        return services;
    }

    // 用于向 IServiceCollection 添加 DevUI(开发时 UI)支持的扩展方法。

    public static IServiceCollection AddDevUIEx(this IServiceCollection services)
    {
        // 检查传入的 services 是否为 null,如果是则抛出异常
        ArgumentNullException.ThrowIfNull(services);
        services.AddKeyedSingleton<AIAgent>(KeyedService.AnyKey, (sp, key) =>
        {
            var keyAsStr = key as string;

            // 这里会抛出 ArgumentNullException,导致应用启动失败。
            // 原始代码假设 key 一定是字符串,但 DevUI 调用时并非如此。
            //Throw.IfNullOrEmpty(keyAsStr);
            if (string.IsNullOrEmpty(keyAsStr))
            {
                var defaultAgent = sp.GetService<AIAgent>()!;
                return defaultAgent;
            }

            var workflows = sp.GetServices<Workflow>().ToList();
            var workflow = workflows.FirstOrDefault(i => i.Name?.Equals(keyAsStr, StringComparison.Ordinal) == true);
            // 检查这个默认 Workflow 的 Name 是否与当前 key 字符串完全匹配(区分大小写)
            if (workflow is not null && workflow.Name?.Equals(keyAsStr, StringComparison.Ordinal) == true)
            {
                // 如果匹配,也转换为 AIAgent 返回
                return workflow.AsAgent(name: workflow.Name);
            }

            // 第三步:再尝试获取一个“非 keyed”的默认 AIAgent 实例
            /*var agent = sp.GetKeyedService<AIAgent>(keyAsStr);*/
            var agents = sp.GetServices<AIAgent>().ToList();
            var keyAgent = agents.FirstOrDefault(i => i.Name?.Equals(keyAsStr, StringComparison.Ordinal) == true);
            // 检查该 agent 的 Name 是否与当前 key 字符串匹配
            if (keyAgent is not null)
            {
                // 如果匹配,直接返回该 agent
                return keyAgent;
            }

            // 如果以上三种方式都没找到匹配的 agent,则返回 null
            // (使用 ! 操作符告诉编译器这里允许 null,尽管返回类型是非空引用)
            return null!;
        });
        // 返回 services 以支持链式调用
        return services;
    }
}

d. 修改AiTryHttpApiHostModule.cs

  1. 在ConfigureServices(ServiceConfigurationContext context)方法中加入如下注册:
 context.Services.AddDevUIEx().AddOpenAIChatCompletions()
                .AddOpenAIResponses().AddAIAgent();
  1. 在OnApplicationInitialization(ApplicationInitializationContext context)加入如下中间件:
app.UseConfiguredEndpoints(endpoints =>
    {
        endpoints.MapHealthChecks("/health");

        //添加中间件
        endpoints.MapDevUI();
        endpoints.MapOpenAIResponses();
        endpoints.MapOpenAIConversations();
    });

e. 说明

这里说明一下Microsoft官方是有一个已经实现的AddDevUI方法的情况下为何还要维护AddDevUIEx 这个方法,官方的实现内容如下:


  public static IServiceCollection AddDevUI(this IServiceCollection services)
  {
    ArgumentNullException.ThrowIfNull((object) services, nameof (services));
    services.AddKeyedSingleton<AIAgent>(KeyedService.AnyKey, (Func<IServiceProvider, object, AIAgent>) ((sp, key) =>
    {
      string serviceKey = key as string;
      Throw.IfNullOrEmpty(serviceKey, "keyAsStr");
      Workflow keyedService = sp.GetKeyedService<Workflow>((object) serviceKey);
      if (keyedService != null)
        return keyedService.AsAgent(name: keyedService.Name);
      Workflow service1 = sp.GetService<Workflow>();
      if (service1 != null)
      {
        string name = service1.Name;
        if ((name != null ? (name.Equals(serviceKey, StringComparison.Ordinal) ? 1 : 0) : 0) != 0)
          return service1.AsAgent(name: service1.Name);
      }
      AIAgent service2 = sp.GetService<AIAgent>();
      if (service2 != null)
      {
        string name = service2.Name;
        if ((name != null ? (name.Equals(serviceKey, StringComparison.Ordinal) ? 1 : 0) : 0) != 0)
          return service2;
      }
      return (AIAgent) null;
    }));
    return services;
  }

这个 AddDevUI 方法的核心功能是:为 .NET 应用程序注册一个灵活的、基于键(key)解析的 AIAgent 服务工厂,用于支持 DevUI(开发者用户界面)的集成。该方法向依赖注入(DI)容器中注册了一个 带键的单例服务(Keyed Singleton),类型为 AIAgent。 当 DevUI 或其他组件通过 DI 请求一个特定名称(key)的 AIAgent 时,系统会动态查找并返回匹配的代理实例。

当某个组件调用:

var agent = serviceProvider.GetKeyedService<AIAgent>("my-workflow");

DI 容器会触发此方法中注册的工厂函数,并按以下优先级尝试解析 AIAgent:

  1. 首先尝试查找带相同 key 的 Workflow

    Workflow keyedService = sp.GetKeyedService<Workflow>(serviceKey);
    • 如果找到,就调用 keyedService.AsAgent(...) 将其转换为 AIAgent 并返回。
  2. 如果没找到带键的 Workflow,尝试获取默认(无键)的 Workflow

    Workflow service1 = sp.GetService<Workflow>();
    • 检查该 Workflow 的 Name 是否与请求的 serviceKey 完全相等(Ordinal 比较)。
    • 如果匹配,也转换为 AIAgent 返回。
  3. 如果仍未找到,尝试获取默认的 AIAgent

    AIAgent service2 = sp.GetService<AIAgent>();
    • 同样检查其 Name 是否等于 serviceKey。
    • 如果匹配,直接返回该 AIAgent。
  4. 如果以上都失败,返回 null

    • 表示没有找到与该 key 对应的智能代理。

设计目的与用途

  • 支持 DevUI 动态加载不同 AI 代理:DevUI 可能需要根据用户选择的“代理名称”(如 "chatbot"、"translator")动态获取对应的 AIAgent。

以上是官方设计这个扩展方法的初衷,但是这给我们集成abp vnext 造成了麻烦,因为 abp vnext 使用的注入框架是autofac ,其并不支持 services.AddKeyedSingleton<AIAgent>(KeyedService.AnyKey, (Func<IServiceProvider, object, AIAgent>) 这种语法,程序启动时,容器会拿取一个默认的AIAgent注入,这时候是没有传入任何键值的,KeyedService.AnyKey会被解读为 “*”,但实质上KeyedService.AnyKey 并不是字符串,而是一个object 对象 , string serviceKey = key as string; 我们拿到的serviceKey 为null,意味着我们不会拿到注册的任何AIAgent服务,会抛出异常:

System.ArgumentNullException: Value cannot be null. (Parameter 'keyAsStr')

这时我们只能妥协,重新去塑造一个新的扩展方法,以适应我们现在的框架。 我们只需要当keyAsStr 为空时,不使用GetKeyedService<T>获取服务,而是使用GetService<T> ,返回一个默认的Agent给到容器注册,就可以解决现在的问题

        var keyAsStr = key as string;

        // 这里会抛出 ArgumentNullException,导致应用启动失败。
        // 原始代码假设 key 一定是字符串,但 DevUI 调用时并非如此。
        //Throw.IfNullOrEmpty(keyAsStr);
        if (string.IsNullOrEmpty(keyAsStr))
        {
            var defaultAgent = sp.GetService<AIAgent>()!;
            return defaultAgent;
        }

效果展示

AI Result

总结

本文详细介绍了如何将 Microsoft Agent Framework(包含 Semantic Kernel 与 Auto Agent 能力)集成到 ABP vNext Pro 项目中,以构建具备智能交互能力的现代化 .NET 应用。通过以下关键步骤完成了深度整合:

  1. 项目初始化:基于 ABP vNext Pro 模板创建了名为 AiTry 的模块化项目结构,为后续 AI 功能开发打下基础。

  2. 依赖引入:在共享层引入 Microsoft Agent Framework 及相关 AI 扩展包,并通过 Directory.Build.Microsoft.targets 统一管理版本,确保兼容性。

  3. 配置与注入:

    • 定义 ChatClientInfo 配置类,支持从 appsettings.json 加载多个 AI 模型端点(如 Qwen2.5-7B-Instruct)。
    • 实现自定义服务扩展 AddAIAgent,注册 OpenAI 兼容的聊天客户端与 AIAgent 实例,并支持工具调用(如天气查询工具)。
  4. 适配 ABP 容器限制:

    • 由于 ABP 默认使用 Autofac 作为 DI 容器,不完全兼容 Microsoft 提供的 AddDevUI 中基于 键控服务(Keyed Service) 的实现逻辑。
    • 为此,重写了 AddDevUIEx 扩展方法,在 key 为空时回退到获取默认 AIAgent,避免因类型转换失败导致的 ArgumentNullException,成功绕过容器兼容性问题。
  5. 中间件集成:在应用启动时注册 DevUI、OpenAI 响应与会话路由,使开发者可通过 /devui 界面调试 AI 代理。

通过上述改造,不仅实现了 AI 能力在 ABP 架构中的无缝嵌入,还保留了框架原有的模块化、多租户与权限控制等企业级特性。该方案为构建可维护、可扩展的智能业务系统提供了可行路径,也为其他开发者在类似场景下的集成提供了参考范式。

> comment on cnblog
>
CC BY-NC-SA 4.0 2021-PRESENT © jaythawme