ai-agents-for-beginners

探索 AI 代理框架

(点击上方图片观看本课视频)

探索 AI 代理框架

AI 代理框架是专为简化 AI 代理的创建、部署和管理而设计的软件平台。这些框架为开发者提供了预构建的组件、抽象和工具,从而简化了复杂 AI 系统的开发过程。

这些框架通过提供标准化的方法来解决 AI 代理开发中的常见挑战,帮助开发者专注于应用程序的独特方面。它们提升了构建 AI 系统的可扩展性、可访问性和效率。

介绍

本课将涵盖以下内容:

学习目标

本课的目标是帮助你理解:

什么是 AI 代理框架,它能帮助开发者实现什么目标?

传统的 AI 框架可以帮助你将 AI 集成到应用程序中,并通过以下方式提升这些应用程序:

听起来很棒,对吧?那么为什么我们还需要 AI 代理框架?

AI 代理框架不仅仅是 AI 框架。它们旨在创建能够与用户、其他代理和环境交互以实现特定目标的智能代理。这些代理可以表现出自主行为、做出决策并适应变化的条件。让我们看看 AI 代理框架所启用的一些关键功能:

总结来说,代理让你能够做更多事情,将自动化提升到一个新的水平,创建能够从环境中学习和适应的更智能系统。

如何快速原型设计、迭代并提升代理的能力?

这是一个快速发展的领域,但大多数 AI 代理框架都有一些共同点,可以帮助你快速原型设计和迭代,主要包括模块化组件、协作工具和实时学习。让我们深入了解这些内容:

使用模块化组件

像 Microsoft Semantic Kernel 和 LangChain 这样的 SDK 提供预构建的组件,例如 AI 连接器、提示模板和内存管理。

团队如何使用这些:团队可以快速组装这些组件以创建功能原型,而无需从头开始,从而实现快速实验和迭代。

实际操作方式:你可以使用预构建的解析器从用户输入中提取信息,使用内存模块存储和检索数据,并使用提示生成器与用户交互,而无需从头构建这些组件。

示例代码。以下是如何使用 Semantic Kernel Python 和 .Net 的预构建 AI 连接器,通过自动函数调用响应用户输入的示例:

# Semantic Kernel Python Example

import asyncio
from typing import Annotated

from semantic_kernel.connectors.ai import FunctionChoiceBehavior
from semantic_kernel.connectors.ai.open_ai import AzureChatCompletion, AzureChatPromptExecutionSettings
from semantic_kernel.contents import ChatHistory
from semantic_kernel.functions import kernel_function
from semantic_kernel.kernel import Kernel

# Define a ChatHistory object to hold the conversation's context
chat_history = ChatHistory()
chat_history.add_user_message("I'd like to go to New York on January 1, 2025")


# Define a sample plugin that contains the function to book travel
class BookTravelPlugin:
    """A Sample Book Travel Plugin"""

    @kernel_function(name="book_flight", description="Book travel given location and date")
    async def book_flight(
        self, date: Annotated[str, "The date of travel"], location: Annotated[str, "The location to travel to"]
    ) -> str:
        return f"Travel was booked to {location} on {date}"

# Create the Kernel
kernel = Kernel()

# Add the sample plugin to the Kernel object
kernel.add_plugin(BookTravelPlugin(), plugin_name="book_travel")

# Define the Azure OpenAI AI Connector
chat_service = AzureChatCompletion(
    deployment_name="YOUR_DEPLOYMENT_NAME", 
    api_key="YOUR_API_KEY", 
    endpoint="https://<your-resource>.azure.openai.com/",
)

# Define the request settings to configure the model with auto-function calling
request_settings = AzureChatPromptExecutionSettings(function_choice_behavior=FunctionChoiceBehavior.Auto())


async def main():
    # Make the request to the model for the given chat history and request settings
    # The Kernel contains the sample that the model will request to invoke
    response = await chat_service.get_chat_message_content(
        chat_history=chat_history, settings=request_settings, kernel=kernel
    )
    assert response is not None

    """
    Note: In the auto function calling process, the model determines it can invoke the 
    `BookTravelPlugin` using the `book_flight` function, supplying the necessary arguments. 
    
    For example:

    "tool_calls": [
        {
            "id": "call_abc123",
            "type": "function",
            "function": {
                "name": "BookTravelPlugin-book_flight",
                "arguments": "{'location': 'New York', 'date': '2025-01-01'}"
            }
        }
    ]

    Since the location and date arguments are required (as defined by the kernel function), if the 
    model lacks either, it will prompt the user to provide them. For instance:

    User: Book me a flight to New York.
    Model: Sure, I'd love to help you book a flight. Could you please specify the date?
    User: I want to travel on January 1, 2025.
    Model: Your flight to New York on January 1, 2025, has been successfully booked. Safe travels!
    """

    print(f"`{response}`")
    # Example AI Model Response: `Your flight to New York on January 1, 2025, has been successfully booked. Safe travels! ✈️🗽`

    # Add the model's response to our chat history context
    chat_history.add_assistant_message(response.content)


