建立 AG2 代理程式

您可以使用框架專用的 AG2 範本 (AutoGen 的社群導向分支版本),透過 Agent Runtime 開發及部署代理。您可以使用 Agent Platform SDK 中的 AG2Agent 類別,建立可執行複雜工作及整合外部工具的代理程式。

本文說明如何開發 AG2 代理程式,包括定義模型、新增工具,以及自訂自動化調度管理流程。

如要進一步瞭解如何管理已部署的代理程式,請參閱「管理已部署的代理程式」。

如要建立 AG2 代理程式,請按照下列步驟操作:

  1. 定義及設定可執行的項目
  2. 定義及使用工具
  3. 選用:自訂協調流程

事前準備

請按照「設定環境」一節中的步驟,確認環境已設定完成。

步驟 1:定義及設定可執行的項目

指定要使用的模型:

model = "gemini-3.5-flash"

定義要使用的可執行檔名稱:

runnable_name = "Get Exchange Rate Agent"

選用:設定模型:

from google.cloud.aiplatform.aiplatform import initializer

llm_config = {
    "config_list": [{
        "project_id":       initializer.global_config.project,
        "location":         initializer.global_config.location,
        "model":            "gemini-3.5-flash",
        "api_type":         "google",
    }]
}

如要進一步瞭解如何在 AG2 中設定模型,請參閱「模型設定深入探討」。

選用:設定模型的安全性設定。 以下範例說明如何設定安全防護設定:

from vertexai.generative_models import HarmBlockThreshold, HarmCategory

safety_settings = {
    HarmCategory.HARM_CATEGORY_HARASSMENT: HarmBlockThreshold.BLOCK_ONLY_HIGH,
    HarmCategory.HARM_CATEGORY_HATE_SPEECH: HarmBlockThreshold.BLOCK_ONLY_HIGH,
    HarmCategory.HARM_CATEGORY_SEXUALLY_EXPLICIT: HarmBlockThreshold.BLOCK_ONLY_HIGH,
    HarmCategory.HARM_CATEGORY_DANGEROUS_CONTENT: HarmBlockThreshold.BLOCK_ONLY_HIGH,
}

for config_item in llm_config["config_list"]:
    config_item["safety_settings"] = safety_settings

如要進一步瞭解 Gemini 安全性設定的可用選項,請參閱「設定安全屬性」。

使用模型設定建立 AG2Agent

from vertexai import agent_engines

agent = agent_engines.AG2Agent(
    model=model,                  # Required.
    runnable_name=runnable_name,  # Required.
    llm_config=llm_config,        # Optional.
)

如果您在互動式環境 (例如終端機或 Colab 筆記本) 中執行,可以執行查詢做為中繼測試步驟:

response = agent.query(input="What is the exchange rate from US dollars to SEK today?", max_turns=1)

print(response)

回應是類似下列範例的 Python 字典:

{'chat_id': None,
 'chat_history': [{'content': 'What is the exchange rate from US dollars to Swedish currency?',
   'role': 'assistant',
   'name': 'user'},
  {'content': 'I do not have access to real-time information, including currency exchange rates. To get the most up-to-date exchange rate from US dollars to Swedish Krona (SEK), I recommend using a reliable online currency converter or checking with your bank. \n',
   'role': 'user',
   'name': 'Exchange Rate Agent'}],
 'summary': 'I do not have access to real-time information, including currency exchange rates. To get the most up-to-date exchange rate from US dollars to Swedish Krona (SEK), I recommend using a reliable online currency converter or checking with your bank. \n',
 'cost': {'usage_including_cached_inference': {'total_cost': 5.2875e-06,
   'gemini-3.5-flash': {'cost': 5.2875e-06,
    'prompt_tokens': 34,
    'completion_tokens': 62,
    'total_tokens': 96}},
  'usage_excluding_cached_inference': {'total_cost': 5.2875e-06,
   'gemini-3.5-flash': {'cost': 5.2875e-06,
    'prompt_tokens': 34,
    'completion_tokens': 62,
    'total_tokens': 96}}},
 'human_input': []}

選用:進階自訂

根據預設,AG2Agent 範本會使用 api_type=="google",因為這項模型可存取 Google Cloud中所有可用的基礎模型。如要使用 api_type=="google" 無法提供的模型,可以自訂 llm_config 參數。

如需 AG2 支援的型號清單及其功能,請參閱「模型供應商」。llm_config= 的支援值組合會因聊天模型而異,因此請參閱對應的文件瞭解詳情。

Gemini

預設為已安裝。

省略 llm_config 引數時,會使用 AG2Agent,例如

from vertexai import agent_engines

agent = agent_engines.AG2Agent(
    model=model,                # Required.
    runnable_name=runnable_name # Required.
)

