车讯:新款杰德/金杯蒂阿兹等 一周新车早知道

百度 加快推进单行税法的立法工作,力争年内完成契税法、资源税法、消费税法、印花税法等草案的起草工作。

无论代理是本地运行还是远程部署,查询代理的代码都相同。因此,在本页中,术语 agent 可互换地指代 local_agentremote_agent。由于不同框架支持的操作集各不相同,因此我们针对特定于框架的模板提供了使用说明:

框架 说明
智能体开发套件(预览版) 根据 Google 内部最佳实践设计,适合构建 AI 应用的开发者或需要快速开发原型并部署基于代理的强大解决方案的团队。
LangChain 由于具有预定义的配置和抽象,因此对于基本使用场景,使用起来更简单。
LangGraph 基于图的方法来定义工作流,具有先进的人机协同和回放/重放功能。
AG2(以前称为 AutoGen) AG2 提供多智能体对话框架,作为构建 LLM 工作流的高级抽象。
LlamaIndex(预览版) LlamaIndex 的查询流水线提供了一个高级接口,用于创建检索增强生成 (RAG) 工作流。

对于并非基于任何框架专用模板的自定义代理,您可以按照以下步骤操作:

  1. 用户身份验证
  2. 获取代理实例
  3. 查找支持的操作
  4. 向代理提出问题
  5. (如果适用)从代理流式传输响应

第 1 步:用户身份验证

遵循与设置环境相同的说明。

第 2 步:获取代理的实例

如需查询代理,您首先需要代理的实例。您可以创建新实例,也可以获取现有实例

如需获取与特定资源 ID 对应的代理,请执行以下操作:

Python 版 Vertex AI SDK

运行以下代码:

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"http://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" \
http://LOCATION-aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/reasoningEngines/RESOURCE_ID

本部分的其余内容假设您有一个名为 agent 的实例。

第 3 步:支持的操作

在本地开发代理时,您可以访问并了解其支持的操作。如需使用已部署的代理,您可以枚举其支持的操作:

Python 版 Vertex AI SDK

运行以下代码:

agent.operation_schemas()

请求

运行以下代码:

import json

json.loads(response.content).get("spec").get("classMethods")

REST

spec.class_methods 形式表示,来自对 curl 请求的响应。

每项操作的架构都是一个字典,用于记录您可以调用的代理方法的相关信息。以下是同步操作的操作架构示例:

以下命令提供了 JSON 格式的架构列表,这些架构与 remote_app 对象的操作相对应:

agent.operation_schemas()

例如,以下是 LangchainAgentquery 操作的架构:

{'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 的操作,nameagent.query)。
  • api_mode 是操作的 API 模式("" 表示同步,"stream" 表示流式传输)。
  • description 是根据方法的文档字符串对操作进行的说明。
  • parameters 是输入实参的架构,采用 OpenAPI 架构格式。

第 4 步:向代理提问

如需使用代理支持的某项操作(例如 query)查询代理,请执行以下操作:

Python 版 Vertex AI SDK

agent.query(input="What is the exchange rate from US dollars to Swedish Krona today?")

请求

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"http://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({
        "class_method": "query",
        "input": {
            "input": "What is the exchange rate from US dollars to Swedish Krona today?"
        }
    })
)

REST

curl \
-H "Authorization: Bearer $(gcloud auth print-access-token)" \
-H "Content-Type: application/json" \
http://LOCATION-aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/reasoningEngines/RESOURCE_ID:query -d '{
  "class_method": "query",
  "input": {
    "input": "What is the exchange rate from US dollars to Swedish Krona today?"
  }
}'

查询响应是一个字符串,类似于本地应用测试的输出:

{"input": "What is the exchange rate from US dollars to Swedish Krona today?",
 # ...
 "output": "For 1 US dollar you will get 10.7345 Swedish Krona."}

第 5 步:从代理流式传输回答

如果适用,您可以使用代理的某项操作(例如 stream_query)来从代理流式传输响应:

Python 版 Vertex AI SDK

agent = agent_engines.get("projects/PROJECT_ID/locations/LOCATION/reasoningEngines/RESOURCE_ID")

for response in agent.stream_query(
    input="What is the exchange rate from US dollars to Swedish Krona today?"
):
    print(response)

请求

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"http://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({
        "class_method": "stream_query",
        "input": {
            "input": "What is the exchange rate from US dollars to Swedish Krona today?"
        },
    }),
    stream=True,
)

REST

curl \
-H "Authorization: Bearer $(gcloud auth print-access-token)" \
-H "Content-Type: application/json" \
http://LOCATION-aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/reasoningEngines/RESOURCE_ID:streamQuery?alt=sse -d '{
  "class_method": "stream_query",
  "input": {
    "input": "What is the exchange rate from US dollars to Swedish Krona today?"
  }
}'

Vertex AI Agent Engine 会以迭代生成的一系列对象的形式流式传输回答。例如,一组包含三条回答的响应可能如下所示:

{'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 2025-08-04.'}  # final response

第 6 步:异步查询代理

如果您在开发智能体时定义了 async_query 操作,则 Vertex AI SDK for Python 支持对智能体进行客户端异步查询。

Python 版 Vertex AI SDK

agent = agent_engines.get("projects/PROJECT_ID/locations/LOCATION/reasoningEngines/RESOURCE_ID")

response = await agent.async_query(
    input="What is the exchange rate from US dollars to Swedish Krona today?"
)
print(response)

查询响应是一个字典,与本地测试的输出相同:

{"input": "What is the exchange rate from US dollars to Swedish Krona today?",
 # ...
 "output": "For 1 US dollar you will get 10.7345 Swedish Krona."}

第 7 步:异步流式传输来自代理的回答

如果您在开发代理时定义了 async_stream_query 操作,则可以使用代理的某个操作(例如 async_stream_query)异步流式传输来自代理的响应:

Python 版 Vertex AI SDK

agent = agent_engines.get("projects/PROJECT_ID/locations/LOCATION/reasoningEngines/RESOURCE_ID")

async for response in agent.async_stream_query(
    input="What is the exchange rate from US dollars to Swedish Krona today?"
):
    print(response)

async_stream_query 操作在后台调用相同的 streamQuery 端点,并以迭代生成的一系列对象的形式异步流式传输响应。例如,一组包含三条回答的响应可能如下所示:

{'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 2025-08-04.'}  # final response

响应应与本地测试期间生成的响应相同。

后续步骤