mosaico-base-agent 0.4.2__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,19 @@
1
+ Metadata-Version: 2.3
2
+ Name: mosaico-base-agent
3
+ Version: 0.4.2
4
+ Requires-Dist: a2a-sdk[http-server]>=1.0.0,<1.1.0
5
+ Requires-Dist: httpx>=0.28.1
6
+ Requires-Dist: langfuse==3.14.5
7
+ Requires-Dist: opentelemetry-exporter-otlp>=1.21.0
8
+ Requires-Dist: opentelemetry-sdk>=1.21.0
9
+ Requires-Dist: pydantic>=2.11.5
10
+ Requires-Dist: uvicorn>=0.34.2
11
+ Requires-Dist: a2a-acl==0.1.2 ; extra == 'acl'
12
+ Requires-Dist: langchain==1.3.1 ; extra == 'langchain'
13
+ Requires-Dist: langchain-litellm==0.6.6 ; extra == 'langchain'
14
+ Requires-Dist: litellm>=1.105.6,<1.106.0 ; extra == 'langchain'
15
+ Requires-Dist: litellm>=1.105.6,<1.106.0 ; extra == 'llm'
16
+ Requires-Python: >=3.12
17
+ Provides-Extra: acl
18
+ Provides-Extra: langchain
19
+ Provides-Extra: llm
@@ -0,0 +1,35 @@
1
+ [build-system]
2
+ requires = ["uv_build>=0.11.7,<0.14"]
3
+ build-backend = "uv_build"
4
+
5
+ [project]
6
+ name = 'mosaico-base-agent'
7
+ version = '0.4.2'
8
+ requires-python = '>=3.12'
9
+ dependencies = [
10
+ "a2a-sdk[http-server]>=1.0.0,<1.1.0",
11
+ "httpx>=0.28.1",
12
+ "langfuse==3.14.5",
13
+ "opentelemetry-exporter-otlp>=1.21.0",
14
+ "opentelemetry-sdk>=1.21.0",
15
+ "pydantic>=2.11.5",
16
+ "uvicorn>=0.34.2"
17
+ ]
18
+
19
+ [project.optional-dependencies]
20
+ llm = [
21
+ "litellm>=1.105.6,<1.106.0"
22
+ ]
23
+
24
+ langchain = [
25
+ "langchain==1.3.1",
26
+ "langchain-litellm==0.6.6",
27
+ "litellm>=1.105.6,<1.106.0"
28
+ ]
29
+
30
+ acl = [
31
+ "a2a-acl==0.1.2"
32
+ ]
33
+
34
+ [tool.uv.build-backend]
35
+ module-name = "mosaico"
@@ -0,0 +1,2 @@
1
+ # SPDX-FileCopyright: 2026 University of York
2
+ # SPDX-License: MIT
@@ -0,0 +1,2 @@
1
+ # SPDX-FileCopyright: 2026 University of York
2
+ # SPDX-License: MIT
@@ -0,0 +1,43 @@
1
+ # SPDX-FileCopyright: 2026 University of York
2
+ # SPDX-License: MIT
3
+
4
+ from starlette.applications import Starlette
5
+ from starlette.routing import Route
6
+ from starlette.requests import Request
7
+ from starlette.responses import JSONResponse
8
+
9
+ HEALTH_PATH = '/health'
10
+
11
+ class MosaicoA2AStarletteApplication:
12
+ """
13
+ Builds a Starlette application with the provided A2A routes and a healthcheck endpoint.
14
+ """
15
+
16
+ def __init__(self, healthcheck, routes):
17
+ self.healthcheck = healthcheck
18
+ self.a2a_routes = routes
19
+
20
+ def routes(self):
21
+ routes = list(self.a2a_routes)
22
+ routes.append(Route(
23
+ HEALTH_PATH,
24
+ self._use_healthcheck,
25
+ methods=['GET'],
26
+ name='a2a_healthcheck'
27
+ ))
28
+
29
+ return routes
30
+
31
+ def build(self) -> Starlette:
32
+ return Starlette(routes=self.routes())
33
+
34
+ async def _use_healthcheck(self, request: Request) -> JSONResponse:
35
+ health = await self.healthcheck()
36
+
37
+ is_healthy = health == "OK"
38
+ status_code = 200 if is_healthy else 503
39
+ content = {
40
+ "is_healthy": health == "OK",
41
+ "status": health
42
+ }
43
+ return JSONResponse(content, status_code=status_code)
@@ -0,0 +1,69 @@
1
+ # SPDX-FileCopyright: 2026 IMT Atlantique
2
+ # SPDX-License: MIT
3
+
4
+ from typing import Optional, List
5
+
6
+ import uuid
7
+
8
+ from a2a.server.agent_execution import RequestContext
9
+ from a2a.server.events import EventQueue
10
+ from a2a.types import Message, Role, Part
11
+
12
+ from a2a_acl.protocol_extension import A2A_ACL_PROTOCOL_URI
13
+ from a2a_acl.protocol_extension.primitives import extract_performative, extract_codec, add_performative, Performative
14
+
15
+ from mosaico.base.executor import MosaicoAgentExecutor
16
+
17
+
18
+ from .observability import MosaicoObservabilityMetadata
19
+
20
+ class BDIAgentExecutor(MosaicoAgentExecutor):
21
+ """
22
+ Base Python class for MOSAICO BDI-enabled agents.
23
+
24
+ Handle performatives in messages sent or received.
25
+ """
26
+
27
+
28
+ async def execute_agent(
29
+ self,
30
+ context: RequestContext,
31
+ event_queue: EventQueue,
32
+ observability_metadata: Optional[MosaicoObservabilityMetadata]
33
+ ) -> None:
34
+ if (
35
+ context.message.metadata is None
36
+ or A2A_ACL_PROTOCOL_URI not in context.message.metadata
37
+ ):
38
+ error_message = "Incoming message not in ACL format (missing metadata)."
39
+ print(error_message)
40
+ raise Exception(error_message)
41
+ else:
42
+ p = extract_performative(context)
43
+ c = extract_codec(context)
44
+
45
+ await self.execute_bdi(context, event_queue, observability_metadata, p, c)
46
+
47
+ # Override-me.
48
+ async def execute_bdi(self, context: RequestContext, event_queue: EventQueue, observability_metadata: Optional[MosaicoObservabilityMetadata], i, c) -> None:
49
+ """
50
+ Implements the logic in this agent, after observability and BDI information has been set up.
51
+
52
+ :param context: A2A context of the request.
53
+ :param event_queue: A2A event queue to use for updates.
54
+ :param observability_metadata: Mosaico observability metadata.
55
+ :param p: performative of the message.
56
+ :param codec: codec of the message.
57
+ :return:
58
+ """
59
+ raise NotImplementedError("execute_bdi not implemented")
60
+
61
+ async def send_bdi_message(self, context: RequestContext, event_queue: EventQueue, parts: List[Part], p:Performative, codec:str) -> None:
62
+ message = Message(context_id=context.context_id, message_id=uuid.uuid4().hex, role=Role.ROLE_AGENT, parts=parts)
63
+ message = add_performative(message, p, codec)
64
+ await event_queue.enqueue_event(message)
65
+
66
+ async def send_text_bdi_message(self, context: RequestContext, event_queue: EventQueue, text: str, p:Performative, codec:str) -> None:
67
+ await self.send_bdi_message(context, event_queue, [
68
+ Part(text=text),
69
+ ], p, codec)
@@ -0,0 +1,75 @@
1
+ # SPDX-FileCopyright: 2026 University of York
2
+ # SPDX-License: MIT
3
+
4
+ import json
5
+ from collections.abc import Mapping
6
+ from pathlib import Path
7
+
8
+ from a2a.types import AgentCard, AgentInterface
9
+ from google.protobuf.json_format import ParseDict
10
+
11
+ from .config import MosaicoConfig
12
+ from .observability import A2A_EXTENSION as OBSERVABILITY_EXTENSION
13
+
14
+ A2A_VERSION = '1.0'
15
+
16
+ TEXT_CONTENT_TYPES = ['text', 'text/plain']
17
+
18
+ AGENT_CARD_FILENAME = 'agent_card.json'
19
+
20
+
21
+ def agent_url(config: MosaicoConfig) -> str:
22
+ return (
23
+ config.agent_card_url if config.agent_card_url is not None
24
+ else f"{config.agent_card_protocol}://{config.agent_card_host}:{config.agent_card_port}/"
25
+ )
26
+
27
+ def create_jsonrpc_interface(config: MosaicoConfig) -> AgentInterface:
28
+ return AgentInterface(
29
+ protocol_binding='JSONRPC',
30
+ protocol_version=A2A_VERSION,
31
+ url=agent_url(config)
32
+ )
33
+
34
+ def mosaico_extensions():
35
+ return [
36
+ OBSERVABILITY_EXTENSION
37
+ ]
38
+
39
+ def load_card(source, config: MosaicoConfig, extensions=None) -> AgentCard:
40
+ """Build an AgentCard from the static fields declared in JSON.
41
+
42
+ ``source`` is a path, an ``importlib.resources`` traversable, or an already
43
+ parsed mapping. Everything that describes the agent itself belongs in the
44
+ JSON; this function overlays only what depends on where the agent is
45
+ deployed.
46
+
47
+ The interface URL is resolved from ``config`` and written into every
48
+ interface that does not already declare one, so the JSON can pin the
49
+ protocol binding and version without knowing the deployment host. MOSAICO
50
+ extensions are merged in by URI, so an agent may also declare them
51
+ explicitly in its JSON without ending up with duplicates.
52
+ """
53
+ if isinstance(source, Mapping):
54
+ raw = dict(source)
55
+ elif isinstance(source, (str, Path)):
56
+ raw = json.loads(Path(source).read_text(encoding='utf-8'))
57
+ else:
58
+ raw = json.loads(source.read_text(encoding='utf-8'))
59
+
60
+ card = ParseDict(raw, AgentCard())
61
+
62
+ if card.supported_interfaces:
63
+ for interface in card.supported_interfaces:
64
+ if not interface.url:
65
+ interface.url = agent_url(config)
66
+ else:
67
+ card.supported_interfaces.append(create_jsonrpc_interface(config))
68
+
69
+ declared = {extension.uri for extension in card.capabilities.extensions}
70
+ for extension in [*mosaico_extensions(), *(extensions or [])]:
71
+ if extension.uri not in declared:
72
+ card.capabilities.extensions.append(extension)
73
+ declared.add(extension.uri)
74
+
75
+ return card
@@ -0,0 +1,48 @@
1
+ # SPDX-FileCopyright: 2026 University of York
2
+ # SPDX-License: MIT
3
+
4
+ import os
5
+ from typing import Optional
6
+
7
+ from pydantic import BaseModel
8
+
9
+ class MosaicoConfig(BaseModel):
10
+ host: str
11
+ port: int
12
+ agent_card_url: Optional[str]
13
+ agent_card_protocol: str
14
+ agent_card_host: str
15
+ agent_card_port: int
16
+
17
+ # LLM API options (if needed)
18
+ api_base: Optional[str]
19
+ api_key: Optional[str]
20
+ model_name: Optional[str]
21
+
22
+ # Langfuse options
23
+ langfuse_host: Optional[str]
24
+ langfuse_public_key: Optional[str]
25
+ langfuse_secret_key: Optional[str]
26
+
27
+ @classmethod
28
+ def from_env(cls) -> 'MosaicoConfig':
29
+ host = os.getenv('HOST', '0.0.0.0')
30
+ port = int(os.getenv('PORT', 9000))
31
+ agent_card_url = os.getenv('AGENT_CARD_URL')
32
+ agent_card_protocol = os.getenv('AGENT_CARD_PROTOCOL', 'http')
33
+ agent_card_host = os.getenv('AGENT_CARD_HOST', 'localhost')
34
+ agent_card_port = os.getenv('AGENT_CARD_PORT', port)
35
+ return MosaicoConfig(
36
+ host=host,
37
+ port=port,
38
+ agent_card_url=agent_card_url,
39
+ agent_card_protocol=agent_card_protocol,
40
+ agent_card_host=agent_card_host,
41
+ agent_card_port=agent_card_port,
42
+ api_base=os.getenv('API_BASE'),
43
+ api_key=os.getenv('API_KEY'),
44
+ model_name=os.getenv('MODEL_NAME'),
45
+ langfuse_host=os.getenv('LANGFUSE_HOST'),
46
+ langfuse_public_key=os.getenv('LANGFUSE_PUBLIC_KEY'),
47
+ langfuse_secret_key=os.getenv('LANGFUSE_SECRET_KEY'),
48
+ )
@@ -0,0 +1,145 @@
1
+ # SPDX-FileCopyright: 2026 University of York
2
+ # SPDX-License: MIT
3
+
4
+ from typing import Optional, List
5
+
6
+ from a2a.server.agent_execution import AgentExecutor, RequestContext
7
+ from a2a.server.events import EventQueue
8
+ from a2a.server.tasks import TaskUpdater
9
+ from a2a.types import Message, Role, Part
10
+ from langfuse import get_client, propagate_attributes
11
+ from mosaico.base.config import MosaicoConfig
12
+
13
+ from .observability import parse_observability_metadata, MosaicoObservabilityMetadata
14
+
15
+ import logging
16
+ logger = logging.getLogger(__name__)
17
+
18
+ import uuid
19
+
20
+ HEALTH_OK = "OK"
21
+
22
+ class MosaicoAgentExecutor(AgentExecutor):
23
+ """
24
+ Base Python class for MOSAICO agents.
25
+
26
+ Embeds observability integration and enforces the need for a healthcheck function.
27
+
28
+ Please note that base Python ADK does not support task cancellation yet:
29
+
30
+ https://github.com/google/adk-python/pull/4161
31
+
32
+ Users of this class
33
+ """
34
+
35
+ def __init__(
36
+ self,
37
+ config: Optional[MosaicoConfig] = None,
38
+ agent_name: Optional[str] = None
39
+ ):
40
+ self.config = config
41
+ self.agent_name = agent_name
42
+
43
+ async def execute(
44
+ self,
45
+ context: RequestContext,
46
+ event_queue: EventQueue,
47
+ ) -> None:
48
+ if not context.message:
49
+ raise Exception('No message provided')
50
+
51
+ # Set up Langfuse tracing context
52
+ lf = get_client()
53
+ session_id = context.context_id
54
+ observability_metadata = self._get_observability_metadata(context)
55
+ trace_id = observability_metadata.get('mosaico-root-task-id') if observability_metadata else None
56
+ trace_name = observability_metadata.get('mosaico-root-task-name') if observability_metadata else None
57
+ parent_span_id = observability_metadata.get('mosaico-super-task-id') if observability_metadata else None
58
+
59
+ with propagate_attributes(session_id=session_id, trace_name=trace_name):
60
+ trace_context = {}
61
+ if trace_id:
62
+ trace_context["trace_id"] = trace_id
63
+ if parent_span_id:
64
+ trace_context["parent_span_id"] = parent_span_id
65
+
66
+ root_span_kwargs = {
67
+ "as_type": "span",
68
+ "name": self.agent_name,
69
+ **({"trace_context": trace_context} if trace_context else {}),
70
+ }
71
+
72
+ with lf.start_as_current_observation(**root_span_kwargs) as root_span:
73
+ await self.execute_agent(context, event_queue, observability_metadata)
74
+
75
+ async def cancel(
76
+ self,
77
+ context: RequestContext,
78
+ event_queue: EventQueue
79
+ ) -> None:
80
+ task = context.current_task
81
+ if task is None or not task.id:
82
+ raise Exception('No task to cancel')
83
+ context.current_task.metadata["isCancelled"] = True
84
+
85
+ def _get_observability_metadata(self, context: RequestContext) -> Optional[MosaicoObservabilityMetadata]:
86
+ """
87
+ Resolve observability metadata from the incoming message metadata, falling back to the
88
+ current task's metadata.
89
+
90
+ Returns None when no observability key is present at all, so that execute() skips tracing
91
+ setup entirely — message metadata may legitimately carry unrelated extension data (e.g.
92
+ client-side tool schemas) and nothing to trace with. A partial set is returned as-is:
93
+ parse_observability_metadata is permissive, and a trace linked by whatever ids were
94
+ supplied is more useful than no trace.
95
+ """
96
+ task = context.current_task
97
+ raw = context.metadata or (task and task.metadata) or (context.message and context.message.metadata)
98
+ if not raw:
99
+ return None
100
+ # An empty parse result means nothing usable was supplied; collapse it to None so the
101
+ # caller treats it as "no observability" rather than opening an unlinked root span.
102
+ return parse_observability_metadata(raw) or None
103
+
104
+ async def execute_agent(self, context: RequestContext, event_queue: EventQueue, observability_metadata: Optional[MosaicoObservabilityMetadata]) -> None:
105
+ """
106
+ Implements the logic in this agent, after observability has been set up.
107
+
108
+ :param context: A2A context of the request.
109
+ :param event_queue: A2A event queue to use for updates.
110
+ :return:
111
+ """
112
+ raise NotImplementedError("execute_agent not implemented")
113
+
114
+ async def health(self) -> str:
115
+ """
116
+ :return: OK if the agent's environment is functioning correctly, or the relevant error message if it is not.
117
+ """
118
+ raise NotImplementedError("health not implemented")
119
+
120
+ async def send_message(self, context: RequestContext, event_queue: EventQueue, parts: List[Part]) -> None:
121
+ await event_queue.enqueue_event(Message(
122
+ context_id=context.context_id,
123
+ message_id=uuid.uuid4().hex,
124
+ role=Role.ROLE_AGENT,
125
+ parts=parts
126
+ ))
127
+
128
+ async def send_text_message(self, context: RequestContext, event_queue: EventQueue, text: str) -> None:
129
+ await self.send_message(context, event_queue, [
130
+ Part(text=text),
131
+ ])
132
+
133
+ def is_task_cancelled(self, context: RequestContext) -> bool:
134
+ task = context.current_task
135
+ return task is not None and "isCancelled" in task.metadata and bool(task.metadata["isCancelled"])
136
+
137
+ async def send_cancelled_status(self, context: RequestContext, event_queue: EventQueue) -> None:
138
+ task = context.current_task
139
+ if task is None:
140
+ raise Exception('No task to cancel')
141
+ if "sentCancelledStatus" in task.metadata and task.metadata["sentCancelledStatus"]:
142
+ logger.info(f"Ignoring repeated cancellation request for task {task.id}: cancelled status has already been sent.")
143
+ return
144
+ task.metadata["sentCancelledStatus"] = True
145
+ await TaskUpdater(event_queue, task.id, task.context_id).cancel()
@@ -0,0 +1,33 @@
1
+ # SPDX-FileCopyright: 2026 University of York
2
+ # SPDX-License: MIT
3
+
4
+ """Shared Langfuse initialization helpers for all agents."""
5
+ from __future__ import annotations
6
+ from typing import Sequence
7
+ from langfuse import Langfuse
8
+
9
+ def initialize_langfuse(
10
+ *,
11
+ blocked_scopes: Sequence[str] | None = None,
12
+ use_litellm_callback: bool = False,
13
+ **client_kwargs: object,
14
+ ) -> Langfuse | None:
15
+ """Create a Langfuse client with consistent configuration.
16
+
17
+ Returns None if initialization or authentication fails, allowing the agent to start anyway.
18
+ """
19
+
20
+ scopes = list(blocked_scopes) if blocked_scopes else None
21
+ try:
22
+ client = Langfuse(
23
+ blocked_instrumentation_scopes=scopes,
24
+ **client_kwargs,
25
+ )
26
+ if use_litellm_callback:
27
+ import litellm
28
+ litellm.callbacks = ["langfuse_otel"]
29
+ except Exception as e:
30
+ print(f"Langfuse initialization failed: {e}. Agent will start without observability.")
31
+ return None
32
+
33
+ return client