chore: import upstream snapshot with attribution
Continuous Integration / Pre-commit Linter (push) Has been cancelled
Continuous Integration / Mypy Check (Python 3.10) (push) Has been cancelled
Continuous Integration / Mypy Check (Python 3.11) (push) Has been cancelled
Continuous Integration / Mypy Check (Python 3.12) (push) Has been cancelled
Continuous Integration / Mypy Check (Python 3.13) (push) Has been cancelled
Continuous Integration / Unit Tests (Python 3.10) (push) Has been cancelled
Continuous Integration / Unit Tests (Python 3.11) (push) Has been cancelled
Continuous Integration / Unit Tests (Python 3.12) (push) Has been cancelled
Continuous Integration / Unit Tests (Python 3.13) (push) Has been cancelled
Continuous Integration / Unit Tests (Python 3.14) (push) Has been cancelled
Continuous Integration / A2A v0.3 Tests (Python 3.10) (push) Has been cancelled
Continuous Integration / A2A v0.3 Tests (Python 3.11) (push) Has been cancelled
Continuous Integration / A2A v0.3 Tests (Python 3.12) (push) Has been cancelled
Copybara PR Handler / close-imported-pr (push) Has been cancelled
Continuous Integration / A2A v0.3 Tests (Python 3.13) (push) Has been cancelled
Continuous Integration / A2A v0.3 Tests (Python 3.14) (push) Has been cancelled
Continuous Integration / Pre-commit Linter (push) Has been cancelled
Continuous Integration / Mypy Check (Python 3.10) (push) Has been cancelled
Continuous Integration / Mypy Check (Python 3.11) (push) Has been cancelled
Continuous Integration / Mypy Check (Python 3.12) (push) Has been cancelled
Continuous Integration / Mypy Check (Python 3.13) (push) Has been cancelled
Continuous Integration / Unit Tests (Python 3.10) (push) Has been cancelled
Continuous Integration / Unit Tests (Python 3.11) (push) Has been cancelled
Continuous Integration / Unit Tests (Python 3.12) (push) Has been cancelled
Continuous Integration / Unit Tests (Python 3.13) (push) Has been cancelled
Continuous Integration / Unit Tests (Python 3.14) (push) Has been cancelled
Continuous Integration / A2A v0.3 Tests (Python 3.10) (push) Has been cancelled
Continuous Integration / A2A v0.3 Tests (Python 3.11) (push) Has been cancelled
Continuous Integration / A2A v0.3 Tests (Python 3.12) (push) Has been cancelled
Copybara PR Handler / close-imported-pr (push) Has been cancelled
Continuous Integration / A2A v0.3 Tests (Python 3.13) (push) Has been cancelled
Continuous Integration / A2A v0.3 Tests (Python 3.14) (push) Has been cancelled
This commit is contained in:
@@ -0,0 +1,15 @@
|
||||
# Copyright 2026 Google LLC
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
|
||||
"""A2A integration tests package."""
|
||||
@@ -0,0 +1,85 @@
|
||||
# Copyright 2026 Google LLC
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
|
||||
"""A2A Client for integration tests."""
|
||||
|
||||
from a2a.client.client_factory import ClientFactory as A2AClientFactory
|
||||
from a2a.extensions.common import HTTP_EXTENSION_HEADER
|
||||
from google.adk.a2a import _compat
|
||||
from google.adk.a2a.agent.interceptors.new_integration_extension import _NEW_A2A_ADK_INTEGRATION_EXTENSION
|
||||
from google.adk.agents.remote_a2a_agent import RemoteA2aAgent
|
||||
import httpx
|
||||
|
||||
from .server import agent_card
|
||||
|
||||
|
||||
def create_client(app, streaming: bool = False) -> RemoteA2aAgent:
|
||||
"""Creates a RemoteA2aAgent connected to the provided FastAPI app.
|
||||
|
||||
Args:
|
||||
app: The FastAPI application (server) to connect to.
|
||||
streaming: Whether to enable streaming mode in the client.
|
||||
|
||||
Returns:
|
||||
A RemoteA2aAgent instance.
|
||||
"""
|
||||
|
||||
client = httpx.AsyncClient(
|
||||
transport=httpx.ASGITransport(app=app), base_url="http://test"
|
||||
)
|
||||
|
||||
client_config = _compat.make_client_config(
|
||||
httpx_client=client,
|
||||
streaming=streaming,
|
||||
polling=False,
|
||||
)
|
||||
factory = A2AClientFactory(config=client_config)
|
||||
|
||||
# use_legacy=False forces the new implementation
|
||||
agent = RemoteA2aAgent(
|
||||
name="remote_agent",
|
||||
agent_card=agent_card,
|
||||
a2a_client_factory=factory,
|
||||
use_legacy=False,
|
||||
)
|
||||
|
||||
return agent
|
||||
|
||||
|
||||
def create_a2a_client(app, streaming: bool = False):
|
||||
"""Creates a bare A2A Client connected to the provided FastAPI app.
|
||||
|
||||
This is in contrast to create_client, which wraps the a2a_client into a
|
||||
RemoteA2aAgent for the standard runner framework ecosystem execution.
|
||||
|
||||
Args:
|
||||
app: The FastAPI application (server) to connect to.
|
||||
streaming: Whether to enable streaming mode in the client.
|
||||
|
||||
Returns:
|
||||
An A2A Client instance.
|
||||
"""
|
||||
client = httpx.AsyncClient(
|
||||
transport=httpx.ASGITransport(app=app),
|
||||
base_url="http://test",
|
||||
headers={HTTP_EXTENSION_HEADER: _NEW_A2A_ADK_INTEGRATION_EXTENSION},
|
||||
)
|
||||
|
||||
client_config = _compat.make_client_config(
|
||||
httpx_client=client,
|
||||
streaming=streaming,
|
||||
polling=False,
|
||||
)
|
||||
factory = A2AClientFactory(config=client_config)
|
||||
return factory.create(agent_card)
|
||||
@@ -0,0 +1,164 @@
|
||||
# Copyright 2026 Google LLC
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
|
||||
"""A2A Server for integration tests."""
|
||||
|
||||
from unittest.mock import AsyncMock
|
||||
from unittest.mock import Mock
|
||||
|
||||
try:
|
||||
from a2a.server.apps.jsonrpc.fastapi_app import A2AFastAPIApplication
|
||||
from a2a.server.request_handlers.default_request_handler import DefaultRequestHandler
|
||||
from a2a.server.tasks.inmemory_task_store import InMemoryTaskStore
|
||||
except ImportError:
|
||||
A2AFastAPIApplication = None
|
||||
DefaultRequestHandler = None
|
||||
InMemoryTaskStore = None
|
||||
from google.adk.a2a import _compat
|
||||
from google.adk.a2a.executor.a2a_agent_executor import A2aAgentExecutor
|
||||
from google.adk.a2a.executor.config import A2aAgentExecutorConfig
|
||||
from google.adk.agents.base_agent import BaseAgent
|
||||
from google.adk.artifacts.in_memory_artifact_service import InMemoryArtifactService
|
||||
from google.adk.runners import Runner
|
||||
from google.adk.sessions.in_memory_session_service import InMemorySessionService
|
||||
from google.genai import types
|
||||
|
||||
|
||||
class FakeRunner(Runner):
|
||||
"""A Fake Runner that delegates run_async to a provided function."""
|
||||
|
||||
def __init__(self, run_async_fn):
|
||||
agent = Mock(spec=BaseAgent)
|
||||
agent.name = "FakeAgent"
|
||||
|
||||
session_service = InMemorySessionService()
|
||||
super().__init__(
|
||||
app_name="FakeApp",
|
||||
agent=agent,
|
||||
session_service=session_service,
|
||||
)
|
||||
self.run_async_fn = run_async_fn
|
||||
|
||||
mock_artifact_service = Mock()
|
||||
mock_artifact_service.load_artifact = AsyncMock(
|
||||
return_value=types.Part(text="artifact content")
|
||||
)
|
||||
self.artifact_service = mock_artifact_service
|
||||
|
||||
async def run_async(self, **kwargs):
|
||||
async for event in self.run_async_fn(**kwargs):
|
||||
yield event
|
||||
|
||||
|
||||
if _compat.IS_A2A_V1:
|
||||
agent_card = _compat.parse_agent_card({
|
||||
"name": "remote_agent",
|
||||
"description": "A fun fact generator agent",
|
||||
"version": "0.0.1",
|
||||
"supported_interfaces": [
|
||||
{"url": "http://test", "protocol_binding": "JSONRPC"}
|
||||
],
|
||||
"default_input_modes": ["text/plain"],
|
||||
"default_output_modes": ["text/plain"],
|
||||
})
|
||||
else:
|
||||
agent_card = _compat.parse_agent_card({
|
||||
"name": "remote_agent",
|
||||
"url": "http://test",
|
||||
"description": "A fun fact generator agent",
|
||||
"capabilities": {"streaming": True},
|
||||
"version": "0.0.1",
|
||||
"defaultInputModes": ["text/plain"],
|
||||
"defaultOutputModes": ["text/plain"],
|
||||
"skills": [],
|
||||
})
|
||||
|
||||
|
||||
def create_server_app(
|
||||
run_async_fn=None,
|
||||
config: A2aAgentExecutorConfig | None = None,
|
||||
task_store=None,
|
||||
):
|
||||
"""Creates an A2A FastAPI application with a mocked runner.
|
||||
|
||||
Args:
|
||||
run_async_fn: A generator function that takes **kwargs and yields Event
|
||||
objects.
|
||||
config: Optional executor configuration.
|
||||
task_store: Optional task store instance. Defaults to InMemoryTaskStore.
|
||||
|
||||
Returns:
|
||||
A FastAPI application instance.
|
||||
"""
|
||||
runner = FakeRunner(run_async_fn)
|
||||
executor = A2aAgentExecutor(runner=runner, config=config)
|
||||
if task_store is None:
|
||||
task_store = InMemoryTaskStore()
|
||||
handler = DefaultRequestHandler(
|
||||
agent_executor=executor, task_store=task_store
|
||||
)
|
||||
|
||||
app = A2AFastAPIApplication(agent_card=agent_card, http_handler=handler)
|
||||
return app.build()
|
||||
|
||||
|
||||
class _FixedContentArtifactService(InMemoryArtifactService):
|
||||
"""``InMemoryArtifactService`` whose ``load_artifact`` always returns content."""
|
||||
|
||||
async def load_artifact(self, **kwargs):
|
||||
return types.Part(text="artifact content")
|
||||
|
||||
|
||||
class FakeRunnerV1(Runner):
|
||||
"""A Fake Runner for 1.x with a real in-memory artifact service."""
|
||||
|
||||
def __init__(self, run_async_fn):
|
||||
agent = Mock(spec=BaseAgent)
|
||||
agent.name = "FakeAgent"
|
||||
super().__init__(
|
||||
app_name="FakeApp",
|
||||
agent=agent,
|
||||
session_service=InMemorySessionService(),
|
||||
artifact_service=_FixedContentArtifactService(),
|
||||
)
|
||||
self.run_async_fn = run_async_fn
|
||||
|
||||
async def run_async(self, **kwargs):
|
||||
async for event in self.run_async_fn(**kwargs):
|
||||
yield event
|
||||
|
||||
|
||||
def create_server_app_v1(
|
||||
run_async_fn=None, config: A2aAgentExecutorConfig | None = None
|
||||
):
|
||||
"""Creates a 1.x Starlette app hosting an A2A executor (JSON-RPC routes).
|
||||
|
||||
Mirrors ``create_server_app`` but uses the 1.x route-factory path via
|
||||
``_compat.attach_a2a_routes_to_app`` instead of the 0.3-only
|
||||
``A2AFastAPIApplication``. Returns the Starlette app; callers must drive the
|
||||
app's lifespan so the routes are attached before sending requests.
|
||||
"""
|
||||
from a2a.server.tasks import InMemoryTaskStore as TaskStore
|
||||
from starlette.applications import Starlette
|
||||
|
||||
runner = FakeRunnerV1(run_async_fn)
|
||||
executor = A2aAgentExecutor(runner=runner, config=config)
|
||||
app = Starlette()
|
||||
_compat.attach_a2a_routes_to_app(
|
||||
app,
|
||||
agent_card=agent_card,
|
||||
agent_executor=executor,
|
||||
task_store=TaskStore(),
|
||||
)
|
||||
return app
|
||||
@@ -0,0 +1,821 @@
|
||||
# Copyright 2026 Google LLC
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
|
||||
"""Integration tests for A2A client-server interaction."""
|
||||
|
||||
import logging
|
||||
from unittest.mock import AsyncMock
|
||||
|
||||
try:
|
||||
from a2a.server.apps.jsonrpc.fastapi_app import A2AFastAPIApplication
|
||||
from a2a.server.request_handlers.request_handler import RequestHandler
|
||||
except ImportError:
|
||||
A2AFastAPIApplication = None
|
||||
RequestHandler = None
|
||||
from a2a.types import Message as A2AMessage
|
||||
from a2a.types import Part as A2APart
|
||||
from a2a.types import Task
|
||||
from a2a.types import TaskStatus
|
||||
|
||||
try:
|
||||
# 0.3.x-only wrapper part type; these integration tests are skipped on 1.x.
|
||||
from a2a.types import TextPart
|
||||
except ImportError:
|
||||
TextPart = None
|
||||
from google.adk.a2a import _compat
|
||||
from google.adk.a2a.agent.interceptors.new_integration_extension import _NEW_A2A_ADK_INTEGRATION_EXTENSION
|
||||
from google.adk.a2a.converters.to_adk_event import MOCK_FUNCTION_CALL_FOR_REQUIRED_USER_INPUT
|
||||
from google.adk.a2a.executor.config import A2aAgentExecutorConfig
|
||||
from google.adk.a2a.executor.interceptors.include_artifacts_in_a2a_event import include_artifacts_in_a2a_event_interceptor
|
||||
from google.adk.agents.remote_a2a_agent import A2A_METADATA_PREFIX
|
||||
from google.adk.events.event import Event
|
||||
from google.adk.events.event_actions import EventActions
|
||||
from google.adk.platform import uuid as platform_uuid
|
||||
from google.adk.runners import Runner
|
||||
from google.adk.sessions.in_memory_session_service import InMemorySessionService
|
||||
from google.genai import types
|
||||
import pytest
|
||||
|
||||
pytestmark = pytest.mark.skipif(
|
||||
_compat.IS_A2A_V1,
|
||||
reason="integration tests use 0.3-only A2AFastAPIApplication",
|
||||
)
|
||||
|
||||
from .client import create_a2a_client
|
||||
from .client import create_client
|
||||
from .server import agent_card
|
||||
from .server import create_server_app
|
||||
|
||||
logger = logging.getLogger("google_adk." + __name__)
|
||||
|
||||
|
||||
def create_streaming_mock_run_async(received_requests: list):
|
||||
"""Creates a mock_run_async that streams multiple chunks."""
|
||||
|
||||
async def mock_run_async(**kwargs):
|
||||
received_requests.append(kwargs)
|
||||
yield Event(
|
||||
author="FakeAgent",
|
||||
content=types.Content(parts=[types.Part(text="Hello")]),
|
||||
partial=True,
|
||||
)
|
||||
yield Event(
|
||||
author="FakeAgent",
|
||||
content=types.Content(parts=[types.Part(text=" world")]),
|
||||
partial=True,
|
||||
)
|
||||
yield Event(
|
||||
author="FakeAgent",
|
||||
partial=True,
|
||||
actions=EventActions(artifact_delta={"file1": 1}),
|
||||
)
|
||||
yield Event(
|
||||
author="FakeAgent",
|
||||
content=types.Content(parts=[types.Part(text="Hello world")]),
|
||||
partial=False,
|
||||
)
|
||||
|
||||
return mock_run_async
|
||||
|
||||
|
||||
def create_non_streaming_mock_run_async(received_requests: list):
|
||||
"""Creates a mock_run_async that returns a single non-streaming event."""
|
||||
|
||||
async def mock_run_async(**kwargs):
|
||||
received_requests.append(kwargs)
|
||||
yield Event(
|
||||
author="FakeAgent",
|
||||
content=types.Content(parts=[types.Part(text="Hello world")]),
|
||||
partial=False,
|
||||
)
|
||||
|
||||
return mock_run_async
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_streaming_adk_to_streaming_a2a():
|
||||
"""Test streaming of normal text chunks."""
|
||||
received_requests = []
|
||||
mock_run_async = create_streaming_mock_run_async(received_requests)
|
||||
|
||||
app = create_server_app(mock_run_async)
|
||||
agent = create_client(app, streaming=True)
|
||||
|
||||
session_service = InMemorySessionService()
|
||||
await session_service.create_session(
|
||||
app_name="ClientApp", user_id="test_user", session_id="test_session"
|
||||
)
|
||||
client_runner = Runner(
|
||||
app_name="ClientApp",
|
||||
agent=agent,
|
||||
session_service=session_service,
|
||||
)
|
||||
|
||||
new_message = types.Content(parts=[types.Part(text="Hi")], role="user")
|
||||
|
||||
texts = []
|
||||
actions = []
|
||||
async for event in client_runner.run_async(
|
||||
user_id="test_user", session_id="test_session", new_message=new_message
|
||||
):
|
||||
if event.content and event.content.parts:
|
||||
for p in event.content.parts:
|
||||
if p.text:
|
||||
texts.append(p.text)
|
||||
if event.actions and event.actions.artifact_delta:
|
||||
actions.append(event.actions)
|
||||
|
||||
assert len(received_requests) == 1
|
||||
assert received_requests[0]["session_id"] is not None
|
||||
|
||||
assert texts == ["Hello", " world", "Hello world"]
|
||||
assert len(actions) == 1
|
||||
assert actions[0].artifact_delta == {"file1": 1}
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_streaming_adk_to_non_streaming_a2a():
|
||||
"""Test ADK streaming into A2A Non-Streaming."""
|
||||
received_requests = []
|
||||
mock_run_async = create_streaming_mock_run_async(received_requests)
|
||||
|
||||
app = create_server_app(mock_run_async)
|
||||
agent = create_client(app, streaming=False)
|
||||
|
||||
session_service = InMemorySessionService()
|
||||
await session_service.create_session(
|
||||
app_name="ClientApp", user_id="test_user", session_id="test_session"
|
||||
)
|
||||
client_runner = Runner(
|
||||
app_name="ClientApp", agent=agent, session_service=session_service
|
||||
)
|
||||
|
||||
new_message = types.Content(parts=[types.Part(text="Hi")], role="user")
|
||||
|
||||
texts = []
|
||||
async for event in client_runner.run_async(
|
||||
user_id="test_user", session_id="test_session", new_message=new_message
|
||||
):
|
||||
if event.content and event.content.parts:
|
||||
for p in event.content.parts:
|
||||
if p.text:
|
||||
texts.append(p.text)
|
||||
|
||||
assert len(received_requests) == 1
|
||||
assert texts == ["Hello world"]
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_non_streaming_adk_to_streaming_a2a():
|
||||
"""Test ADK Non-Streaming into A2A Streaming."""
|
||||
received_requests = []
|
||||
mock_run_async = create_non_streaming_mock_run_async(received_requests)
|
||||
|
||||
app = create_server_app(mock_run_async)
|
||||
agent = create_client(app, streaming=True)
|
||||
|
||||
session_service = InMemorySessionService()
|
||||
await session_service.create_session(
|
||||
app_name="ClientApp", user_id="test_user", session_id="test_session"
|
||||
)
|
||||
client_runner = Runner(
|
||||
app_name="ClientApp", agent=agent, session_service=session_service
|
||||
)
|
||||
|
||||
new_message = types.Content(parts=[types.Part(text="Hi")], role="user")
|
||||
|
||||
texts = []
|
||||
async for event in client_runner.run_async(
|
||||
user_id="test_user", session_id="test_session", new_message=new_message
|
||||
):
|
||||
if event.content and event.content.parts:
|
||||
for p in event.content.parts:
|
||||
if p.text:
|
||||
texts.append(p.text)
|
||||
|
||||
assert len(received_requests) == 1
|
||||
assert texts == ["Hello world"]
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_non_streaming_adk_to_non_streaming_a2a():
|
||||
"""Test ADK Non-Streaming into A2A Non-Streaming."""
|
||||
received_requests = []
|
||||
mock_run_async = create_non_streaming_mock_run_async(received_requests)
|
||||
|
||||
app = create_server_app(mock_run_async)
|
||||
agent = create_client(app, streaming=False)
|
||||
|
||||
session_service = InMemorySessionService()
|
||||
await session_service.create_session(
|
||||
app_name="ClientApp", user_id="test_user", session_id="test_session"
|
||||
)
|
||||
client_runner = Runner(
|
||||
app_name="ClientApp", agent=agent, session_service=session_service
|
||||
)
|
||||
|
||||
new_message = types.Content(parts=[types.Part(text="Hi")], role="user")
|
||||
|
||||
texts = []
|
||||
async for event in client_runner.run_async(
|
||||
user_id="test_user", session_id="test_session", new_message=new_message
|
||||
):
|
||||
if event.content and event.content.parts:
|
||||
for p in event.content.parts:
|
||||
if p.text:
|
||||
texts.append(p.text)
|
||||
|
||||
assert len(received_requests) == 1
|
||||
assert texts == ["Hello world"]
|
||||
|
||||
|
||||
def create_streaming_mock_run_async_with_multiple_agents(
|
||||
received_requests: list,
|
||||
):
|
||||
"""Creates a mock_run_async that streams multiple chunks."""
|
||||
|
||||
async def mock_run_async(**kwargs):
|
||||
received_requests.append(kwargs)
|
||||
yield Event(
|
||||
author="FakeAgent1",
|
||||
content=types.Content(parts=[types.Part(text="Hello")]),
|
||||
partial=True,
|
||||
)
|
||||
yield Event(
|
||||
author="FakeAgent2",
|
||||
content=types.Content(parts=[types.Part(text=" Hi")]),
|
||||
partial=True,
|
||||
)
|
||||
yield Event(
|
||||
author="FakeAgent1",
|
||||
content=types.Content(parts=[types.Part(text=" world")]),
|
||||
partial=True,
|
||||
)
|
||||
yield Event(
|
||||
author="FakeAgent2",
|
||||
content=types.Content(parts=[types.Part(text=" human")]),
|
||||
partial=True,
|
||||
)
|
||||
yield Event(
|
||||
author="FakeAgent1",
|
||||
content=types.Content(parts=[types.Part(text="Hello world")]),
|
||||
partial=False,
|
||||
)
|
||||
yield Event(
|
||||
author="FakeAgent2",
|
||||
content=types.Content(parts=[types.Part(text="Hi human")]),
|
||||
partial=False,
|
||||
)
|
||||
|
||||
return mock_run_async
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_multiple_agents_streaming_adk_to_streaming_a2a():
|
||||
"""Test streaming multiple agents chunks into A2A Streaming."""
|
||||
received_requests = []
|
||||
mock_run_async = create_streaming_mock_run_async_with_multiple_agents(
|
||||
received_requests
|
||||
)
|
||||
|
||||
app = create_server_app(mock_run_async)
|
||||
agent = create_client(app, streaming=True)
|
||||
|
||||
session_service = InMemorySessionService()
|
||||
await session_service.create_session(
|
||||
app_name="ClientApp", user_id="test_user", session_id="test_session"
|
||||
)
|
||||
client_runner = Runner(
|
||||
app_name="ClientApp", agent=agent, session_service=session_service
|
||||
)
|
||||
|
||||
new_message = types.Content(parts=[types.Part(text="Hi")], role="user")
|
||||
|
||||
texts = []
|
||||
async for event in client_runner.run_async(
|
||||
user_id="test_user", session_id="test_session", new_message=new_message
|
||||
):
|
||||
if event.content and event.content.parts:
|
||||
for p in event.content.parts:
|
||||
if p.text:
|
||||
texts.append(p.text)
|
||||
|
||||
assert len(received_requests) == 1
|
||||
assert texts == [
|
||||
"Hello",
|
||||
" Hi",
|
||||
" world",
|
||||
" human",
|
||||
"Hello world",
|
||||
"Hi human",
|
||||
]
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_function_calls():
|
||||
"""Test function call execution from agent."""
|
||||
received_requests = []
|
||||
|
||||
async def mock_run_async(**kwargs):
|
||||
received_requests.append(kwargs)
|
||||
yield Event(
|
||||
author="FakeAgent",
|
||||
content=types.Content(
|
||||
parts=[
|
||||
types.Part(
|
||||
function_call=types.FunctionCall(
|
||||
name="get_weather",
|
||||
args={"location": "San Francisco"},
|
||||
id="call_1",
|
||||
)
|
||||
),
|
||||
types.Part(
|
||||
function_response=types.FunctionResponse(
|
||||
name="get_weather",
|
||||
response={"temperature": "22C"},
|
||||
id="call_1",
|
||||
)
|
||||
),
|
||||
],
|
||||
role="model",
|
||||
),
|
||||
)
|
||||
|
||||
app = create_server_app(mock_run_async)
|
||||
agent = create_client(app)
|
||||
|
||||
session_service = InMemorySessionService()
|
||||
await session_service.create_session(
|
||||
app_name="ClientApp", user_id="test_user", session_id="test_session"
|
||||
)
|
||||
client_runner = Runner(
|
||||
app_name="ClientApp",
|
||||
agent=agent,
|
||||
session_service=session_service,
|
||||
)
|
||||
|
||||
new_message = types.Content(parts=[types.Part(text="Hi")], role="user")
|
||||
|
||||
func_calls = []
|
||||
func_responses = []
|
||||
async for event in client_runner.run_async(
|
||||
user_id="test_user", session_id="test_session", new_message=new_message
|
||||
):
|
||||
func_calls.extend(event.get_function_calls())
|
||||
if event.content and event.content.parts:
|
||||
for p in event.content.parts:
|
||||
if p.function_response:
|
||||
func_responses.append(p.function_response)
|
||||
|
||||
assert len(func_calls) == 1
|
||||
assert func_calls[0].name == "get_weather"
|
||||
assert func_calls[0].args == {"location": "San Francisco"}
|
||||
|
||||
assert len(func_responses) == 1
|
||||
assert func_responses[0].name == "get_weather"
|
||||
assert func_responses[0].response == {"temperature": "22C"}
|
||||
|
||||
|
||||
def create_long_running_mock_run_async(received_requests: list):
|
||||
"""Creates a mock_run_async for long running function tests."""
|
||||
|
||||
async def mock_run_async(**kwargs):
|
||||
received_requests.append(kwargs)
|
||||
if len(received_requests) == 1:
|
||||
yield Event(
|
||||
author="FakeAgent",
|
||||
content=types.Content(
|
||||
parts=[
|
||||
types.Part(
|
||||
function_call=types.FunctionCall(
|
||||
name="long_task", args={}, id="call_long"
|
||||
)
|
||||
)
|
||||
],
|
||||
role="model",
|
||||
),
|
||||
long_running_tool_ids={"call_long"},
|
||||
)
|
||||
yield Event(
|
||||
author="FakeAgent",
|
||||
content=types.Content(
|
||||
parts=[
|
||||
types.Part(
|
||||
function_response=types.FunctionResponse(
|
||||
name="long_task",
|
||||
response={"status": "pending"},
|
||||
id="call_long",
|
||||
)
|
||||
)
|
||||
],
|
||||
role="model",
|
||||
),
|
||||
)
|
||||
else:
|
||||
yield Event(
|
||||
author="FakeAgent",
|
||||
content=types.Content(
|
||||
parts=[types.Part(text="Task completed well")], role="model"
|
||||
),
|
||||
)
|
||||
|
||||
return mock_run_async
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_long_running_function_calls_success():
|
||||
"""Test long running function calls flow success with user response."""
|
||||
received_requests = []
|
||||
mock_run_async = create_long_running_mock_run_async(received_requests)
|
||||
|
||||
app = create_server_app(mock_run_async)
|
||||
agent = create_client(app, streaming=True)
|
||||
|
||||
session_service = InMemorySessionService()
|
||||
await session_service.create_session(
|
||||
app_name="ClientApp", user_id="test_user", session_id="test_session"
|
||||
)
|
||||
client_runner = Runner(
|
||||
app_name="ClientApp",
|
||||
agent=agent,
|
||||
session_service=session_service,
|
||||
)
|
||||
|
||||
new_message_1 = types.Content(parts=[types.Part(text="Hi")], role="user")
|
||||
|
||||
func_calls_1 = []
|
||||
func_responses_1 = []
|
||||
task_id_1 = ""
|
||||
has_long_running_id = False
|
||||
async for event in client_runner.run_async(
|
||||
user_id="test_user", session_id="test_session", new_message=new_message_1
|
||||
):
|
||||
if event.custom_metadata:
|
||||
task_id_1 = event.custom_metadata.get(
|
||||
A2A_METADATA_PREFIX + "task_id", task_id_1
|
||||
)
|
||||
if (
|
||||
event.long_running_tool_ids
|
||||
and "call_long" in event.long_running_tool_ids
|
||||
):
|
||||
has_long_running_id = True
|
||||
|
||||
func_calls_1.extend(event.get_function_calls())
|
||||
if event.content and event.content.parts:
|
||||
for p in event.content.parts:
|
||||
if p.function_response:
|
||||
func_responses_1.append(p.function_response)
|
||||
|
||||
assert has_long_running_id
|
||||
assert len(func_calls_1) == 1
|
||||
assert func_calls_1[0].name == "long_task"
|
||||
|
||||
assert len(func_responses_1) == 1
|
||||
assert func_responses_1[0].name == "long_task"
|
||||
assert func_responses_1[0].response == {"status": "pending"}
|
||||
|
||||
new_message_2 = types.Content(
|
||||
parts=[
|
||||
types.Part(
|
||||
function_response=types.FunctionResponse(
|
||||
name="long_task", response={"result": "done"}, id="call_long"
|
||||
)
|
||||
)
|
||||
],
|
||||
role="user",
|
||||
)
|
||||
|
||||
texts = []
|
||||
task_id_2 = ""
|
||||
async for event in client_runner.run_async(
|
||||
user_id="test_user", session_id="test_session", new_message=new_message_2
|
||||
):
|
||||
if event.custom_metadata:
|
||||
task_id_2 = event.custom_metadata.get(
|
||||
A2A_METADATA_PREFIX + "task_id", task_id_2
|
||||
)
|
||||
if event.content and event.content.parts:
|
||||
for p in event.content.parts:
|
||||
if p.text:
|
||||
texts.append(p.text)
|
||||
|
||||
assert task_id_1 == task_id_2
|
||||
assert "Task completed well" in texts
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_long_running_function_calls_error():
|
||||
"""Test long running function calls returns error on missing response."""
|
||||
received_requests = []
|
||||
mock_run_async = create_long_running_mock_run_async(received_requests)
|
||||
|
||||
app = create_server_app(mock_run_async)
|
||||
a2a_client = create_a2a_client(app, streaming=False)
|
||||
|
||||
request_1 = A2AMessage(
|
||||
message_id=platform_uuid.new_uuid(),
|
||||
parts=[A2APart(root=TextPart(text="Hi"))],
|
||||
role="user",
|
||||
)
|
||||
response_1_events = []
|
||||
async for event in a2a_client.send_message(request=request_1):
|
||||
response_1_events.append(event)
|
||||
|
||||
assert len(response_1_events) == 1
|
||||
# Extract task_id from Turn 1 responses
|
||||
assert response_1_events[0][1] is None
|
||||
task = response_1_events[0][0]
|
||||
assert isinstance(task, Task)
|
||||
assert task.status.state == _compat.TS_INPUT_REQUIRED
|
||||
extracted_task_id = task.id
|
||||
assert extracted_task_id is not None
|
||||
|
||||
request_2 = A2AMessage(
|
||||
message_id=platform_uuid.new_uuid(),
|
||||
parts=[A2APart(root=TextPart(text="Any update?"))],
|
||||
role="user",
|
||||
task_id=extracted_task_id,
|
||||
context_id=task.context_id if hasattr(task, "context_id") else None,
|
||||
)
|
||||
response_2_events = []
|
||||
async for event in a2a_client.send_message(request=request_2):
|
||||
response_2_events.append(event)
|
||||
|
||||
# Verify that we get an error response for the second request due to missing function response
|
||||
assert len(response_2_events) == 1
|
||||
assert response_2_events[0][1] is None
|
||||
error_response = response_2_events[0][0]
|
||||
assert isinstance(error_response, Task)
|
||||
assert error_response.status.message.parts[0].root.text == (
|
||||
"It was not provided a function response for the function call."
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_user_follow_up():
|
||||
"""Test multi-turn interaction or follow up with state."""
|
||||
received_requests = []
|
||||
|
||||
async def mock_run_async(**kwargs):
|
||||
received_requests.append(kwargs)
|
||||
# Yield response with custom metadata to test passing back
|
||||
yield Event(
|
||||
author="FakeAgent",
|
||||
content=types.Content(
|
||||
parts=[types.Part(text="Follow up response")], role="model"
|
||||
),
|
||||
custom_metadata={"server_state": "active"},
|
||||
)
|
||||
|
||||
app = create_server_app(mock_run_async)
|
||||
agent = create_client(app)
|
||||
|
||||
session_service = InMemorySessionService()
|
||||
await session_service.create_session(
|
||||
app_name="ClientApp", user_id="test_user", session_id="test_session"
|
||||
)
|
||||
client_runner = Runner(
|
||||
app_name="ClientApp",
|
||||
agent=agent,
|
||||
session_service=session_service,
|
||||
)
|
||||
|
||||
# First Turn
|
||||
new_message_1 = types.Content(parts=[types.Part(text="Turn 1")], role="user")
|
||||
async for _ in client_runner.run_async(
|
||||
user_id="test_user", session_id="test_session", new_message=new_message_1
|
||||
):
|
||||
pass
|
||||
|
||||
# Second Turn
|
||||
new_message_2 = types.Content(parts=[types.Part(text="Turn 2")], role="user")
|
||||
last_event = None
|
||||
async for event in client_runner.run_async(
|
||||
user_id="test_user", session_id="test_session", new_message=new_message_2
|
||||
):
|
||||
last_event = event
|
||||
|
||||
assert len(received_requests) == 2
|
||||
# The second request should carry the same session ID as the first
|
||||
assert (
|
||||
received_requests[1]["session_id"] == received_requests[0]["session_id"]
|
||||
)
|
||||
|
||||
assert last_event is not None
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_include_artifacts_in_a2a_event():
|
||||
"""Test that artifacts are included in A2A events when the interceptor is enabled."""
|
||||
|
||||
async def mock_run_async(**kwargs):
|
||||
yield Event(
|
||||
actions=EventActions(artifact_delta={"artifact1": 1, "artifact2": 1}),
|
||||
author="agent",
|
||||
content=types.Content(
|
||||
parts=[types.Part(text="Here are the artifacts")]
|
||||
),
|
||||
)
|
||||
|
||||
config = A2aAgentExecutorConfig(
|
||||
execute_interceptors=[include_artifacts_in_a2a_event_interceptor]
|
||||
)
|
||||
built_app = create_server_app(mock_run_async, config=config)
|
||||
|
||||
a2a_client = create_a2a_client(built_app, streaming=False)
|
||||
|
||||
request = A2AMessage(
|
||||
message_id="test_message_id",
|
||||
parts=[A2APart(root=TextPart(text="Hi"))],
|
||||
role="user",
|
||||
)
|
||||
|
||||
events = []
|
||||
async for event in a2a_client.send_message(request=request):
|
||||
events.append(event)
|
||||
|
||||
assert len(events) == 1
|
||||
|
||||
task = events[0][0]
|
||||
assert isinstance(task, Task)
|
||||
assert task.artifacts is not None
|
||||
assert len(task.artifacts) == 3
|
||||
|
||||
assert task.artifacts[0].parts[0].root.text == "Here are the artifacts"
|
||||
|
||||
assert task.artifacts[1].artifact_id == "artifact1_1"
|
||||
assert task.artifacts[1].name == "artifact1"
|
||||
assert task.artifacts[1].parts[0].root.text == "artifact content"
|
||||
|
||||
assert task.artifacts[2].artifact_id == "artifact2_1"
|
||||
assert task.artifacts[2].name == "artifact2"
|
||||
assert task.artifacts[2].parts[0].root.text == "artifact content"
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_user_follow_up_sends_task_id_with_input_required():
|
||||
"""Test that client follow-up sends the same task_id."""
|
||||
|
||||
task_id = "mocked-task-id-123"
|
||||
context_id = "mocked-context-id-456"
|
||||
mock_task = Task(
|
||||
id=task_id,
|
||||
context_id=context_id,
|
||||
kind="task",
|
||||
status=TaskStatus(
|
||||
state=_compat.TS_INPUT_REQUIRED,
|
||||
message=A2AMessage(
|
||||
message_id="mocked-message-id-789",
|
||||
role="user",
|
||||
parts=[A2APart(root=TextPart(text="Input required"))],
|
||||
),
|
||||
),
|
||||
metadata={_NEW_A2A_ADK_INTEGRATION_EXTENSION: True},
|
||||
)
|
||||
|
||||
mock_handler = AsyncMock(spec=RequestHandler)
|
||||
# First call returns input_required, second call completes
|
||||
mock_handler.on_message_send.side_effect = [
|
||||
mock_task,
|
||||
Task(
|
||||
id=task_id,
|
||||
context_id=context_id,
|
||||
kind="task",
|
||||
status=TaskStatus(state=_compat.TS_COMPLETED),
|
||||
metadata={_NEW_A2A_ADK_INTEGRATION_EXTENSION: True},
|
||||
),
|
||||
]
|
||||
|
||||
app = A2AFastAPIApplication(
|
||||
agent_card=agent_card, http_handler=mock_handler
|
||||
).build()
|
||||
agent = create_client(app, streaming=False)
|
||||
|
||||
session_service = InMemorySessionService()
|
||||
await session_service.create_session(
|
||||
app_name="ClientApp", user_id="test_user", session_id="test_session"
|
||||
)
|
||||
client_runner = Runner(
|
||||
app_name="ClientApp", agent=agent, session_service=session_service
|
||||
)
|
||||
|
||||
# First Turn
|
||||
new_message_1 = types.Content(parts=[types.Part(text="Turn 1")], role="user")
|
||||
found_call_id = None
|
||||
async for event in client_runner.run_async(
|
||||
user_id="test_user", session_id="test_session", new_message=new_message_1
|
||||
):
|
||||
for call in event.get_function_calls():
|
||||
if call.name == MOCK_FUNCTION_CALL_FOR_REQUIRED_USER_INPUT:
|
||||
found_call_id = call.id
|
||||
|
||||
assert found_call_id is not None
|
||||
|
||||
# Second Turn (Follow-up)
|
||||
function_response = types.FunctionResponse(
|
||||
id=found_call_id,
|
||||
name=MOCK_FUNCTION_CALL_FOR_REQUIRED_USER_INPUT,
|
||||
response={"result": "Turn 2"},
|
||||
)
|
||||
new_message_2 = types.Content(
|
||||
parts=[types.Part(function_response=function_response)], role="user"
|
||||
)
|
||||
async for _ in client_runner.run_async(
|
||||
user_id="test_user", session_id="test_session", new_message=new_message_2
|
||||
):
|
||||
pass
|
||||
|
||||
assert mock_handler.on_message_send.call_count == 2
|
||||
# Second call args
|
||||
call_args_2 = mock_handler.on_message_send.call_args_list[1]
|
||||
params_2 = call_args_2[0][0]
|
||||
assert params_2.message.task_id == task_id
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_user_follow_up_sends_task_id_with_input_required_legacy_impl():
|
||||
"""Test that client follow-up sends the same task_id."""
|
||||
|
||||
task_id = "mocked-task-id-123"
|
||||
context_id = "mocked-context-id-456"
|
||||
mock_task = Task(
|
||||
id=task_id,
|
||||
context_id=context_id,
|
||||
kind="task",
|
||||
status=TaskStatus(
|
||||
state=_compat.TS_INPUT_REQUIRED,
|
||||
message=A2AMessage(
|
||||
message_id="mocked-message-id-789",
|
||||
role="user",
|
||||
parts=[A2APart(root=TextPart(text="Input required"))],
|
||||
),
|
||||
),
|
||||
)
|
||||
|
||||
mock_handler = AsyncMock(spec=RequestHandler)
|
||||
# First call returns input_required, second call completes
|
||||
mock_handler.on_message_send.side_effect = [
|
||||
mock_task,
|
||||
Task(
|
||||
id=task_id,
|
||||
context_id=context_id,
|
||||
kind="task",
|
||||
status=TaskStatus(state=_compat.TS_COMPLETED),
|
||||
),
|
||||
]
|
||||
|
||||
app = A2AFastAPIApplication(
|
||||
agent_card=agent_card, http_handler=mock_handler
|
||||
).build()
|
||||
agent = create_client(app, streaming=False)
|
||||
|
||||
session_service = InMemorySessionService()
|
||||
await session_service.create_session(
|
||||
app_name="ClientApp", user_id="test_user", session_id="test_session"
|
||||
)
|
||||
client_runner = Runner(
|
||||
app_name="ClientApp", agent=agent, session_service=session_service
|
||||
)
|
||||
|
||||
# First Turn
|
||||
new_message_1 = types.Content(parts=[types.Part(text="Turn 1")], role="user")
|
||||
found_call_id = None
|
||||
async for event in client_runner.run_async(
|
||||
user_id="test_user", session_id="test_session", new_message=new_message_1
|
||||
):
|
||||
for call in event.get_function_calls():
|
||||
if call.name == MOCK_FUNCTION_CALL_FOR_REQUIRED_USER_INPUT:
|
||||
found_call_id = call.id
|
||||
|
||||
assert found_call_id is not None
|
||||
|
||||
# Second Turn (Follow-up)
|
||||
function_response = types.FunctionResponse(
|
||||
id=found_call_id,
|
||||
name=MOCK_FUNCTION_CALL_FOR_REQUIRED_USER_INPUT,
|
||||
response={"result": "Turn 2"},
|
||||
)
|
||||
new_message_2 = types.Content(
|
||||
parts=[types.Part(function_response=function_response)], role="user"
|
||||
)
|
||||
async for _ in client_runner.run_async(
|
||||
user_id="test_user", session_id="test_session", new_message=new_message_2
|
||||
):
|
||||
pass
|
||||
|
||||
assert mock_handler.on_message_send.call_count == 2
|
||||
# Second call args
|
||||
call_args_2 = mock_handler.on_message_send.call_args_list[1]
|
||||
params_2 = call_args_2[0][0]
|
||||
assert params_2.message.task_id == task_id
|
||||
@@ -0,0 +1,749 @@
|
||||
# Copyright 2026 Google LLC
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
|
||||
"""End-to-end client-server integration tests for a2a-sdk 1.x."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from google.adk.a2a import _compat
|
||||
from google.adk.a2a.executor.config import A2aAgentExecutorConfig
|
||||
from google.adk.a2a.executor.interceptors.include_artifacts_in_a2a_event import include_artifacts_in_a2a_event_interceptor
|
||||
from google.adk.agents.remote_a2a_agent import A2A_METADATA_PREFIX
|
||||
from google.adk.events.event import Event
|
||||
from google.adk.events.event_actions import EventActions
|
||||
from google.adk.platform import uuid as platform_uuid
|
||||
from google.adk.runners import Runner
|
||||
from google.adk.sessions.in_memory_session_service import InMemorySessionService
|
||||
from google.genai import types
|
||||
import pytest
|
||||
|
||||
pytestmark = pytest.mark.skipif(
|
||||
not _compat.IS_A2A_V1,
|
||||
reason="1.x-only client-server tests (0.3.x covered by test_client_server)",
|
||||
)
|
||||
|
||||
from .client import create_a2a_client
|
||||
from .client import create_client
|
||||
from .server import agent_card
|
||||
from .server import create_server_app_v1
|
||||
|
||||
|
||||
# -----------------------------------------------------------------------------
|
||||
# Mock server-side agents
|
||||
# -----------------------------------------------------------------------------
|
||||
def _streaming_run_async(received_requests: list):
|
||||
"""A mock run_async that streams partial chunks (text + artifact) then final."""
|
||||
|
||||
async def run_async(**kwargs):
|
||||
received_requests.append(kwargs)
|
||||
yield Event(
|
||||
author="FakeAgent",
|
||||
content=types.Content(parts=[types.Part(text="Hello")]),
|
||||
partial=True,
|
||||
)
|
||||
yield Event(
|
||||
author="FakeAgent",
|
||||
content=types.Content(parts=[types.Part(text=" world")]),
|
||||
partial=True,
|
||||
)
|
||||
yield Event(
|
||||
author="FakeAgent",
|
||||
partial=True,
|
||||
actions=EventActions(artifact_delta={"file1": 1}),
|
||||
)
|
||||
yield Event(
|
||||
author="FakeAgent",
|
||||
content=types.Content(parts=[types.Part(text="Hello world")]),
|
||||
partial=False,
|
||||
)
|
||||
|
||||
return run_async
|
||||
|
||||
|
||||
def _non_streaming_run_async(received_requests: list):
|
||||
"""A mock run_async that yields a single non-partial event."""
|
||||
|
||||
async def run_async(**kwargs):
|
||||
received_requests.append(kwargs)
|
||||
yield Event(
|
||||
author="FakeAgent",
|
||||
content=types.Content(parts=[types.Part(text="Hello world")]),
|
||||
partial=False,
|
||||
)
|
||||
|
||||
return run_async
|
||||
|
||||
|
||||
def _multi_agent_run_async(received_requests: list):
|
||||
"""A mock run_async that interleaves two agents' streamed chunks."""
|
||||
|
||||
async def run_async(**kwargs):
|
||||
received_requests.append(kwargs)
|
||||
yield Event(
|
||||
author="FakeAgent1",
|
||||
content=types.Content(parts=[types.Part(text="Hello")]),
|
||||
partial=True,
|
||||
)
|
||||
yield Event(
|
||||
author="FakeAgent2",
|
||||
content=types.Content(parts=[types.Part(text=" Hi")]),
|
||||
partial=True,
|
||||
)
|
||||
yield Event(
|
||||
author="FakeAgent1",
|
||||
content=types.Content(parts=[types.Part(text=" world")]),
|
||||
partial=True,
|
||||
)
|
||||
yield Event(
|
||||
author="FakeAgent2",
|
||||
content=types.Content(parts=[types.Part(text=" human")]),
|
||||
partial=True,
|
||||
)
|
||||
yield Event(
|
||||
author="FakeAgent1",
|
||||
content=types.Content(parts=[types.Part(text="Hello world")]),
|
||||
partial=False,
|
||||
)
|
||||
yield Event(
|
||||
author="FakeAgent2",
|
||||
content=types.Content(parts=[types.Part(text="Hi human")]),
|
||||
partial=False,
|
||||
)
|
||||
|
||||
return run_async
|
||||
|
||||
|
||||
def _function_call_run_async(received_requests: list):
|
||||
"""A mock run_async that yields a function call + response pair."""
|
||||
|
||||
async def run_async(**kwargs):
|
||||
received_requests.append(kwargs)
|
||||
yield Event(
|
||||
author="FakeAgent",
|
||||
content=types.Content(
|
||||
parts=[
|
||||
types.Part(
|
||||
function_call=types.FunctionCall(
|
||||
name="get_weather",
|
||||
args={"location": "San Francisco"},
|
||||
id="call_1",
|
||||
)
|
||||
),
|
||||
types.Part(
|
||||
function_response=types.FunctionResponse(
|
||||
name="get_weather",
|
||||
response={"temperature": "22C"},
|
||||
id="call_1",
|
||||
)
|
||||
),
|
||||
],
|
||||
role="model",
|
||||
),
|
||||
)
|
||||
|
||||
return run_async
|
||||
|
||||
|
||||
def _long_running_run_async(received_requests: list):
|
||||
"""A mock run_async modeling a long-running tool needing a user response."""
|
||||
|
||||
async def run_async(**kwargs):
|
||||
received_requests.append(kwargs)
|
||||
if len(received_requests) == 1:
|
||||
yield Event(
|
||||
author="FakeAgent",
|
||||
content=types.Content(
|
||||
parts=[
|
||||
types.Part(
|
||||
function_call=types.FunctionCall(
|
||||
name="long_task", args={}, id="call_long"
|
||||
)
|
||||
)
|
||||
],
|
||||
role="model",
|
||||
),
|
||||
long_running_tool_ids={"call_long"},
|
||||
)
|
||||
yield Event(
|
||||
author="FakeAgent",
|
||||
content=types.Content(
|
||||
parts=[
|
||||
types.Part(
|
||||
function_response=types.FunctionResponse(
|
||||
name="long_task",
|
||||
response={"status": "pending"},
|
||||
id="call_long",
|
||||
)
|
||||
)
|
||||
],
|
||||
role="model",
|
||||
),
|
||||
)
|
||||
else:
|
||||
yield Event(
|
||||
author="FakeAgent",
|
||||
content=types.Content(
|
||||
parts=[types.Part(text="Task completed well")], role="model"
|
||||
),
|
||||
)
|
||||
|
||||
return run_async
|
||||
|
||||
|
||||
# -----------------------------------------------------------------------------
|
||||
# Client driver helpers
|
||||
# -----------------------------------------------------------------------------
|
||||
async def _run_client(agent, *, message_text: str = "Hi"):
|
||||
"""Drives the agent through a client-side Runner and collects results."""
|
||||
session_service = InMemorySessionService()
|
||||
await session_service.create_session(
|
||||
app_name="ClientApp", user_id="test_user", session_id="test_session"
|
||||
)
|
||||
client_runner = Runner(
|
||||
app_name="ClientApp", agent=agent, session_service=session_service
|
||||
)
|
||||
new_message = types.Content(
|
||||
parts=[types.Part(text=message_text)], role="user"
|
||||
)
|
||||
|
||||
texts = []
|
||||
artifact_deltas = []
|
||||
func_calls = []
|
||||
func_responses = []
|
||||
async for event in client_runner.run_async(
|
||||
user_id="test_user", session_id="test_session", new_message=new_message
|
||||
):
|
||||
if event.content and event.content.parts:
|
||||
for part in event.content.parts:
|
||||
if part.text:
|
||||
texts.append(part.text)
|
||||
if part.function_response:
|
||||
func_responses.append(part.function_response)
|
||||
func_calls.extend(event.get_function_calls())
|
||||
if event.actions and event.actions.artifact_delta:
|
||||
artifact_deltas.append(event.actions.artifact_delta)
|
||||
return {
|
||||
"texts": texts,
|
||||
"artifact_deltas": artifact_deltas,
|
||||
"func_calls": func_calls,
|
||||
"func_responses": func_responses,
|
||||
}
|
||||
|
||||
|
||||
# -----------------------------------------------------------------------------
|
||||
# RemoteA2aAgent round-trip tests (streaming variants)
|
||||
# -----------------------------------------------------------------------------
|
||||
@pytest.mark.asyncio
|
||||
async def test_non_streaming_round_trip():
|
||||
"""A non-streaming agent response round-trips to the client on 1.x."""
|
||||
received_requests = []
|
||||
app = create_server_app_v1(_non_streaming_run_async(received_requests))
|
||||
|
||||
async with app.router.lifespan_context(app):
|
||||
agent = create_client(app, streaming=False)
|
||||
result = await _run_client(agent)
|
||||
|
||||
assert len(received_requests) == 1
|
||||
assert received_requests[0]["session_id"] is not None
|
||||
assert "Hello world" in result["texts"]
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_non_streaming_adk_to_streaming_a2a():
|
||||
"""A non-streaming agent response round-trips over a streaming client."""
|
||||
received_requests = []
|
||||
app = create_server_app_v1(_non_streaming_run_async(received_requests))
|
||||
|
||||
async with app.router.lifespan_context(app):
|
||||
agent = create_client(app, streaming=True)
|
||||
result = await _run_client(agent)
|
||||
|
||||
assert len(received_requests) == 1
|
||||
assert "Hello world" in result["texts"]
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_streaming_round_trip():
|
||||
"""A streaming agent response delivers its aggregate text on 1.x."""
|
||||
received_requests = []
|
||||
app = create_server_app_v1(_streaming_run_async(received_requests))
|
||||
|
||||
async with app.router.lifespan_context(app):
|
||||
agent = create_client(app, streaming=True)
|
||||
result = await _run_client(agent)
|
||||
|
||||
assert len(received_requests) == 1
|
||||
assert "Hello world" in result["texts"]
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_streaming_adk_to_non_streaming_a2a():
|
||||
"""A streaming agent response collapses to its final text on a non-streaming client."""
|
||||
received_requests = []
|
||||
app = create_server_app_v1(_streaming_run_async(received_requests))
|
||||
|
||||
async with app.router.lifespan_context(app):
|
||||
agent = create_client(app, streaming=False)
|
||||
result = await _run_client(agent)
|
||||
|
||||
assert len(received_requests) == 1
|
||||
assert "Hello world" in result["texts"]
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_multiple_agents_streaming_round_trip():
|
||||
"""Interleaved chunks from multiple server-side agents stream on 1.x."""
|
||||
received_requests = []
|
||||
app = create_server_app_v1(_multi_agent_run_async(received_requests))
|
||||
|
||||
async with app.router.lifespan_context(app):
|
||||
agent = create_client(app, streaming=True)
|
||||
result = await _run_client(agent)
|
||||
|
||||
assert len(received_requests) == 1
|
||||
# The request reached the server and the last author's final text arrives.
|
||||
assert "Hi human" in result["texts"]
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_artifact_producing_agent_round_trip():
|
||||
"""An agent that records an artifact delta still round-trips its content."""
|
||||
received_requests = []
|
||||
|
||||
async def run_async(**kwargs):
|
||||
received_requests.append(kwargs)
|
||||
yield Event(
|
||||
author="FakeAgent",
|
||||
content=types.Content(parts=[types.Part(text="with artifact")]),
|
||||
actions=EventActions(artifact_delta={"file1": 1}),
|
||||
partial=False,
|
||||
)
|
||||
|
||||
app = create_server_app_v1(run_async)
|
||||
|
||||
async with app.router.lifespan_context(app):
|
||||
agent = create_client(app, streaming=True)
|
||||
result = await _run_client(agent)
|
||||
|
||||
assert len(received_requests) == 1
|
||||
assert "with artifact" in result["texts"]
|
||||
|
||||
|
||||
# -----------------------------------------------------------------------------
|
||||
# Function-call round trip
|
||||
# -----------------------------------------------------------------------------
|
||||
@pytest.mark.asyncio
|
||||
async def test_function_calls():
|
||||
"""Function call + response pairs round-trip to the client on 1.x."""
|
||||
received_requests = []
|
||||
app = create_server_app_v1(_function_call_run_async(received_requests))
|
||||
|
||||
async with app.router.lifespan_context(app):
|
||||
agent = create_client(app)
|
||||
result = await _run_client(agent)
|
||||
|
||||
assert len(result["func_calls"]) == 1
|
||||
assert result["func_calls"][0].name == "get_weather"
|
||||
assert result["func_calls"][0].args == {"location": "San Francisco"}
|
||||
|
||||
assert len(result["func_responses"]) == 1
|
||||
assert result["func_responses"][0].name == "get_weather"
|
||||
assert result["func_responses"][0].response == {"temperature": "22C"}
|
||||
|
||||
|
||||
# -----------------------------------------------------------------------------
|
||||
# Long-running flows (multi-turn)
|
||||
# -----------------------------------------------------------------------------
|
||||
@pytest.mark.asyncio
|
||||
async def test_long_running_function_calls_success():
|
||||
"""A long-running tool flow completes across two turns, preserving task_id."""
|
||||
received_requests = []
|
||||
app = create_server_app_v1(_long_running_run_async(received_requests))
|
||||
|
||||
async with app.router.lifespan_context(app):
|
||||
agent = create_client(app, streaming=True)
|
||||
session_service = InMemorySessionService()
|
||||
await session_service.create_session(
|
||||
app_name="ClientApp", user_id="test_user", session_id="test_session"
|
||||
)
|
||||
client_runner = Runner(
|
||||
app_name="ClientApp", agent=agent, session_service=session_service
|
||||
)
|
||||
|
||||
# Turn 1: triggers the long-running tool, surfaces it to the client.
|
||||
new_message_1 = types.Content(parts=[types.Part(text="Hi")], role="user")
|
||||
func_calls_1 = []
|
||||
task_id_1 = ""
|
||||
has_long_running_id = False
|
||||
async for event in client_runner.run_async(
|
||||
user_id="test_user",
|
||||
session_id="test_session",
|
||||
new_message=new_message_1,
|
||||
):
|
||||
if event.custom_metadata:
|
||||
task_id_1 = event.custom_metadata.get(
|
||||
A2A_METADATA_PREFIX + "task_id", task_id_1
|
||||
)
|
||||
if (
|
||||
event.long_running_tool_ids
|
||||
and "call_long" in event.long_running_tool_ids
|
||||
):
|
||||
has_long_running_id = True
|
||||
func_calls_1.extend(event.get_function_calls())
|
||||
|
||||
assert has_long_running_id
|
||||
assert any(c.name == "long_task" for c in func_calls_1)
|
||||
|
||||
# Turn 2: provide the function response; task should complete.
|
||||
new_message_2 = types.Content(
|
||||
parts=[
|
||||
types.Part(
|
||||
function_response=types.FunctionResponse(
|
||||
name="long_task",
|
||||
response={"result": "done"},
|
||||
id="call_long",
|
||||
)
|
||||
)
|
||||
],
|
||||
role="user",
|
||||
)
|
||||
texts = []
|
||||
task_id_2 = ""
|
||||
async for event in client_runner.run_async(
|
||||
user_id="test_user",
|
||||
session_id="test_session",
|
||||
new_message=new_message_2,
|
||||
):
|
||||
if event.custom_metadata:
|
||||
task_id_2 = event.custom_metadata.get(
|
||||
A2A_METADATA_PREFIX + "task_id", task_id_2
|
||||
)
|
||||
if event.content and event.content.parts:
|
||||
for p in event.content.parts:
|
||||
if p.text:
|
||||
texts.append(p.text)
|
||||
|
||||
assert task_id_1 == task_id_2
|
||||
assert "Task completed well" in texts
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_long_running_function_calls_error():
|
||||
"""A follow-up without a function response yields an INPUT_REQUIRED error."""
|
||||
received_requests = []
|
||||
app = create_server_app_v1(_long_running_run_async(received_requests))
|
||||
|
||||
async with app.router.lifespan_context(app):
|
||||
a2a_client = create_a2a_client(app, streaming=False)
|
||||
|
||||
request_1 = _compat.make_message(
|
||||
message_id=platform_uuid.new_uuid(),
|
||||
role=_compat.ROLE_USER,
|
||||
parts=[_compat.make_text_part("Hi")],
|
||||
)
|
||||
response_1_events = []
|
||||
normalize = _compat.make_stream_normalizer()
|
||||
async for item in _compat.send_message(a2a_client, request=request_1):
|
||||
response_1_events.append(normalize(item))
|
||||
|
||||
assert len(response_1_events) == 1
|
||||
task, update = response_1_events[0]
|
||||
assert update is None
|
||||
assert task.status.state == _compat.TS_INPUT_REQUIRED
|
||||
extracted_task_id = task.id
|
||||
assert extracted_task_id
|
||||
|
||||
request_2 = _compat.make_message(
|
||||
message_id=platform_uuid.new_uuid(),
|
||||
role=_compat.ROLE_USER,
|
||||
parts=[_compat.make_text_part("Any update?")],
|
||||
task_id=extracted_task_id,
|
||||
context_id=task.context_id,
|
||||
)
|
||||
response_2_events = []
|
||||
normalize = _compat.make_stream_normalizer()
|
||||
async for item in _compat.send_message(a2a_client, request=request_2):
|
||||
response_2_events.append(normalize(item))
|
||||
|
||||
assert len(response_2_events) == 1
|
||||
error_task, error_update = response_2_events[0]
|
||||
assert error_update is None
|
||||
status_message = _compat.normalize_message(error_task.status.message)
|
||||
assert status_message is not None
|
||||
assert _compat.part_text(status_message.parts[0]) == (
|
||||
"It was not provided a function response for the function call."
|
||||
)
|
||||
|
||||
|
||||
# -----------------------------------------------------------------------------
|
||||
# Multi-turn session continuity
|
||||
# -----------------------------------------------------------------------------
|
||||
@pytest.mark.asyncio
|
||||
async def test_user_follow_up():
|
||||
"""Two turns on the same session reuse the same server-side session id."""
|
||||
received_requests = []
|
||||
|
||||
async def run_async(**kwargs):
|
||||
received_requests.append(kwargs)
|
||||
yield Event(
|
||||
author="FakeAgent",
|
||||
content=types.Content(
|
||||
parts=[types.Part(text="Follow up response")], role="model"
|
||||
),
|
||||
custom_metadata={"server_state": "active"},
|
||||
)
|
||||
|
||||
app = create_server_app_v1(run_async)
|
||||
|
||||
async with app.router.lifespan_context(app):
|
||||
agent = create_client(app)
|
||||
session_service = InMemorySessionService()
|
||||
await session_service.create_session(
|
||||
app_name="ClientApp", user_id="test_user", session_id="test_session"
|
||||
)
|
||||
client_runner = Runner(
|
||||
app_name="ClientApp", agent=agent, session_service=session_service
|
||||
)
|
||||
|
||||
new_message_1 = types.Content(
|
||||
parts=[types.Part(text="Turn 1")], role="user"
|
||||
)
|
||||
async for _ in client_runner.run_async(
|
||||
user_id="test_user",
|
||||
session_id="test_session",
|
||||
new_message=new_message_1,
|
||||
):
|
||||
pass
|
||||
|
||||
new_message_2 = types.Content(
|
||||
parts=[types.Part(text="Turn 2")], role="user"
|
||||
)
|
||||
last_event = None
|
||||
async for event in client_runner.run_async(
|
||||
user_id="test_user",
|
||||
session_id="test_session",
|
||||
new_message=new_message_2,
|
||||
):
|
||||
last_event = event
|
||||
|
||||
assert len(received_requests) == 2
|
||||
assert (
|
||||
received_requests[1]["session_id"] == received_requests[0]["session_id"]
|
||||
)
|
||||
assert last_event is not None
|
||||
|
||||
|
||||
# -----------------------------------------------------------------------------
|
||||
# Artifact interceptor
|
||||
# -----------------------------------------------------------------------------
|
||||
@pytest.mark.asyncio
|
||||
async def test_include_artifacts_in_a2a_event():
|
||||
"""The artifact interceptor surfaces recorded artifacts on the task on 1.x."""
|
||||
|
||||
async def run_async(**kwargs):
|
||||
yield Event(
|
||||
actions=EventActions(artifact_delta={"artifact1": 1, "artifact2": 1}),
|
||||
author="agent",
|
||||
content=types.Content(
|
||||
parts=[types.Part(text="Here are the artifacts")]
|
||||
),
|
||||
)
|
||||
|
||||
config = A2aAgentExecutorConfig(
|
||||
execute_interceptors=[include_artifacts_in_a2a_event_interceptor]
|
||||
)
|
||||
app = create_server_app_v1(run_async, config=config)
|
||||
|
||||
async with app.router.lifespan_context(app):
|
||||
a2a_client = create_a2a_client(app, streaming=False)
|
||||
|
||||
request = _compat.make_message(
|
||||
message_id="test_message_id",
|
||||
role=_compat.ROLE_USER,
|
||||
parts=[_compat.make_text_part("Hi")],
|
||||
)
|
||||
events = []
|
||||
normalize = _compat.make_stream_normalizer()
|
||||
async for item in _compat.send_message(a2a_client, request=request):
|
||||
events.append(normalize(item))
|
||||
|
||||
assert len(events) == 1
|
||||
task, update = events[0]
|
||||
assert update is None
|
||||
assert task.artifacts is not None
|
||||
# The text part plus the two recorded artifacts.
|
||||
assert len(task.artifacts) == 3
|
||||
assert _compat.part_text(task.artifacts[0].parts[0]) == (
|
||||
"Here are the artifacts"
|
||||
)
|
||||
artifact_names = {a.name for a in task.artifacts[1:]}
|
||||
assert artifact_names == {"artifact1", "artifact2"}
|
||||
for art in task.artifacts[1:]:
|
||||
assert _compat.part_text(art.parts[0]) == "artifact content"
|
||||
|
||||
|
||||
def _multi_artifact_streaming_run_async(received_requests: list):
|
||||
"""A streaming agent that records two distinct artifacts across chunks."""
|
||||
|
||||
async def run_async(**kwargs):
|
||||
received_requests.append(kwargs)
|
||||
yield Event(
|
||||
author="FakeAgent",
|
||||
partial=True,
|
||||
content=types.Content(parts=[types.Part(text="chunk one")]),
|
||||
actions=EventActions(artifact_delta={"file1": 1}),
|
||||
)
|
||||
yield Event(
|
||||
author="FakeAgent",
|
||||
partial=True,
|
||||
content=types.Content(parts=[types.Part(text="chunk two")]),
|
||||
actions=EventActions(artifact_delta={"file2": 1}),
|
||||
)
|
||||
yield Event(
|
||||
author="FakeAgent",
|
||||
partial=False,
|
||||
content=types.Content(parts=[types.Part(text="done")]),
|
||||
)
|
||||
|
||||
return run_async
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_streaming_artifacts_are_aggregated_into_single_task():
|
||||
"""Streaming multi-artifact responses arrive aggregated as one ``task`` item."""
|
||||
received_requests = []
|
||||
config = A2aAgentExecutorConfig(
|
||||
execute_interceptors=[include_artifacts_in_a2a_event_interceptor]
|
||||
)
|
||||
app = create_server_app_v1(
|
||||
_multi_artifact_streaming_run_async(received_requests), config=config
|
||||
)
|
||||
|
||||
async with app.router.lifespan_context(app):
|
||||
a2a_client = create_a2a_client(app, streaming=True)
|
||||
|
||||
request = _compat.make_message(
|
||||
message_id="test_message_id",
|
||||
role=_compat.ROLE_USER,
|
||||
parts=[_compat.make_text_part("Hi")],
|
||||
)
|
||||
events = []
|
||||
normalize = _compat.make_stream_normalizer()
|
||||
async for item in _compat.send_message(a2a_client, request=request):
|
||||
events.append(normalize(item))
|
||||
|
||||
# The whole stream collapses to a single aggregated task carrier.
|
||||
assert len(events) == 1
|
||||
task, update = events[0]
|
||||
assert update is None
|
||||
assert task.artifacts is not None
|
||||
# Both recorded artifacts are present (plus any text-carrying artifact).
|
||||
artifact_names = {a.name for a in task.artifacts}
|
||||
assert {"file1", "file2"}.issubset(artifact_names)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_streaming_artifact_run_completes_through_remote_agent():
|
||||
"""A streaming multi-artifact run round-trips through RemoteA2aAgent"""
|
||||
received_requests = []
|
||||
config = A2aAgentExecutorConfig(
|
||||
execute_interceptors=[include_artifacts_in_a2a_event_interceptor]
|
||||
)
|
||||
app = create_server_app_v1(
|
||||
_multi_artifact_streaming_run_async(received_requests), config=config
|
||||
)
|
||||
|
||||
async with app.router.lifespan_context(app):
|
||||
agent = create_client(app, streaming=True)
|
||||
result = await _run_client(agent)
|
||||
|
||||
assert len(received_requests) == 1
|
||||
# The aggregated final response reaches the client (no mid-stream failure).
|
||||
assert "done" in result["texts"]
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_make_stream_normalizer_aggregates_incremental_artifacts():
|
||||
"""The stateful normalizer accumulates artifacts across incremental updates."""
|
||||
from a2a.types import a2a_pb2 as pb
|
||||
|
||||
def _artifact_update(name: str) -> pb.StreamResponse:
|
||||
item = pb.StreamResponse()
|
||||
item.artifact_update.task_id = "task-1"
|
||||
item.artifact_update.context_id = "ctx-1"
|
||||
item.artifact_update.append = False
|
||||
item.artifact_update.last_chunk = True
|
||||
artifact = item.artifact_update.artifact
|
||||
artifact.artifact_id = name
|
||||
artifact.name = name
|
||||
artifact.parts.add().text = f"content-{name}"
|
||||
return item
|
||||
|
||||
initial = pb.StreamResponse()
|
||||
initial.task.id = "task-1"
|
||||
initial.task.context_id = "ctx-1"
|
||||
|
||||
stream = [initial, _artifact_update("file1"), _artifact_update("file2")]
|
||||
|
||||
normalize = _compat.make_stream_normalizer()
|
||||
results = [normalize(item) for item in stream]
|
||||
|
||||
# The running task accumulates artifacts across updates.
|
||||
names_per_step = [{a.name for a in task.artifacts} for task, _ in results]
|
||||
assert names_per_step[0] == set()
|
||||
assert names_per_step[1] == {"file1"}
|
||||
assert names_per_step[2] == {"file1", "file2"}
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_make_stream_normalizer_accumulates_status_history():
|
||||
"""Status update messages accumulate into task.history; status is applied.
|
||||
|
||||
Mirrors the 0.3.x ClientTaskManager, which appended each status message to
|
||||
task.history before overwriting the task status.
|
||||
"""
|
||||
from a2a.types import a2a_pb2 as pb
|
||||
|
||||
def _status_update(text: str, state: int) -> pb.StreamResponse:
|
||||
item = pb.StreamResponse()
|
||||
item.status_update.task_id = "task-1"
|
||||
item.status_update.context_id = "ctx-1"
|
||||
item.status_update.status.state = state
|
||||
item.status_update.status.message.message_id = text
|
||||
item.status_update.status.message.parts.add().text = text
|
||||
return item
|
||||
|
||||
initial = pb.StreamResponse()
|
||||
initial.task.id = "task-1"
|
||||
initial.task.context_id = "ctx-1"
|
||||
|
||||
stream = [
|
||||
initial,
|
||||
_status_update("working", pb.TASK_STATE_WORKING),
|
||||
_status_update("done", pb.TASK_STATE_COMPLETED),
|
||||
]
|
||||
|
||||
normalize = _compat.make_stream_normalizer()
|
||||
results = [normalize(item) for item in stream]
|
||||
|
||||
# history accumulates one message per status update carrying a message.
|
||||
history_ids_per_step = [
|
||||
[m.message_id for m in task.history] for task, _ in results
|
||||
]
|
||||
assert history_ids_per_step[0] == []
|
||||
assert history_ids_per_step[1] == ["working"]
|
||||
assert history_ids_per_step[2] == ["working", "done"]
|
||||
# the latest status is applied to the running task.
|
||||
final_task, _ = results[2]
|
||||
assert final_task.status.state == pb.TASK_STATE_COMPLETED
|
||||
Reference in New Issue
Block a user