Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 26 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -182,6 +182,32 @@ class MyWorker(Worker[Context]):
A `message/send` or `message/stream` that leaves a `required` extension inactive is refused with a
`-32600` error whose `data.missing_required_extensions` names it, before any task is created.

## Output modes

The card says which media types the agent answers in: `default_output_modes` (and `default_input_modes`)
on the application, `application/json` when unsaid, and each `Skill`'s own `output_modes`. A mode that is not
a media type (`type/subtype`) is refused when the application is made.

```python
app = FastA2A(
storage=storage,
broker=broker,
default_input_modes=['text/plain'],
default_output_modes=['text/markdown', 'application/x-ipynb+json'],
)
```

A client names the media types it accepts for a request in its configuration (`acceptedOutputModes`), and
the worker reads them from its task's params, `accepted_output_modes`, absent when the client named none.
What the worker gives in those modes goes in its artifacts, each part carrying its `media_type`:

```python
class MyWorker(Worker[Context]):
async def run_task(self, params: TaskSendParams) -> None:
if 'application/x-ipynb+json' in params.get('accepted_output_modes', []):
... # add an artifact with a part of that media type
```

## Design

**FastA2A** is built on top of [Starlette](https://www.starlette.io/), which means it's fully compatible
Expand Down
33 changes: 30 additions & 3 deletions fasta2a/applications.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

import html
import json
import re
from collections.abc import AsyncIterator, Sequence
from contextlib import asynccontextmanager
from pathlib import Path
Expand Down Expand Up @@ -64,6 +65,8 @@ def __init__(
security_schemes: dict[str, SecurityScheme] | None = None,
security_requirements: list[SecurityRequirement] | None = None,
docs_url: str | None = '/docs',
default_input_modes: Sequence[str] | None = None,
default_output_modes: Sequence[str] | None = None,
# Starlette
debug: bool = False,
routes: Sequence[Route] | None = None,
Expand Down Expand Up @@ -94,9 +97,11 @@ def __init__(
self.security_schemes = security_schemes
self.security_requirements = security_requirements
self.docs_url = docs_url
# NOTE: For now, I don't think there's any reason to support any other input/output modes.
self.default_input_modes = ['application/json']
self.default_output_modes = ['application/json']
# The media types the agent takes and gives unless a skill says otherwise. A client
# names the ones it accepts in a request (`acceptedOutputModes`), which the worker
# reads from its task's params (`accepted_output_modes`).
self.default_input_modes = _media_types('default_input_modes', default_input_modes)
self.default_output_modes = _media_types('default_output_modes', default_output_modes)

self.task_manager = TaskManager(broker=broker, storage=storage)

Expand Down Expand Up @@ -273,3 +278,25 @@ async def _answer(self, request: Request, a2a_request: A2ARequest) -> Response:
async def _default_lifespan(app: FastA2A) -> AsyncIterator[None]:
async with app.task_manager:
yield


def _media_types(name: str, modes: Sequence[str] | None) -> list[str]:
"""The media types the card declares, `application/json` when unsaid; a mode that is not one is refused."""
if modes is None:
return ['application/json']
if isinstance(modes, str):
raise TypeError(f'{name} is a list of media types, not one string.')
declared = list(modes)
if not declared:
raise ValueError(f'{name} names at least one media type.')
for mode in declared:
if not isinstance(mode, str) or not _MEDIA_TYPE.fullmatch(mode):
raise ValueError(f'{name}: {mode!r} is not a media type (type/subtype).')
# Media type names are case-insensitive: `TEXT/PLAIN` is `text/plain`.
if len({mode.lower() for mode in declared}) != len(declared):
raise ValueError(f'{name} names a media type twice.')
return declared


# ASCII only: with Unicode case folding, `[a-z]` under IGNORECASE also matches `ı` and `K`.
_MEDIA_TYPE = re.compile(r'[a-z0-9][a-z0-9!#$&^_.+-]*/[a-z0-9][a-z0-9!#$&^_.+-]*', re.IGNORECASE | re.ASCII)
16 changes: 14 additions & 2 deletions fasta2a/jsonrpc_v1.py
Original file line number Diff line number Diff line change
Expand Up @@ -60,11 +60,18 @@ def _array(value: Any) -> list[Any]:
return cast(list[Any], value)


# A part's `data` and any `metadata` are the application's, not the protocol's:
# their `role` or `state` keys are values, copied as they are in both directions.
_APPLICATION_KEYS = frozenset({'data', 'metadata'})


def _enums_from_v1(value: Any) -> Any:
if isinstance(value, dict):
out: dict[str, Any] = {}
for key, item in _object(value).items():
if key == 'role' and isinstance(item, str):
if key in _APPLICATION_KEYS:
out[key] = item
elif key == 'role' and isinstance(item, str):
out[key] = _ROLE_FROM_V1.get(item, item)
elif key == 'state' and isinstance(item, str):
out[key] = _STATE_FROM_V1.get(item, item)
Expand All @@ -81,7 +88,9 @@ def to_v1(value: Any) -> Any:
if isinstance(value, dict):
out: dict[str, Any] = {}
for key, item in _object(value).items():
if key == 'role' and isinstance(item, str):
if key in _APPLICATION_KEYS:
out[key] = item
elif key == 'role' and isinstance(item, str):
out[key] = _ROLE_TO_V1.get(item, item)
elif key == 'state' and isinstance(item, str):
out[key] = _STATE_TO_V1.get(item, item)
Expand Down Expand Up @@ -109,6 +118,9 @@ def from_v1_request(request: Any) -> dict[str, Any] | None:
return None
params = _object(_enums_from_v1(dict(_object(envelope.get('params') or {}))))
params.pop('tenant', None)
# ListTasks filters by `status`, a TaskState rather than a task's status object.
if method == 'ListTasks' and isinstance(params.get('status'), str):
params['status'] = _STATE_FROM_V1.get(params['status'], params['status'])
configuration = params.get('configuration')
if isinstance(configuration, dict):
settings = _object(configuration)
Expand Down
3 changes: 3 additions & 0 deletions fasta2a/schema.py
Original file line number Diff line number Diff line change
Expand Up @@ -716,6 +716,9 @@ class TaskSendParams(TypedDict):
history_length: NotRequired[int]
"""Number of recent messages to be retrieved."""

accepted_output_modes: NotRequired[list[str]]
"""The media types the client accepts for the answer (`acceptedOutputModes`), when it named any."""

metadata: NotRequired[dict[str, Any]]
"""Extension metadata."""

Expand Down
6 changes: 6 additions & 0 deletions fasta2a/task_manager.py
Original file line number Diff line number Diff line change
Expand Up @@ -138,6 +138,9 @@ async def send_message(self, request: SendMessageRequest) -> SendMessageResponse
history_length = config.get('history_length')
if history_length is not None:
broker_params['history_length'] = history_length
accepted_output_modes = config.get('accepted_output_modes')
if accepted_output_modes:
broker_params['accepted_output_modes'] = list(accepted_output_modes)
metadata = request['params'].get('metadata')
if metadata:
broker_params['metadata'] = metadata
Expand Down Expand Up @@ -187,6 +190,9 @@ async def stream_message(self, request: StreamMessageRequest) -> AsyncIterator[b
history_length = config.get('history_length')
if history_length is not None:
broker_params['history_length'] = history_length
accepted_output_modes = config.get('accepted_output_modes')
if accepted_output_modes:
broker_params['accepted_output_modes'] = list(accepted_output_modes)
metadata = request['params'].get('metadata')
if metadata:
broker_params['metadata'] = metadata
Expand Down
44 changes: 44 additions & 0 deletions tests/test_jsonrpc_v1.py
Original file line number Diff line number Diff line change
Expand Up @@ -86,6 +86,50 @@ def test_an_answer_is_written_with_1_0_enums():
}


def test_application_data_and_metadata_keep_their_values_both_ways():
data = {'role': 'ROLE_AGENT', 'state': 'working', 'nested': [{'state': 'TASK_STATE_FAILED'}]}
metadata = {'role': 'agent', 'state': 'TASK_STATE_WORKING'}
request = from_v1_request(
{
'jsonrpc': '2.0',
'id': '1',
'method': 'SendMessage',
'params': {
'message': {
'role': 'ROLE_USER',
'messageId': 'm',
'parts': [{'kind': 'data', 'data': data, 'metadata': metadata}],
'metadata': metadata,
}
},
}
)
assert request is not None
message = request['params']['message']
assert message['role'] == 'user'
assert message['parts'][0]['data'] == data
assert message['parts'][0]['metadata'] == metadata
assert message['metadata'] == metadata
answer = to_v1(
{
'status': {'state': 'working'},
'artifacts': [{'parts': [{'kind': 'data', 'data': data, 'metadata': metadata}]}],
'metadata': metadata,
}
)
assert answer['status'] == {'state': 'TASK_STATE_WORKING'}
assert answer['artifacts'][0]['parts'][0] == {'kind': 'data', 'data': data, 'metadata': metadata}
assert answer['metadata'] == metadata


def test_list_tasks_reads_its_status_filter_as_a_task_state():
request = from_v1_request(
{'jsonrpc': '2.0', 'id': '1', 'method': 'ListTasks', 'params': {'status': 'TASK_STATE_WORKING'}}
)
assert request is not None
assert request['params']['status'] == 'working'


async def test_the_card_says_how_a_caller_authenticates():
app = FastA2A(
storage=InMemoryStorage(),
Expand Down
155 changes: 155 additions & 0 deletions tests/test_output_modes.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,155 @@
"""Output modes: what the card declares, and the modes a request accepts, as the worker sees them."""

from __future__ import annotations as _annotations

import uuid
from collections.abc import AsyncIterator
from contextlib import asynccontextmanager
from typing import Any

import httpx
import pytest

from fasta2a import FastA2A
from fasta2a.broker import InMemoryBroker
from fasta2a.schema import (
Artifact,
Message,
StreamResponse,
TaskIdParams,
TaskSendParams,
TaskStatus,
TaskStatusUpdateEvent,
)
from fasta2a.storage import InMemoryStorage
from fasta2a.worker import Worker

pytestmark = pytest.mark.anyio

NOTEBOOK = 'application/x-ipynb+json'


class RecordingWorker(Worker[Any]):
"""Completes each task, and records the output modes it was accepted in."""

def __init__(self, broker: InMemoryBroker, storage: InMemoryStorage[Any]) -> None:
super().__init__(broker=broker, storage=storage)
self.seen: list[list[str] | None] = []

async def run_task(self, params: TaskSendParams) -> None:
self.seen.append(params.get('accepted_output_modes'))
await self.storage.update_task(params['id'], state='completed')
await self.broker.event_bus.emit(
params['id'],
StreamResponse(
status_update=TaskStatusUpdateEvent(
task_id=params['id'], context_id=params['context_id'], status=TaskStatus(state='completed')
)
),
)
await self.broker.event_bus.close(params['id'])

async def cancel_task(self, params: TaskIdParams) -> None:
pass

def build_message_history(self, history: list[Message]) -> list[Any]:
return []

def build_artifacts(self, result: Any) -> list[Artifact]:
return []


def build_app(**card: Any) -> tuple[FastA2A, RecordingWorker]:
storage: InMemoryStorage[Any] = InMemoryStorage()
broker = InMemoryBroker()
worker = RecordingWorker(broker=broker, storage=storage)

@asynccontextmanager
async def lifespan(app: FastA2A) -> AsyncIterator[None]:
async with app.task_manager, worker.run():
yield

return FastA2A(storage=storage, broker=broker, lifespan=lifespan, **card), worker


@asynccontextmanager
async def client_for(app: FastA2A) -> AsyncIterator[httpx.AsyncClient]:
async with app.router.lifespan_context(app):
transport = httpx.ASGITransport(app=app)
async with httpx.AsyncClient(transport=transport, base_url='http://testclient') as client:
yield client


def request(method: str, configuration: dict[str, Any] | None) -> dict[str, Any]:
params: dict[str, Any] = {
'message': {
'role': 'user',
'parts': [{'kind': 'text', 'text': 'hello'}],
'kind': 'message',
'messageId': str(uuid.uuid4()),
}
}
if configuration is not None:
params['configuration'] = configuration
return {'jsonrpc': '2.0', 'id': str(uuid.uuid4()), 'method': method, 'params': params}


async def test_the_card_declares_the_default_modes_it_is_given():
app, _ = build_app(default_input_modes=['text/plain'], default_output_modes=['text/markdown', NOTEBOOK])
async with client_for(app) as client:
card = (await client.get('/.well-known/agent-card.json')).json()
assert card['defaultInputModes'] == ['text/plain']
assert card['defaultOutputModes'] == ['text/markdown', NOTEBOOK]


async def test_unsaid_the_card_keeps_application_json():
app, _ = build_app()
async with client_for(app) as client:
card = (await client.get('/.well-known/agent-card.json')).json()
assert card['defaultInputModes'] == ['application/json']
assert card['defaultOutputModes'] == ['application/json']


@pytest.mark.parametrize(
'modes, refusal',
[
([], 'at least one media type'),
(['notebook'], 'is not a media type'),
(['text/plain', 'text/plain'], 'twice'),
(['text/plain', 'TEXT/PLAIN'], 'twice'),
(['text/pla\u0131n'], 'is not a media type'),
(['te\u212axt/plain'], 'is not a media type'),
('text/plain', 'not one string'),
],
)
def test_a_mode_that_is_not_a_media_type_is_refused(modes: Any, refusal: str):
with pytest.raises((ValueError, TypeError), match=refusal):
FastA2A(storage=InMemoryStorage(), broker=InMemoryBroker(), default_output_modes=modes)


@pytest.mark.parametrize('method', ['message/send', 'SendMessage'])
async def test_the_worker_sees_the_modes_a_request_accepts(method: str):
app, worker = build_app(default_output_modes=['text/markdown', NOTEBOOK])
async with client_for(app) as client:
response = await client.post('/', json=request(method, {'acceptedOutputModes': [NOTEBOOK, 'text/markdown']}))
assert response.status_code == 200
assert worker.seen == [[NOTEBOOK, 'text/markdown']]


async def test_a_stream_hands_the_modes_to_the_worker_too():
app, worker = build_app()
async with client_for(app) as client:
async with client.stream(
'POST', '/', json=request('message/stream', {'acceptedOutputModes': [NOTEBOOK]})
) as response:
async for _ in response.aiter_lines():
pass
assert worker.seen == [[NOTEBOOK]]


@pytest.mark.parametrize('configuration', [None, {'acceptedOutputModes': []}])
async def test_no_modes_named_leaves_them_unsaid(configuration: dict[str, Any] | None):
app, worker = build_app()
async with client_for(app) as client:
await client.post('/', json=request('message/send', configuration))
assert worker.seen == [None]
Loading