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 都有專門的功能,例如數據檢索、分析或決策。這些 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 應用程式,支持多個 LLMs 和 SLMs、工具以及高級多 Agent 設計模式。

AutoGen 的核心概念是 Agent,它是能夠感知環境、做出決策並採取行動以實現特定目標的自主實體。Agent 通過非同步消息進行通信,使其能夠獨立並並行工作,提升系統的可擴展性和響應能力。

Agent 基於 Actor 模型。根據維基百科,Actor 是 並行計算的基本構建塊。Actor 在接收到消息後可以:做出本地決策、創建更多 Actor、發送更多消息以及確定如何響應接收到的下一條消息

使用案例:自動化程式碼生成、數據分析任務以及為規劃和研究功能構建自定義 Agent。

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

Semantic Kernel + Agent 框架

Semantic Kernel 是一個企業級 AI 編排 SDK。它由 AI 和記憶體連接器以及 Agent 框架組成。

首先介紹一些核心元件:

這些事實會被存儲在記憶集合 SummarizedAzureDocs 中。這是一個非常簡化的例子,但您可以看到如何將資訊存儲在記憶中供 LLM 使用。

這就是 Semantic Kernel 框架的基本概念,那麼 Agent Framework 呢?

Azure AI Agent Service

Azure AI Agent Service 是最近新增的功能,於 Microsoft 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 事件驅動的分佈式代理應用 代理、角色、功能、資料 代碼生成、資料分析任務
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 SDKs 從代理中與 Azure 服務互動。此外,如前所述,您可以使用 Azure AI Agent Service 作為協作器,來協作由 AutoGen 或 Semantic Kernel 構建的代理,這將使得訪問 Azure 生態系統更加容易。

對 AI Agent 框架有更多疑問?

加入 Azure AI Foundry Discord,與其他學習者交流,參加辦公時間並解答您的 AI 代理相關問題。

參考資料

上一課

AI 代理和代理使用案例介紹

下一課

理解代理設計模式


免責聲明
本文件已使用 AI 翻譯服務 Co-op Translator 進行翻譯。雖然我們致力於提供準確的翻譯,但請注意,自動翻譯可能包含錯誤或不準確之處。原始文件的母語版本應被視為權威來源。對於關鍵信息,建議使用專業人工翻譯。我們對因使用此翻譯而引起的任何誤解或誤釋不承擔責任。