Type something to search...
精通多智能体系统:使用 Microsoft Semantic Kernel 构建投资组合管理器的逐步指南

精通多智能体系统:使用 Microsoft Semantic Kernel 构建投资组合管理器的逐步指南

利用 SelectionFunction 实现高效协作

在我之前的博客中,我们介绍了如何使用 Semantic Kernel 创建一个多智能体系统。链接

然而,智能体之间的协作确实具有挑战性,因为我们无法控制智能体如何协作。我们可以设置终止策略来决定何时停止智能体之间的协作,但不能决定智能体将如何参与。

新版本的 Semantic Kernel 引入了 selectionFunction,解决了这个问题。如何解决?让我们通过一个例子和一步一步的指南来深入了解。

多智能体系统中的 Selection Function 选择

Semantic Kernel 中的选择函数有助于定义智能体协作的基本规则。在多智能体系统中,智能体经常进入错误的循环,导致输出不一致。Semantic Kernel 中的选择函数解决了这个问题。

我们将通过一个“投资组合管理多智能体系统”的例子来理解选择函数的工作原理。 让我们首先定义 3 个智能体:

  1. 投资组合优化器智能体:该智能体将有权访问我的个人财务状况和目标,并可以帮助优化我的投资组合。
  2. 网络冲浪者智能体:该智能体可以浏览网络以获取最新新闻和信息。
  3. 股票分析器智能体:该智能体分析历史股票数据、当前新闻和趋势以评估股票。

我创建了一个应用程序,它将向我展示托管的智能体,并且我应该能够按需以及按计划运行智能体。

Semantic Kernel 智能体平台截图

构建投资组合管理器的分步指南

关于如何创建 Semantic Kernel,请参考我之前的 博客 或 python 代码示例,请参考官方 文档

步骤 1:定义 Agent

            /// Step 1: Define Agents
            /// Creating individual agents for portfolio management, web surfing, and stock analysis.
            PortfolioManagerAgent = new()
            {
                Name = nameof(PortfolioManagerAgents),
                Instructions = @"Your are experieced Portfolio Manager.
                                You have access to user's porfolio.
                                You make recommendations based on latest news and stock analysis report.
                                You provide the portfolio to other participant if needed.
                                If you don't have latest news or stock analysis report, you ask for it to other participants. Never give general guidelines",
                Kernel = Kernel,
                Arguments = new KernelArguments(openAIPromptExecutionSettings)
            };

WebAgent = new()
            {
                Name = nameof(WebSurferAgent),
                Instructions = "Your task is to retrieve and summarize the latest stock market news from reliable sources. " +
                   "You will monitor stock trends, economic events, and financial updates, providing real-time insights. " +
                   "to enhance investment recommendations. Ensure the news is current, relevant, and sourced from credible financial sources. Never provide general insights. You only provide news",
                Kernel = Kernel,
                Arguments = new KernelArguments(openAIPromptExecutionSettings)
            };

/// Defining the Stock Analyzer Agent using OpenAI
            Agent = OpenAIAssistantAgent.CreateAsync(
                OpenAIClientProvider.ForAzureOpenAI(apiKeyCredential, new Uri("https://testmediumazureopenai.openai.azure.com")),
                new OpenAIAssistantDefinition("GPT4ov1")
                {
                    Name = nameof(StockAnalyzerAgent),
                    Instructions = "You are responsible for analyzing stock market data and sentiment analysis on news updates. " +
                   "Leverage historical stock data, technical indicators, and fundamental analysis to assess market trends. " +
                   "Perform sentiment analysis on news provided by the WebSurferAgent to gauge market sentiment.. Create charts in HTML",
                },
                Kernel);

步骤 2:定义选择策略

 /// Step 2: Define Selection Strategy
/// This function determines which agent should take the next turn in the collaboration.
private KernelFunction GetSelectionFunction()
{
    return AgentGroupChat.CreatePromptFunctionForStrategy(
        $$$"""
        Determine which participant takes the next turn in a conversation based on the most recent participant.
        State only the name of the participant to take the next turn.
        No participant should take more than one turn in a row.

Choose only from these participants:
        - {{{nameof(PortfolioManagerAgents)}}}
        - {{{nameof(WebSurferAgent)}}}
        - {{{nameof(StockAnalyzerAgent)}}}

Always follow these rules when selecting the next participant:
        - After {{{nameof(PortfolioManagerAgents)}}}, it is {{{nameof(WebSurferAgent)}}}'s turn.
        - After {{{nameof(WebSurferAgent)}}}, it is {{{nameof(StockAnalyzerAgent)}}}'s turn.
        - After {{{nameof(StockAnalyzerAgent)}}}, it is {{{nameof(PortfolioManagerAgents)}}}'s turn.

History:
        {{$history}}
        """,
        safeParameterNames: "history");
}