if __name__ == "__main__":
    asyncio.run(main())
// Semantic Kernel C# example

using Microsoft.SemanticKernel;
using Microsoft.SemanticKernel.ChatCompletion;
using System.ComponentModel;
using Microsoft.SemanticKernel.Connectors.AzureOpenAI;

ChatHistory chatHistory = [];
chatHistory.AddUserMessage("I'd like to go to New York on January 1, 2025");

var kernelBuilder = Kernel.CreateBuilder();
kernelBuilder.AddAzureOpenAIChatCompletion(
    deploymentName: "NAME_OF_YOUR_DEPLOYMENT",
    apiKey: "YOUR_API_KEY",
    endpoint: "YOUR_AZURE_ENDPOINT"
);
kernelBuilder.Plugins.AddFromType<BookTravelPlugin>("BookTravel"); 
var kernel = kernelBuilder.Build();

var settings = new AzureOpenAIPromptExecutionSettings()
{
    FunctionChoiceBehavior = FunctionChoiceBehavior.Auto()
};

var chatCompletion = kernel.GetRequiredService<IChatCompletionService>();

var response = await chatCompletion.GetChatMessageContentAsync(chatHistory, settings, kernel);

/*
Behind the scenes, the model recognizes the tool to call, what arguments it already has (location) and (date)
{

"tool_calls": [
    {
        "id": "call_abc123",
        "type": "function",
        "function": {
            "name": "BookTravelPlugin-book_flight",
            "arguments": "{'location': 'New York', 'date': '2025-01-01'}"
        }
    }
]
*/

Console.WriteLine(response.Content);
chatHistory.AddMessage(response!.Role, response!.Content!);

// Example AI Model Response: Your flight to New York on January 1, 2025, has been successfully booked. Safe travels! ✈️🗽

// Define a plugin that contains the function to book travel
public class BookTravelPlugin
{
    [KernelFunction("book_flight")]
    [Description("Book travel given location and date")]
    public async Task<string> BookFlight(DateTime date, string location)
    {
        return await Task.FromResult( $"Travel was booked to {location} on {date}");
    }
}

从这个示例中可以看到如何利用预构建的解析器从用户输入中提取关键信息,例如航班预订请求的出发地、目的地和日期。这种模块化方法让你可以专注于高层逻辑。

利用协作工具

像 CrewAI、Microsoft AutoGen 和 Semantic Kernel 这样的框架促进了多个代理的创建,这些代理可以协作完成任务。

团队如何使用这些:团队可以设计具有特定角色和任务的代理,测试并优化协作工作流,从而提高整体系统效率。

实际操作方式:你可以创建一个代理团队,每个代理都有专门的功能,例如数据检索、分析或决策。这些代理可以沟通并共享信息,以实现共同目标,例如回答用户查询或完成任务。

示例代码 (AutoGen)

# creating agents, then create a round robin schedule where they can work together, in this case in order

# Data Retrieval Agent
# Data Analysis Agent
# Decision Making Agent

agent_retrieve = AssistantAgent(
    name="dataretrieval",
    model_client=model_client,
    tools=[retrieve_tool],
    system_message="Use tools to solve tasks."
)

agent_analyze = AssistantAgent(
    name="dataanalysis",
    model_client=model_client,
    tools=[analyze_tool],
    system_message="Use tools to solve tasks."
)

# conversation ends when user says "APPROVE"
termination = TextMentionTermination("APPROVE")

user_proxy = UserProxyAgent("user_proxy", input_func=input)

team = RoundRobinGroupChat([agent_retrieve, agent_analyze, user_proxy], termination_condition=termination)

stream = team.run_stream(task="Analyze data", max_turns=10)
# Use asyncio.run(...) when running in a script.
await Console(stream)

