使用 AG2 代理程式

除了使用代理程式的一般操作說明外,本頁面也會說明 AG2Agent 的專屬功能。

事前準備

本教學課程假設您已詳閱並按照下列教學課程的指示操作:

支援的作業

AG2Agent 支援下列作業:

  • query:用於同步取得查詢的回覆。

query 方法支援下列引數:

  • input:要傳送給服務專員的訊息。
  • max_turns:允許的對話輪次上限。使用工具時,至少需要 max_turns=2:一輪生成工具引數,第二輪執行工具。

查詢代理程式

query() 方法提供與代理程式互動的簡化方式。一般呼叫方式如下:

response = agent.query(input="What is the exchange rate from US dollars to Swedish currency?", max_turns=2)

這個方法會處理與代理程式的基礎通訊,並以字典形式傳回代理程式的最終回應。這等同於下列完整形式:

from autogen import ConversableAgent
import dataclasses
import json

input_message: str = "What is the exchange rate from US dollars to Swedish currency?"
max_turns: int = 2

with agent._runnable._create_or_get_executor(
    tools=agent._ag2_tool_objects,            # Use the agent's existing tools
    agent_name="user",                        # Default
    agent_human_input_mode="NEVER",           # query() enforces this
) as executor:
    chat_result = executor.initiate_chat(
        agent._runnable,
        message=input_message,
        max_turns=max_turns,
        clear_history=False,                  # Default
        summary_method="last_msg"             # Default
    )

response = json.loads(
  json.dumps(dataclasses.asdict(chat_result)) # query() does this conversion
)

如要進一步自訂代理程式的行為,請將其他關鍵字引數傳遞至 query(),而不只是 inputmax_turns

response = agent.query(
    input="What is the exchange rate from US dollars to Swedish currency?",
    max_turns=2,
    msg_to="user"  # Start the conversation with the "user" agent
)
print(response)

如需可用參數的完整清單,請參閱 ConversableAgent.run 說明文件。不過請注意,AG2Agent 範本一律會將 user_input 覆寫為 False

後續步驟