步骤 3:定义终止策略

/// Step 3: Define Termination Strategy
/// This function ensures that the process stops once the Portfolio Manager makes a recommendation.
private KernelFunction GetTerminationStrategy()
{
    KernelFunction terminationFunction =
        AgentGroupChat.CreatePromptFunctionForStrategy(
            $$$"""
            Determine if the PortfolioManager is done with recommendations.
            If so, respond with a single word: done

History:
            {{$history}}
            """,
            safeParameterNames: "history");

return terminationFunction;
}

步骤 4:创建有用的工具。

我正在添加 2 个工具

  1. NewsAPI 用于获取最新新闻(已注册 WebSurfer agent)
  2. GetPortfolio 用于获取我的最新投资组合(已注册 PortfolioManagement Agent)

我不会深入研究如何为 Semantic Kernel 编写工具,因为我之前的博客中已经涵盖了这一点。相反,我将分享一个关于如何为代理启用函数调用的简短代码片段。有关官方文档,请查看 此处

// Define function/tools
[KernelFunction, Description("Get my latest portfolio information.")]
public string GetMyPortfolio(string user)
{
  // implmentation here
}

Kernel.Plugins.AddFromObject(portfolioTools);

OpenAIPromptExecutionSettings openAIPromptExecutionSettings = new()
{
   FunctionChoiceBehavior = FunctionChoiceBehavior.Auto()
};

PortfolioManagerAgent = new()
            {
                ....
                Arguments = new KernelArguments(openAIPromptExecutionSettings)
                .....
            };

步骤 5:创建多代理聊天

