6. 与服务器交互

Helloworld A2A 服务端运行起来之后,我们向它发送一些请求。

Helloworld 测试客户端

test_client.py 脚本演示了如何:

  1. 从服务端获取 Agent Card;
  2. 用 create_client 创建客户端;
  3. 发送非流式(SendMessage)与流式(SendStreamingMessage)请求。

打开一个新的终端窗口,先进入你已有的 a2a-samples 检出根目录(包含 samples/ 和 .venv/ 的那一层),再在那里激活同一个虚拟环境:

cd /path/to/a2a-samples
source .venv/bin/activate
cd C:\path\to\a2a-samples
./.venv/Scripts/Activate.ps1

如果 PowerShell 拦截了激活脚本,直接调用这个环境里的 Python:./.venv/Scripts/python.exe samples/python/agents/helloworld/test_client.py。

运行测试客户端:

# from the a2a-samples directory
python samples/python/agents/helloworld/test_client.py

脚本的入口 main() 会开启一个交互会话,提示符为 user >:输入一句话就会向服务端发送一次非流式请求并打印响应,输入 exit 退出。文件中的 test_client_workflow 是一个 pytest 用例,会依次演示获取 Agent Card、非流式调用、流式调用和获取扩展 Agent Card 四个环节,并通过 fixture 自动启动服务端。

第一次交互长什么样

让上一步的服务器保持运行,按上面的方式启动客户端,输入 hello,再输入 exit。下面是固定提交加钉定版本下 hello 的真实响应(任务与消息 ID 每次都不同,此处截取关键字段):

Initializing a non-streaming client.
Response:
task {
  id: "f71502f1-…"
  context_id: "91c4377e-…"
  status {
    state: TASK_STATE_COMPLETED
    message {
      role: ROLE_AGENT
      parts { text: "Request is completed!" }
    }
  }
  artifacts {
    parts { text: "Hello, World! I have received your request (hello)" }
  }
  history {
    role: ROLE_USER
    parts { text: "hello" }
  }
  history {
    role: ROLE_AGENT
    parts { text: "Processing request..." }
  }
}

按协议的术语,这段输出里有四处值得核对:

  • 任务已完成:status.state 是 TASK_STATE_COMPLETED;
  • 是智能体在说话:输出中智能体消息的角色是 ROLE_AGENT,与 history 里的用户消息(ROLE_USER)相区别;
  • 结果是一个产出物(artifact):Hello, World! I have received your request (hello)——helloworld 执行器对你的输入生成的回显文本;
  • 状态消息不是产出物:Processing request...(history 中的中间状态消息)与 Request is completed!(最终状态消息)描述任务的进度,你要展示给用户的内容是 artifact。

交互会话是非流式的:每输入一行,得到一个最终的 Task。结束时输入 exit 退出客户端,再在服务器终端按 Ctrl+C 停止 __main__.py——两者都是正常退出。流式调用(SendStreamingMessage)由 pytest 工作流演练,交互会话不涉及:在手动服务器已停止后,于检出根目录运行 pytest samples/python/agents/helloworld/test_client.py(fixture 会自己启动服务器);在钉定版本下输出 1 passed。

理解客户端代码

来看 test_client.py 的几个关键部分。

1. 获取 Agent Card

import httpx

from a2a.client import A2ACardResolver

# Initializes the A2ACardResolver instance with an HTTP client, base URL,
# and uses the default path for the agent card.
async with httpx.AsyncClient() as httpx_client:
    resolver = A2ACardResolver(
        httpx_client=httpx_client,
        base_url='http://127.0.0.1:9999',
        # Provide agent_card_path, if your agent uses a different path
        # agent_card_path=''
    )
    public_agent_card = await resolver.get_agent_card()

A2ACardResolver 是一个便利类。调用 get_agent_card() 时,它会根据提供的基础 URL,从服务端的 /.well-known/agent-card.json 端点获取 AgentCard,随后用它来初始化客户端。

2. 初始化客户端并发送非流式消息

from a2a.client import ClientConfig, create_client
from a2a.helpers import new_text_message
from a2a.types import Role, SendMessageRequest

print('\nInitializing a non-streaming client.')
config = ClientConfig(streaming=False)
client = await create_client(agent=public_agent_card, client_config=config)

# Creates a new text message to be sent to the A2A Server.
# Ex: text_query = 'Why is the sky blue?'
message = new_text_message(text_query, role=Role.ROLE_USER)
request = SendMessageRequest(message=message)

print('Response:')
async for chunk in client.send_message(request):
    print(chunk)
  • create_client 函数根据 AgentCard 提供的信息与 ClientConfig 创建一个 Client;
  • 用 new_text_message 辅助函数构造 Message(传入 role=Role.ROLE_USER),再包装进 SendMessageRequest;
  • 客户端的 send_message 方法返回一个异步迭代器,它会产出智能体的最终 Task 或 Message 响应。在本例中是一个 Task。

3. 初始化客户端并发送流式消息

print('\nInitializing a streaming client.')
client_config = ClientConfig(streaming=True)  # Streaming
client = await create_client(agent=public_agent_card, client_config=client_config)

print('Response:')
async for chunk in client.send_message(request):
    print(chunk)
  • 通过在 ClientConfig 中设置 streaming=True,用 create_client 创建一个独立的流式客户端;
  • 再次调用 send_message,此时它会以流的方式产出事件:循环的每一次迭代都打印一个随网络到达的数据块;
  • 循环结束后调用 await client.close() 释放底层的 HTTP 连接。

预期的输出

每类输出来自哪里很关键——两个入口,两种输出。结合 Helloworld 执行器的逻辑:

交互会话里(test_client.py,非流式——即上面的实录):

  • 公开 Agent Card:以格式化摘要展示 Hello World Agent 的基本信息、接口、能力、输入输出模式和技能;
  • 非流式响应:单个以 protobuf 文本格式打印的 Task,其状态为 TASK_STATE_COMPLETED,最终状态消息为 “Request is completed!”,包含一个带有问候文本的产出物,历史中有用户消息和智能体的中间状态消息 “Processing request…”。

只在 pytest 工作流里(test_client_workflow;交互会话不会输出这两项):

  • 流式响应:依次到达的数据块——初始的 task(状态为 TASK_STATE_SUBMITTED)、状态为 TASK_STATE_WORKING 的 status_update、带有结果的 artifact_update,以及状态为 TASK_STATE_COMPLETED 的最终 status_update;
  • 扩展 Agent Card:在公开卡片的基础上多出 echo_bot_super_mode 技能(通过 GetExtendedAgentCard 获取)。

输出中的 id 字段每次运行都会不同。看到上述结果,说明服务端已经能正确处理基础的 A2A 交互。

下一步

Helloworld 演示了 A2A 的基本机制。接下来通过 LangGraph 示例了解流式传输与多轮交互 。

来源:A2A 官方文档 · Interacting with the Server