AG2 エージェントを開発する

AG2 は、元の AutoGen のコミュニティ主導のフォークであり、AI を活用したエージェントを構築するためのオープンソース フレームワークです。このページでは、フレームワーク固有の AG2 テンプレート(Vertex AI SDK for Python の AG2Agent クラス)を使用してエージェントを開発する方法について説明します。エージェントは、指定された日付の 2 つの通貨間の為替レートを返します。手順は次のとおりです。

  1. ランナブルを定義して構成する
  2. ツールを定義して使用する
  3. (省略可)オーケストレーションをカスタマイズする

始める前に

環境の設定の手順に沿って環境が設定されていることを確認します。

ステップ 1. 実行可能ファイルを定義して構成する

使用するモデル バージョンを定義します。

model = "gemini-1.5-flash-001"

使用する実行可能名を定義します。

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-1.5-flash-001",
        "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 を作成します。

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 Swedish currency?", 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-1.5-flash-001': {'cost': 5.2875e-06,
    'prompt_tokens': 34,
    'completion_tokens': 62,
    'total_tokens': 96}},
  'usage_excluding_cached_inference': {'total_cost': 5.2875e-06,
   'gemini-1.5-flash-001': {'cost': 5.2875e-06,
    'prompt_tokens': 34,
    'completion_tokens': 62,
    'total_tokens': 96}}},
 'human_input': []}

(省略可)高度なカスタマイズ

AG2Agent テンプレートは、 Google Cloudで利用可能なすべての基盤モデルにアクセスできるため、デフォルトで api_type=="google" を使用します。api_type=="google" で使用できないモデルを使用するには、llm_config パラメータをカスタマイズします。

AG2 でサポートされているモデルとその機能の一覧については、モデル プロバイダをご覧ください。llm_config= でサポートされる値のセットはチャットモデルごとに異なります。詳細については、それぞれのドキュメントをご覧ください。

Gemini

デフォルトでインストールされています。

llm_config 引数を省略すると、AG2Agent テンプレートで使用されます。次に例を示します。

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 テンプレートで使用します。

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-1.5-flash-001",  # Required.
        "api_type": "openai",                    # Required.
        "base_url": base_url,                    # Required.
        "api_key": creds.token,                  # Required.
    }]
}

最後に、次のコードを使用して AG2Agent テンプレートで使用します。

agent = agent_engines.AG2Agent(
    model="google/gemini-1.5-flash-001",  # 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= 引数のリストにツールを追加します。

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-1.5-flash-001': {'cost': 0.0002790625,
    'prompt_tokens': 757,
    'completion_tokens': 34,
    'total_tokens': 791}},
  'usage_excluding_cached_inference': {'total_cost': 0.0002790625,
   'gemini-1.5-flash-001': {'cost': 0.0002790625,
    'prompt_tokens': 757,
    'completion_tokens': 34,
    'total_tokens': 791}}},
 'human_input': []}

ステップ 3. オーケストレーションをカスタマイズする

すべての AG2 エージェントは、オーケストレーション用の入力スキーマと出力スキーマを提供する ConversableAgent インターフェースを実装します。AG2Agent では、クエリに応答するために実行可能ファイルをビルドする必要があります。デフォルトでは、AG2Agentモデルをツールにバインドして、このような実行可能ファイルをビルドします。

次のいずれかを行う場合は、オーケストレーションをカスタマイズすることを検討してください。i)モデルを使用してタスクを解決するアシスタント エージェントを実装する。ii)コードを実行して他のエージェントにフィードバックを提供するユーザー プロキシ エージェントを実装する。iii)モデルと思考のツリーによる推論でタスクを解決する推論エージェントを実装する。そのためには、AG2Agent を作成するときに、次の署名を持つ Python 関数を使用して runnable_builder= 引数を指定し、デフォルトの実行可能ファイルをオーバーライドする必要があります。


def runnable_builder(
    **runnable_kwargs,
):

これにより、オーケストレーション ロジックをカスタマイズするためのさまざまなオプションが提供されます。

アシスタント エージェント

最も簡単なケースで、オーケストレーションなしでアシスタント エージェントを作成するには、AG2Agentrunnable_builder をオーバーライドします。

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,
)

ユーザー プロキシ エージェント

最も簡単なケースで、オーケストレーションなしでアシスタント エージェントを作成するには、AG2Agentrunnable_builder をオーバーライドします。

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,
)

Reasoning Agent

最も簡単なケースで、オーケストレーションなしで推論エージェントを作成するには、AG2Agentrunnable_builder をオーバーライドします。

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,
)

次のステップ