ai-agents-for-beginners

探索 AI Agent 框架

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

探索 AI Agent 框架

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

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

介绍

本课将涵盖以下内容:

学习目标

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

什么是 AI Agent 框架?它能帮助开发者做什么?

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

听起来很棒,对吧?那为什么还需要 AI Agent 框架?

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

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

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

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

使用模块化组件

像 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 这样的框架支持创建能够协作的多个 Agent。

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

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

示例代码 (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)

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

实时学习

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

团队如何使用这些功能:团队可以实现反馈循环,使 Agent 从交互中学习并动态调整其行为,从而不断改进和优化能力。

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

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

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

AutoGen

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

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

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

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

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

Semantic Kernel + Agent 框架

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

首先让我们了解一些核心组件:

Azure AI Agent Service

Azure AI Agent Service是最近推出的一项服务,于2024年微软Ignite大会上发布。它允许使用更灵活的模型开发和部署AI代理,例如直接调用开源LLM(如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 事件驱动的分布式代理应用 代理、角色、功能、数据 代码生成、数据分析任务
Semantic Kernel 理解和生成类似人类的文本内容 代理、模块化组件、协作 自然语言理解、内容生成
Azure AI Agent Service 灵活模型、企业安全、代码生成、工具调用 模块化、协作、流程编排 安全、可扩展和灵活的AI代理部署

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

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

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

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

关于AI代理框架还有更多问题?

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

参考资料

上一课

AI代理简介及使用场景

下一课

理解代理设计模式


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