在上述代码中,你可以看到如何创建一个涉及多个代理协作分析数据的任务。每个代理执行特定功能,通过协调代理来实现预期结果。通过创建具有专门角色的代理,可以提高任务效率和性能。

实时学习

高级框架提供实时上下文理解和适应的能力。

团队如何使用这些:团队可以实施反馈循环,让代理从交互中学习并动态调整其行为,从而实现能力的持续改进和优化。

实际操作方式:代理可以分析用户反馈、环境数据和任务结果,以更新其知识库、调整决策算法并随着时间推移提高性能。这种迭代学习过程使代理能够适应变化的条件和用户偏好,从而增强整体系统的有效性。

AutoGen、Semantic Kernel 和 Azure AI Agent Service 框架之间有什么区别?

比较这些框架有很多方法,但我们可以从设计、功能和目标使用场景的角度来看一些关键差异:

AutoGen

AutoGen 是由微软研究院 AI Frontiers Lab 开发的开源框架。它专注于事件驱动的分布式 agentic 应用程序,支持多个 LLMs 和 SLMs、工具以及高级多代理设计模式。

AutoGen 围绕代理的核心概念构建,代理是能够感知环境、做出决策并采取行动以实现特定目标的自主实体。代理通过异步消息进行通信,使它们能够独立并行工作,从而增强系统的可扩展性和响应能力。

代理基于 Actor 模型。根据维基百科,Actor 是 并发计算的基本构建块。响应接收到的消息时,Actor 可以:做出本地决策、创建更多 Actor、发送更多消息以及决定如何响应接收到的下一条消息

使用场景:自动化代码生成、数据分析任务以及为规划和研究功能构建自定义代理。

以下是 AutoGen 的一些重要核心概念:

Semantic Kernel + Agent Framework

Semantic Kernel 是一个企业级 AI 编排 SDK。它由 AI 和内存连接器以及一个代理框架组成。

首先介绍一些核心组件:

这些事实随后存储在内存集合 SummarizedAzureDocs 中。这是一个非常简化的示例,但你可以看到如何将信息存储在内存中供 LLM 使用。

这就是 Semantic Kernel 框架的基础,那么 Agent Framework 又是什么呢?

Azure AI Agent Service

Azure AI Agent Service 是最近推出的服务,于微软 Ignite 2024 上发布。它允许使用更灵活的模型开发和部署 AI 代理,例如直接调用开源 LLMs,如 Llama 3、Mistral 和 Cohere。

Azure AI Agent Service 提供更强大的企业安全机制和数据存储方法,使其适合企业应用。

它可以直接与多代理编排框架(如 AutoGen 和 Semantic Kernel)协同工作。

该服务目前处于公开预览阶段,支持使用 Python 和 C# 构建代理。

使用 Semantic Kernel Python,我们可以通过用户定义的插件创建一个 Azure AI Agent:

import asyncio
from typing import Annotated

from azure.identity.aio import DefaultAzureCredential

from semantic_kernel.agents import AzureAIAgent, AzureAIAgentSettings, AzureAIAgentThread
from semantic_kernel.contents import ChatMessageContent
from semantic_kernel.contents import AuthorRole
from semantic_kernel.functions import kernel_function


# Define a sample plugin for the sample
class MenuPlugin:
    """A sample Menu Plugin used for the concept sample."""

    @kernel_function(description="Provides a list of specials from the menu.")
    def get_specials(self) -> Annotated[str, "Returns the specials from the menu."]:
        return """
        Special Soup: Clam Chowder
        Special Salad: Cobb Salad
        Special Drink: Chai Tea
        """

    @kernel_function(description="Provides the price of the requested menu item.")
    def get_item_price(
        self, menu_item: Annotated[str, "The name of the menu item."]
    ) -> Annotated[str, "Returns the price of the menu item."]:
        return "$9.99"


