samcoadk 0.4.0__py3-none-any.whl

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.
samcoadk/__init__.py ADDED
@@ -0,0 +1,143 @@
1
+ """samcoadk — a small Agent Development Kit.
2
+
3
+ Four ideas, and nothing underneath them:
4
+
5
+ Agent one turn: build the prompt, call the model, run the tools
6
+ it asks for, return the reply. Holds NO conversation.
7
+ Runner one turn *for a user in a session*: load the history, call
8
+ the agent, commit the result. What a service calls.
9
+ SessionService where conversations live. InMemory, or a real database.
10
+ A2A one agent calling another, in-process or over HTTP.
11
+
12
+ Everything else here serves those: prompts, tools, an LLM client, skills,
13
+ callbacks and observability.
14
+
15
+ THE CORE IS STDLIB ONLY, and that is a promise rather than an accident —
16
+ ``import samcoadk`` must not pull a single third-party module, which is what makes
17
+ this library auditable by reading it. Names that need a driver or a web
18
+ framework resolve lazily through ``__getattr__`` below and name the extra that
19
+ would provide them.
20
+
21
+ pip install samcoadk # the agent, in memory
22
+ pip install "samcoadk[mongo]" # + durable sessions in Mongo
23
+ pip install "samcoadk[mysql]" # + durable sessions in MySQL
24
+ pip install "samcoadk[server]" # + the HTTP surface
25
+ pip install "samcoadk[all]" # everything
26
+
27
+ THE ONE RULE. An ``Agent`` carries no conversation state, so build one and share
28
+ it across every request — that is the supported pattern. Per-user history lives
29
+ in a ``Session``, and ``Runner`` is what binds the two:
30
+
31
+ agent = Agent(name="support", model="gateway/gpt-4.1", instruction="...")
32
+ runner = Runner(agent, session_service=DatabaseSessionService(uri))
33
+ reply = runner.run(user_id="u1", session_id="s1", message="hello")
34
+
35
+ Two callers cannot leak into each other's transcript, because there is no shared
36
+ transcript to leak through.
37
+ """
38
+
39
+ from .a2a import (
40
+ A2AClient, A2AContractError, A2AError, A2ARemoteError, A2AUnavailable,
41
+ AgentCard, AgentSkill, Clarify, RemoteAgent, TaskState, data_of,
42
+ request_data, status_data, text_of,
43
+ )
44
+ from .agent import Agent
45
+ from .callbacks import (
46
+ AgentCallbacks, CallbackDecision, CallbackManager, RunContext,
47
+ )
48
+ from .llm import (
49
+ LLM, AnthropicLLM, EchoLLM, GatewayLLM, GeminiLLM, LLMHTTPError, OllamaLLM,
50
+ OpenAICompatibleLLM, OpenAILLM, ScriptedLLM, resolve_model,
51
+ )
52
+ from .observability import Metrics, Tracer, log_event, setup_logging
53
+ from .prompts import FewShotExample, FewShotTemplates, SystemPrompt, UserPrompt
54
+ from .runner import Runner
55
+ from .sessions import (
56
+ Event, InMemorySessionService, Session, SessionService, events_as_messages,
57
+ )
58
+ from .skills import Skill, SkillLibrary
59
+ from .tools import Tool, ToolRegistry
60
+
61
+ # Names behind an optional extra: (module, attribute). The module is imported on
62
+ # FIRST ACCESS, never at import time.
63
+ #
64
+ # This table is the stdlib-only promise made mechanical. A plain
65
+ # `from .backends import MongoBackend` at the top of this file would drag pymongo
66
+ # into every process that says `import samcoadk`, and the promise would be gone in
67
+ # one line that reviews as harmless.
68
+ _LAZY: dict[str, tuple[str, str]] = {
69
+ "DatabaseSessionService": ("samcoadk.database", "DatabaseSessionService"),
70
+ "SessionBackend": ("samcoadk.database", "SessionBackend"),
71
+ "DictBackend": ("samcoadk.backends", "DictBackend"),
72
+ "MongoBackend": ("samcoadk.backends", "MongoBackend"),
73
+ "SqlBackend": ("samcoadk.backends", "SqlBackend"),
74
+ # Stdlib-only, but kept lazy so a bare `import samcoadk` does not drag in
75
+ # subprocess/queue for the majority of agents that use no MCP server.
76
+ "MCPToolset": ("samcoadk.mcp", "MCPToolset"),
77
+ "MCPClient": ("samcoadk.mcp", "MCPClient"),
78
+ "MCPStdioClient": ("samcoadk.mcp", "MCPStdioClient"),
79
+ "MCPHTTPClient": ("samcoadk.mcp", "MCPHTTPClient"),
80
+ "BaseMCPClient": ("samcoadk.mcp", "BaseMCPClient"),
81
+ "MCPError": ("samcoadk.mcp", "MCPError"),
82
+ "create_app": ("samcoadk.server", "create_app"),
83
+ }
84
+
85
+ # Which extra to name when a lazy import fails, keyed by module.
86
+ _EXTRA_FOR = {
87
+ "samcoadk.database": "mongo' or 'samcoadk[mysql]",
88
+ "samcoadk.backends": "mongo' or 'samcoadk[mysql]",
89
+ "samcoadk.server": "server",
90
+ }
91
+
92
+
93
+ def __getattr__(name: str):
94
+ """Resolve a lazy export, or fail naming the extra that would provide it."""
95
+ target = _LAZY.get(name)
96
+ if target is None:
97
+ raise AttributeError(f"module {__name__!r} has no attribute {name!r}")
98
+ module, attribute = target
99
+ import importlib
100
+ try:
101
+ return getattr(importlib.import_module(module), attribute)
102
+ except ImportError as exc:
103
+ extra = _EXTRA_FOR.get(module, "all")
104
+ raise ImportError(
105
+ f"samcoadk.{name} needs an optional dependency: "
106
+ f"pip install 'samcoadk[{extra}]' (underlying error: {exc})") from exc
107
+
108
+
109
+ def __dir__() -> list[str]:
110
+ # Without this, `dir(samcoadk)` and tab-completion hide every lazy name, and
111
+ # people conclude the feature does not exist.
112
+ return sorted(set(globals()) | set(_LAZY))
113
+
114
+
115
+ __all__ = [
116
+ # the four ideas
117
+ "Agent", "Runner", "SessionService", "InMemorySessionService", "Session",
118
+ "Event", "events_as_messages",
119
+ # prompts
120
+ "SystemPrompt", "UserPrompt", "FewShotTemplates", "FewShotExample",
121
+ # tools
122
+ "Tool", "ToolRegistry",
123
+ # models
124
+ "LLM", "OpenAICompatibleLLM", "GatewayLLM", "OpenAILLM", "OllamaLLM",
125
+ "AnthropicLLM", "GeminiLLM", "EchoLLM", "ScriptedLLM", "LLMHTTPError",
126
+ "resolve_model",
127
+ # callbacks
128
+ "AgentCallbacks", "CallbackDecision", "CallbackManager", "RunContext",
129
+ # a2a
130
+ "AgentCard", "AgentSkill", "RemoteAgent", "A2AClient", "TaskState",
131
+ "Clarify", "A2AError", "A2AUnavailable", "A2ARemoteError",
132
+ "A2AContractError", "text_of", "data_of", "status_data", "request_data",
133
+ # skills
134
+ "Skill", "SkillLibrary",
135
+ # observability
136
+ "Metrics", "Tracer", "log_event", "setup_logging",
137
+ # lazy
138
+ "DatabaseSessionService", "SessionBackend", "DictBackend", "MongoBackend",
139
+ "SqlBackend", "MCPToolset", "MCPClient", "MCPStdioClient", "MCPHTTPClient",
140
+ "BaseMCPClient", "MCPError",
141
+ "create_app",
142
+ ]
143
+ __version__ = "0.4.0"
samcoadk/a2a.py ADDED
@@ -0,0 +1,375 @@
1
+ """One agent calling another.
2
+
3
+ AgentCard who an agent is, and what it can do
4
+ RemoteAgent an agent living behind someone else's HTTP endpoint
5
+ A2AClient the JSON-RPC transport
6
+ TaskState where a piece of work has got to
7
+
8
+ THE REUSE POINT. A ``RemoteAgent`` and a local ``Agent`` satisfy the same
9
+ one-method interface — ``.run(text) -> str``, plus a ``.name`` — so a caller
10
+ that holds one can hold the other unchanged. Calling in-process and calling
11
+ across the network are one code path here, not two, which is what lets an
12
+ agent be moved out to its own service without the caller changing.
13
+
14
+ billing = RemoteAgent.discover("http://billing:8000")
15
+ reply = billing.run("what is invoice 42?")
16
+
17
+ TWO DIALECTS, ONE METHOD. ``message/send`` carries parts, and a part is either
18
+ prose or a JSON object:
19
+
20
+ client.send("what is invoice 42?") # TextPart — a conversation
21
+ client.send(data={"op": "screen", "index": ...}) # DataPart — a contract
22
+
23
+ Text is what you want when the answer is for a person and the caller cannot
24
+ know the question in advance. Data is what you want between two programs that
25
+ have agreed on fields: it needs no model to interpret it, so a peer can answer
26
+ deterministically and prove it did. ``text_of`` unwraps the first, ``data_of``
27
+ the second. On the server, ``create_app(data_handler=...)`` is the door a
28
+ DataPart goes through.
29
+
30
+ WHY TASK STATES EXIST. A caller that cannot see the worker needs to be told
31
+ "I need more input" without holding a connection open for a human. That is
32
+ ``input-required``, and it is the whole reason this is a task protocol rather
33
+ than a function call: a turn can pause, be reported, and be resumed later
34
+ against the same session.
35
+
36
+ Stdlib ``urllib`` only, so importing this costs nothing. The SERVER half lives
37
+ in ``samcoadk.server`` and needs the ``[server]`` extra.
38
+ """
39
+ from __future__ import annotations
40
+
41
+ import json
42
+ import urllib.error
43
+ import urllib.request
44
+ import uuid
45
+ from dataclasses import asdict, dataclass, field
46
+ from typing import Any
47
+ from urllib.parse import urljoin
48
+
49
+ PROTOCOL_VERSION = "0.3.0"
50
+
51
+
52
+ class TaskState:
53
+ """The states a task may be in. ``INPUT_REQUIRED`` is the load-bearing one:
54
+ it is how a worker pauses for a human without blocking a socket."""
55
+ SUBMITTED = "submitted"
56
+ WORKING = "working"
57
+ INPUT_REQUIRED = "input-required"
58
+ COMPLETED = "completed"
59
+ FAILED = "failed"
60
+ CANCELED = "canceled"
61
+ REJECTED = "rejected"
62
+
63
+ ALL = frozenset({SUBMITTED, WORKING, INPUT_REQUIRED, COMPLETED, FAILED,
64
+ CANCELED, REJECTED})
65
+ TERMINAL = frozenset({COMPLETED, FAILED, CANCELED, REJECTED})
66
+
67
+
68
+ class A2AError(RuntimeError):
69
+ """Base for everything that can go wrong between two agents."""
70
+
71
+
72
+ class A2AUnavailable(A2AError):
73
+ """The other agent could not be reached at all."""
74
+
75
+
76
+ class A2ARemoteError(A2AError):
77
+ """The other agent was reached and answered with an error."""
78
+
79
+ def __init__(self, message: str, code: int = -32000):
80
+ super().__init__(message)
81
+ self.code = code
82
+
83
+
84
+ class A2AContractError(A2AError):
85
+ """The other agent answered something that is not the agreed shape.
86
+
87
+ Separate from ``A2ARemoteError`` because the two call for opposite
88
+ responses: "the agent says no" is an answer and retrying will not change
89
+ it, while "the agent answered a shape nobody agreed to" is a bug on one
90
+ side of the wire and should surface as one rather than as a transient
91
+ fault a caller quietly retries.
92
+ """
93
+
94
+
95
+ @dataclass
96
+ class AgentSkill:
97
+ """One thing an agent can do. Published on the card so a caller can choose
98
+ a worker without having been told about it in advance."""
99
+ id: str
100
+ name: str
101
+ description: str = ""
102
+ tags: list[str] = field(default_factory=list)
103
+
104
+
105
+ @dataclass
106
+ class AgentCard:
107
+ """Who an agent is. Served at ``/.well-known/agent-card.json``."""
108
+ name: str
109
+ description: str = ""
110
+ url: str = ""
111
+ version: str = "1.0.0"
112
+ protocol_version: str = PROTOCOL_VERSION
113
+ skills: list[AgentSkill] = field(default_factory=list)
114
+ # Free-form, and deliberately not a fixed vocabulary — an organisation's
115
+ # zones, tiers and markets are its own business, not this library's.
116
+ tags: list[str] = field(default_factory=list)
117
+ provider: dict = field(default_factory=dict)
118
+
119
+ def to_dict(self) -> dict:
120
+ d = asdict(self)
121
+ d["provider"] = self.provider or {"organization": self.name}
122
+ return d
123
+
124
+ @classmethod
125
+ def from_dict(cls, d: dict) -> "AgentCard":
126
+ skills = [AgentSkill(**s) if isinstance(s, dict) else s
127
+ for s in d.get("skills") or []]
128
+ known = set(cls.__dataclass_fields__)
129
+ return cls(**{k: v for k, v in d.items() if k in known and k != "skills"},
130
+ skills=skills)
131
+
132
+
133
+ class Clarify(Exception):
134
+ """Raised by a handler that cannot continue without an answer.
135
+
136
+ The server turns this into ``input-required`` rather than a failure, which
137
+ is the difference between "this agent is broken" and "this agent is waiting
138
+ for you" — and a caller that cannot tell those apart does not know whether
139
+ replying is worth anything.
140
+
141
+ It must be a real exception, not a value: ``except Clarify`` against a plain
142
+ dataclass raises TypeError ("catching classes that do not inherit from
143
+ BaseException"), so the pause path would fail on the one line meant to
144
+ handle it.
145
+ """
146
+
147
+ def __init__(self, question: str, payload: dict | None = None):
148
+ super().__init__(question)
149
+ self.question = question
150
+ self.payload = payload or {}
151
+
152
+
153
+ class A2AClient:
154
+ """JSON-RPC 2.0 over HTTP. Stdlib only."""
155
+
156
+ def __init__(self, url: str, *, timeout: float = 120.0,
157
+ headers: dict | None = None):
158
+ self.url = url.rstrip("/")
159
+ self.timeout = timeout
160
+ self.headers = dict(headers or {})
161
+
162
+ def _rpc(self, method: str, params: dict) -> Any:
163
+ body = json.dumps({"jsonrpc": "2.0", "id": uuid.uuid4().hex,
164
+ "method": method, "params": params}).encode()
165
+ headers = {"Content-Type": "application/json", **self.headers}
166
+ request = urllib.request.Request(self.url, data=body, headers=headers,
167
+ method="POST")
168
+ try:
169
+ with urllib.request.urlopen(request, timeout=self.timeout) as resp:
170
+ payload = json.loads(resp.read().decode())
171
+ except urllib.error.HTTPError as exc:
172
+ raise A2ARemoteError(
173
+ f"{self.url} answered HTTP {exc.code}: "
174
+ f"{exc.read().decode(errors='replace')[:300]}", exc.code) from None
175
+ except urllib.error.URLError as exc:
176
+ # Distinguished from a remote error on purpose: "the agent is down"
177
+ # and "the agent says no" call for different responses, and a caller
178
+ # that cannot tell them apart retries the wrong one.
179
+ raise A2AUnavailable(f"Cannot reach {self.url}: {exc.reason}") from None
180
+ if "error" in payload and payload["error"]:
181
+ err = payload["error"]
182
+ raise A2ARemoteError(err.get("message", "unknown error"),
183
+ err.get("code", -32000))
184
+ return payload.get("result")
185
+
186
+ def send(self, message: str = "", *, data: dict | None = None,
187
+ session_id: str | None = None, user_id: str = "a2a") -> dict:
188
+ """``message/send`` — returns the task, including its state.
189
+
190
+ Two dialects, one method. ``send("what is invoice 42?")`` is the
191
+ conversational one: a person's words, and a person's words back.
192
+ ``send(data={"op": "screen", ...})`` is the machine one: a JSON object
193
+ in a DataPart, which is how services that dispatch on a payload rather
194
+ than on prose talk to each other.
195
+
196
+ Both may be sent together — a DataPart carrying the request and a
197
+ TextPart carrying a human-readable summary of it — because a peer that
198
+ understands only one of them still gets something it can act on.
199
+ """
200
+ if not message and data is None:
201
+ raise ValueError("send() needs a message, data, or both")
202
+
203
+ parts: list[dict] = []
204
+ if data is not None:
205
+ if not isinstance(data, dict):
206
+ # Caught here rather than on the wire: a list or a string in a
207
+ # DataPart is accepted by JSON and rejected by every peer in
208
+ # this mesh, a long way from the call that built it.
209
+ raise TypeError(f"data must be a dict, got {type(data).__name__}")
210
+ parts.append({"kind": "data", "data": data})
211
+ if message:
212
+ parts.append({"kind": "text", "text": message})
213
+
214
+ return self._rpc("message/send", {
215
+ # `kind` and `messageId` are part of the envelope this platform's
216
+ # peers validate; a general text client can omit them and a mesh
217
+ # client cannot, so they are always sent.
218
+ "message": {"role": "user", "kind": "message",
219
+ "messageId": uuid.uuid4().hex, "parts": parts},
220
+ "sessionId": session_id, "userId": user_id})
221
+
222
+ def get_task(self, task_id: str) -> dict:
223
+ return self._rpc("tasks/get", {"id": task_id})
224
+
225
+ def cancel(self, task_id: str) -> dict:
226
+ return self._rpc("tasks/cancel", {"id": task_id})
227
+
228
+
229
+ def text_of(task: dict) -> str:
230
+ """The reply text out of a task result.
231
+
232
+ Parts are collapsed here rather than at every call site: a worker may split
233
+ an answer across several text parts for its own reasons, and no caller
234
+ should have to know that.
235
+ """
236
+ parts = ((task.get("status") or {}).get("message") or {}).get("parts") or []
237
+ if not parts:
238
+ for artifact in task.get("artifacts") or []:
239
+ parts.extend(artifact.get("parts") or [])
240
+ return "".join(p.get("text", "") for p in parts if p.get("kind", "text") == "text")
241
+
242
+
243
+ def data_of(task: dict, *, agent: str = "agent") -> dict:
244
+ """The result DataPart out of a completed task.
245
+
246
+ The mirror of ``text_of`` for the machine dialect, and deliberately stricter
247
+ than it: ``text_of`` returning ``""`` is a thin answer, but a caller that
248
+ cannot tell "the screener is down" from "the screen matched nothing" will
249
+ present an unresolved universe as a resolved one. So every way this can be
250
+ wrong raises, and the exception names which.
251
+
252
+ A completed task carries its result as an artifact DataPart. Every other
253
+ state carries its payload on the status message instead — the question for
254
+ an ``input-required`` pause, the reason for a failure — so use
255
+ ``status_data`` for those rather than widening this.
256
+ """
257
+ if not isinstance(task, dict):
258
+ raise A2AContractError(f"{agent}: expected a task, got "
259
+ f"{type(task).__name__}")
260
+ state = ((task.get("status") or {}).get("state") or "").strip()
261
+ if state and state not in TaskState.ALL:
262
+ raise A2AContractError(f"{agent}: unknown task state {state!r}")
263
+ if state in (TaskState.FAILED, TaskState.REJECTED):
264
+ detail = text_of(task) or (status_data(task) or {}).get("error") or state
265
+ raise A2ARemoteError(f"{agent}: task {state}: {detail}")
266
+ if state != TaskState.COMPLETED:
267
+ raise A2AContractError(
268
+ f"{agent}: task returned non-terminal state {state!r}; this "
269
+ f"transport is synchronous and requires a terminal task")
270
+
271
+ artifacts = task.get("artifacts") or []
272
+ if not artifacts:
273
+ raise A2AContractError(f"{agent}: completed task returned no artifacts")
274
+ for part in (artifacts[0].get("parts") or []):
275
+ if part.get("kind") == "data":
276
+ data = part.get("data")
277
+ if not isinstance(data, dict):
278
+ raise A2AContractError(
279
+ f"{agent}: artifact DataPart is {type(data).__name__}, "
280
+ f"expected an object")
281
+ return data
282
+ raise A2AContractError(f"{agent}: artifact carries no DataPart")
283
+
284
+
285
+ def status_data(task: dict) -> dict:
286
+ """The DataPart off a task's STATUS message — where a paused or failed task
287
+ puts its payload, since only a completed one has artifacts."""
288
+ message = ((task.get("status") or {}).get("message") or {})
289
+ for part in (message.get("parts") or []):
290
+ if part.get("kind") == "data" and isinstance(part.get("data"), dict):
291
+ return part["data"]
292
+ return {}
293
+
294
+
295
+ def request_data(params: dict) -> dict:
296
+ """The DataPart out of an inbound ``message/send``. The server-side mirror
297
+ of ``send(data=...)``; returns ``{}`` when the caller sent only text."""
298
+ for part in ((params.get("message") or {}).get("parts") or []):
299
+ if part.get("kind") == "data" and isinstance(part.get("data"), dict):
300
+ return part["data"]
301
+ return {}
302
+
303
+
304
+ class RemoteAgent:
305
+ """An agent behind an HTTP endpoint, usable exactly like a local one.
306
+
307
+ billing = RemoteAgent.discover("http://billing:8000")
308
+ reply = billing.run("what is invoice 42?")
309
+
310
+ ``run`` returns a string, so a caller cannot tell the difference. A task
311
+ that comes back ``input-required`` is rendered as the question, because
312
+ that is the useful thing to hand a model that is deciding what to do next.
313
+ """
314
+
315
+ def __init__(self, card: AgentCard, *, timeout: float = 120.0,
316
+ headers: dict | None = None):
317
+ if not card.url:
318
+ raise ValueError(
319
+ f"RemoteAgent needs a url on the card for '{card.name}'.")
320
+ if "://" not in card.url:
321
+ # Caught here rather than at the first delegation, where it surfaces
322
+ # as urllib's "unknown url type" from inside a tool call.
323
+ raise ValueError(
324
+ f"RemoteAgent needs an absolute url for '{card.name}', got "
325
+ f"{card.url!r}. Use RemoteAgent.discover(base_url), which "
326
+ f"resolves a relative card url against the address it worked at.")
327
+ self.card = card
328
+ self.client = A2AClient(card.url, timeout=timeout, headers=headers)
329
+
330
+ @property
331
+ def name(self) -> str:
332
+ return self.card.name
333
+
334
+ @property
335
+ def description(self) -> str:
336
+ return self.card.description
337
+
338
+ @classmethod
339
+ def discover(cls, base_url: str, *, timeout: float = 30.0,
340
+ headers: dict | None = None) -> "RemoteAgent":
341
+ """Fetch the published card. The endpoint tells you who it is, so a
342
+ caller does not have to be configured with the answer twice."""
343
+ base = base_url.rstrip("/")
344
+ url = f"{base}/.well-known/agent-card.json"
345
+ request = urllib.request.Request(url, headers=dict(headers or {}))
346
+ try:
347
+ with urllib.request.urlopen(request, timeout=timeout) as resp:
348
+ data = json.loads(resp.read().decode())
349
+ except urllib.error.URLError as exc:
350
+ raise A2AUnavailable(f"Cannot reach {url}: {exc.reason}") from None
351
+ card = AgentCard.from_dict(data)
352
+ # A server does not reliably know its own public address — behind a
353
+ # proxy or in a container it sees a port nobody else can reach — so it
354
+ # may publish a RELATIVE url, or none. The address we just fetched the
355
+ # card from is the one that demonstrably works, so resolve against it.
356
+ # Keeping a bare "/a2a" here produces "unknown url type: '/a2a'" at the
357
+ # first delegation, a long way from the cause.
358
+ card.url = urljoin(f"{base}/", card.url or "a2a")
359
+ return cls(card, timeout=timeout, headers=headers)
360
+
361
+ def run(self, text: str, *, session_id: str | None = None) -> str:
362
+ try:
363
+ task = self.client.send(text, session_id=session_id)
364
+ except A2AError as exc:
365
+ # Returned, not raised: this runs inside a tool call, and a model
366
+ # that is told "billing is unreachable" can try something else,
367
+ # while an exception ends the turn.
368
+ return f"Error calling agent '{self.name}': {exc}"
369
+ state = (task.get("status") or {}).get("state")
370
+ reply = text_of(task)
371
+ if state == TaskState.INPUT_REQUIRED:
372
+ return f"[{self.name} needs more input] {reply}"
373
+ if state == TaskState.FAILED:
374
+ return f"Agent '{self.name}' failed: {reply}"
375
+ return reply