/// Step 5: Putting It All Together
/// This function initializes the agent system and manages the execution workflow.
public async Task StartAsync(CancellationToken cancellationToken)
{
    StringBuilder interactions = new StringBuilder();

try
    {
        var PAgent = new PortfolioManagerAgents().GetAgent();
        var WebAgent = new WebSurferAgent().GetAgent();
        var stockAgent = new StockAnalyzerAgent().GetAgent();

// Define selection strategy
        KernelFunctionSelectionStrategy selectionStrategy =
            new(GetSelectionFunction(), Kernel)
            {
                InitialAgent = PAgent,
                HistoryVariableName = "history",
                HistoryReducer = new ChatHistoryTruncationReducer(10),
            };

// Define termination strategy
        KernelFunctionTerminationStrategy terminationStrategy =
          new(GetTerminationStrategy(), Kernel)
          {
              Agents = [PAgent],
              ResultParser = (result) =>
                result.GetValue<string>()?.Contains("done", StringComparison.OrdinalIgnoreCase) ?? false,
              HistoryVariableName = "history",
              HistoryReducer = new ChatHistoryTruncationReducer(1),
              MaximumIterations = 10,
          };

// Initialize the multi-agent system
        Agen

投资组合管理的多智能体系统

public async Task RunPortfolioManagementAgentSystem(CancellationToken cancellationToken = default)
{
    try
    {
        var kernel = Kernel.CreateBuilder()
            .AddAzureOpenAIChatCompletion(
                "gpt-35-turbo",
                Environment.GetEnvironmentVariable("AZURE_OPENAI_ENDPOINT")!,
                Environment.GetEnvironmentVariable("AZURE_OPENAI_API_KEY")!)
            .AddSemanticFunction(
                "PortfolioManagerAgent",
                "PortfolioManagerAgent",
                "PortfolioManagerAgent")
            .AddSemanticFunction(
                "WebAgent",
                "WebAgent",
                "WebAgent")
            .AddSemanticFunction(
                "StockAgent",
                "StockAgent",
                "StockAgent")
            .Build();

        // Define the agents
        var PAgent = new Agent(kernel, "PortfolioManagerAgent");
        var WebAgent = new Agent(kernel, "WebAgent");
        var stockAgent = new Agent(kernel, "StockAgent");

        // Define the termination strategy
        var terminationStrategy = new MaxTurnsStrategy(3);

        // Define the selection strategy
        var selectionStrategy = new RoundRobinStrategy();

        // Create the chat
        tGroupChat chat = new(PAgent, WebAgent, stockAgent)
        {
            ExecutionSettings = new()
            {
                TerminationStrategy = terminationStrategy,
                SelectionStrategy = selectionStrategy,
            }
        };

        chat.AddChatMessage(new ChatMessageContent(AuthorRole.User, "start. Note today is Jan 15th 2025"));

        // Execute the multi-agent collaboration
        await foreach (var content in chat.InvokeAsync(cancellationToken))
        {
            string interaction = $"<b>#{content.Role}</b> - <i>{content.AuthorName ?? "*"}</i>: \"{content.Content}\"";
            Console.WriteLine(interaction);
            interactions.Append(interaction + "\n");
        }

        Console.WriteLine("PortfolioManagementAgentSystem has completed execution.");
    }
    catch (Exception ex)
    {
        Console.WriteLine($"Error: {ex.Message}");
    }

    var prompt = @"Write an email body outlining the necessary actions for my portfolio.
                      Provide the output in HTML format and keep it concise.
                      Include graphs and charts in HTML format.
                      Start directly with the email content without any additional text before or after.";

    var emailContent = await Kernel.InvokePromptAsync($"{prompt} {interactions}");

    EmailSender.SendEmail("Portfolio Agent Update", emailContent.ToString());
}

这是我的投资组合,PortfolioManagerAgent 可以访问

示例投资组合。数值是虚构的,不是股票或债券的真实价格

这是我运行这个多智能体系统后收到的电子邮件。你可以在控制台日志中输出它。

我收到的示例电子邮件

Related Posts

结合chatgpt-o3-mini与perplexity Deep Research的3步提示:提升论文写作质量的终极指南

结合chatgpt-o3-mini与perplexity Deep Research的3步提示:提升论文写作质量的终极指南

AI 研究报告和论文写作 合并两个系统指令以获得两个模型的最佳效果 Perplexity AI 的 Deep Research 工具提供专家级的研究报告,而 OpenAI 的 ChatGPT-o3-mini-high 擅长推理。我发现你可以将它们结合起来生成令人难以置信的论文,这些论文比任何一个模型单独撰写的都要好。你只需要将这个一次性提示复制到 **

阅读更多
让 Excel 过时的 10 种 Ai 工具:实现数据分析自动化,节省手工作业时间

让 Excel 过时的 10 种 Ai 工具:实现数据分析自动化,节省手工作业时间

Non members click here作为一名软件开发人员,多年来的一个发现总是让我感到惊讶,那就是人们还在 Excel

阅读更多
使用 ChatGPT 搜索网络功能的 10 种创意方法

使用 ChatGPT 搜索网络功能的 10 种创意方法

例如,提示和输出 你知道可以使用 ChatGPT 的“搜索网络”功能来完成许多任务,而不仅仅是基本的网络搜索吗? 对于那些不知道的人,ChatGPT 新的“搜索网络”功能提供实时信息。 截至撰写此帖时,该功能仅对使用 ChatGPT 4o 和 4o-mini 的付费会员开放。 ![](https://images.weserv.nl/?url=https://cdn-im

阅读更多
掌握Ai代理:解密Google革命性白皮书的10个关键问题解答

掌握Ai代理:解密Google革命性白皮书的10个关键问题解答

10 个常见问题解答 本文是我推出的一个名为“10 个常见问题解答”的新系列的一部分。在本系列中,我旨在通过回答关于该主题的十个最常见问题来分解复杂的概念。我的目标是使用简单的语言和相关的类比,使这些想法易于理解。 图片来自 [Solen Feyissa](https://unsplash.com/@solenfeyissa?utm_source=medium&utm_medi

阅读更多
在人工智能和技术领域保持领先地位的 10 项必学技能 📚

在人工智能和技术领域保持领先地位的 10 项必学技能 📚

在人工智能和科技这样一个动态的行业中,保持领先意味着不断提升你的技能。无论你是希望深入了解人工智能模型性能、掌握数据分析,还是希望通过人工智能转变传统领域如法律,这些课程都是你成功的捷径。以下是一个精心策划的高价值课程列表,可以助力你的职业发展,并让你始终处于创新的前沿。 1. 生成性人工智能简介课程: [生成性人工智能简介](https://genai.works

阅读更多
揭开真相!深度探悉DeepSeek AI的十大误区,您被误导了吗?

揭开真相!深度探悉DeepSeek AI的十大误区,您被误导了吗?

在AI军备竞赛中分辨事实与虚构 DeepSeek AI真的是它所宣传的游戏规则改变者,还是仅仅聪明的营销和战略炒作?👀 虽然一些人将其视为AI效率的革命性飞跃,但另一些人则认为它的成功建立在借用(甚至窃取的)创新和可疑的做法之上。传言称,DeepSeek的首席执行官在疫情期间像囤积卫生纸一样囤积Nvidia芯片——这只是冰山一角。 从其声称的550万美元培训预算到使用Open

阅读更多
Type something to search...