async def main() -> None:
    ai_agent_settings = AzureAIAgentSettings.create()

    async with (
        DefaultAzureCredential() as creds,
        AzureAIAgent.create_client(
            credential=creds,
            conn_str=ai_agent_settings.project_connection_string.get_secret_value(),
        ) as client,
    ):
        # Create agent definition
        agent_definition = await client.agents.create_agent(
            model=ai_agent_settings.model_deployment_name,
            name="Host",
            instructions="Answer questions about the menu.",
        )

        # Create the AzureAI Agent using the defined client and agent definition
        agent = AzureAIAgent(
            client=client,
            definition=agent_definition,
            plugins=[MenuPlugin()],
        )

        # Create a thread to hold the conversation
        # If no thread is provided, a new thread will be
        # created and returned with the initial response
        thread: AzureAIAgentThread | None = None

        user_inputs = [
            "Hello",
            "What is the special soup?",
            "How much does that cost?",
            "Thank you",
        ]

        try:
            for user_input in user_inputs:
                print(f"# User: '{user_input}'")
                # Invoke the agent for the specified thread
                response = await agent.get_response(
                    messages=user_input,
                    thread_id=thread,
                )
                print(f"# {response.name}: {response.content}")
                thread = response.thread
        finally:
            await thread.delete() if thread else None
            await client.agents.delete_agent(agent.id)


if __name__ == "__main__":
    asyncio.run(main())

核心概念

Azure AI Agent Service 包含以下核心概念:

使用场景:Azure AI Agent Service 专为需要安全、可扩展和灵活的 AI 代理部署的企业应用设计。

这些框架之间有什么区别?

听起来这些框架之间有很多重叠,但它们在设计、功能和目标使用场景方面有一些关键区别:

仍然不确定该选择哪个?

使用场景

让我们通过一些常见的使用场景来帮助你选择:

问:我正在进行实验、学习并构建概念验证代理应用,我希望能够快速构建和实验。

答:AutoGen 是此场景的一个不错选择,因为它专注于事件驱动的分布式代理应用,并支持高级多代理设计模式。

问:为什么 AutoGen 比 Semantic Kernel 和 Azure AI Agent Service 更适合这个使用场景?

答:AutoGen 专为事件驱动的分布式代理应用设计,非常适合自动化代码生成和数据分析任务。它提供了构建复杂多代理系统所需的工具和功能。

问:听起来 Azure AI Agent Service 在这里也可以工作,它有代码生成工具和更多功能?

答:是的,Azure AI Agent Service 是一个代理的平台服务,并内置了多个模型、Azure AI Search、Bing Search 和 Azure Functions 的功能。它使你可以轻松在 Foundry Portal 中构建代理并进行大规模部署。

问:我还是很困惑,直接给我一个选项吧。

答:一个很好的选择是先在 Semantic Kernel 中构建你的应用,然后使用 Azure AI Agent Service 部署你的代理。这种方法使你能够轻松持久化代理,同时利用 Semantic Kernel 构建多代理系统的能力。此外,Semantic Kernel 在 AutoGen 中有一个连接器,可以轻松将两个框架结合使用。

让我们用表格总结关键区别:

框架 重点 核心概念 使用场景
AutoGen 事件驱动的分布式代理应用 Agents, Personas, Functions, Data 代码生成、数据分析任务
Semantic Kernel 理解和生成类似人类的文本内容 Agents, Modular Components, Collaboration 自然语言理解、内容生成
Azure AI Agent Service 灵活的模型、企业安全、代码生成、工具调用 Modularity, Collaboration, Process Orchestration 安全、可扩展和灵活的 AI 代理部署

每个框架的理想使用场景是什么?

我可以直接集成现有的 Azure 生态系统工具,还是需要独立解决方案?

答案是肯定的,你可以直接将现有的 Azure 生态系统工具与 Azure AI Agent Service 集成,尤其是因为它被设计为与其他 Azure 服务无缝协作。例如,你可以集成 Bing、Azure AI Search 和 Azure Functions。此外,它还与 Azure AI Foundry 深度集成。

对于 AutoGen 和 Semantic Kernel,你也可以与 Azure 服务集成,但可能需要从代码中调用 Azure 服务。另一种集成方式是使用 Azure SDKs 从代理中与 Azure 服务交互。此外,如前所述,你可以使用 Azure AI Agent Service 作为 AutoGen 或 Semantic Kernel 构建的代理的编排器,从而轻松访问 Azure 生态系统。

关于 AI Agent Frameworks 有更多问题?

加入 Azure AI Foundry Discord,与其他学习者交流,参加办公时间并解答你的 AI Agents 问题。

参考资料

上一课

AI Agents 和代理使用场景简介

下一课

理解代理设计模式


免责声明
本文档使用AI翻译服务 Co-op Translator 进行翻译。尽管我们努力确保翻译的准确性,但请注意,自动翻译可能包含错误或不准确之处。原始语言的文档应被视为权威来源。对于关键信息,建议使用专业人工翻译。我们不对因使用此翻译而产生的任何误解或误读承担责任。