Anthropic

首先,請按照他們的文件設定帳戶並安裝套件。

接著,定義 llm_config

llm_config = {
    "config_list": [{
        "model": "claude-3-5-sonnet-20240620",            # Required.
        "api_key": "ANTHROPIC_API_KEY",  # Required.
        "api_type": "anthropic",                          # Required.
     }]
}

最後,在 AG2Agent 中使用下列程式碼:

from vertexai import agent_engines

agent = agent_engines.AG2Agent(
    model="claude-3-5-sonnet-20240620",             # Required.
    runnable_name=runnable_name,                    # Required.
    llm_config=llm_config,                          # Optional.
)

OpenAI

您可以搭配使用 OpenAI 和 Gemini 的 ChatCompletions API

首先,請定義 llm_config

import google.auth
from google.cloud.aiplatform.aiplatform import initializer

project = initializer.global_config.project
location = initializer.global_config.location
base_url = f"https://{location}-aiplatform.googleapis.com/v1beta1/projects/{project}/locations/{location}/endpoints/openapi"

# Note: the credential lives for 1 hour by default.
# After expiration, it must be refreshed.
creds, _ = google.auth.default(scopes=["https://www.googleapis.com/auth/cloud-platform"])
auth_req = google.auth.transport.requests.Request()
creds.refresh(auth_req)

llm_config = {
    "config_list": [{
        "model": "google/gemini-3.5-flash",  # Required.
        "api_type": "openai",                    # Required.
        "base_url": base_url,                    # Required.
        "api_key": creds.token,                  # Required.
    }]
}

最後,在 AG2Agent 中使用下列程式碼:

from vertexai import agent_engines

agent = agent_engines.AG2Agent(
    model="google/gemini-3.5-flash",  # Or "meta/llama3-405b-instruct-maas".
    runnable_name=runnable_name,          # Required.
    llm_config=llm_config,                # Optional.
)

步驟 2:定義及使用工具

定義模型後,下一步是定義模型用於推論的工具。工具可以是 AG2 工具 或 Python 函式。

定義函式時,請務必加入註解,完整清楚地說明函式的參數、函式用途和函式傳回的內容。模型會根據這項資訊判斷要使用哪個函式。您也必須在本機測試函式,確認函式運作正常。

使用下列程式碼定義會傳回匯率的函式:

def get_exchange_rate(
    currency_from: str = "USD",
    currency_to: str = "EUR",
    currency_date: str = "latest",
):
    """Retrieves the exchange rate between two currencies on a specified date.

    Uses the Frankfurter API (https://api.frankfurter.app/) to obtain
    exchange rate data.

    Args:
        currency_from: The base currency (3-letter currency code).
            Defaults to "USD" (US Dollar).
        currency_to: The target currency (3-letter currency code).
            Defaults to "EUR" (Euro).
        currency_date: The date for which to retrieve the exchange rate.
            Defaults to "latest" for the most recent exchange rate data.
            Can be specified in YYYY-MM-DD format for historical rates.

    Returns:
        dict: A dictionary containing the exchange rate information.
            Example: {"amount": 1.0, "base": "USD", "date": "2023-11-24",
                "rates": {"EUR": 0.95534}}
    """
    import requests
    response = requests.get(
        f"https://api.frankfurter.app/{currency_date}",
        params={"from": currency_from, "to": currency_to},
    )
    return response.json()

如要在代理程式中使用函式前先測試,請執行下列指令:

get_exchange_rate(currency_from="USD", currency_to="SEK")

回覆內容應類似下方範例:

{'amount': 1.0, 'base': 'USD', 'date': '2024-02-22', 'rates': {'SEK': 10.3043}}

如要在 AG2Agent 中使用這項工具,請將其新增至 tools= 引數下的工具清單:

from vertexai import agent_engines

agent = agent_engines.AG2Agent(
    model=model,                 # Required.
    runnable_name=runnable_name, # Required.
    tools=[get_exchange_rate],   # Optional.
)

您可以對代理執行測試查詢,在本機測試代理。執行下列指令,使用美元和瑞典克朗在本機測試代理:

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

回應是類似下列內容的字典:

