エージェントをクエリするコードは、エージェントがローカルで実行されているか、リモートでデプロイされているかに関係なく同じです。したがって、このページでは、agent
という用語は local_agent
または remote_agent
のいずれかを区別なく指します。サポートされるオペレーションのセットはフレームワークによって異なるため、フレームワーク固有のテンプレートを使用する手順を以下に示します。
フレームワーク | 説明 |
---|---|
LangChain | 事前定義された構成と抽象化により、基本的なユースケースで使いやすくなっています。 |
LangGraph | ワークフローを定義するためのグラフベースのアプローチ。高度な人間参加型機能と巻き戻し/再生機能を備えています。 |
AG2(旧 AutoGen) | AG2 は、LLM ワークフローを構築するための高レベルの抽象化として、マルチエージェント会話フレームワークを提供します。 |
フレームワーク固有のテンプレートのいずれにも基づいていないカスタム エージェントの場合は、次の手順を行います。
- ユーザー認証。
- エージェント インスタンスを取得する。
- サポートされているオペレーションを検索する。
- エージェントにクエリを実行する。
- (該当する場合)エージェントからの回答をストリーミングします。
ステップ 1: ユーザー認証
環境の設定と同じ手順に沿って操作します。
ステップ 2: エージェントのインスタンスを取得する
エージェントをクエリするには、まずエージェントのインスタンスが必要です。エージェントの新しいインスタンスを作成するか、既存のインスタンスを取得します。
特定のリソース ID に対応するエージェントを取得するには:
Vertex AI SDK for Python
次のコードを実行します。
from vertexai import agent_engines
agent = agent_engines.get(RESOURCE_ID)
または、エージェントの完全なリソース名を指定することもできます。
agent = agent_engines.get("projects/PROJECT_ID/locations/LOCATION/reasoningEngines/RESOURCE_ID")
リクエスト
次のコードを実行します。
from google import auth as google_auth
from google.auth.transport import requests as google_requests
import requests
def get_identity_token():
credentials, _ = google_auth.default()
auth_request = google_requests.Request()
credentials.refresh(auth_request)
return credentials.token
response = requests.get(
f"https://LOCATION-aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/reasoningEngines/RESOURCE_ID",
headers={
"Content-Type": "application/json; charset=utf-8",
"Authorization": f"Bearer {get_identity_token()}",
},
)
REST
curl \
-H "Authorization: Bearer $(gcloud auth print-access-token)" \
-H "Content-Type: application/json" \
https://LOCATION-aiplatform.googleapis.com/v1beta1/projects/PROJECT_ID/locations/LOCATION/reasoningEngines/RESOURCE_ID
このセクションの残りの部分では、agent
という名前のインスタンスがあることを前提としています。
ステップ 3: サポートされているオペレーション
エージェントをローカルで開発する場合は、エージェントがサポートするオペレーションにアクセスして知識を得ることができます。デプロイされたエージェントを使用するには、エージェントがサポートするオペレーションを列挙します。
Vertex AI SDK for Python
次のコードを実行します。
agent.operation_schemas()
リクエスト
次のコードを実行します。
import json
json.loads(response.content).get("spec").get("classMethods")
REST
curl リクエストのレスポンスから spec.class_methods
で表されます。
各オペレーションのスキーマは、呼び出せるエージェントのメソッドに関する情報を記述するディクショナリです。同期オペレーションのオペレーション スキーマの例を次に示します。
次のコマンドは、remote_app
オブジェクトのオペレーションに対応するスキーマのリストを JSON 形式で提供します。
agent.operation_schemas()
たとえば、LangchainAgent
の query
オペレーションのスキーマは次のとおりです。
{'api_mode': '',
'name': 'query',
'description': """Queries the Agent with the given input and config.
Args:
input (Union[str, Mapping[str, Any]]):
Required. The input to be passed to the Agent.
config (langchain_core.runnables.RunnableConfig):
Optional. The config (if any) to be used for invoking the Agent.
Returns:
The output of querying the Agent with the given input and config.
""", ' ',
'parameters': {'$defs': {'RunnableConfig': {'description': 'Configuration for a Runnable.',
'properties': {'configurable': {...},
'run_id': {...},
'run_name': {...},
...},
'type': 'object'}},
'properties': {'config': {'nullable': True},
'input': {'anyOf': [{'type': 'string'}, {'type': 'object'}]}},
'required': ['input'],
'type': 'object'}}
ここで
name
はオペレーションの名前です(query
という名前のオペレーションの場合はagent.query
です)。api_mode
はオペレーションの API モードです(同期の場合は""
、ストリーミングの場合は"stream"
)。description
は、メソッドのドキュメントに基づくオペレーションの説明です。parameters
は、OpenAPI スキーマ形式の入力引数のスキーマです。
ステップ 4: エージェントに問い合わせる
サポートされているオペレーション(query
など)を使用してエージェントにクエリを実行するには:
Vertex AI SDK for Python
agent.query(input={"messages": [
("user", "What is the exchange rate from US dollars to Swedish currency?")
]})
リクエスト
from google import auth as google_auth
from google.auth.transport import requests as google_requests
import requests
def get_identity_token():
credentials, _ = google_auth.default()
auth_request = google_requests.Request()
credentials.refresh(auth_request)
return credentials.token
requests.post(
f"https://{LOCATION}-aiplatform.googleapis.com/v1/projects/{PROJECT_ID}/locations/{LOCATION}/reasoningEngines/{RESOURCE_ID}:query",
headers={
"Content-Type": "application/json; charset=utf-8",
"Authorization": f"Bearer {get_identity_token()}",
},
data=json.dumps({"input": {
"input": {"messages": [
("user", "What is the exchange rate from US dollars to Swedish currency?")
]},
}})
)
REST
curl \
-H "Authorization: Bearer $(gcloud auth print-access-token)" \
-H "Content-Type: application/json" \
https://us-central1-aiplatform.googleapis.com/v1beta1/projects/PROJECT_ID/locations/LOCATION/reasoningEngines/RESOURCE_ID:query -d '{
"input": {
"input": {"messages": [
("user", "What is the exchange rate from US dollars to Swedish currency?")
]},
}
}'
クエリのレスポンスは、ローカル アプリケーション テストの出力に似た文字列になります。
{"input": "What is the exchange rate from US dollars to Swedish currency?",
# ...
"output": "For 1 US dollar you will get 10.7345 Swedish Krona."}
ステップ 5: エージェントからのレスポンスをストリーミングする
必要に応じて、エージェントのいずれかのオペレーション(stream_query
など)を使用して、エージェントからのレスポンスをストリーミングできます。
Vertex AI SDK for Python
agent = agent_engines.get("projects/PROJECT_ID/locations/LOCATION/reasoningEngines/RESOURCE_ID")
agent.stream_query(input={"messages": [
("user", "What is the exchange rate from US dollars to Swedish currency?")
]})
リクエスト
from google import auth as google_auth
from google.auth.transport import requests as google_requests
import requests
def get_identity_token():
credentials, _ = google_auth.default()
auth_request = google_requests.Request()
credentials.refresh(auth_request)
return credentials.token
requests.post(
f"https://{LOCATION}-aiplatform.googleapis.com/v1/projects/{PROJECT_ID}/locations/{LOCATION}/reasoningEngines/{RESOURCE_ID}:streamQuery",
headers={
"Content-Type": "application/json",
"Authorization": f"Bearer {get_identity_token()}",
},
data=json.dumps({"input": {
"input": {"messages": [
("user", "What is the exchange rate from US dollars to Swedish currency?")
]},
}}),
stream=True,
)
REST
curl \
-H "Authorization: Bearer $(gcloud auth print-access-token)" \
-H "Content-Type: application/json" \
https://us-central1-aiplatform.googleapis.com/v1beta1/projects/PROJECT_ID/locations/LOCATION/reasoningEngines/RESOURCE_ID:streamQuery?alt=sse -d '{
"input": {
"input": {"messages": [
("user", "What is the exchange rate from US dollars to Swedish currency?")
]},
}
}'
Agent Engine は、反復的に生成されたオブジェクトのシーケンスとしてレスポンスをストリーミングします。たとえば、3 つのレスポンスのセットは次のようになります。
{'actions': [{'tool': 'get_exchange_rate', ...}]} # first response
{'steps': [{'action': {'tool': 'get_exchange_rate', ...}}]} # second response
{'output': 'The exchange rate is 11.0117 SEK per USD as of 2024-12-03.'} # final response