Build and run agents you can see, understand and trust.
Python agentchatbotlarge-language-modelsllmllm-agentmcpmulti-agentmulti-modalreact-agentrealtime-agentvoice-agentvoice-assistant
feat(a2a): support A2A protocol for inter-agent communication (#1027)
Sunriseaf6aa1389b09e
diff --git a/.github/workflows/stale.yml b/.github/workflows/stale.ymlindex a68e83eb5..9000ad0bb 100644--- a/.github/workflows/stale.yml+++ b/.github/workflows/stale.yml@@ -21,15 +21,15 @@ jobs:- uses: actions/stale@v5with:repo-token: ${{ secrets.GITHUB_TOKEN }}- stale-issue-message: 'This issue is marked as stale because there has been no activity for 21 days. Remove stale label or add new comments or this issue will be closed in 3 day.'+ stale-issue-message: 'This issue is marked as stale because there has been no activity for 60 days. Remove stale label or add new comments or this issue will be closed in 90 day.'close-issue-message: 'Close this stale issue.'stale-issue-label: 'stale-issue'exempt-issue-labels: 'RoadMap,Roadmap'- days-before-stale: 21- days-before-close: 3+ days-before-stale: 60+ days-before-close: 30- stale-pr-message: 'This PR is marked as stale because there has been no activity for 30 days. Remove stale label or add new comments or this PR will be closed in 5 day.'+ stale-pr-message: 'This PR is marked as stale because there has been no activity for 60 days. Remove stale label or add new comments or this PR will be closed in 30 days.'close-pr-message: 'Close this stale PR.'stale-pr-label: 'stale-pr'- days-before-pr-stale: 40- days-before-pr-close: 5\ No newline at end of file+ days-before-pr-stale: 60+ days-before-pr-close: 30diff --git a/README.md b/README.mdindex b054f4401..7e4c70609 100644--- a/README.md+++ b/README.md@@ -54,7 +54,8 @@</p>## 📢 News-- **[2025-12]** AgentScope supports [TTS(Text-to-Speech)](https://doc.agentscope.io/tutorial/task_tts.html) now! Check our [example]() and [tutorial](https://doc.agentscope.io/tutorial/task_tts.html) for more details.+- **[2025-12]** AgentScope supports [A2A(Agent-to-Agent) protocol](https://doc.agentscope.io/tutorial/task_a2a_protocol.html) now! Check our [example](https://github.com/agentscope-ai/agentscope/tree/main/examples/agent/a2a_agent) and [tutorial](https://doc.agentscope.io/tutorial/task_a2a_protocol.html) for more details.+- **[2025-12]** AgentScope supports [TTS(Text-to-Speech)](https://doc.agentscope.io/tutorial/task_tts.html) now! Check our [example](https://github.com/agentscope-ai/agentscope/tree/main/examples/functionality/tts) and [tutorial](https://doc.agentscope.io/tutorial/task_tts.html) for more details.- **[2025-11]** AgentScope supports [Anthropic Agent Skill](https://claude.com/blog/skills) now! Check our [example](https://github.com/agentscope-ai/agentscope/tree/main/examples/functionality/agent_skill) and [tutorial](https://doc.agentscope.io/tutorial/task_agent_skill.html) for more details.- **[2025-11]** AgentScope open-sources [Alias-Agent](https://github.com/agentscope-ai/agentscope-samples/tree/main/alias) for diverse real-world tasks and [Data-Juicer Agent](https://github.com/agentscope-ai/agentscope-samples/tree/main/data_juicer_agent) for data processing.- **[2025-11]** AgentScope supports [Agentic RL](https://github.com/agentscope-ai/agentscope/tree/main/examples/training/react_agent) via integrating [Trinity-RFT](https://github.com/modelscope/Trinity-RFT) library.@@ -88,38 +89,39 @@ Easy for beginners, powerful for experts.Quick overview of important features in **AgentScope 1.0**:-| Module | Feature | Tutorial |-|------------|------------------------------------------------------------------------------------|-------------------------------------------------------------------------|-| model | Support async invocation | [Model](https://doc.agentscope.io/tutorial/task_model.html) |-| | Support reasoning model | |-| | Support streaming/non-streaming returns | |-| tool | Support async/sync tool functions | [Tool](https://doc.agentscope.io/tutorial/task_tool.html) |-| | Support streaming/non-streaming returns | |-| | Support user interruption | |-| | Support post-processing | |-| | Support group-wise tools management | |-| | Support agentic tools management by meta tool | |-| MCP | Support streamable HTTP/SSE/StdIO transport | [MCP](https://doc.agentscope.io/tutorial/task_mcp.html) |-| | Support both **stateful** and **stateless** mode MCP Client | |-| | Support client- & function-level fine-grained control | |-| agent | Support async execution | |-| | Support parallel tool calls | |-| | Support realtime steering interruption and customized handling | |-| | Support automatic state management | |-| | Support agent-controlled long-term memory | |-| | Support agent hooks | |-| tracing | Support OpenTelemetry-based tracing in LLM, tools, agent and formatter | [Tracing](https://doc.agentscope.io/tutorial/task_tracing.html) |+| Module | Feature | Tutorial |+|------------|----------------------------------------------------------------------------------------------------------------|-------------------------------------------------------------------------|+| model | Support async invocation | [Model](https://doc.agentscope.io/tutorial/task_model.html) |+| | Support reasoning model | |+| | Support streaming/non-streaming returns | |+| tool | Support async/sync tool functions | [Tool](https://doc.agentscope.io/tutorial/task_tool.html) |+| | Support streaming/non-streaming returns | |+| | Support user interruption | |+| | Support post-processing | |+| | Support group-wise tools management | |+| | Support agentic tools management by meta tool | |+| MCP | Support streamable HTTP/SSE/StdIO transport | [MCP](https://doc.agentscope.io/tutorial/task_mcp.html) |+| | Support both **stateful** and **stateless** mode MCP Client | |+| | Support client- & function-level fine-grained control | |+| agent | Support async execution | |+| | Support parallel tool calls | |+| | Support realtime steering interruption and customized handling | |+| | Support automatic state management | |+| | Support agent-controlled long-term memory | |+| | Support agent hooks | |+| tracing | Support OpenTelemetry-based tracing in LLM, tools, agent and formatter | [Tracing](https://doc.agentscope.io/tutorial/task_tracing.html) || | Support connecting to third-party tracing platforms (e.g. Alibaba Cloud CloudMonitor, Arize-Phoenix, Langfuse) | |-| memory | Support long-term memory | [Memory](https://doc.agentscope.io/tutorial/task_long_term_memory.html) |-| session | Provide session/application-level automatic state management | [Session](https://doc.agentscope.io/tutorial/task_state.html) |-| evaluation | Provide distributed and parallel evaluation | [Evaluation](https://doc.agentscope.io/tutorial/task_eval.html) |-| formatter | Support multi-agent prompt formatting with tools API | [Prompt Formatter](https://doc.agentscope.io/tutorial/task_prompt.html) |-| | Support truncation-based formatter strategy | |-| plan | Support ReAct-based long-term planning | [Plan](https://doc.agentscope.io/tutorial/task_plan.html) |-| | Support manual plan specification | |-| RAG | Support agentic RAG | [RAG](https://doc.agentscope.io/tutorial/task_rag.html) |-| | Support multimodal RAG | |-| ... | | |+| memory | Support long-term memory | [Memory](https://doc.agentscope.io/tutorial/task_long_term_memory.html) |+| session | Provide session/application-level automatic state management | [Session](https://doc.agentscope.io/tutorial/task_state.html) |+| evaluation | Provide distributed and parallel evaluation | [Evaluation](https://doc.agentscope.io/tutorial/task_eval.html) |+| formatter | Support multi-agent prompt formatting with tools API | [Prompt Formatter](https://doc.agentscope.io/tutorial/task_prompt.html) |+| | Support truncation-based formatter strategy | |+| plan | Support ReAct-based long-term planning | [Plan](https://doc.agentscope.io/tutorial/task_plan.html) |+| | Support manual plan specification | |+| RAG | Support agentic RAG | [RAG](https://doc.agentscope.io/tutorial/task_rag.html) |+| | Support multimodal RAG | |+| A2A | Support A2A agent | [A2A](https://doc.agentscope.io/tutorial/task_a2a.html) |+| ... | | |## 💬 Contact@@ -398,6 +400,7 @@ as_studio- [Deep Research Agent](https://github.com/agentscope-ai/agentscope/tree/main/examples/agent/deep_research_agent)- [Browser-use Agent](https://github.com/agentscope-ai/agentscope/tree/main/examples/agent/browser_agent)- [Meta Planner Agent](https://github.com/agentscope-ai/agentscope/tree/main/examples/agent/meta_planner_agent)+ - [A2A Agent](https://github.com/agentscope-ai/agentscope/tree/main/examples/agent/a2a_agent)- Game- [Nine-player Werewolves](https://github.com/agentscope-ai/agentscope/tree/main/examples/game/werewolves)- Workflowdiff --git a/README_zh.md b/README_zh.mdindex 721965378..c9b4f0239 100644--- a/README_zh.md+++ b/README_zh.md@@ -54,6 +54,7 @@</p>## 📢 新闻+- **[2025-12]** AgentScope 已支持 [A2A(Agent-to-Agent) 通信协议](https://doc.agentscope.io/tutorial/task_a2a_protocol.html)!查看 [样例](https://github.com/agentscope-ai/agentscope/tree/main/examples/agent/a2a_agent) 和 [教程](https://doc.agentscope.io/zh_CN/tutorial/task_a2a_protocol.html) 了解更多详情。- **[2025-12]** AgentScope 已支持 [TTS(Text-to-Speech) 模型](https://doc.agentscope.io/zh_CN/tutorial/task_tts.html) !欢迎查看 [样例]() 和 [教程](https://doc.agentscope.io/zh_CN/tutorial/task_tts.html) 了解更多详情。- **[2025-11]** AgentScope 已支持 [Anthropic Agent Skill](https://claude.com/blog/skills) !欢迎查看 [样例](https://github.com/agentscope-ai/agentscope/tree/main/examples/functionality/agent_skill) 和 [教程](https://doc.agentscope.io/zh_CN/tutorial/task_agent_skill.html) 了解更多详情。- **[2025-11]** AgentScope 开源 [Alias-Agent](https://github.com/agentscope-ai/agentscope-samples/tree/main/alias) 用于处理多样化的真实任务,以及 [Data-Juicer Agent](https://github.com/agentscope-ai/agentscope-samples/tree/main/data_juicer_agent) 用于自然语言驱动的数据处理。@@ -88,39 +89,40 @@AgentScope v1.0 新功能概览:-| 模块 | 功能 | 文档 |-|------------|----------------------------------------|-------------------------------------------------------------------------------|-| model | 支持异步调用 | [Model](https://doc.agentscope.io/zh_CN/tutorial/task_model.html) |-| | 支持推理模型 | |-| | 支持流式/非流式返回 | |-| | 支持工具API | |-| tool | 支持异步/同步工具函数 | [Tool](https://doc.agentscope.io/zh_CN/tutorial/task_tool.html) |-| | 支持工具函数流式/非流式返回 | |-| | 支持用户打断 | |-| | 支持工具函数的后处理 | |-| | 支持分组工具管理 | |-| | 支持智能体通过 Meta Tool 自主管理工具 | |-| MCP | 支持 Streamable HTTP/SSE/StdIO 传输 | [MCP](https://doc.agentscope.io/zh_CN/tutorial/task_mcp.html) |-| | 支持**有状态**和**无状态**两种模式的MCP客户端 | |-| | 支持客户端和函数级别的精细控制 | |-| agent | 支持异步执行 | |-| | 支持并行工具调用 | |-| | 支持用户实时介入和自定义的中断处理 | |-| | 支持自动状态管理 | |-| | 允许智能体自主控制长期记忆 | |-| | 支持智能体钩子函数 | |-| tracing | 支持基于 OpenTelemetry 的 LLM、工具、智能体和格式化器追踪 | [Tracing](https://doc.agentscope.io/zh_CN/tutorial/task_tracing.html) |-| | 支持连接到第三方追踪平台(如阿里云云监控、Arize-Phoenix、Langfuse) | |-| memory | 支持长期记忆 | [Memory](https://doc.agentscope.io/zh_CN/tutorial/task_long_term_memory.html) |-| session | 提供会话/应用级状态管理 | [Session](https://doc.agentscope.io/zh_CN/tutorial/task_state.html) |-| evaluation | 提供分布式和并行评估 | [Evaluation](https://doc.agentscope.io/zh_CN/tutorial/task_eval.html) |-| formatter | 支持多Agent提示格式化与工具API | [Prompt Formatter](https://doc.agentscope.io/zh_CN/tutorial/task_prompt.html) |-| | 支持基于截断的格式化策略 | |-| plan | 支持任务分解和计划制定 | [Plan](https://doc.agentscope.io/zh_CN/tutorial/task_plan.html) |-| | 支持开发者手动设定计划 | |-| RAG | 支持 agentic RAG | [RAG](https://doc.agentscope.io/tutorial/task_rag.html) |-| | 支持多模态 RAG | |-| ... | | |+| 模块 | 功能 | 文档 |+|------------|----------------------------------------------|-------------------------------------------------------------------------------|+| model | 支持异步调用 | [Model](https://doc.agentscope.io/zh_CN/tutorial/task_model.html) |+| | 支持推理模型 | |+| | 支持流式/非流式返回 | |+| | 支持工具API | |+| tool | 支持异步/同步工具函数 | [Tool](https://doc.agentscope.io/zh_CN/tutorial/task_tool.html) |+| | 支持工具函数流式/非流式返回 | |+| | 支持用户打断 | |+| | 支持工具函数的后处理 | |+| | 支持分组工具管理 | |+| | 支持智能体通过 Meta Tool 自主管理工具 | |+| MCP | 支持 Streamable HTTP/SSE/StdIO 传输 | [MCP](https://doc.agentscope.io/zh_CN/tutorial/task_mcp.html) |+| | 支持**有状态**和**无状态**两种模式的MCP客户端 | |+| | 支持客户端和函数级别的精细控制 | |+| agent | 支持异步执行 | |+| | 支持并行工具调用 | |+| | 支持用户实时介入和自定义的中断处理 | |+| | 支持自动状态管理 | |+| | 允许智能体自主控制长期记忆 | |+| | 支持智能体钩子函数 | |+| tracing | 支持基于 OpenTelemetry 的 LLM、工具、智能体和格式化器追踪 | [Tracing](https://doc.agentscope.io/zh_CN/tutorial/task_tracing.html) |+| | 支持连接到第三方追踪平台(如阿里云云监控、Arize-Phoenix、Langfuse) | |+| memory | 支持长期记忆 | [Memory](https://doc.agentscope.io/zh_CN/tutorial/task_long_term_memory.html) |+| session | 提供会话/应用级状态管理 | [Session](https://doc.agentscope.io/zh_CN/tutorial/task_state.html) |+| evaluation | 提供分布式和并行评估 | [Evaluation](https://doc.agentscope.io/zh_CN/tutorial/task_eval.html) |+| formatter | 支持多Agent提示格式化与工具API | [Prompt Formatter](https://doc.agentscope.io/zh_CN/tutorial/task_prompt.html) |+| | 支持基于截断的格式化策略 | |+| plan | 支持任务分解和计划制定 | [Plan](https://doc.agentscope.io/zh_CN/tutorial/task_plan.html) |+| | 支持开发者手动设定计划 | |+| RAG | 支持 agentic RAG | [RAG](https://doc.agentscope.io/tutorial/task_rag.html) |+| | 支持多模态 RAG | |+| A2A | 支持 A2A 智能体 | [A2A](https://doc.agentscope.io/tutorial/task_a2a.html) |+| ... | | |## 💬 联系我们@@ -399,6 +401,7 @@ as_studio- [Deep Research 智能体](https://github.com/agentscope-ai/agentscope/tree/main/examples/agent/deep_research_agent)- [Browser-use 智能体](https://github.com/agentscope-ai/agentscope/tree/main/examples/agent/browser_agent)- [Meta Planner 智能体](https://github.com/agentscope-ai/agentscope/tree/main/examples/agent/meta_planner_agent)+ - [A2A 智能体](https://github.com/agentscope-ai/agentscope/tree/main/examples/agent/a2a_agent)- 游戏- [九人制狼人杀](https://github.com/agentscope-ai/agentscope/tree/main/examples/game/werewolves)- 工作流diff --git a/docs/tutorial/en/index.rst b/docs/tutorial/en/index.rstindex e5ecb2684..cab201aba 100644--- a/docs/tutorial/en/index.rst+++ b/docs/tutorial/en/index.rst@@ -56,6 +56,7 @@ Welcome to AgentScope's documentation!tutorial/task_agenttutorial/task_statetutorial/task_hook+ tutorial/task_a2a.. toctree:::maxdepth: 1diff --git a/docs/tutorial/en/src/task_a2a.py b/docs/tutorial/en/src/task_a2a.pynew file mode 100644index 000000000..c46ec0e8a--- /dev/null+++ b/docs/tutorial/en/src/task_a2a.py@@ -0,0 +1,212 @@+# -*- coding: utf-8 -*-+"""+.. _a2a:++A2A Agent+============================++A2A (Agent-to-Agent) is an open standard protocol for enabling interoperable communication between different AI agents.++AgentScope provides support for the A2A protocol at two levels: obtaining Agent Card information and connecting to remote agents. The related APIs are as follows:++.. list-table:: A2A Related Classes+ :header-rows: 1++ * - Class+ - Description+ * - ``A2AAgent``+ - Agent class for communicating with remote A2A agents+ * - ``A2AChatFormatter``+ - Formatter for converting between AgentScope messages and A2A message/task formats+ * - ``AgentCardResolverBase``+ - Base class for Agent Card resolvers+ * - ``FileAgentCardResolver``+ - Resolver for loading Agent Cards from local JSON files+ * - ``WellKnownAgentCardResolver``+ - Resolver for fetching Agent Cards from the well-known path of a URL+ * - ``NacosAgentCardResolver``+ - Resolver for fetching Agent Cards from the Nacos Agent Registry++This section demonstrates how to create an ``A2AAgent`` and communicate with remote A2A agents.++.. note:: Note that A2A support is an **experimental feature** and may change in future versions. Due to limitations of the A2A protocol itself, ``A2AAgent`` cannot fully align with local agents like ``ReActAgent``, including:++ - Only supports chatbot scenarios, i.e., only supports conversations between one user and one agent (does not affect handoff/router usage patterns)+ - Does not support real-time interruption during conversations+ - Does not support agentic structured output+ - In the current implementation, messages received by the ``observe`` method are stored locally and sent to the remote agent together when the ``reply`` method is called. Therefore, if several ``observe`` calls are made without a subsequent ``reply`` call, those messages will not be seen by the remote agent+++"""++from a2a.types import AgentCard, AgentCapabilities+from v2.nacos import ClientConfig++from agentscope.a2a import WellKnownAgentCardResolver, NacosAgentCardResolver+from agentscope.agent import A2AAgent, UserAgent+from agentscope.message import Msg, TextBlock+from agentscope.tool import ToolResponse++# %%+# Obtaining Agent Cards+# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~+#+# First, we need to obtain an Agent Card to connect to the corresponding agent. An Agent Card contains information such as the agent's name, description, capabilities, and connection details.+#+# Manually Creating Agent Card+# --------------------------------+#+# If you know all the information of an Agent Card, you can directly create an Agent Card object from `a2a.types.AgentCard`.+#++# Create an Agent Card object+agent_card = AgentCard(+ name="Friday", # Agent name+ description="A fun chatting companion", # Agent description+ url="http://localhost:8000", # Agent's RPC service URL+ version="1.0.0", # Agent version+ capabilities=AgentCapabilities( # Agent capability configuration+ push_notifications=False,+ state_transition_history=True,+ streaming=True,+ ),+ default_input_modes=["text/plain"], # Supported input formats+ default_output_modes=["text/plain"], # Supported output formats+ skills=[], # Agent skill list+)++# %%+#+# Fetching from Remote Services+# --------------------------------+# AgentScope also supports fetching from the standard path of remote services (well-known server).+# Here's an example using ``WellKnownAgentCardResolver`` to fetch an Agent Card from the standard path of a remote service:+#+++async def agent_card_from_well_known_website() -> AgentCard:+ """Example of fetching an Agent Card from the well-known path of a remote service."""+ # Create an Agent Card resolver+ resolver = WellKnownAgentCardResolver(+ base_url="http://localhost:8000",+ )+ # Fetch and return the Agent Card+ return await resolver.get_agent_card()+++# %%+# Loading Agent Cards from Local Files+# --------------------------------+#+# The ``FileAgentCardResolver`` class supports loading Agent Cards from local JSON files, suitable for configuration file management scenarios.+# An example of an Agent Card in JSON format is shown below:+#+# .. code-block:: json+# :caption: Example Agent Card JSON file content+#+# {+# "name": "RemoteAgent",+# "url": "http://localhost:8000",+# "description": "Remote A2A Agent",+# "version": "1.0.0",+# "capabilities": {},+# "default_input_modes": ["text/plain"],+# "default_output_modes": ["text/plain"],+# "skills": []+# }+#+# You can easily load this file using ``FileAgentCardResolver``:+#+++async def agent_card_from_file() -> AgentCard:+ """Example of loading an Agent Card from a local JSON file."""+ from agentscope.a2a import FileAgentCardResolver++ # Load Agent Card from JSON file+ resolver = FileAgentCardResolver(+ file_path="./agent_card.json", # JSON file path+ )+ # Fetch and return the Agent Card+ return await resolver.get_agent_card()+++# %%+# Fetching Agent Cards from Nacos Registry+# --------------------------------+#+# Nacos is an open-source dynamic service discovery, configuration management, and service management platform. In version 3.1.0, it introduced the Agent Registry feature, supporting distributed registration, discovery, and version management of A2A agents.+#+# .. important:: The prerequisite for using ``NacosAgentCardResolver`` is that the user has deployed a Nacos server version 3.1.0 or higher. For deployment and registration procedures, please refer to the `official documentation <https://nacos.io/docs/latest/quickstart/quick-start>`_.+#+++async def agent_card_from_nacos() -> AgentCard:+ """Example of fetching an Agent Card from the Nacos registry."""++ # Create a Nacos Agent Card resolver+ resolver = NacosAgentCardResolver(+ remote_agent_name="my-remote-agent", # Agent name registered in Nacos+ nacos_client_config=ClientConfig(+ server_addresses="http://localhost:8848", # Nacos server address+ # Other optional configuration items+ ),+ )+ # Fetch and return the Agent Card+ return await resolver.get_agent_card()+++# %%+# Building an A2A Agent+# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~+#+# The ``A2AAgent`` class provided by AgentScope is used to communicate with remote A2A agents, and its usage is similar to regular agents.++agent = A2AAgent(agent_card=agent_card)++# %%+# Using ``A2AAgent``, developers can build chatbot scenario conversations, or encapsulate it as a tool function to build more complex application scenarios such as handoff/router.+# Currently, the format protocol conversion supported by ``A2AAgent`` is handled by ``agentscope.formatter.A2AChatFormatter``, which supports:+#+# - Converting AgentScope's ``Msg`` messages to A2A protocol's ``Message`` format+# - Converting A2A protocol responses back to AgentScope's ``Msg`` format+# - Converting A2A protocol's ``Task`` responses to AgentScope's ``Msg`` format+# - Supporting multiple content types such as text, images, audio, and video+#+++async def a2a_in_chatbot() -> None:+ """Example of chatting using A2AAgent."""++ user = UserAgent("user")++ msg = None+ while True:+ msg = await user(msg)+ if msg.get_text_content() == "exit":+ break+ msg = await agent(msg)+++# %%+# Or encapsulate it as a tool function for invocation:+++async def create_worker(query: str) -> ToolResponse:+ """Complete a given task through a sub-agent++ Args:+ query (`str`):+ Description of the task to be completed by the sub-agent+ """+ res = await agent(+ Msg("user", query, "user"),+ )+ return ToolResponse(+ content=[+ TextBlock(+ type="text",+ text=res.get_text_content(),+ ),+ ],+ )diff --git a/docs/tutorial/en/src/task_agent.py b/docs/tutorial/en/src/task_agent.pyindex 6177154c1..4a63baa41 100644--- a/docs/tutorial/en/src/task_agent.py+++ b/docs/tutorial/en/src/task_agent.py@@ -289,6 +289,12 @@ asyncio.run(example_structured_output())# -# -# - A special agent that represents the user, used to interact with the agent+# * - ``A2aAgent``+# - \-+# - | pre\_/post_reply+# | pre\_/post_observe+# | pre\_/post_print+# - Agent for communicating with remote A2A agents, see :ref:`a2a`###@@ -296,4 +302,5 @@ asyncio.run(example_structured_output())# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~# - :ref:`tool`# - :ref:`hook`+# - :ref:`a2a`#diff --git a/docs/tutorial/zh_CN/index.rst b/docs/tutorial/zh_CN/index.rstindex 704bcf4b6..7e8683fac 100644--- a/docs/tutorial/zh_CN/index.rst+++ b/docs/tutorial/zh_CN/index.rst@@ -57,6 +57,7 @@ Welcome to AgentScope's documentation!tutorial/task_agenttutorial/task_statetutorial/task_hook+ tutorial/task_a2a.. toctree:::maxdepth: 1diff --git a/docs/tutorial/zh_CN/src/task_a2a.py b/docs/tutorial/zh_CN/src/task_a2a.pynew file mode 100644index 000000000..954c21230--- /dev/null+++ b/docs/tutorial/zh_CN/src/task_a2a.py@@ -0,0 +1,213 @@+# -*- coding: utf-8 -*-+"""+.. _a2a:++A2A 智能体+============================++A2A(Agent-to-Agent)是一种开放标准协议,用于实现不同 AI 智能体之间的互操作通信。++AgentScope 从获取 Agent Card 信息和连接远程智能体两个层面提供对 A2A 协议的支持,涉及到的相关 API 如下:++.. list-table:: A2A 相关类+ :header-rows: 1++ * - 类+ - 描述+ * - ``A2AAgent``+ - 用于与远程 A2A 智能体通信的智能体类+ * - ``A2AChatFormatter``+ - 用于在 AgentScope 消息和 A2A 消息/任务格式之间进行转换的格式化器+ * - ``AgentCardResolverBase``+ - Agent Card 解析器基类+ * - ``FileAgentCardResolver``+ - 从本地 JSON 文件加载 Agent Card 的解析器+ * - ``WellKnownAgentCardResolver``+ - 从 URL 的 well-known 路径获取 Agent Card 的解析器+ * - ``NacosAgentCardResolver``+ - 从 Nacos Agent 注册中心获取 Agent Card 的解析器++本节将演示如何创建 ``A2aAgent`` 并与远程 A2A 智能体进行通信。++.. note:: 注意 A2A 的支持为**实验性功能**,可能会在未来版本中发生变化。同时由于 A2A 协议自身+ 的局限性,因此功能上 ``A2AAgent`` 无法完全对齐 ``ReActAgent`` 等本地智能体,包括:++ - 仅支持 chatbot 场景,即仅支持一个用户与一个智能体之间的对话(不影响 handsoff/router 等使用方式)+ - 不支持在对话过程中实时打断+ - 不支持 agentic 结构化输出+ - 目前实现中,``observe`` 方法收到的消息会被存储在本地,并在调用 ``reply`` 方法时一并发送给远程智能体,因此如果最后若干 ``observe`` 调用后未发生 ``reply`` 调用,则这些消息不会被远程智能体看到+++"""++# %%+# 获取 Agent Card+# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~+#+# 首先,我们需要获得一个 Agent Card 来连接对应的智能体。Agent Card 中包含了智能体的名称,描述,能力以及连接方式等信息。+#+# 手动创建 Agent Card 对象+# --------------------------------+#+# 在已知 Agent Card 各项信息的情况下,可以直接从 `a2a.types.AgentCard` 手动创建 Agent Card 对象。+#++from a2a.types import AgentCard, AgentCapabilities+from v2.nacos import ClientConfig++from agentscope.a2a import WellKnownAgentCardResolver, NacosAgentCardResolver+from agentscope.agent import A2AAgent, UserAgent+from agentscope.message import Msg, TextBlock+from agentscope.tool import ToolResponse++# 创建 Agent Card 对象+agent_card = AgentCard(+ name="Friday", # 智能体名称+ description="一个有趣的聊天伙伴", # 智能体描述+ url="http://localhost:8000", # 智能体的 RPC 服务地址+ version="1.0.0", # 智能体版本+ capabilities=AgentCapabilities( # 智能体能力配置+ push_notifications=False,+ state_transition_history=True,+ streaming=True,+ ),+ default_input_modes=["text/plain"], # 支持的输入格式+ default_output_modes=["text/plain"], # 支持的输出格式+ skills=[], # 智能体技能列表+)++# %%+#+# 从远程服务获取 Agent Card+# --------------------------------+# 同时,AgentScope 也支持通过多种方式动态获取 Agent Card,包括从本地文件加载、从远程服务 (well-known server) 的标准路径获取以及从 Nacos 注册中心获取等。+# 这里以 ``WellKnownAgentCardResolver`` 为例,从远程服务的标准路径获取 Agent Card:+#+++async def agent_card_from_well_known_website() -> AgentCard:+ """从远程服务的 well-known 路径获取 Agent Card 的示例。"""+ # 创建 Agent Card 解析器+ resolver = WellKnownAgentCardResolver(+ base_url="http://localhost:8000",+ )+ # 获取并返回 Agent Card+ return await resolver.get_agent_card()+++# %%+# 从本地文件加载 Agent Card+# --------------------------------+#+# ``FileAgentCardResolver`` 类支持从本地 JSON 文件加载 Agent Card,适用于配置文件管理的场景。+# 一个 JSON 格式的 Agent Card 样例如下所示:+#+# .. code-block:: json+# :caption: 示例 Agent Card JSON 文件内容+#+# {+# "name": "RemoteAgent",+# "url": "http://localhost:8000",+# "description": "远程 A2A 智能体",+# "version": "1.0.0",+# "capabilities": {},+# "default_input_modes": ["text/plain"],+# "default_output_modes": ["text/plain"],+# "skills": []+# }+#+# 通过 ``FileAgentCardResolver`` 可以方便地加载该文件:+#+++async def agent_card_from_file() -> AgentCard:+ """从本地 JSON 文件加载 Agent Card 的示例。"""+ from agentscope.a2a import FileAgentCardResolver++ # 从 JSON 文件加载 Agent Card+ resolver = FileAgentCardResolver(+ file_path="./agent_card.json", # JSON 文件路径+ )+ # 获取并返回 Agent Card+ return await resolver.get_agent_card()+++# %%+# 从 Nacos 注册中心获取 Agent Card+# --------------------------------+#+# Nacos 是一款开源的动态服务发现、配置管理和服务管理平台,在 3.1.0 版本中引入了 Agent 注册中心功能,支持 A2A 智能体的分布式注册、发现和版本管理。+#+# .. important:: 使用 ``NacosAgentCardResolver`` 的前提是用户已经部署了 3.1.0 版本以上的 Nacos 服务端,部署与注册流程请参考`官方文档 <https://nacos.io/docs/latest/quickstart/quick-start>`_。+#+++async def agent_card_from_nacos() -> AgentCard:+ """从 Nacos 注册中心获取 Agent Card 的示例。"""++ # 创建 Nacos Agent Card 解析器+ resolver = NacosAgentCardResolver(+ remote_agent_name="my-remote-agent", # Nacos 中注册的智能体名称+ nacos_client_config=ClientConfig(+ server_addresses="http://localhost:8848", # Nacos 服务器地址+ # 其他可选配置项+ ),+ )+ # 获取并返回 Agent Card+ return await resolver.get_agent_card()+++# %%+# 构建 A2A 智能体+# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~+#+# AgentScope 提供的 ``A2AAgent`` 类用于与远程 A2A 智能体进行通信,其使用方式与普通智能体类似。++agent = A2AAgent(agent_card=agent_card)++# %%+# 利用 ``A2AAgent``,开发者可以构建 chatbot 场景的聊天,或是封装成工具函数,从而构建 handsoff/router 等更复杂的应用场景。+# 目前 ``A2AAgent`` 支持的格式协议转换由 ``agentscope.formatter.A2AChatFormatter`` 负责,支持+#+# - 将 AgentScope 的 ``Msg`` 消息转换为 A2A 协议的 ``Message`` 格式+# - 将 A2A 协议的响应转换回 AgentScope 的 ``Msg`` 格式+# - 将 A2A 协议的 ``Task`` 相应转换成 AgentScope 的 ``Msg`` 格式+# - 支持文本、图像、音频、视频等多种内容类型+#+++async def a2a_in_chatbot() -> None:+ """使用 A2AAgent 进行聊天的示例。"""++ user = UserAgent("user")++ msg = None+ while True:+ msg = await user(msg)+ if msg.get_text_content() == "exit":+ break+ msg = await agent(msg)+++# %%+# 或是如下封装成工具函数用于调用:+++async def create_worker(query: str) -> ToolResponse:+ """通过子智能体完成给定的任务++ Args:+ query (`str`):+ 需要子智能体完成的任务描述+ """+ res = await agent(+ Msg("user", query, "user"),+ )+ return ToolResponse(+ content=[+ TextBlock(+ type="text",+ text=res.get_text_content(),+ ),+ ],+ )diff --git a/docs/tutorial/zh_CN/src/task_agent.py b/docs/tutorial/zh_CN/src/task_agent.pyindex c4d3c79dd..19e0c7a0b 100644--- a/docs/tutorial/zh_CN/src/task_agent.py+++ b/docs/tutorial/zh_CN/src/task_agent.py@@ -267,6 +267,12 @@ asyncio.run(example_structured_output())# -# -# - 代表用户的特殊智能体,用于与智能体交互+# * - ``A2aAgent``+# - \-+# - | pre\_/post_reply+# | pre\_/post_observe+# | pre\_/post_print+# - 用于与远程 A2A 代理通信的智能体,详见 :ref:`a2a`###@@ -274,4 +280,5 @@ asyncio.run(example_structured_output())# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~# - :ref:`tool`# - :ref:`hook`+# - :ref:`a2a`#diff --git a/examples/agent/a2a_agent/README.md b/examples/agent/a2a_agent/README.mdnew file mode 100644index 000000000..31dfb460c--- /dev/null+++ b/examples/agent/a2a_agent/README.md@@ -0,0 +1,47 @@+# Agent-to-Agent Protocol Example++The `A2AAgent` in AgentScope is an A2A client that connects to an external agent server via the Agent-to-Agent (A2A) protocol.+This example demonstrates how to set up and use the `A2AAgent` to interact with an agent hosted on an A2A server.++Note the A2A feature is experimental and subject to change, and due to the limitations of A2A protocol, the `A2AAgent`+currently++1. only supports chatbot scenarios, where only a user and an agent are involved+2. does not support realtime steering/interruption during the conversation+3. does not support agentic structured outputs+4. stores the observed messages locally and send them together with the input message(s) of the `reply` function++## Files++The example contains the following files:++```+examples/agent/a2a_agent+├── main.py # The main script to run the A2A agent example+├── setup_a2a_server.py # The script to set up a simple A2A server+├── agent_card.py # The agent card definition for the A2A agent+└── README.md # This README file+```++## Setup++This example provides a simple setup to demonstrate how to use the `A2AAgent` in AgentScope.+First you need to install the required dependencies:++```bash+uv pip install a2a-sdk[http-server] agentscope[a2a]+# or+pip install a2a-sdk[http-server] agentscope[a2a]+```++Then we first set up a simple A2A server that hosts a ReAct agent:+```bash+uvicorn setup_a2a_server:app --host 0.0.0.0 --port 8000+```+This will start an A2A server locally on port 8000.++After that, you can run the A2A agent example to run a chatbot conversation with the agent hosted on the A2A server:+```bash+python main.py+```+diff --git a/examples/agent/a2a_agent/agent_card.py b/examples/agent/a2a_agent/agent_card.pynew file mode 100644index 000000000..be2470728--- /dev/null+++ b/examples/agent/a2a_agent/agent_card.py@@ -0,0 +1,37 @@+# -*- coding: utf-8 -*-+"""The agent card definition for the A2A agent."""+from a2a.types import AgentCard, AgentCapabilities, AgentSkill++agent_card = AgentCard(+ name="Friday",+ description="A simple ReAct agent that handles input queries",+ url="http://localhost:8000",+ version="1.0.0",+ capabilities=AgentCapabilities(+ push_notifications=False,+ state_transition_history=True,+ streaming=True,+ ),+ default_input_modes=["text/plain"],+ default_output_modes=["text/plain"],+ skills=[+ AgentSkill(+ name="execute_python_code",+ id="execute_python_code",+ description="Execute Python code snippets.",+ tags=["code_execution"],+ ),+ AgentSkill(+ name="execute_shell_command",+ id="execute_shell_command",+ description="Execute shell commands on the server.",+ tags=["code_execution"],+ ),+ AgentSkill(+ name="view_text_file",+ id="view_text_file",+ description="View the content of a text file on the server.",+ tags=["file_viewing"],+ ),+ ],+)diff --git a/examples/agent/a2a_agent/main.py b/examples/agent/a2a_agent/main.pynew file mode 100644index 000000000..14a5413ee--- /dev/null+++ b/examples/agent/a2a_agent/main.py@@ -0,0 +1,28 @@+# -*- coding: utf-8 -*-+"""The main entry for the A2A agent example."""+import asyncio++from agent_card import agent_card++from agentscope.agent import UserAgent, A2AAgent+++async def main() -> None:+ """The main entry for the example, where we build a simple conversation+ between the A2A agent and the user."""++ user = UserAgent("user")++ agent = A2AAgent(+ agent_card=agent_card,+ )++ msg = None+ while True:+ msg = await user(msg)+ if msg.get_text_content() == "exit":+ break+ msg = await agent(msg)+++asyncio.run(main())diff --git a/examples/agent/a2a_agent/setup_a2a_server.py b/examples/agent/a2a_agent/setup_a2a_server.pynew file mode 100644index 000000000..8255aab36--- /dev/null+++ b/examples/agent/a2a_agent/setup_a2a_server.py@@ -0,0 +1,131 @@+# -*- coding: utf-8 -*-+"""Set up an A2A server with a ReAct agent to handle the input query"""+import os+import uuid+from typing import AsyncGenerator, Any++from agent_card import agent_card++from a2a.server.events import Event+from a2a.types import (+ TaskStatus,+ TaskState,+ MessageSendParams,+ TaskStatusUpdateEvent,+)+from a2a.server.apps import A2AStarletteApplication++from agentscope.agent import ReActAgent+from agentscope.formatter import DashScopeChatFormatter, A2AChatFormatter+from agentscope.model import DashScopeChatModel+from agentscope.pipeline import stream_printing_messages+from agentscope.session import JSONSession+from agentscope.tool import (+ Toolkit,+ execute_python_code,+ execute_shell_command,+ view_text_file,+)+++class SimpleStreamHandler:+ """A simple request handler that handles the input query by an+ ReAct agent."""++ async def on_message_send_stream(+ self, # pylint: disable=unused-argument+ params: MessageSendParams,+ **kwargs: Any,+ ) -> AsyncGenerator[Event, None]:+ """Handles the message_send method by the agent++ Args:+ params (`MessageSendParams`):+ The parameters for sending the message.++ Returns:+ `AsyncGenerator[Event, None]`:+ An asynchronous generator that yields task status update+ events.+ """+ task_id = params.message.task_id or uuid.uuid4().hex+ context_id = params.message.context_id or "default-context"+ # ============ Agent Logic ============++ # Register the tool functions+ toolkit = Toolkit()+ toolkit.register_tool_function(execute_python_code)+ toolkit.register_tool_function(execute_shell_command)+ toolkit.register_tool_function(view_text_file)++ # Create the agent instance+ agent = ReActAgent(+ name="Friday",+ sys_prompt="You're a helpful assistant named Friday.",+ model=DashScopeChatModel(+ model_name="qwen-max",+ api_key=os.getenv("DASHSCOPE_API_KEY"),+ ),+ formatter=DashScopeChatFormatter(),+ toolkit=toolkit,+ )++ session = JSONSession(save_dir="./sessions")+ await session.load_session_state(+ session_id="test-a2a-agent",+ agent=agent,+ )++ # Convert the A2A message to AgentScope Msg objects+ formatter = A2AChatFormatter()+ as_msg = await formatter.format_a2a_message(+ name="Friday",+ message=params.message,+ )++ yield TaskStatusUpdateEvent(+ task_id=task_id,+ context_id=context_id,+ status=TaskStatus(state=TaskState.working),+ final=False,+ )++ async for msg, last in stream_printing_messages(+ agents=[agent],+ coroutine_task=agent(as_msg),+ ):+ # The A2A streaming response is one complete Message object rather+ # than accumulated or incremental text+ if last:+ a2a_message = await formatter.format([msg])++ yield TaskStatusUpdateEvent(+ task_id=task_id,+ context_id=context_id,+ status=TaskStatus(+ state=TaskState.working,+ message=a2a_message,+ ),+ final=False,+ )++ # Finish the task+ yield TaskStatusUpdateEvent(+ task_id=task_id,+ context_id=context_id,+ status=TaskStatus(state=TaskState.completed),+ final=True,+ )++ await session.save_session_state(+ session_id="test-a2a-agent",+ agent=agent,+ )+++handler = SimpleStreamHandler()+app_instance = A2AStarletteApplication(+ agent_card,+ handler,+)+app = app_instance.build()diff --git a/pyproject.toml b/pyproject.tomlindex b9f8b5b52..4a351bd23 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -42,6 +42,13 @@ dependencies = [][project.optional-dependencies]+# A2A protocol support+a2a = [+ "a2a-sdk",+ "httpx",+ "nacos-sdk-python>=3.0.0",+]+full = [# Model"ollama>=0.5.4",@@ -63,9 +70,12 @@ full = [# the version to 1.15.1 here."qdrant-client==1.15.1",]+dev = [# Include full dependencies from local package"agentscope[full]",+ # A2A protocol support+ "agentscope[a2a]",# Development tools"pre-commit","pytest",diff --git a/src/agentscope/__init__.py b/src/agentscope/__init__.pyindex a7d0097d7..092828bc2 100644--- a/src/agentscope/__init__.py+++ b/src/agentscope/__init__.py@@ -56,6 +56,7 @@ from . import evaluatefrom . import pipelinefrom . import tracingfrom . import rag+from . import a2afrom ._logging import (logger,@@ -173,6 +174,7 @@ __all__ = ["pipeline","tracing","rag",+ "a2a",# functions"init","setup_logger",diff --git a/src/agentscope/a2a/__init__.py b/src/agentscope/a2a/__init__.pynew file mode 100644index 000000000..828f2621d--- /dev/null+++ b/src/agentscope/a2a/__init__.py@@ -0,0 +1,14 @@+# -*- coding: utf-8 -*-+"""The A2A related modules."""+from ._base import AgentCardResolverBase+from ._file_resolver import FileAgentCardResolver+from ._well_known_resolver import WellKnownAgentCardResolver+from ._nacos_resolver import NacosAgentCardResolver+++__all__ = [+ "AgentCardResolverBase",+ "FileAgentCardResolver",+ "WellKnownAgentCardResolver",+ "NacosAgentCardResolver",+]diff --git a/src/agentscope/a2a/_base.py b/src/agentscope/a2a/_base.pynew file mode 100644index 000000000..23ff1ea7e--- /dev/null+++ b/src/agentscope/a2a/_base.py@@ -0,0 +1,25 @@+# -*- coding: utf-8 -*-+"""The A2A agent card resolver base class."""+from abc import abstractmethod+from typing import Any, TYPE_CHECKING++if TYPE_CHECKING:+ from a2a.types import AgentCard+else:+ AgentCard = "a2a.types.AgentCard"+++class AgentCardResolverBase:+ """Base class for A2A agent card resolvers, responsible for fetching+ agent cards from various sources. Implementations must provide the+ `get_agent_card` method to retrieve the agent card.+ """++ @abstractmethod+ async def get_agent_card(self, *args: Any, **kwargs: Any) -> AgentCard:+ """Get Agent Card from the configured source.++ Returns:+ `AgentCard`:+ The resolved agent card object.+ """diff --git a/src/agentscope/a2a/_file_resolver.py b/src/agentscope/a2a/_file_resolver.pynew file mode 100644index 000000000..e47114096--- /dev/null+++ b/src/agentscope/a2a/_file_resolver.py@@ -0,0 +1,78 @@+# -*- coding: utf-8 -*-+"""The JSON file based A2A agent card resolver."""+import json+from pathlib import Path+from typing import TYPE_CHECKING++from ._base import AgentCardResolverBase++if TYPE_CHECKING:+ from a2a.types import AgentCard+else:+ AgentCard = "a2a.types.AgentCard"+++class FileAgentCardResolver(AgentCardResolverBase):+ """Agent card resolver that loads AgentCard from a JSON file.++ The JSON file should contain an AgentCard object with the following+ required fields:++ - name (str): The name of the agent+ - url (str): The URL of the agent+ - version (str): The version of the agent+ - capabilities (dict): The capabilities of the agent+ - default_input_modes (list[str]): Default input modes+ - default_output_modes (list[str]): Default output modes+ - skills (list): List of agent skills++ Example JSON file content:++ .. code-block:: json++ {+ "name": "RemoteAgent",+ "url": "http://localhost:8000",+ "description": "A remote A2A agent",+ "version": "1.0.0",+ "capabilities": {},+ "default_input_modes": ["text/plain"],+ "default_output_modes": ["text/plain"],+ "skills": []+ }++ """++ def __init__(+ self,+ file_path: str,+ ) -> None:+ """Initialize the FileAgentCardResolver with the path to the JSON file.++ Args:+ file_path (`str`):+ The path to the JSON file containing the agent card.+ """+ self._file_path = file_path++ async def get_agent_card(self) -> AgentCard:+ """Get the agent card from the JSON file.++ Returns:+ `AgentCard`:+ The agent card loaded from the file.+ """+ from a2a.types import AgentCard++ path = Path(self._file_path)+ if not path.exists():+ raise FileNotFoundError(+ f"Agent card file not found: {self._file_path}",+ )++ if not path.is_file():+ raise ValueError(f"Path is not a file: {self._file_path}")++ with path.open("r", encoding="utf-8") as f:+ agent_json_data = json.load(f)+ return AgentCard.model_validate(agent_json_data)diff --git a/src/agentscope/a2a/_nacos_resolver.py b/src/agentscope/a2a/_nacos_resolver.pynew file mode 100644index 000000000..5a5690234--- /dev/null+++ b/src/agentscope/a2a/_nacos_resolver.py@@ -0,0 +1,98 @@+# -*- coding: utf-8 -*-+"""The Nacos-based A2A Agent Card resolver."""++from typing import TYPE_CHECKING++from ._base import AgentCardResolverBase+from .._logging import logger++if TYPE_CHECKING:+ from a2a.types import AgentCard+ from v2.nacos.common.client_config import ClientConfig+else:+ AgentCard = "a2a.types.AgentCard"+ ClientConfig = "v2.nacos.common.client_config.ClientConfig"+++class NacosAgentCardResolver(AgentCardResolverBase):+ """Nacos-based A2A Agent Card resolver.++ Nacos is a dynamic service discovery, configuration and service+ management platform for building cloud native applications. This resolver+ fetches the agent card from a Nacos server and subscribes to updates.+ """++ def __init__(+ self,+ remote_agent_name: str,+ nacos_client_config: ClientConfig,+ version: str | None = None,+ ) -> None:+ """Initialize the nacos agent card resolver.++ Args:+ remote_agent_name (`str`):+ Name of the remote agent in Nacos.+ nacos_client_config (`ClientConfig | None`, optional):+ Nacos client configuration, where a `server_addresses`+ parameter is required.+ version (`str | None`, optional):+ Version of the agent card to fetch. If None, fetches the+ latest version. This version is also used when subscribing+ to agent card updates.+ Defaults to None (latest version).+ """+ if not remote_agent_name:+ raise ValueError(+ "The remote_agent_name cannot be empty.",+ )++ if not nacos_client_config:+ raise ValueError(+ "The nacos_client_config cannot be None.",+ )++ self._nacos_client_config = nacos_client_config+ self._remote_agent_name = remote_agent_name+ self._version = version++ async def get_agent_card(self) -> AgentCard:+ """Get agent card from Nacos with lazy initialization.++ Returns:+ `AgentCard`:+ The resolved agent card from Nacos.+ """+ try:+ from v2.nacos.ai.model.ai_param import GetAgentCardParam+ from v2.nacos.ai.nacos_ai_service import NacosAIService+ except ImportError as e:+ raise ImportError(+ "Please install the nacos sdk by running `pip install "+ "nacos-sdk-python>=3.0.0` first.",+ ) from e++ client = None+ try:+ client = await NacosAIService.create_ai_service(+ self._nacos_client_config,+ )++ await client.start()+ return await client.get_agent_card(+ GetAgentCardParam(+ agent_name=self._remote_agent_name,+ version=self._version,+ ),+ )++ finally:+ if client:+ # Close the Nacos client to free resources+ try:+ await client.shutdown()+ except Exception as e:+ logger.warning(+ "Failed to shutdown Nacos client: %s",+ str(e),+ )diff --git a/src/agentscope/a2a/_well_known_resolver.py b/src/agentscope/a2a/_well_known_resolver.pynew file mode 100644index 000000000..2f9445884--- /dev/null+++ b/src/agentscope/a2a/_well_known_resolver.py@@ -0,0 +1,90 @@+# -*- coding: utf-8 -*-+"""The A2A well-known agent card resolver."""+from typing import TYPE_CHECKING+from urllib.parse import urlparse++from ._base import AgentCardResolverBase+from .._logging import logger++if TYPE_CHECKING:+ from a2a.types import AgentCard+else:+ AgentCard = "a2a.types.AgentCard"+++class WellKnownAgentCardResolver(AgentCardResolverBase):+ """Agent card resolver that loads AgentCard from a well-known URL."""++ def __init__(+ self,+ base_url: str,+ agent_card_path: str | None = None,+ ) -> None:+ """Initialize the WellKnownAgentCardResolver.++ Args:+ base_url (`str`):+ The base URL to resolve the agent card from.+ agent_card_path (`str | None`, optional):+ The path to the agent card relative to the base URL.+ Defaults to AGENT_CARD_WELL_KNOWN_PATH from a2a.utils.+ """+ self._base_url = base_url+ self._agent_card_path = agent_card_path++ async def get_agent_card(self) -> AgentCard:+ """Get the agent card from the well-known URL.++ Returns:+ `AgentCard`:+ The agent card loaded from the URL.+ """+ import httpx+ from a2a.client import A2ACardResolver+ from a2a.utils import AGENT_CARD_WELL_KNOWN_PATH++ try:+ parsed_url = urlparse(self._base_url)+ if not parsed_url.scheme or not parsed_url.netloc:+ logger.error(+ "[%s] Invalid URL format: %s",+ self.__class__.__name__,+ self._base_url,+ )+ raise ValueError(+ f"Invalid URL format: {self._base_url}",+ )++ base_url = f"{parsed_url.scheme}://{parsed_url.netloc}"+ relative_card_path = parsed_url.path++ # Use default path if not specified+ agent_card_path = (+ self._agent_card_path+ if self._agent_card_path is not None+ else AGENT_CARD_WELL_KNOWN_PATH+ )++ # Use async context manager to ensure proper cleanup+ async with httpx.AsyncClient(+ timeout=httpx.Timeout(timeout=600),+ ) as _http_client:+ resolver = A2ACardResolver(+ httpx_client=_http_client,+ base_url=base_url,+ agent_card_path=agent_card_path,+ )+ return await resolver.get_agent_card(+ relative_card_path=relative_card_path,+ )+ except Exception as e:+ logger.error(+ "[%s] Failed to resolve agent card from URL %s: %s",+ self.__class__.__name__,+ self._base_url,+ e,+ )+ raise RuntimeError(+ f"Failed to resolve AgentCard from URL "+ f"{self._base_url}: {e}",+ ) from ediff --git a/src/agentscope/agent/__init__.py b/src/agentscope/agent/__init__.pyindex 388d7956a..e7f02083f 100644--- a/src/agentscope/agent/__init__.py+++ b/src/agentscope/agent/__init__.py@@ -10,6 +10,7 @@ from ._user_input import (StudioUserInput,)from ._user_agent import UserAgent+from ._a2a_agent import A2AAgent__all__ = [@@ -21,4 +22,5 @@ __all__ = ["TerminalUserInput","StudioUserInput","UserAgent",+ "A2AAgent",]diff --git a/src/agentscope/agent/_a2a_agent.py b/src/agentscope/agent/_a2a_agent.pynew file mode 100644index 000000000..7e1b67d17--- /dev/null+++ b/src/agentscope/agent/_a2a_agent.py@@ -0,0 +1,288 @@+# -*- coding: utf-8 -*-+"""A2A agent implementation for AgentScope.++This module provides the A2A (Agent-to-Agent) protocol implementation,+enabling AgentScope agents to communicate with remote agents using the+A2A standard protocol.+"""+from __future__ import annotations+from typing import TYPE_CHECKING, Any, Type++import httpx+from pydantic import BaseModel++from ._agent_base import AgentBase+from ..message import Msg+from ..formatter import A2AChatFormatter++if TYPE_CHECKING:+ from a2a.types import AgentCard+ from a2a.client import ClientConfig, Consumer+ from a2a.client.client_factory import TransportProducer+else:+ AgentCard = "a2a.types.AgentCard"+ ClientConfig = "a2a.client.ClientConfig"+ Consumer = "a2a.client.Consumer"+ TransportProducer = "a2a.client.client_factory.TransportProducer"+++class A2AAgent(AgentBase):+ """An A2A agent implementation in AgentScope, which supports++ - Communication with remote agents using the A2A protocol+ - Bidirectional message conversion between AgentScope and A2A formats+ - Task lifecycle management with streaming and polling+ - Artifact handling and status tracking++ .. note:: Due to the limitation of A2A protocol. The A2AAgent class++ - Only support chatbot-scenario (a user and an assistant) interactions.+ To support multi-agent interactions requires the server side to handle+ the `name` field in the A2A messages properly.+ - Does not support structured output in `reply()` method due to the lack+ of structured output support in A2A protocol.+ - Stores observed messages locally and merges them with input messages+ when `reply()` is called. Observed messages are cleared after processing.+ """++ def __init__(+ self,+ agent_card: AgentCard,+ client_config: ClientConfig | None = None,+ consumers: list[Consumer] | None = None,+ additional_transport_producers: dict[str, TransportProducer]+ | None = None,+ ) -> None:+ """Initialize the A2A agent instance by the given agent card.++ Args:+ agent_card (`AgentCard`):+ The agent card that contains the information about the remote+ agent, such as its URL and capabilities.+ client_config (`ClientConfig | None`, optional):+ The configuration for the A2A client, including transport+ preferences and streaming options.+ consumers (`list[Consumer] | None`, optional):+ The list of consumers for handling A2A client events.+ These intercept request/response flows for logging,+ metrics, and security.+ additional_transport_producers (`dict[str, TransportProducer] | \+ None`, optional):+ Additional transport producers for creating A2A clients+ with specific transport protocols.+ """+ super().__init__()++ from a2a.types import AgentCard+ from a2a.client import ClientConfig, ClientFactory++ if not isinstance(agent_card, AgentCard):+ raise ValueError(+ f"agent_card must be an instance of AgentCard, "+ f"got {type(agent_card)}",+ )++ self.name: str = agent_card.name+ self.agent_card = agent_card++ # Create the client factory so that we can create clients later+ # in reply()+ self._a2a_client_factory = ClientFactory(+ config=client_config+ or ClientConfig(+ httpx_client=httpx.AsyncClient(+ timeout=httpx.Timeout(timeout=600),+ ),+ ),+ consumers=consumers,+ )++ # Register additional transport producers if provided+ if additional_transport_producers:+ for label, producer in additional_transport_producers.items():+ self._a2a_client_factory.register(+ label,+ producer,+ )++ # The variables to store observed messages+ self._observed_msgs: list[Msg] = []++ # The formatter used for message conversion+ self.formatter = A2AChatFormatter()++ def state_dict(self) -> dict:+ """Get the state dictionary of the A2A agent.++ Returns:+ `dict`:+ The state dictionary containing the observed messages.+ """+ return {+ "_observed_msgs": [msg.to_dict() for msg in self._observed_msgs],+ }++ def load_state_dict(self, state_dict: dict, strict: bool = True) -> None:+ """Load the state dictionary into the module.++ Args:+ state_dict (`dict`):+ The state dictionary to load.+ strict (`bool`, defaults to `True`):+ If `True`, raises an error if any key in the module is not+ found in the state_dict. If `False`, skips missing keys.++ Raises:+ `KeyError`:+ If a required key is missing in the state_dict when strict+ is `True`.+ """+ if "_observed_msgs" in state_dict:+ self._observed_msgs = [+ Msg.from_dict(d) for d in state_dict["_observed_msgs"]+ ]+ else:+ raise KeyError(+ "_observed_msgs key not found in state_dict",+ )++ if strict:+ for key in state_dict.keys():+ if key != "_observed_msgs":+ raise KeyError(f"Unexpected key {key} in state_dict")++ async def observe(self, msg: Msg | list[Msg] | None) -> None:+ """Receive the given message(s) without generating a reply.++ The observed messages are stored and will be merged with the+ input messages when `reply` is called. After `reply` completes,+ the stored messages will be cleared.++ Args:+ msg (`Msg | list[Msg] | None`):+ The message(s) to be observed. If None, no action is taken.+ """+ if msg is None:+ return++ if isinstance(msg, Msg):+ self._observed_msgs.append(msg)+ elif isinstance(msg, list) and all(isinstance(m, Msg) for m in msg):+ self._observed_msgs.extend(msg)+ else:+ raise TypeError(+ f"msg must be a Msg or a list of Msg, got {type(msg)}",+ )++ async def reply(+ self,+ msg: Msg | list[Msg] | None = None,+ **kwargs: Any,+ ) -> Msg:+ """Send message(s) to the remote A2A agent and receive a response.++ .. note:: This method merges any previously observed messages with the+ input messages, sends them to the remote agent, and clears the+ observed messages after processing.++ .. note:: The A2A protocol does not support structured output, so the+ `structured_model` parameter is not supported in this method.++ Args:+ msg (`Msg | list[Msg] | None`, optional):+ The message(s) to send to the remote agent. Can be a single+ Msg, a list of Msgs, or None. If None, only observed messages+ will be sent. Defaults to None.++ Returns:+ `Msg`:+ The response message from the remote agent. For tasks, this+ may be either a status update message or the final artifacts+ message, depending on the task state. If no messages are+ provided (both msg and observed messages are empty), returns+ a prompt message. If an error occurs during communication,+ returns an error message.+ """+ if "structured_model" in kwargs:+ raise ValueError(+ "structured_model is not supported in A2AAgent.reply() "+ "due to the lack of structured output support in A2A "+ "protocol.",+ )++ from a2a.types import Message as A2AMessage++ # Merge observed messages with input messages+ msgs_list = self._observed_msgs++ if msg is not None:+ if isinstance(msg, Msg):+ msgs_list.append(msg)+ else:+ msgs_list.extend(msg)++ # Create A2A client and send message+ client = self._a2a_client_factory.create(+ card=self.agent_card,+ )++ # Convert Msg objects into A2A Message object+ a2a_message = await self.formatter.format([_ for _ in msgs_list if _])++ response_msg = None+ async for item in client.send_message(a2a_message):+ if isinstance(item, A2AMessage):+ response_msg = await self.formatter.format_a2a_message(+ self.name,+ item,+ )+ await self.print(response_msg)++ elif isinstance(item, tuple):+ task, _ = item++ if task is not None:+ for _ in await self.formatter.format_a2a_task(+ self.name,+ task,+ ):+ await self.print(_)+ response_msg = _++ # Clear the observed messages after processing+ self._observed_msgs.clear()++ if response_msg:+ return response_msg++ raise ValueError(+ "No response received from remote agent",+ )++ # pylint: disable=unused-argument+ async def handle_interrupt(+ self,+ msg: Msg | list[Msg] | None = None,+ structured_model: Type[BaseModel] | None = None,+ ) -> Msg:+ """The post-processing logic when the reply is interrupted by the+ user or something else.+ """++ response_msg = Msg(+ self.name,+ "I noticed that you have interrupted me. What can I "+ "do for you?",+ "assistant",+ metadata={+ # Expose this field to indicate the interruption+ "_is_interrupted": True,+ },+ )++ await self.print(response_msg, True)++ # Add to observed messages for context in next reply+ self._observed_msgs.append(response_msg)++ return response_msgdiff --git a/src/agentscope/agent/_user_input.py b/src/agentscope/agent/_user_input.pyindex 881abf66f..1bc881bb9 100644--- a/src/agentscope/agent/_user_input.py+++ b/src/agentscope/agent/_user_input.py@@ -95,7 +95,11 @@ class TerminalUserInput(UserInputBase):The user input data."""- text_input = input(self.input_hint)+ text_input = (+ input(self.input_hint)+ .encode("utf-8", errors="ignore")+ .decode("utf-8")+ )structured_input = Noneif structured_model is not None:diff --git a/src/agentscope/formatter/__init__.py b/src/agentscope/formatter/__init__.pyindex 7a8f5b560..320229813 100644--- a/src/agentscope/formatter/__init__.py+++ b/src/agentscope/formatter/__init__.py@@ -27,6 +27,7 @@ from ._deepseek_formatter import (DeepSeekChatFormatter,DeepSeekMultiAgentFormatter,)+from ._a2a_formatter import A2AChatFormatter__all__ = ["FormatterBase",@@ -43,4 +44,5 @@ __all__ = ["OllamaMultiAgentFormatter","DeepSeekChatFormatter","DeepSeekMultiAgentFormatter",+ "A2AChatFormatter",]diff --git a/src/agentscope/formatter/_a2a_formatter.py b/src/agentscope/formatter/_a2a_formatter.pynew file mode 100644index 000000000..4382dd89d--- /dev/null+++ b/src/agentscope/formatter/_a2a_formatter.py@@ -0,0 +1,364 @@+# -*- coding: utf-8 -*-+"""The A2A message formatter class."""+import mimetypes+import uuid+from typing import Literal, TYPE_CHECKING+++from .._logging import logger+from ._formatter_base import FormatterBase+from ..message import (+ Msg,+ TextBlock,+ URLSource,+ Base64Source,+ ContentBlock,+)+++if TYPE_CHECKING:+ from a2a.types import (+ Message,+ Task,+ Part,+ )+else:+ Message = "a2a.types.Message"+ Task = "a2a.types.Task"+ Part = "a2a.types.Part"+++class A2AChatFormatter(FormatterBase):+ """A2A message formatter class, which convert AgentScope messages into+ A2A message format."""++ async def format(self, msgs: list[Msg]) -> Message:+ """Convert AgentScope messages into a A2A message object. Note that+ A2A server only supports single request message, so the input msgs+ list will be merged into a single A2A Message.++ .. note:: Note the A2A protocol receives a single message per request,+ so multi-message inputs will be merged into one A2A Message with role+ 'user'.++ Args:+ msgs (`list[Msg]`):+ List of AgentScope Msg objects to be converted.++ Returns:+ `Message`:+ The converted A2A Message object.+ """++ from a2a.types import (+ Part,+ TextPart,+ FilePart,+ FileWithUri,+ FileWithBytes,+ DataPart,+ Role,+ Message,+ )++ self.assert_list_of_msgs(msgs)++ parts = []+ for msg in msgs:+ for block in msg.get_content_blocks():+ block_type = block.get("type")+ if block_type == "text" and block.get("text"):+ parts.append(+ Part(+ root=TextPart(+ text=block.get("text"),+ ),+ ),+ )++ elif block_type == "thinking" and block.get("thinking"):+ parts.append(+ Part(+ root=TextPart(+ text=block.get("thinking"),+ ),+ ),+ )++ elif block_type in [+ "image",+ "video",+ "audio",+ ] and block.get("source"):+ source = block.get("source", {})+ source_type = source.get("type")++ if source_type == "url":+ parts.append(+ Part(+ root=FilePart(+ file=FileWithUri(+ uri=source.get("url"),+ ),+ ),+ ),+ )++ elif source_type == "base64":+ parts.append(+ Part(+ root=FilePart(+ file=FileWithBytes(+ bytes=source.get("data"),+ mime_type=source.get("media_type"),+ ),+ ),+ ),+ )++ else:+ raise ValueError(+ f"Unsupported source type: {source_type}",+ )++ elif block_type in ["tool_use", "tool_result"]:+ parts.append(+ Part(+ root=DataPart(+ data=block,+ ),+ ),+ )++ else:+ logger.error(+ "Unsupported block type %s in A2AFormatter.",+ block_type,+ )++ a2a_message = Message(+ message_id=str(uuid.uuid4()),+ role=Role.user,+ parts=parts,+ )++ return a2a_message++ async def format_a2a_message(self, name: str, message: Message) -> Msg:+ """Convert A2A Message object back to AgentScope Msg format.++ Args:+ name (`str`):+ The name of the message sender.+ message (`Message`):+ The A2A Message object to be converted.++ Returns:+ `list[Msg]`:+ List of converted AgentScope Msg objects.+ """++ from a2a.types import Role++ content = []+ metadata = None+ for part in message.parts:+ content.append(+ await self._format_a2a_part(part),+ )++ if message.role == Role.user:+ role: Literal["user", "assistant"] = "user"+ elif message.role == Role.agent:+ role = "assistant"+ else:+ raise ValueError(+ f"Unsupported role: {message.role} in A2A message.",+ )++ return Msg(+ name=name,+ role=role,+ content=content,+ metadata=metadata,+ )++ @staticmethod+ def _guess_type(+ uri: str | None = None,+ mime_type: str | None = None,+ ) -> Literal["image", "video", "audio", "unknown"]:+ """Guess the content type from the uri or mime type.++ Args:+ uri (`str | None`, optional):+ The uri of the content.+ mime_type (`str | None`, optional):+ The mime type of the content.++ Returns:+ `Literal["image", "video", "audio", "unknown"]`:+ The guessed content type.+ """+ if mime_type is None and uri is None:+ raise ValueError(+ "Either uri or mime_type must be provided to guess the"+ " content type.",+ )++ if mime_type is None:+ mime_type, _encoding = mimetypes.guess_type(uri or "")++ if isinstance(mime_type, str):+ if mime_type.startswith("image/"):+ return "image"++ if mime_type.startswith("video/"):+ return "video"++ if mime_type.startswith("audio/"):+ return "audio"++ return "unknown"++ async def format_a2a_task(self, name: str, task: Task) -> list[Msg]:+ """Convert A2A Task object back to AgentScope Msg format.++ Args:+ name (`str`):+ The name of the message sender.+ task (`Task`):+ The A2A Task object to be converted.++ Returns:+ `list[Msg]`:+ Converted AgentScope Msg objects.+ """+ msgs = []+ if task.status and task.status.message:+ msgs.append(+ await self.format_a2a_message(name, task.status.message),+ )++ merged_msgs = []+ for msg in msgs:+ if merged_msgs and merged_msgs[-1].role == msg.role:+ merged_msgs[-1].content.extend(msg.content)++ else:+ merged_msgs.append(msg)++ if task.artifacts:+ for artifact in task.artifacts:+ artifact_content = [+ await self._format_a2a_part(_) for _ in artifact.parts+ ]++ if merged_msgs and merged_msgs[-1].role == "assistant":+ merged_msgs[-1].content.extend(artifact_content)+ merged_msgs[-1].metadata = artifact.metadata++ else:+ merged_msgs.append(+ Msg(+ name=name,+ role="assistant",+ content=artifact_content,+ metadata=artifact.metadata,+ ),+ )++ return merged_msgs++ async def _format_a2a_part(self, part: Part) -> ContentBlock:+ """Convert a single A2A Part object into AgentScope ContentBlock.++ .. note:: We will try to convert the `DataPart` into tool use and tool+ result blocks if possible.++ Args:+ part (`Part`):+ The A2A Part object to be converted.++ Returns:+ `ContentBlock`:+ The converted AgentScope ContentBlock.+ """++ from a2a.types import (+ TextPart,+ FilePart,+ FileWithUri,+ FileWithBytes,+ DataPart,+ )++ if isinstance(part.root, TextPart):+ return TextBlock(+ type="text",+ text=part.root.text,+ )++ if isinstance(part.root, FilePart):+ if isinstance(part.root.file, FileWithUri):+ return { # type: ignore[return-value, misc]+ "type": self._guess_type(+ part.root.file.uri,+ part.root.file.mime_type,+ ),+ "source": URLSource(+ type="url",+ url=part.root.file.uri,+ ),+ }++ if isinstance(part.root.file, FileWithBytes):+ return { # type: ignore[return-value, misc]+ "type": self._guess_type(+ mime_type=part.root.file.mime_type,+ ),+ "source": Base64Source(+ type="base64",+ media_type=part.root.file.mime_type+ or "application/octet-stream",+ data=part.root.file.bytes,+ ),+ }++ raise ValueError(+ f"Unsupported File type: {type(part.root.file)} in A2A"+ "message.",+ )++ if isinstance(part.root, DataPart):+ # Maybe the tool use and tool result blocks+ if {+ "type",+ "name",+ "input",+ "id",+ } <= part.root.data.keys() and part.root.data[+ "type"+ ] == "tool_use":+ return part.root.data++ if {+ "type",+ "name",+ "output",+ "id",+ } <= part.root.data.keys() and part.root.data[+ "type"+ ] == "tool_result":+ return part.root.data++ # TODO: what about the other data parts?+ return TextBlock(+ type="text",+ text=str(part.root.data),+ )++ raise ValueError(+ f"Unsupported Part type: {type(part.root)} in A2A message"+ f": {part.root}",+ )diff --git a/tests/a2a_agent_test.py b/tests/a2a_agent_test.pynew file mode 100644index 000000000..ad50aaa1f--- /dev/null+++ b/tests/a2a_agent_test.py@@ -0,0 +1,253 @@+# -*- coding: utf-8 -*-+# pylint: disable=protected-access+"""The A2A agent unittests."""+from typing import Any, AsyncIterator+from unittest import IsolatedAsyncioTestCase++from a2a.types import (+ AgentCard,+ AgentCapabilities,+ Message as A2AMessage,+ Part,+ Role as A2ARole,+ Task,+ TaskState,+ TaskStatus,+ TextPart,+ Artifact,+)++from agentscope.agent import A2AAgent+from agentscope.message import Msg+++class MockA2AClient:+ """Mock A2A client for testing."""++ def __init__(self, response_type: str = "message") -> None:+ """Initialize mock client.++ Args:+ response_type (`str`):+ Type of response to simulate: "message", "task", or "error".+ """+ self.response_type = response_type+ self.sent_messages = []++ async def send_message(+ self,+ message: A2AMessage,+ ) -> AsyncIterator[A2AMessage | tuple[Task, Any]]:+ """Mock send_message method."""+ self.sent_messages.append(message)++ if self.response_type == "message":+ # Return a simple A2A message+ response = A2AMessage(+ message_id="test-msg-id",+ role=A2ARole.agent,+ parts=[+ Part(root=TextPart(text="Hello from remote agent")),+ ],+ )+ yield response++ elif self.response_type == "task":+ # Return a task with completed state+ task = Task(+ id="test-task-id",+ context_id="test-context-id",+ status=TaskStatus(+ state=TaskState.completed,+ message=A2AMessage(+ message_id="status-msg-id",+ role=A2ARole.agent,+ parts=[+ Part(root=TextPart(text="Task completed")),+ ],+ ),+ ),+ artifacts=[+ Artifact(+ artifact_id="artifact-1",+ name="test_artifact",+ description="Test artifact",+ parts=[+ Part(root=TextPart(text="Artifact content")),+ ],+ ),+ ],+ )+ yield (task, None)++ elif self.response_type == "error":+ raise RuntimeError("Simulated communication error")+++class MockClientFactory:+ """Mock ClientFactory for testing."""++ def __init__(self, response_type: str = "message") -> None:+ """Initialize mock factory."""+ self.response_type = response_type+ self.created_clients = []++ def create(self, card: AgentCard) -> MockA2AClient:+ """Create a mock client."""+ _ = card # Used by real ClientFactory, not needed in mock+ client = MockA2AClient(self.response_type)+ self.created_clients.append(client)+ return client+++class A2AAgentTest(IsolatedAsyncioTestCase):+ """Test class for A2AAgent."""++ async def asyncSetUp(self) -> None:+ """Set up test fixtures."""+ self.test_agent_card = AgentCard(+ name="TestAgent",+ url="http://localhost:8000",+ description="Test A2A agent",+ version="1.0.0",+ capabilities=AgentCapabilities(),+ default_input_modes=["text/plain"],+ default_output_modes=["text/plain"],+ skills=[],+ )+ self.agent = A2AAgent(self.test_agent_card)++ async def test_reply_with_task(self) -> None:+ """Test reply method with task response."""+ # Mock the client factory+ self.agent._a2a_client_factory = MockClientFactory(+ response_type="task",+ )++ response = await self.agent(+ Msg(name="user", content="Process this", role="user"),+ )++ self.assertEqual(response.name, "TestAgent")+ self.assertEqual(response.role, "assistant")++ # Should contain artifact content+ self.assertEqual(+ response.content,+ [+ {+ "type": "text",+ "text": "Task completed",+ },+ {+ "type": "text",+ "text": "Artifact content",+ },+ ],+ )++ async def test_reply_with_no_messages(self) -> None:+ """Test reply method with no messages returns prompt message."""+ self.agent._a2a_client_factory = MockClientFactory()++ # Test with None - should return prompt message+ response = await self.agent(None)+ self.assertEqual(response.name, "TestAgent")+ self.assertEqual(response.role, "assistant")+ self.assertListEqual(+ response.get_content_blocks(),+ [+ {+ "type": "text",+ "text": "Hello from remote agent",+ },+ ],+ )++ # Test with empty list - should return prompt message+ response = await self.agent([])+ self.assertListEqual(+ response.get_content_blocks(),+ [+ {+ "type": "text",+ "text": "Hello from remote agent",+ },+ ],+ )++ # Test with list of None - should return prompt message+ response = await self.agent([None, None])+ self.assertListEqual(+ response.get_content_blocks(),+ [+ {+ "type": "text",+ "text": "Hello from remote agent",+ },+ ],+ )++ async def test_observe_method(self) -> None:+ """Test observe method stores messages for next reply."""+ # Initially no observed messages+ self.assertEqual(len(self.agent._observed_msgs), 0)++ # Observe single message+ await self.agent.observe(+ Msg(name="user", content="First observed", role="user"),+ )+ self.assertEqual(len(self.agent._observed_msgs), 1)++ # Observe multiple messages+ msg2 = Msg(name="user", content="Second observed", role="user")+ msg3 = Msg(name="user", content="Third observed", role="user")+ await self.agent.observe([msg2, msg3])+ self.assertEqual(len(self.agent._observed_msgs), 3)++ # Observe None should not change anything+ await self.agent.observe(None)+ self.assertEqual(len(self.agent._observed_msgs), 3)++ async def test_observe_and_reply_merge(self) -> None:+ """Test that observed messages are merged with reply input."""+ mock_factory = MockClientFactory()+ self.agent._a2a_client_factory = mock_factory++ # Observe some messages+ await self.agent.observe(+ Msg(name="user", content="Observed message", role="user"),+ )++ # Reply with another message+ await self.agent.reply(+ Msg(name="user", content="Reply message", role="user"),+ )++ # Check that the send A2A message contains both observed and input+ sent_msg = mock_factory.created_clients[0].sent_messages[0]+ self.assertEqual(len(sent_msg.parts), 2)++ # Check observed messages were cleared after reply+ self.assertEqual(len(self.agent._observed_msgs), 0)++ async def test_reply_with_only_observed_messages(self) -> None:+ """Test reply with None input uses only observed messages."""+ mock_factory = MockClientFactory()+ self.agent._a2a_client_factory = mock_factory++ # Observe a message+ await self.agent.observe(+ Msg(name="user", content="Only observed", role="user"),+ )++ # Reply with None+ await self.agent(None)++ # Should have sent the observed message+ sent_msg = mock_factory.created_clients[0].sent_messages[0]+ self.assertEqual(len(sent_msg.parts), 1)+ self.assertEqual(sent_msg.parts[0].root.text, "Only observed")++ # Observed messages should be cleared+ self.assertEqual(len(self.agent._observed_msgs), 0)diff --git a/tests/a2a_resolver_test.py b/tests/a2a_resolver_test.pynew file mode 100644index 000000000..633fabda0--- /dev/null+++ b/tests/a2a_resolver_test.py@@ -0,0 +1,72 @@+# -*- coding: utf-8 -*-+"""The agent card resolver tests for A2A agents."""+import json+import os+from unittest import IsolatedAsyncioTestCase++from a2a.types import AgentCard, AgentCapabilities, AgentSkill++from agentscope.a2a import FileAgentCardResolver+++class A2AAgentCardResolverTest(IsolatedAsyncioTestCase):+ """Test the A2A agent card resolver."""++ async def asyncSetUp(self) -> None:+ """Set up the test case."""+ self.agent_card = AgentCard(+ name="Friday",+ description="A simple ReAct agent that handles input queries",+ url="http://localhost:8000",+ version="1.0.0",+ capabilities=AgentCapabilities(+ push_notifications=False,+ state_transition_history=True,+ streaming=True,+ ),+ default_input_modes=["text/plain"],+ default_output_modes=["text/plain"],+ skills=[+ AgentSkill(+ name="execute_python_code",+ id="execute_python_code",+ description="Execute Python code snippets.",+ tags=["code_execution"],+ ),+ AgentSkill(+ name="execute_shell_command",+ id="execute_shell_command",+ description="Execute shell commands on the server.",+ tags=["code_execution"],+ ),+ AgentSkill(+ name="view_text_file",+ id="view_text_file",+ description="View the content of a text file on the "+ "server.",+ tags=["file_viewing"],+ ),+ ],+ )+ self.agent_card_path = "./test_agent_card.json"++ async def test_file_card_resolver(self) -> None:+ """Test the file agent card resolver."""+ try:+ # Save one agent card to a file+ json_dict = self.agent_card.model_dump()+ with open(self.agent_card_path, "w", encoding="utf-8") as file:+ json.dump(json_dict, file)++ agent_card = await FileAgentCardResolver(+ file_path=self.agent_card_path,+ ).get_agent_card()++ self.assertDictEqual(+ agent_card.model_dump(),+ self.agent_card.model_dump(),+ )++ finally:+ if os.path.exists(self.agent_card_path):+ os.remove(self.agent_card_path)diff --git a/tests/formatter_a2a_test.py b/tests/formatter_a2a_test.pynew file mode 100644index 000000000..2c7ec9f8f--- /dev/null+++ b/tests/formatter_a2a_test.py@@ -0,0 +1,404 @@+# -*- coding: utf-8 -*-+"""Test the a2a formatter class."""+from unittest import IsolatedAsyncioTestCase++from a2a.types import (+ Message,+ TextPart,+ FilePart,+ DataPart,+ FileWithUri,+ FileWithBytes,+ Role,+ Part,+ Task,+ Artifact,+ TaskStatus,+ TaskState,+)++from agentscope.formatter import A2AChatFormatter+from agentscope.message import (+ Msg,+ TextBlock,+ ThinkingBlock,+ ToolUseBlock,+ ToolResultBlock,+ ImageBlock,+ URLSource,+ Base64Source,+ AudioBlock,+ VideoBlock,+)+++class A2AFormatterTest(IsolatedAsyncioTestCase):+ """Test the A2A formatter class."""++ async def asyncSetUp(self) -> None:+ """Set up the test case."""+ self.formatter = A2AChatFormatter()+ self.as_msgs = [+ Msg(+ "user",+ content="Hello, how are you?",+ role="user",+ ),+ Msg(+ "user",+ content=[+ TextBlock(+ type="text",+ text="Hello, how are you?",+ ),+ ThinkingBlock(+ type="thinking",+ thinking="yes",+ ),+ ToolUseBlock(+ type="tool_use",+ id="tool_1",+ name="tool_1",+ input={"param1": "value1"},+ ),+ ToolResultBlock(+ type="tool_result",+ id="tool_1",+ name="tool_1",+ output="Tool output here.",+ ),+ ImageBlock(+ type="image",+ source=URLSource(+ type="url",+ url="https://example.com/image.png",+ ),+ ),+ AudioBlock(+ type="audio",+ source=Base64Source(+ type="base64",+ data="UklGRigAAABXQVZFZm10IBAAAAABAAEAQB8AAIA+"+ "AAACABAAZGF0YQAAAAA=",+ media_type="audio/wav",+ ),+ ),+ VideoBlock(+ type="video",+ source=URLSource(+ type="url",+ url="https://example.com/video.mp4",+ ),+ ),+ ],+ role="user",+ ),+ ]+ self.a2a_msg = Message(+ role=Role.user,+ context_id="123",+ extensions=["ext1", "ext2"],+ message_id="abc",+ parts=[+ Part(+ root=TextPart(+ text="Hello, how are you?",+ ),+ ),+ Part(+ root=FilePart(+ file=FileWithUri(+ mime_type="audio/wav",+ name="greeting.wav",+ uri="https://example.com/greeting.wav",+ ),+ ),+ ),+ Part(+ root=FilePart(+ file=FileWithBytes(+ bytes="UklGRigAAABXQVZFZm10IBAAAAABAAEAQB8AAIA+"+ "AAACABAAZGF0YQAAAAA=",+ mime_type="audio/wav",+ name="greeting.wav",+ ),+ ),+ ),+ Part(+ root=DataPart(+ data={+ "type": "tool_use",+ "id": "tool_1",+ "name": "tool_1",+ "input": {+ "param1": "value1",+ },+ },+ ),+ ),+ Part(+ root=DataPart(+ data={+ "type": "tool_result",+ "id": "tool_1",+ "name": "tool_1",+ "output": "Tool output here.",+ },+ ),+ ),+ Part(+ root=DataPart(+ data={+ "type": "unknown_type",+ "content": "Some unknown content",+ },+ ),+ ),+ ],+ )++ async def test_as_to_a2a(self) -> None:+ """Test conversion from agentscope message to A2A message."""+ a2a_msg = await self.formatter.format(self.as_msgs)+ self.assertIsInstance(a2a_msg, Message)+ self.assertListEqual(+ [_.model_dump() for _ in a2a_msg.parts],+ [+ {+ "kind": "text",+ "metadata": None,+ "text": "Hello, how are you?",+ },+ {+ "kind": "text",+ "metadata": None,+ "text": "Hello, how are you?",+ },+ {+ "kind": "text",+ "metadata": None,+ "text": "yes",+ },+ {+ "data": {+ "type": "tool_use",+ "id": "tool_1",+ "name": "tool_1",+ "input": {+ "param1": "value1",+ },+ },+ "kind": "data",+ "metadata": None,+ },+ {+ "data": {+ "type": "tool_result",+ "id": "tool_1",+ "name": "tool_1",+ "output": "Tool output here.",+ },+ "kind": "data",+ "metadata": None,+ },+ {+ "file": {+ "mimeType": None,+ "name": None,+ "uri": "https://example.com/image.png",+ },+ "kind": "file",+ "metadata": None,+ },+ {+ "file": {+ "bytes": "UklGRigAAABXQVZFZm10IBAAAAABAAEAQB8AAIA+"+ "AAACABAAZGF0YQAAAAA=",+ "mimeType": "audio/wav",+ "name": None,+ },+ "kind": "file",+ "metadata": None,+ },+ {+ "file": {+ "mimeType": None,+ "name": None,+ "uri": "https://example.com/video.mp4",+ },+ "kind": "file",+ "metadata": None,+ },+ ],+ )+ self.assertEqual(+ a2a_msg.role,+ "user",+ )++ a2a_msg = await self.formatter.format([])+ self.assertListEqual(+ a2a_msg.parts,+ [],+ )+ self.assertEqual(+ a2a_msg.role,+ "user",+ )++ async def test_a2a_msg_to_as(self) -> None:+ """Test conversion from A2A message to agentscope message."""+ as_msg = await self.formatter.format_a2a_message(+ "Friday",+ self.a2a_msg,+ )++ self.assertEqual(+ as_msg.role,+ "user",+ )+ self.assertListEqual(+ as_msg.get_content_blocks(),+ [+ {"type": "text", "text": "Hello, how are you?"},+ {+ "type": "audio",+ "source": {+ "type": "url",+ "url": "https://example.com/greeting.wav",+ },+ },+ {+ "type": "audio",+ "source": {+ "type": "base64",+ "media_type": "audio/wav",+ "data": "UklGRigAAABXQVZFZm10IBAAAAABAAEAQB8AAIA+"+ "AAACABAAZGF0YQAAAAA=",+ },+ },+ {+ "type": "tool_use",+ "id": "tool_1",+ "name": "tool_1",+ "input": {"param1": "value1"},+ },+ {+ "type": "tool_result",+ "id": "tool_1",+ "name": "tool_1",+ "output": "Tool output here.",+ },+ {+ "type": "text",+ "text": "{'type': 'unknown_type', 'content': 'Some "+ "unknown content'}",+ },+ ],+ )++ async def test_a2a_task_to_as(self) -> None:+ """Test conversion from A2A task to agentscope message."""++ as_msgs = await self.formatter.format_a2a_task(+ name="Friday",+ task=Task(+ context_id="abc",+ artifacts=[+ Artifact(+ artifact_id="123",+ parts=[+ Part(+ root=TextPart(+ text="This is an artifact text part.",+ ),+ ),+ Part(+ root=DataPart(+ data={+ "type": "tool_result",+ "id": "tool_2",+ "name": "tool_2",+ "output": "Artifact tool output.",+ },+ ),+ ),+ ],+ ),+ ],+ id="task_1",+ status=TaskStatus(+ message=self.a2a_msg,+ state=TaskState.completed,+ timestamp="def",+ ),+ ),+ )+ self.assertEqual(len(as_msgs), 2)+ self.maxDiff = None+ self.assertDictEqual(+ as_msgs[0].to_dict(),+ {+ "id": as_msgs[0].id,+ "name": "Friday",+ "role": "user",+ "content": [+ {"type": "text", "text": "Hello, how are you?"},+ {+ "type": "audio",+ "source": {+ "type": "url",+ "url": "https://example.com/greeting.wav",+ },+ },+ {+ "type": "audio",+ "source": {+ "type": "base64",+ "media_type": "audio/wav",+ "data": "UklGRigAAABXQVZFZm10IBAAAAABAAEAQB8AAIA+"+ "AAACABAAZGF0YQAAAAA=",+ },+ },+ {+ "type": "tool_use",+ "id": "tool_1",+ "name": "tool_1",+ "input": {"param1": "value1"},+ },+ {+ "type": "tool_result",+ "id": "tool_1",+ "name": "tool_1",+ "output": "Tool output here.",+ },+ {+ "type": "text",+ "text": "{'type': 'unknown_type', 'content': 'Some "+ "unknown content'}",+ },+ ],+ "metadata": None,+ "timestamp": as_msgs[0].timestamp,+ },+ )++ self.assertDictEqual(+ as_msgs[1].to_dict(),+ {+ "id": as_msgs[1].id,+ "name": "Friday",+ "role": "assistant",+ "content": [+ {"type": "text", "text": "This is an artifact text part."},+ {+ "type": "tool_result",+ "id": "tool_2",+ "name": "tool_2",+ "output": "Artifact tool output.",+ },+ ],+ "metadata": None,+ "timestamp": as_msgs[1].timestamp,+ },+ )