{'chat_id': None,
 'chat_history': [{'content': 'What is the exchange rate from US dollars to Swedish currency?',
   'role': 'assistant',
   'name': 'user'},
  {'content': '',
   'tool_calls': [{'id': '2285',
     'function': {'arguments': '{"currency_from": "USD", "currency_to": "SEK"}',
      'name': 'get_exchange_rate'},
     'type': 'function'}],
   'role': 'assistant'},
  {'content': "{'amount': 1.0, 'base': 'USD', 'date': '2025-02-27', 'rates': {'SEK': 10.6509}}",
   'tool_responses': [{'tool_call_id': '2285',
     'role': 'tool',
     'content': "{'amount': 1.0, 'base': 'USD', 'date': '2025-02-27', 'rates': {'SEK': 10.6509}}"}],
   'role': 'tool',
   'name': 'user'},
  {'content': 'The current exchange rate is 1 USD to 10.6509 SEK. \n',
   'role': 'user',
   'name': 'Get Exchange Rate Agent'},
  {'content': 'What is the exchange rate from US dollars to Swedish currency?',
   'role': 'assistant',
   'name': 'user'},
  {'content': '',
   'tool_calls': [{'id': '4270',
     'function': {'arguments': '{"currency_from": "USD", "currency_to": "SEK"}',
      'name': 'get_exchange_rate'},
     'type': 'function'}],
   'role': 'assistant'},
  {'content': "{'amount': 1.0, 'base': 'USD', 'date': '2025-02-27', 'rates': {'SEK': 10.6509}}",
   'tool_responses': [{'tool_call_id': '4270',
     'role': 'tool',
     'content': "{'amount': 1.0, 'base': 'USD', 'date': '2025-02-27', 'rates': {'SEK': 10.6509}}"}],
   'role': 'tool',
   'name': 'user'},
  {'content': 'The current exchange rate is 1 USD to 10.6509 SEK. \n',
   'role': 'user',
   'name': 'Get Exchange Rate Agent'}],
 'summary': 'The current exchange rate is 1 USD to 10.6509 SEK. \n',
 'cost': {'usage_including_cached_inference': {'total_cost': 0.0002790625,
   'gemini-3.5-flash': {'cost': 0.0002790625,
    'prompt_tokens': 757,
    'completion_tokens': 34,
    'total_tokens': 791}},
  'usage_excluding_cached_inference': {'total_cost': 0.0002790625,
   'gemini-3.5-flash': {'cost': 0.0002790625,
    'prompt_tokens': 757,
    'completion_tokens': 34,
    'total_tokens': 791}}},
 'human_input': []}

步驟 3:自訂協調流程

所有 AG2 代理程式都會實作 ConversableAgent 介面,提供用於協調流程的輸入和輸出結構定義。這個AG2Agent範本需要建構可執行的項目,才能回應查詢。根據預設,AG2Agent 會透過將模型與工具繫結,建構這類可執行的項目。

如果您打算 (i) 實作可使用模型解決工作的 Assistant Agent,或 (ii) 實作可執行程式碼並向其他代理提供意見回饋的 User Proxy Agent,或 (iii) 實作可使用模型和思維鏈推理解決工作的 Reasoning Agent,則可能需要自訂協調程序。如要執行這項操作,您必須在建立 AG2Agent 時,透過指定 runnable_builder= 引數和下列簽章的 Python 函式,覆寫預設可執行檔:


def runnable_builder(
    **runnable_kwargs,
):

這可提供多種自訂協調邏輯的選項。

助理代理程式

在最簡單的情況下,如要建立不含協調機制的助理代理程式,可以覆寫 AG2Agentrunnable_builder

from vertexai import agent_engines

def runnable_builder(**kwargs):
    from autogen import agentchat

    return agentchat.AssistantAgent(**kwargs)

agent = agent_engines.AG2Agent(
    model=model,
    runnable_name=runnable_name,
    runnable_builder=runnable_builder,
)

使用者 Proxy 代理程式

在最簡單的情況下,如要建立不含協調機制的使用者 Proxy 代理程式,您可以覆寫 AG2Agentrunnable_builder

from vertexai import agent_engines

def runnable_builder(**kwargs):
    from autogen import agentchat

    return agentchat.UserProxyAgent(**kwargs)

agent = agent_engines.AG2Agent(
    model=model,
    runnable_name=runnable_name,
    runnable_builder=runnable_builder,
)

推論代理

在最簡單的情況下,如要建立不含自動調度的推理代理程式,可以覆寫 AG2Agentrunnable_builder

from vertexai import agent_engines

def runnable_builder(**kwargs):
    from autogen import agentchat

    return agentchat.ReasoningAgent(**kwargs)

agent = agent_engines.AG2Agent(
    model=model,
    runnable_name=runnable_name,
    runnable_builder=runnable_builder,
)

後續步驟

指南

瞭解如何根據開發需求,在 Agent Platform Runtime 部署代理程式。

指南

使用 Agent Platform Runtime 搭配 AG2 代理。

指南

建立及部署基本代理,並使用 Gen AI Evaluation Service 評估代理

疑難排解

瞭解如何解決建立自訂代理程式時的常見錯誤。

資源

尋找 Google Agent Platform 的相關資源和支援。