samtale 0.1.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.
- samtale/__init__.py +24 -0
- samtale/agent.py +370 -0
- samtale/exceptions.py +50 -0
- samtale/helpers.py +196 -0
- samtale/message.py +166 -0
- samtale-0.1.0.dist-info/METADATA +282 -0
- samtale-0.1.0.dist-info/RECORD +9 -0
- samtale-0.1.0.dist-info/WHEEL +4 -0
- samtale-0.1.0.dist-info/licenses/LICENSE +202 -0
samtale/__init__.py
ADDED
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
from .agent import Agent
|
|
2
|
+
from .exceptions import (
|
|
3
|
+
AgentClosedError,
|
|
4
|
+
ChatterError,
|
|
5
|
+
MessageValidationError,
|
|
6
|
+
RemoteError,
|
|
7
|
+
RemoteRejection,
|
|
8
|
+
SendTimeout,
|
|
9
|
+
TransportError,
|
|
10
|
+
)
|
|
11
|
+
from .message import Message, Status
|
|
12
|
+
|
|
13
|
+
__all__ = [
|
|
14
|
+
"Agent",
|
|
15
|
+
"AgentClosedError",
|
|
16
|
+
"ChatterError",
|
|
17
|
+
"Message",
|
|
18
|
+
"MessageValidationError",
|
|
19
|
+
"RemoteError",
|
|
20
|
+
"RemoteRejection",
|
|
21
|
+
"SendTimeout",
|
|
22
|
+
"Status",
|
|
23
|
+
"TransportError",
|
|
24
|
+
]
|
samtale/agent.py
ADDED
|
@@ -0,0 +1,370 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
"""HTTP agent runtime.
|
|
4
|
+
|
|
5
|
+
The `Agent` class exposes a small peer-to-peer HTTP message endpoint, a handler
|
|
6
|
+
registry, an internal queue, and outbound helpers for sending messages to other
|
|
7
|
+
agents. Handler execution is intentionally serialized through the queue.
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
import asyncio
|
|
11
|
+
import logging
|
|
12
|
+
import math
|
|
13
|
+
from contextlib import asynccontextmanager
|
|
14
|
+
from typing import Any
|
|
15
|
+
|
|
16
|
+
import httpx
|
|
17
|
+
from pydantic import BaseModel
|
|
18
|
+
import uvicorn
|
|
19
|
+
from starlette.applications import Starlette
|
|
20
|
+
from starlette.requests import Request
|
|
21
|
+
from starlette.routing import Route
|
|
22
|
+
|
|
23
|
+
from .exceptions import (
|
|
24
|
+
AgentClosedError,
|
|
25
|
+
MessageValidationError,
|
|
26
|
+
RemoteError,
|
|
27
|
+
RemoteRejection,
|
|
28
|
+
SendTimeout,
|
|
29
|
+
TransportError,
|
|
30
|
+
)
|
|
31
|
+
from .helpers import (
|
|
32
|
+
Handler,
|
|
33
|
+
HandlerDefinition,
|
|
34
|
+
complete_future,
|
|
35
|
+
dispatch_handler,
|
|
36
|
+
error_response,
|
|
37
|
+
fail_future,
|
|
38
|
+
json_message,
|
|
39
|
+
remote_error_payload,
|
|
40
|
+
request_message,
|
|
41
|
+
response_message,
|
|
42
|
+
status_for,
|
|
43
|
+
validate_response,
|
|
44
|
+
)
|
|
45
|
+
from .message import Message, Status
|
|
46
|
+
|
|
47
|
+
logger = logging.getLogger(__name__)
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
class Agent:
|
|
51
|
+
"""An asynchronous HTTP endpoint that receives and sends `Message` objects.
|
|
52
|
+
|
|
53
|
+
Each agent owns a Starlette app at `app`, an inbox queue, a bounded worker
|
|
54
|
+
pool, and a reusable HTTP client for outbound messages.
|
|
55
|
+
"""
|
|
56
|
+
|
|
57
|
+
def __init__(
|
|
58
|
+
self,
|
|
59
|
+
name: str,
|
|
60
|
+
*,
|
|
61
|
+
timeout: float = 5.0,
|
|
62
|
+
handler_timeout: float | None = None,
|
|
63
|
+
max_concurrency: int = 1,
|
|
64
|
+
):
|
|
65
|
+
"""Create an agent.
|
|
66
|
+
|
|
67
|
+
Args:
|
|
68
|
+
name: Stable sender name used in outbound and response messages.
|
|
69
|
+
timeout: HTTP client timeout for outbound sends.
|
|
70
|
+
handler_timeout: Optional timeout for each handler invocation.
|
|
71
|
+
max_concurrency: Maximum number of handlers that may run at once.
|
|
72
|
+
"""
|
|
73
|
+
if not isinstance(name, str) or not name.strip():
|
|
74
|
+
raise ValueError("name must be a non-empty string")
|
|
75
|
+
if not _valid_timeout(timeout):
|
|
76
|
+
raise ValueError("timeout must be greater than zero")
|
|
77
|
+
if handler_timeout is not None and not _valid_timeout(handler_timeout):
|
|
78
|
+
raise ValueError("handler_timeout must be greater than zero")
|
|
79
|
+
if (
|
|
80
|
+
not isinstance(max_concurrency, int)
|
|
81
|
+
or isinstance(max_concurrency, bool)
|
|
82
|
+
or max_concurrency <= 0
|
|
83
|
+
):
|
|
84
|
+
raise ValueError("max_concurrency must be a positive integer")
|
|
85
|
+
|
|
86
|
+
# Keep construction cheap: the HTTP app is ready, but the worker pool
|
|
87
|
+
# starts with the app lifespan or an explicit start() call.
|
|
88
|
+
self.name = name.strip()
|
|
89
|
+
self.timeout = timeout
|
|
90
|
+
self.handler_timeout = handler_timeout
|
|
91
|
+
self.max_concurrency = max_concurrency
|
|
92
|
+
self.handlers: dict[str, HandlerDefinition] = {}
|
|
93
|
+
self.inbox: asyncio.Queue[tuple[Message, asyncio.Future[Message]]] = (
|
|
94
|
+
asyncio.Queue()
|
|
95
|
+
)
|
|
96
|
+
self._workers: list[asyncio.Task[None]] = []
|
|
97
|
+
self._client: httpx.AsyncClient | None = None
|
|
98
|
+
self._active_futures: set[asyncio.Future[Message]] = set()
|
|
99
|
+
self._accepting = False
|
|
100
|
+
|
|
101
|
+
@asynccontextmanager
|
|
102
|
+
async def lifespan(app: Starlette):
|
|
103
|
+
# Starlette owns the server lifecycle; the agent owns the inbox worker.
|
|
104
|
+
await self.start()
|
|
105
|
+
try:
|
|
106
|
+
yield
|
|
107
|
+
finally:
|
|
108
|
+
await self.close()
|
|
109
|
+
|
|
110
|
+
async def receive(request: Request):
|
|
111
|
+
# HTTP requests stop at the queue boundary. The agent loop does the
|
|
112
|
+
# actual handler lookup and execution.
|
|
113
|
+
try:
|
|
114
|
+
message = await request_message(request)
|
|
115
|
+
except MessageValidationError as exc:
|
|
116
|
+
return error_response(self.name, None, "malformed_message", str(exc))
|
|
117
|
+
except Exception:
|
|
118
|
+
logger.exception("Failed to read inbound message")
|
|
119
|
+
return error_response(
|
|
120
|
+
self.name,
|
|
121
|
+
None,
|
|
122
|
+
"internal_error",
|
|
123
|
+
"The message could not be processed",
|
|
124
|
+
)
|
|
125
|
+
|
|
126
|
+
if not self._accepting:
|
|
127
|
+
return error_response(
|
|
128
|
+
self.name, message, "agent_closed", "The agent is closed"
|
|
129
|
+
)
|
|
130
|
+
|
|
131
|
+
future: asyncio.Future[Message] = asyncio.get_running_loop().create_future()
|
|
132
|
+
await self.inbox.put((message, future))
|
|
133
|
+
try:
|
|
134
|
+
response = await future
|
|
135
|
+
except asyncio.CancelledError:
|
|
136
|
+
future.cancel()
|
|
137
|
+
raise
|
|
138
|
+
except AgentClosedError:
|
|
139
|
+
response = Message.error(
|
|
140
|
+
self.name,
|
|
141
|
+
message,
|
|
142
|
+
"agent_closed",
|
|
143
|
+
{"message": "The agent is closed"},
|
|
144
|
+
)
|
|
145
|
+
|
|
146
|
+
return json_message(response, status_for(response))
|
|
147
|
+
|
|
148
|
+
self.app = Starlette(
|
|
149
|
+
lifespan=lifespan, routes=[Route("/messages", receive, methods=["POST"])]
|
|
150
|
+
)
|
|
151
|
+
|
|
152
|
+
def on(
|
|
153
|
+
self,
|
|
154
|
+
message_type: str,
|
|
155
|
+
*,
|
|
156
|
+
model: type[BaseModel] | None = None,
|
|
157
|
+
):
|
|
158
|
+
"""Register an async handler for a message type.
|
|
159
|
+
|
|
160
|
+
Args:
|
|
161
|
+
message_type: Domain message type, for example `temperature.read`.
|
|
162
|
+
model: Optional Pydantic model used to validate and parse the payload.
|
|
163
|
+
|
|
164
|
+
Returns:
|
|
165
|
+
A decorator that stores the handler and returns it unchanged.
|
|
166
|
+
"""
|
|
167
|
+
if not isinstance(message_type, str) or not message_type:
|
|
168
|
+
raise ValueError("message_type must be a non-empty string")
|
|
169
|
+
if model is not None and (
|
|
170
|
+
not isinstance(model, type) or not issubclass(model, BaseModel)
|
|
171
|
+
):
|
|
172
|
+
raise TypeError("model must be a Pydantic BaseModel subclass")
|
|
173
|
+
|
|
174
|
+
# Decorator API: @agent.on("read") registers the async handler.
|
|
175
|
+
def decorator(fn: Handler):
|
|
176
|
+
if message_type in self.handlers:
|
|
177
|
+
raise ValueError(f"handler already registered for {message_type!r}")
|
|
178
|
+
self.handlers[message_type] = HandlerDefinition(
|
|
179
|
+
handler=fn,
|
|
180
|
+
model=model,
|
|
181
|
+
schema=model.model_json_schema() if model is not None else {},
|
|
182
|
+
)
|
|
183
|
+
return fn
|
|
184
|
+
|
|
185
|
+
return decorator
|
|
186
|
+
|
|
187
|
+
def reject(
|
|
188
|
+
self, request: Message, reason: str, payload: dict[str, Any] | None = None
|
|
189
|
+
) -> Message:
|
|
190
|
+
"""Build a correlated domain rejection from inside a handler."""
|
|
191
|
+
return Message.reject(self.name, request, reason, payload)
|
|
192
|
+
|
|
193
|
+
def ok(self, request: Message, payload: dict[str, Any] | None = None) -> Message:
|
|
194
|
+
"""Build a correlated successful response from inside a handler."""
|
|
195
|
+
return Message.ok(self.name, request, payload)
|
|
196
|
+
|
|
197
|
+
async def start(self) -> None:
|
|
198
|
+
"""Start the outbound HTTP client and handler workers."""
|
|
199
|
+
# Idempotent so tests or embedding code can call it directly.
|
|
200
|
+
if self._client is None or self._client.is_closed:
|
|
201
|
+
self._client = httpx.AsyncClient(timeout=self.timeout)
|
|
202
|
+
self._workers = [worker for worker in self._workers if not worker.done()]
|
|
203
|
+
self._workers.extend(
|
|
204
|
+
asyncio.create_task(self._loop())
|
|
205
|
+
for _ in range(self.max_concurrency - len(self._workers))
|
|
206
|
+
)
|
|
207
|
+
self._accepting = True
|
|
208
|
+
|
|
209
|
+
async def close(self) -> None:
|
|
210
|
+
"""Stop the worker pool, fail pending requests, and close the client."""
|
|
211
|
+
# Cancel the background worker cleanly during app shutdown.
|
|
212
|
+
self._accepting = False
|
|
213
|
+
error = AgentClosedError(f"agent {self.name!r} is closed")
|
|
214
|
+
for future in tuple(self._active_futures):
|
|
215
|
+
fail_future(future, error)
|
|
216
|
+
|
|
217
|
+
for worker in self._workers:
|
|
218
|
+
worker.cancel()
|
|
219
|
+
if self._workers:
|
|
220
|
+
await asyncio.gather(*self._workers, return_exceptions=True)
|
|
221
|
+
self._workers.clear()
|
|
222
|
+
self._active_futures.clear()
|
|
223
|
+
|
|
224
|
+
while not self.inbox.empty():
|
|
225
|
+
_message, future = self.inbox.get_nowait()
|
|
226
|
+
fail_future(future, error)
|
|
227
|
+
self.inbox.task_done()
|
|
228
|
+
|
|
229
|
+
if self._client is not None:
|
|
230
|
+
await self._client.aclose()
|
|
231
|
+
self._client = None
|
|
232
|
+
|
|
233
|
+
async def _loop(self) -> None:
|
|
234
|
+
"""Dispatch queued messages until cancelled."""
|
|
235
|
+
while True:
|
|
236
|
+
message, future = await self.inbox.get()
|
|
237
|
+
self._active_futures.add(future)
|
|
238
|
+
try:
|
|
239
|
+
if not future.done():
|
|
240
|
+
complete_future(future, await self._dispatch(message))
|
|
241
|
+
except Exception:
|
|
242
|
+
logger.exception("Handler %r failed unexpectedly", message.type)
|
|
243
|
+
complete_future(
|
|
244
|
+
future,
|
|
245
|
+
Message.error(
|
|
246
|
+
self.name,
|
|
247
|
+
message,
|
|
248
|
+
"handler_failure",
|
|
249
|
+
{"message": "The message handler failed"},
|
|
250
|
+
),
|
|
251
|
+
)
|
|
252
|
+
finally:
|
|
253
|
+
self._active_futures.discard(future)
|
|
254
|
+
self.inbox.task_done()
|
|
255
|
+
|
|
256
|
+
async def _dispatch(self, message: Message) -> Message:
|
|
257
|
+
"""Run the registered handler and normalize its result to a response."""
|
|
258
|
+
definition = self.handlers.get(message.type)
|
|
259
|
+
if definition is None:
|
|
260
|
+
return Message.reject(
|
|
261
|
+
self.name,
|
|
262
|
+
message,
|
|
263
|
+
"unsupported_message",
|
|
264
|
+
{
|
|
265
|
+
"accepted_messages": [
|
|
266
|
+
{
|
|
267
|
+
"type": message_type,
|
|
268
|
+
"schema": self.handlers[message_type].schema,
|
|
269
|
+
}
|
|
270
|
+
for message_type in sorted(self.handlers)
|
|
271
|
+
],
|
|
272
|
+
},
|
|
273
|
+
)
|
|
274
|
+
|
|
275
|
+
return await dispatch_handler(
|
|
276
|
+
self.name, definition, message, self.handler_timeout
|
|
277
|
+
)
|
|
278
|
+
|
|
279
|
+
async def send(self, address: str, message_type: str, **payload: Any) -> Message:
|
|
280
|
+
"""Send a request to another agent and return the full response message.
|
|
281
|
+
|
|
282
|
+
Raises:
|
|
283
|
+
SendTimeout: The HTTP request timed out.
|
|
284
|
+
TransportError: The transport failed or the response envelope was invalid.
|
|
285
|
+
RemoteError: The peer returned an HTTP error with a valid agent error.
|
|
286
|
+
"""
|
|
287
|
+
# Create the wire message, POST it to the peer, and return the complete
|
|
288
|
+
# validated response envelope.
|
|
289
|
+
message = Message(sender=self.name, type=message_type, payload=payload)
|
|
290
|
+
await self.start()
|
|
291
|
+
assert self._client is not None
|
|
292
|
+
|
|
293
|
+
try:
|
|
294
|
+
response = await self._client.post(
|
|
295
|
+
f"{address.rstrip('/')}/messages", json=message.to_dict()
|
|
296
|
+
)
|
|
297
|
+
response.raise_for_status()
|
|
298
|
+
except httpx.TimeoutException as exc:
|
|
299
|
+
raise SendTimeout(address, message.id, self.timeout) from exc
|
|
300
|
+
except httpx.HTTPStatusError as exc:
|
|
301
|
+
envelope = response_message(exc.response, address)
|
|
302
|
+
validate_response(address, message, envelope)
|
|
303
|
+
if envelope.status is Status.ERROR:
|
|
304
|
+
raise RemoteError(
|
|
305
|
+
address, message.id, remote_error_payload(envelope)
|
|
306
|
+
) from exc
|
|
307
|
+
raise TransportError(
|
|
308
|
+
f"{address} returned HTTP {exc.response.status_code}"
|
|
309
|
+
) from exc
|
|
310
|
+
except httpx.HTTPError as exc:
|
|
311
|
+
raise TransportError(str(exc)) from exc
|
|
312
|
+
|
|
313
|
+
envelope = response_message(response, address)
|
|
314
|
+
validate_response(address, message, envelope)
|
|
315
|
+
return envelope
|
|
316
|
+
|
|
317
|
+
async def ask(
|
|
318
|
+
self, address: str, message_type: str, **payload: Any
|
|
319
|
+
) -> dict[str, Any]:
|
|
320
|
+
"""Send a request that is expected to succeed and return only payload."""
|
|
321
|
+
response = await self.send(address, message_type, **payload)
|
|
322
|
+
self._require_ok(address, response)
|
|
323
|
+
return response.payload
|
|
324
|
+
|
|
325
|
+
async def emit(
|
|
326
|
+
self,
|
|
327
|
+
address: str,
|
|
328
|
+
message_type: str,
|
|
329
|
+
**payload: Any,
|
|
330
|
+
) -> None:
|
|
331
|
+
"""Send a message and discard the successful response payload.
|
|
332
|
+
|
|
333
|
+
This is an acknowledgement-based convenience method, not guaranteed
|
|
334
|
+
delivery and not true fire-and-forget.
|
|
335
|
+
"""
|
|
336
|
+
response = await self.send(
|
|
337
|
+
address,
|
|
338
|
+
message_type,
|
|
339
|
+
**payload,
|
|
340
|
+
)
|
|
341
|
+
|
|
342
|
+
self._require_ok(address, response)
|
|
343
|
+
|
|
344
|
+
@staticmethod
|
|
345
|
+
def _require_ok(address: str, response: Message) -> None:
|
|
346
|
+
if response.status is Status.REJECTED:
|
|
347
|
+
raise RemoteRejection(
|
|
348
|
+
address,
|
|
349
|
+
response.reply_to or "",
|
|
350
|
+
response.reason or "rejected",
|
|
351
|
+
response.payload,
|
|
352
|
+
)
|
|
353
|
+
if response.status is Status.ERROR:
|
|
354
|
+
raise RemoteError(
|
|
355
|
+
address, response.reply_to or "", remote_error_payload(response)
|
|
356
|
+
)
|
|
357
|
+
|
|
358
|
+
def run(self, *, host: str = "0.0.0.0", port: int = 8000) -> None:
|
|
359
|
+
"""Run the agent's Starlette app with uvicorn."""
|
|
360
|
+
# Convenience runner for examples and small local processes.
|
|
361
|
+
uvicorn.run(self.app, host=host, port=port)
|
|
362
|
+
|
|
363
|
+
|
|
364
|
+
def _valid_timeout(value: object) -> bool:
|
|
365
|
+
return (
|
|
366
|
+
isinstance(value, int | float)
|
|
367
|
+
and not isinstance(value, bool)
|
|
368
|
+
and math.isfinite(value)
|
|
369
|
+
and value > 0
|
|
370
|
+
)
|
samtale/exceptions.py
ADDED
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
from typing import Any
|
|
2
|
+
|
|
3
|
+
|
|
4
|
+
class ChatterError(Exception):
|
|
5
|
+
"""Base exception for samtale."""
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
class AgentClosedError(ChatterError):
|
|
9
|
+
"""Raised when work cannot complete because the agent is closing."""
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
class MessageValidationError(ChatterError):
|
|
13
|
+
"""Raised when a wire message is malformed."""
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
class RemoteError(ChatterError):
|
|
17
|
+
def __init__(self, target: str, message_id: str, error: dict):
|
|
18
|
+
self.target = target
|
|
19
|
+
self.message_id = message_id
|
|
20
|
+
self.error = error
|
|
21
|
+
super().__init__(f"{target} returned error for {message_id}: {error}")
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
class RemoteRejection(ChatterError):
|
|
25
|
+
"""Raised when a remote agent rejects an otherwise valid request."""
|
|
26
|
+
|
|
27
|
+
def __init__(
|
|
28
|
+
self,
|
|
29
|
+
target: str,
|
|
30
|
+
message_id: str,
|
|
31
|
+
reason: str,
|
|
32
|
+
payload: dict[str, Any],
|
|
33
|
+
):
|
|
34
|
+
self.target = target
|
|
35
|
+
self.message_id = message_id
|
|
36
|
+
self.reason = reason
|
|
37
|
+
self.payload = payload
|
|
38
|
+
super().__init__(f"{target} rejected message {message_id}: {reason}")
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
class SendTimeout(ChatterError):
|
|
42
|
+
def __init__(self, target: str, message_id: str, timeout: float):
|
|
43
|
+
self.target = target
|
|
44
|
+
self.message_id = message_id
|
|
45
|
+
self.timeout = timeout
|
|
46
|
+
super().__init__(f"message {message_id} to {target} timed out after {timeout:g}s")
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
class TransportError(ChatterError):
|
|
50
|
+
"""Raised when the HTTP transport fails or returns a malformed response."""
|
samtale/helpers.py
ADDED
|
@@ -0,0 +1,196 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import asyncio
|
|
4
|
+
import logging
|
|
5
|
+
from collections.abc import Awaitable, Callable
|
|
6
|
+
from dataclasses import dataclass, field
|
|
7
|
+
from typing import Any
|
|
8
|
+
|
|
9
|
+
import httpx
|
|
10
|
+
from pydantic import BaseModel, ValidationError
|
|
11
|
+
from starlette.requests import Request
|
|
12
|
+
from starlette.responses import JSONResponse
|
|
13
|
+
|
|
14
|
+
from .exceptions import MessageValidationError, TransportError
|
|
15
|
+
from .message import Message, Status
|
|
16
|
+
|
|
17
|
+
Handler = Callable[..., Awaitable[Any]]
|
|
18
|
+
PayloadModel = type[BaseModel]
|
|
19
|
+
logger = logging.getLogger(__name__)
|
|
20
|
+
HANDLER_FAILURE_MESSAGE = "The message handler failed"
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
@dataclass(slots=True)
|
|
24
|
+
class HandlerDefinition:
|
|
25
|
+
handler: Handler
|
|
26
|
+
model: PayloadModel | None = None
|
|
27
|
+
schema: dict[str, Any] = field(default_factory=dict)
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def json_message(message: Message, status: int) -> JSONResponse:
|
|
31
|
+
return JSONResponse(message.to_dict(), status_code=status)
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def error_response(
|
|
35
|
+
sender: str,
|
|
36
|
+
request: Message | None,
|
|
37
|
+
reason: str,
|
|
38
|
+
detail: str,
|
|
39
|
+
) -> JSONResponse:
|
|
40
|
+
message = Message.error(sender, request, reason, {"message": detail})
|
|
41
|
+
return json_message(message, status_for(message))
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
async def request_message(request: Request) -> Message:
|
|
45
|
+
try:
|
|
46
|
+
data = await request.json()
|
|
47
|
+
except (ValueError, UnicodeDecodeError) as exc:
|
|
48
|
+
raise MessageValidationError(f"invalid JSON: {exc}") from exc
|
|
49
|
+
|
|
50
|
+
message = Message.from_dict(data)
|
|
51
|
+
if not message.is_request:
|
|
52
|
+
raise MessageValidationError("the messages endpoint only accepts requests")
|
|
53
|
+
return message
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def status_for(message: Message) -> int:
|
|
57
|
+
if message.status is not Status.ERROR:
|
|
58
|
+
return 200
|
|
59
|
+
return {
|
|
60
|
+
"malformed_message": 400,
|
|
61
|
+
"handler_timeout": 504,
|
|
62
|
+
"agent_closed": 503,
|
|
63
|
+
}.get(message.reason, 500)
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def parse_payload(
|
|
67
|
+
agent_name: str,
|
|
68
|
+
definition: HandlerDefinition,
|
|
69
|
+
message: Message,
|
|
70
|
+
) -> tuple[Message | None, BaseModel | None]:
|
|
71
|
+
if definition.model is not None:
|
|
72
|
+
try:
|
|
73
|
+
return None, definition.model.model_validate(message.payload)
|
|
74
|
+
except ValidationError as exc:
|
|
75
|
+
return (
|
|
76
|
+
Message.reject(
|
|
77
|
+
agent_name,
|
|
78
|
+
message,
|
|
79
|
+
"invalid_payload",
|
|
80
|
+
{
|
|
81
|
+
"expected_message": {"type": message.type, "schema": definition.schema},
|
|
82
|
+
"issues": pydantic_issues(exc),
|
|
83
|
+
},
|
|
84
|
+
),
|
|
85
|
+
None,
|
|
86
|
+
)
|
|
87
|
+
|
|
88
|
+
return None, None
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
async def dispatch_handler(
|
|
92
|
+
sender: str,
|
|
93
|
+
definition: HandlerDefinition,
|
|
94
|
+
message: Message,
|
|
95
|
+
timeout: float | None,
|
|
96
|
+
) -> Message:
|
|
97
|
+
invalid, parsed_payload = parse_payload(sender, definition, message)
|
|
98
|
+
if invalid is not None:
|
|
99
|
+
return invalid
|
|
100
|
+
|
|
101
|
+
try:
|
|
102
|
+
invocation = (
|
|
103
|
+
definition.handler(message, parsed_payload)
|
|
104
|
+
if definition.model is not None
|
|
105
|
+
else definition.handler(message)
|
|
106
|
+
)
|
|
107
|
+
result = await invocation if timeout is None else await asyncio.wait_for(invocation, timeout)
|
|
108
|
+
except asyncio.TimeoutError:
|
|
109
|
+
return Message.error(
|
|
110
|
+
sender,
|
|
111
|
+
message,
|
|
112
|
+
"handler_timeout",
|
|
113
|
+
{"message": f"Handler timed out after {timeout:g}s"},
|
|
114
|
+
)
|
|
115
|
+
except Exception:
|
|
116
|
+
logger.exception("Handler %r failed", message.type)
|
|
117
|
+
return Message.error(sender, message, "handler_failure", {"message": HANDLER_FAILURE_MESSAGE})
|
|
118
|
+
|
|
119
|
+
return normalize_handler_result(sender, message, result)
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
def normalize_handler_result(sender: str, request: Message, result: Any) -> Message:
|
|
123
|
+
try:
|
|
124
|
+
if isinstance(result, Message):
|
|
125
|
+
response = normalize_handler_message(sender, request, result)
|
|
126
|
+
elif result is None:
|
|
127
|
+
response = Message.ok(sender, request)
|
|
128
|
+
elif isinstance(result, dict):
|
|
129
|
+
response = Message.ok(sender, request, result)
|
|
130
|
+
else:
|
|
131
|
+
raise MessageValidationError("Handler must return a dict, Message, or None")
|
|
132
|
+
except MessageValidationError as exc:
|
|
133
|
+
return Message.error(sender, request, "invalid_handler_result", {"message": str(exc)})
|
|
134
|
+
|
|
135
|
+
return response
|
|
136
|
+
|
|
137
|
+
|
|
138
|
+
def pydantic_issues(exc: ValidationError) -> list[dict[str, Any]]:
|
|
139
|
+
return [
|
|
140
|
+
{
|
|
141
|
+
"field": ".".join(str(part) for part in error["loc"]),
|
|
142
|
+
"reason": error["type"],
|
|
143
|
+
"message": error["msg"],
|
|
144
|
+
}
|
|
145
|
+
for error in exc.errors()
|
|
146
|
+
]
|
|
147
|
+
|
|
148
|
+
|
|
149
|
+
def normalize_handler_message(sender: str, request: Message, result: Message) -> Message:
|
|
150
|
+
if result.reply_to != request.id or result.type != request.type:
|
|
151
|
+
raise MessageValidationError("handler response must match the request")
|
|
152
|
+
if result.sender != sender:
|
|
153
|
+
return Message(
|
|
154
|
+
sender=sender,
|
|
155
|
+
type=result.type,
|
|
156
|
+
payload=result.payload,
|
|
157
|
+
id=result.id,
|
|
158
|
+
reply_to=result.reply_to,
|
|
159
|
+
status=result.status,
|
|
160
|
+
reason=result.reason,
|
|
161
|
+
)
|
|
162
|
+
return result
|
|
163
|
+
|
|
164
|
+
|
|
165
|
+
def validate_response(address: str, request: Message, response: Message) -> None:
|
|
166
|
+
if response.reply_to != request.id:
|
|
167
|
+
raise TransportError(f"{address} response did not match message {request.id}")
|
|
168
|
+
if response.type != request.type:
|
|
169
|
+
raise TransportError(f"{address} response type {response.type!r} did not match {request.type!r}")
|
|
170
|
+
if response.status is None:
|
|
171
|
+
raise TransportError(f"{address} response did not include status")
|
|
172
|
+
|
|
173
|
+
|
|
174
|
+
def remote_error_payload(response: Message) -> dict[str, Any]:
|
|
175
|
+
return {
|
|
176
|
+
"status": response.status.value if response.status else None,
|
|
177
|
+
"reason": response.reason,
|
|
178
|
+
"payload": response.payload,
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
|
|
182
|
+
def complete_future(future: asyncio.Future[Message] | None, result: Message) -> None:
|
|
183
|
+
if future is not None and not future.done():
|
|
184
|
+
future.set_result(result)
|
|
185
|
+
|
|
186
|
+
|
|
187
|
+
def fail_future(future: asyncio.Future[Message] | None, exc: Exception) -> None:
|
|
188
|
+
if future is not None and not future.done():
|
|
189
|
+
future.set_exception(exc)
|
|
190
|
+
|
|
191
|
+
|
|
192
|
+
def response_message(response: httpx.Response, target: str) -> Message:
|
|
193
|
+
try:
|
|
194
|
+
return Message.from_dict(response.json())
|
|
195
|
+
except Exception as exc:
|
|
196
|
+
raise TransportError(f"{target} returned a malformed response") from exc
|
samtale/message.py
ADDED
|
@@ -0,0 +1,166 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import json
|
|
4
|
+
from dataclasses import dataclass, field
|
|
5
|
+
from enum import StrEnum
|
|
6
|
+
from typing import Any
|
|
7
|
+
from uuid import uuid4
|
|
8
|
+
|
|
9
|
+
from .exceptions import MessageValidationError
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
class Status(StrEnum):
|
|
13
|
+
OK = "ok"
|
|
14
|
+
REJECTED = "rejected"
|
|
15
|
+
ERROR = "error"
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
@dataclass(slots=True)
|
|
19
|
+
class Message:
|
|
20
|
+
sender: str
|
|
21
|
+
type: str
|
|
22
|
+
payload: dict[str, Any] = field(default_factory=dict)
|
|
23
|
+
id: str = field(default_factory=lambda: str(uuid4()))
|
|
24
|
+
reply_to: str | None = None
|
|
25
|
+
status: Status | None = None
|
|
26
|
+
reason: str | None = None
|
|
27
|
+
|
|
28
|
+
def __post_init__(self) -> None:
|
|
29
|
+
_require_text(self.id, "id")
|
|
30
|
+
_require_text(self.sender, "sender")
|
|
31
|
+
_require_text(self.type, "type")
|
|
32
|
+
if not isinstance(self.payload, dict):
|
|
33
|
+
raise MessageValidationError("payload must be an object")
|
|
34
|
+
try:
|
|
35
|
+
json.dumps(self.payload, allow_nan=False)
|
|
36
|
+
except (TypeError, ValueError) as exc:
|
|
37
|
+
raise MessageValidationError("payload must be JSON-compatible") from exc
|
|
38
|
+
if self.status is not None and not isinstance(self.status, Status):
|
|
39
|
+
try:
|
|
40
|
+
self.status = Status(self.status)
|
|
41
|
+
except (TypeError, ValueError) as exc:
|
|
42
|
+
raise MessageValidationError(f"invalid status: {self.status!r}") from exc
|
|
43
|
+
|
|
44
|
+
if self.reply_to is None:
|
|
45
|
+
self._validate_uncorrelated()
|
|
46
|
+
return
|
|
47
|
+
|
|
48
|
+
_require_text(self.reply_to, "reply_to")
|
|
49
|
+
if self.status is None:
|
|
50
|
+
raise MessageValidationError("responses require status")
|
|
51
|
+
if self.status is Status.OK:
|
|
52
|
+
if self.reason is not None:
|
|
53
|
+
raise MessageValidationError("ok responses cannot have reason")
|
|
54
|
+
return
|
|
55
|
+
_require_text(self.reason, "reason")
|
|
56
|
+
|
|
57
|
+
def _validate_uncorrelated(self) -> None:
|
|
58
|
+
if self.type == "_agent.error":
|
|
59
|
+
if self.status is not Status.ERROR:
|
|
60
|
+
raise MessageValidationError("uncorrelated framework errors require error status")
|
|
61
|
+
_require_text(self.reason, "reason")
|
|
62
|
+
return
|
|
63
|
+
if self.status is not None:
|
|
64
|
+
raise MessageValidationError("requests cannot have status")
|
|
65
|
+
if self.reason is not None:
|
|
66
|
+
raise MessageValidationError("requests cannot have reason")
|
|
67
|
+
|
|
68
|
+
@classmethod
|
|
69
|
+
def from_dict(cls, data: object) -> "Message":
|
|
70
|
+
if not isinstance(data, dict):
|
|
71
|
+
raise MessageValidationError("message must be a JSON object")
|
|
72
|
+
|
|
73
|
+
allowed = {"id", "sender", "type", "payload", "reply_to", "status", "reason"}
|
|
74
|
+
extra = set(data) - allowed
|
|
75
|
+
if extra:
|
|
76
|
+
raise MessageValidationError(f"unknown message field: {sorted(extra)[0]}")
|
|
77
|
+
for field_name in ("id", "sender", "type"):
|
|
78
|
+
if field_name not in data:
|
|
79
|
+
raise MessageValidationError(f"missing required field: {field_name}")
|
|
80
|
+
if "reply_to" in data and data["reply_to"] is None:
|
|
81
|
+
raise MessageValidationError("reply_to must be a non-empty string")
|
|
82
|
+
if "status" in data and data["status"] is None:
|
|
83
|
+
raise MessageValidationError("status must be one of: ok, rejected, error")
|
|
84
|
+
if "reason" in data and data["reason"] is None:
|
|
85
|
+
raise MessageValidationError("reason must be a non-empty string")
|
|
86
|
+
|
|
87
|
+
try:
|
|
88
|
+
status = Status(data["status"]) if "status" in data else None
|
|
89
|
+
except (TypeError, ValueError) as exc:
|
|
90
|
+
raise MessageValidationError(f"invalid status: {data.get('status')!r}") from exc
|
|
91
|
+
|
|
92
|
+
return cls(
|
|
93
|
+
id=data["id"],
|
|
94
|
+
sender=data["sender"],
|
|
95
|
+
type=data["type"],
|
|
96
|
+
payload=data.get("payload", {}),
|
|
97
|
+
reply_to=data.get("reply_to"),
|
|
98
|
+
status=status,
|
|
99
|
+
reason=data.get("reason"),
|
|
100
|
+
)
|
|
101
|
+
|
|
102
|
+
def to_dict(self) -> dict[str, Any]:
|
|
103
|
+
data: dict[str, Any] = {
|
|
104
|
+
"id": self.id,
|
|
105
|
+
"sender": self.sender,
|
|
106
|
+
"type": self.type,
|
|
107
|
+
"payload": self.payload,
|
|
108
|
+
}
|
|
109
|
+
if self.reply_to is not None:
|
|
110
|
+
data["reply_to"] = self.reply_to
|
|
111
|
+
if self.status is not None:
|
|
112
|
+
data["status"] = self.status.value
|
|
113
|
+
if self.reason is not None:
|
|
114
|
+
data["reason"] = self.reason
|
|
115
|
+
return data
|
|
116
|
+
|
|
117
|
+
@classmethod
|
|
118
|
+
def ok(cls, sender: str, request: "Message", payload: dict[str, Any] | None = None) -> "Message":
|
|
119
|
+
return cls(sender=sender, type=request.type, payload=payload or {}, reply_to=request.id, status=Status.OK)
|
|
120
|
+
|
|
121
|
+
@classmethod
|
|
122
|
+
def reject(
|
|
123
|
+
cls,
|
|
124
|
+
sender: str,
|
|
125
|
+
request: "Message",
|
|
126
|
+
reason: str,
|
|
127
|
+
payload: dict[str, Any] | None = None,
|
|
128
|
+
) -> "Message":
|
|
129
|
+
return cls(
|
|
130
|
+
sender=sender,
|
|
131
|
+
type=request.type,
|
|
132
|
+
payload=payload or {},
|
|
133
|
+
reply_to=request.id,
|
|
134
|
+
status=Status.REJECTED,
|
|
135
|
+
reason=reason,
|
|
136
|
+
)
|
|
137
|
+
|
|
138
|
+
@classmethod
|
|
139
|
+
def error(
|
|
140
|
+
cls,
|
|
141
|
+
sender: str,
|
|
142
|
+
request: "Message" | None,
|
|
143
|
+
reason: str,
|
|
144
|
+
payload: dict[str, Any] | None = None,
|
|
145
|
+
) -> "Message":
|
|
146
|
+
return cls(
|
|
147
|
+
sender=sender,
|
|
148
|
+
type=request.type if request else "_agent.error",
|
|
149
|
+
payload=payload or {},
|
|
150
|
+
reply_to=request.id if request else None,
|
|
151
|
+
status=Status.ERROR,
|
|
152
|
+
reason=reason,
|
|
153
|
+
)
|
|
154
|
+
|
|
155
|
+
@property
|
|
156
|
+
def is_request(self) -> bool:
|
|
157
|
+
return self.reply_to is None and self.status is None
|
|
158
|
+
|
|
159
|
+
@property
|
|
160
|
+
def is_response(self) -> bool:
|
|
161
|
+
return self.reply_to is not None
|
|
162
|
+
|
|
163
|
+
|
|
164
|
+
def _require_text(value: object, field: str) -> None:
|
|
165
|
+
if not isinstance(value, str) or not value:
|
|
166
|
+
raise MessageValidationError(f"{field} must be a non-empty string")
|
|
@@ -0,0 +1,282 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: samtale
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: A modern, minimal messaging framework for agents.
|
|
5
|
+
Project-URL: Homepage, https://github.com/devjc/samtale
|
|
6
|
+
Project-URL: Repository, https://github.com/devjc/samtale
|
|
7
|
+
Project-URL: Issues, https://github.com/devjc/samtale/issues
|
|
8
|
+
Author: Joshua Croft
|
|
9
|
+
License-Expression: MIT
|
|
10
|
+
License-File: LICENSE
|
|
11
|
+
Keywords: agents,asyncio,http,messaging,multi-agent
|
|
12
|
+
Classifier: Development Status :: 3 - Alpha
|
|
13
|
+
Classifier: Framework :: AsyncIO
|
|
14
|
+
Classifier: Intended Audience :: Developers
|
|
15
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
16
|
+
Classifier: Programming Language :: Python :: 3
|
|
17
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
18
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
19
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
20
|
+
Requires-Python: >=3.11
|
|
21
|
+
Requires-Dist: httpx
|
|
22
|
+
Requires-Dist: pydantic>=2
|
|
23
|
+
Requires-Dist: starlette
|
|
24
|
+
Requires-Dist: uvicorn
|
|
25
|
+
Description-Content-Type: text/markdown
|
|
26
|
+
|
|
27
|
+
# Samtale
|
|
28
|
+
|
|
29
|
+
A modern, minimal messaging framework for agents.
|
|
30
|
+
|
|
31
|
+
Samtale lets independent Python components exchange typed requests and
|
|
32
|
+
structured outcomes over HTTP. An agent can be a sensor, controller, service,
|
|
33
|
+
state machine, or LLM-backed application.
|
|
34
|
+
|
|
35
|
+
Samtale provides a uniform message envelope, Pydantic payload validation,
|
|
36
|
+
bounded handler concurrency, and three outcomes: `ok`, `rejected`, or `error`.
|
|
37
|
+
When an agent does not understand a request, it responds with the message types
|
|
38
|
+
and JSON schemas it accepts.
|
|
39
|
+
|
|
40
|
+
Samtale provides no broker, orchestration, memory, conversation history,
|
|
41
|
+
workflow engine, or LLM dependency.
|
|
42
|
+
|
|
43
|
+
```text
|
|
44
|
+
request → envelope validation → handler lookup → payload validation
|
|
45
|
+
→ handler execution → ok / rejected / error
|
|
46
|
+
```
|
|
47
|
+
|
|
48
|
+
Python 3.11 or later is required.
|
|
49
|
+
|
|
50
|
+
## Installation
|
|
51
|
+
|
|
52
|
+
```bash
|
|
53
|
+
pip install samtale
|
|
54
|
+
```
|
|
55
|
+
|
|
56
|
+
## A small agent
|
|
57
|
+
|
|
58
|
+
```python
|
|
59
|
+
from typing import Literal
|
|
60
|
+
|
|
61
|
+
from pydantic import BaseModel
|
|
62
|
+
|
|
63
|
+
from samtale import Agent, Message
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
class WeatherRequest(BaseModel):
|
|
67
|
+
location: str
|
|
68
|
+
unit: Literal["c", "f"] = "c"
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
weather = Agent("weather")
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
@weather.on("weather_request", model=WeatherRequest)
|
|
75
|
+
async def get_weather(message: Message, request: WeatherRequest):
|
|
76
|
+
return {
|
|
77
|
+
"location": request.location,
|
|
78
|
+
"temperature": 18.4,
|
|
79
|
+
"unit": request.unit,
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
if __name__ == "__main__":
|
|
84
|
+
weather.run(port=8003)
|
|
85
|
+
```
|
|
86
|
+
|
|
87
|
+
Call it from another agent:
|
|
88
|
+
|
|
89
|
+
```python
|
|
90
|
+
import asyncio
|
|
91
|
+
|
|
92
|
+
from samtale import Agent
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
async def main() -> None:
|
|
96
|
+
consumer = Agent("consumer")
|
|
97
|
+
|
|
98
|
+
try:
|
|
99
|
+
result = await consumer.ask(
|
|
100
|
+
"http://localhost:8003",
|
|
101
|
+
"weather_request",
|
|
102
|
+
location="London",
|
|
103
|
+
unit="c",
|
|
104
|
+
)
|
|
105
|
+
print(result)
|
|
106
|
+
finally:
|
|
107
|
+
await consumer.close()
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
if __name__ == "__main__":
|
|
111
|
+
asyncio.run(main())
|
|
112
|
+
```
|
|
113
|
+
|
|
114
|
+
## Rejection is an outcome
|
|
115
|
+
|
|
116
|
+
An agent can understand a request and still decline it for a domain reason:
|
|
117
|
+
|
|
118
|
+
```python
|
|
119
|
+
from pydantic import BaseModel
|
|
120
|
+
|
|
121
|
+
from samtale import Message, Agent
|
|
122
|
+
|
|
123
|
+
|
|
124
|
+
class SetTemperature(BaseModel):
|
|
125
|
+
value: float
|
|
126
|
+
|
|
127
|
+
weather = Agent("weather")
|
|
128
|
+
|
|
129
|
+
@weather.on("temperature.set", model=SetTemperature)
|
|
130
|
+
async def set_temperature(message: Message, request: SetTemperature):
|
|
131
|
+
if request.value > 21:
|
|
132
|
+
return weather.reject(
|
|
133
|
+
message,
|
|
134
|
+
"outside_supported_range",
|
|
135
|
+
{
|
|
136
|
+
"requested": request.value,
|
|
137
|
+
"maximum": 21,
|
|
138
|
+
},
|
|
139
|
+
)
|
|
140
|
+
|
|
141
|
+
return {"value": request.value}
|
|
142
|
+
```
|
|
143
|
+
|
|
144
|
+
`send()` returns that rejection normally, leaving the next decision to the
|
|
145
|
+
caller:
|
|
146
|
+
|
|
147
|
+
```python
|
|
148
|
+
from samtale import Status, Agent
|
|
149
|
+
|
|
150
|
+
consumer = Agent("consumer")
|
|
151
|
+
|
|
152
|
+
async def set_temperature_with_fallback() -> None:
|
|
153
|
+
response = await consumer.send(
|
|
154
|
+
"http://localhost:8003",
|
|
155
|
+
"temperature.set",
|
|
156
|
+
value=24,
|
|
157
|
+
)
|
|
158
|
+
|
|
159
|
+
if (
|
|
160
|
+
response.status is Status.REJECTED
|
|
161
|
+
and response.reason == "outside_supported_range"
|
|
162
|
+
):
|
|
163
|
+
response = await consumer.send(
|
|
164
|
+
"http://localhost:8003",
|
|
165
|
+
"temperature.set",
|
|
166
|
+
value=response.payload["maximum"],
|
|
167
|
+
)
|
|
168
|
+
```
|
|
169
|
+
|
|
170
|
+
The framework standardizes the exchange; the agents decide what happens next.
|
|
171
|
+
|
|
172
|
+
## Self-describing rejections
|
|
173
|
+
|
|
174
|
+
If the consumer sends an unsupported message type, the weather agent returns a
|
|
175
|
+
normal rejection with its accepted messages. The relevant response fields look
|
|
176
|
+
like this:
|
|
177
|
+
|
|
178
|
+
```json
|
|
179
|
+
{
|
|
180
|
+
"status": "rejected",
|
|
181
|
+
"reason": "unsupported_message",
|
|
182
|
+
"payload": {
|
|
183
|
+
"accepted_messages": [
|
|
184
|
+
{
|
|
185
|
+
"type": "weather_request",
|
|
186
|
+
"schema": {
|
|
187
|
+
"type": "object",
|
|
188
|
+
"properties": {
|
|
189
|
+
"location": {"type": "string"},
|
|
190
|
+
"unit": {"enum": ["c", "f"], "default": "c"}
|
|
191
|
+
},
|
|
192
|
+
"required": ["location"]
|
|
193
|
+
}
|
|
194
|
+
}
|
|
195
|
+
]
|
|
196
|
+
}
|
|
197
|
+
}
|
|
198
|
+
```
|
|
199
|
+
|
|
200
|
+
Invalid payloads are also rejected and include the expected message schema
|
|
201
|
+
alongside structured validation issues.
|
|
202
|
+
|
|
203
|
+
## Sending messages
|
|
204
|
+
|
|
205
|
+
The three outbound methods share the same acknowledged HTTP exchange:
|
|
206
|
+
|
|
207
|
+
- `send()` returns the complete response `Message`, including rejections.
|
|
208
|
+
- `ask()` expects success and returns only the response payload.
|
|
209
|
+
- `emit()` expects success and discards the response payload.
|
|
210
|
+
|
|
211
|
+
`ask()` and `emit()` raise `RemoteRejection` for ordinary domain rejections and
|
|
212
|
+
`RemoteError` for unexpected remote failures. `emit()` is a convenience method,
|
|
213
|
+
not guaranteed delivery or true fire-and-forget.
|
|
214
|
+
|
|
215
|
+
## Concurrency
|
|
216
|
+
|
|
217
|
+
Agents execute one handler at a time by default. Set `max_concurrency` when an
|
|
218
|
+
agent should continue processing while another handler awaits I/O:
|
|
219
|
+
|
|
220
|
+
```python
|
|
221
|
+
agent = Agent("weather", max_concurrency=8)
|
|
222
|
+
```
|
|
223
|
+
|
|
224
|
+
At most eight handlers execute simultaneously; additional messages remain in
|
|
225
|
+
the inbox. Concurrent handlers can access the same local state across `await`
|
|
226
|
+
points, so applications should protect shared mutable state when necessary.
|
|
227
|
+
|
|
228
|
+
## Wire format
|
|
229
|
+
|
|
230
|
+
A request is a JSON object:
|
|
231
|
+
|
|
232
|
+
```json
|
|
233
|
+
{
|
|
234
|
+
"id": "request-id",
|
|
235
|
+
"sender": "consumer",
|
|
236
|
+
"type": "weather_request",
|
|
237
|
+
"payload": {"location": "London", "unit": "c"}
|
|
238
|
+
}
|
|
239
|
+
```
|
|
240
|
+
|
|
241
|
+
The response retains the domain type and correlates itself with `reply_to`:
|
|
242
|
+
|
|
243
|
+
```json
|
|
244
|
+
{
|
|
245
|
+
"id": "response-id",
|
|
246
|
+
"sender": "weather",
|
|
247
|
+
"type": "weather_request",
|
|
248
|
+
"payload": {"location": "London", "temperature": 18.4, "unit": "c"},
|
|
249
|
+
"reply_to": "request-id",
|
|
250
|
+
"status": "ok"
|
|
251
|
+
}
|
|
252
|
+
```
|
|
253
|
+
|
|
254
|
+
HTTP status describes the HTTP-level outcome. Message status describes the
|
|
255
|
+
domain outcome. Rejections use HTTP 200; malformed input and runtime failures
|
|
256
|
+
use the corresponding HTTP error status.
|
|
257
|
+
|
|
258
|
+
## Run the included example
|
|
259
|
+
|
|
260
|
+
From a checkout:
|
|
261
|
+
|
|
262
|
+
```bash
|
|
263
|
+
uv sync --locked
|
|
264
|
+
uv run python examples/weather.py
|
|
265
|
+
```
|
|
266
|
+
|
|
267
|
+
In another terminal:
|
|
268
|
+
|
|
269
|
+
```bash
|
|
270
|
+
uv run python examples/weather_consumer.py
|
|
271
|
+
```
|
|
272
|
+
|
|
273
|
+
The consumer first demonstrates schema discovery with an unsupported request,
|
|
274
|
+
then sends a valid typed request.
|
|
275
|
+
|
|
276
|
+
## Tests
|
|
277
|
+
|
|
278
|
+
```bash
|
|
279
|
+
uv run python -m unittest discover -s tests -v
|
|
280
|
+
```
|
|
281
|
+
|
|
282
|
+
The GitHub Actions workflow runs the suite on Python 3.11, 3.12, and 3.13.
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
samtale/__init__.py,sha256=GtX07b-NyPimRydKv6_YTfaKAfVfhqdNlHmvNzG3umw,447
|
|
2
|
+
samtale/agent.py,sha256=HucC8U6OEk95WyuJ8yJGgCsbdnfurePf9zPKqSnv9KU,13424
|
|
3
|
+
samtale/exceptions.py,sha256=Y5DAY84cfkuJj1ItHWIEE5EaiJb4KdSFHWLlsUOFg_k,1445
|
|
4
|
+
samtale/helpers.py,sha256=ojablal9BTmxQ2Xvo1fagwpAa7EZG-AgtyyLv0flOHg,6280
|
|
5
|
+
samtale/message.py,sha256=fM__KvwXBJdxF_8ma15Tr6TLwEQPM44Z-TPo0uUnl0o,5786
|
|
6
|
+
samtale-0.1.0.dist-info/METADATA,sha256=DDxLlbmdmHI0VdeOyeamdpDCoLZyjqKn_aE6ypNOdFo,6930
|
|
7
|
+
samtale-0.1.0.dist-info/WHEEL,sha256=W3fkpkm7-wf9vBI5Z-7s0eWkeM-spu78I8Neb98DeEg,87
|
|
8
|
+
samtale-0.1.0.dist-info/licenses/LICENSE,sha256=WNHhf_5RCaeuKWyq_K39vmp9F28LxKsB4SpomwSZ2L0,11357
|
|
9
|
+
samtale-0.1.0.dist-info/RECORD,,
|
|
@@ -0,0 +1,202 @@
|
|
|
1
|
+
|
|
2
|
+
Apache License
|
|
3
|
+
Version 2.0, January 2004
|
|
4
|
+
http://www.apache.org/licenses/
|
|
5
|
+
|
|
6
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
7
|
+
|
|
8
|
+
1. Definitions.
|
|
9
|
+
|
|
10
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
11
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
12
|
+
|
|
13
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
14
|
+
the copyright owner that is granting the License.
|
|
15
|
+
|
|
16
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
17
|
+
other entities that control, are controlled by, or are under common
|
|
18
|
+
control with that entity. For the purposes of this definition,
|
|
19
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
20
|
+
direction or management of such entity, whether by contract or
|
|
21
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
22
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
23
|
+
|
|
24
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
25
|
+
exercising permissions granted by this License.
|
|
26
|
+
|
|
27
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
28
|
+
including but not limited to software source code, documentation
|
|
29
|
+
source, and configuration files.
|
|
30
|
+
|
|
31
|
+
"Object" form shall mean any form resulting from mechanical
|
|
32
|
+
transformation or translation of a Source form, including but
|
|
33
|
+
not limited to compiled object code, generated documentation,
|
|
34
|
+
and conversions to other media types.
|
|
35
|
+
|
|
36
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
37
|
+
Object form, made available under the License, as indicated by a
|
|
38
|
+
copyright notice that is included in or attached to the work
|
|
39
|
+
(an example is provided in the Appendix below).
|
|
40
|
+
|
|
41
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
42
|
+
form, that is based on (or derived from) the Work and for which the
|
|
43
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
44
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
45
|
+
of this License, Derivative Works shall not include works that remain
|
|
46
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
47
|
+
the Work and Derivative Works thereof.
|
|
48
|
+
|
|
49
|
+
"Contribution" shall mean any work of authorship, including
|
|
50
|
+
the original version of the Work and any modifications or additions
|
|
51
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
52
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
53
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
54
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
55
|
+
means any form of electronic, verbal, or written communication sent
|
|
56
|
+
to the Licensor or its representatives, including but not limited to
|
|
57
|
+
communication on electronic mailing lists, source code control systems,
|
|
58
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
59
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
60
|
+
excluding communication that is conspicuously marked or otherwise
|
|
61
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
62
|
+
|
|
63
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
64
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
65
|
+
subsequently incorporated within the Work.
|
|
66
|
+
|
|
67
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
68
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
69
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
70
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
71
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
72
|
+
Work and such Derivative Works in Source or Object form.
|
|
73
|
+
|
|
74
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
75
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
76
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
77
|
+
(except as stated in this section) patent license to make, have made,
|
|
78
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
79
|
+
where such license applies only to those patent claims licensable
|
|
80
|
+
by such Contributor that are necessarily infringed by their
|
|
81
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
82
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
83
|
+
institute patent litigation against any entity (including a
|
|
84
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
85
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
86
|
+
or contributory patent infringement, then any patent licenses
|
|
87
|
+
granted to You under this License for that Work shall terminate
|
|
88
|
+
as of the date such litigation is filed.
|
|
89
|
+
|
|
90
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
91
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
92
|
+
modifications, and in Source or Object form, provided that You
|
|
93
|
+
meet the following conditions:
|
|
94
|
+
|
|
95
|
+
(a) You must give any other recipients of the Work or
|
|
96
|
+
Derivative Works a copy of this License; and
|
|
97
|
+
|
|
98
|
+
(b) You must cause any modified files to carry prominent notices
|
|
99
|
+
stating that You changed the files; and
|
|
100
|
+
|
|
101
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
102
|
+
that You distribute, all copyright, patent, trademark, and
|
|
103
|
+
attribution notices from the Source form of the Work,
|
|
104
|
+
excluding those notices that do not pertain to any part of
|
|
105
|
+
the Derivative Works; and
|
|
106
|
+
|
|
107
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
108
|
+
distribution, then any Derivative Works that You distribute must
|
|
109
|
+
include a readable copy of the attribution notices contained
|
|
110
|
+
within such NOTICE file, excluding those notices that do not
|
|
111
|
+
pertain to any part of the Derivative Works, in at least one
|
|
112
|
+
of the following places: within a NOTICE text file distributed
|
|
113
|
+
as part of the Derivative Works; within the Source form or
|
|
114
|
+
documentation, if provided along with the Derivative Works; or,
|
|
115
|
+
within a display generated by the Derivative Works, if and
|
|
116
|
+
wherever such third-party notices normally appear. The contents
|
|
117
|
+
of the NOTICE file are for informational purposes only and
|
|
118
|
+
do not modify the License. You may add Your own attribution
|
|
119
|
+
notices within Derivative Works that You distribute, alongside
|
|
120
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
121
|
+
that such additional attribution notices cannot be construed
|
|
122
|
+
as modifying the License.
|
|
123
|
+
|
|
124
|
+
You may add Your own copyright statement to Your modifications and
|
|
125
|
+
may provide additional or different license terms and conditions
|
|
126
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
127
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
128
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
129
|
+
the conditions stated in this License.
|
|
130
|
+
|
|
131
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
132
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
133
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
134
|
+
this License, without any additional terms or conditions.
|
|
135
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
136
|
+
the terms of any separate license agreement you may have executed
|
|
137
|
+
with Licensor regarding such Contributions.
|
|
138
|
+
|
|
139
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
140
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
141
|
+
except as required for reasonable and customary use in describing the
|
|
142
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
143
|
+
|
|
144
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
145
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
146
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
147
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
148
|
+
implied, including, without limitation, any warranties or conditions
|
|
149
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
150
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
151
|
+
appropriateness of using or redistributing the Work and assume any
|
|
152
|
+
risks associated with Your exercise of permissions under this License.
|
|
153
|
+
|
|
154
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
155
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
156
|
+
unless required by applicable law (such as deliberate and grossly
|
|
157
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
158
|
+
liable to You for damages, including any direct, indirect, special,
|
|
159
|
+
incidental, or consequential damages of any character arising as a
|
|
160
|
+
result of this License or out of the use or inability to use the
|
|
161
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
162
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
163
|
+
other commercial damages or losses), even if such Contributor
|
|
164
|
+
has been advised of the possibility of such damages.
|
|
165
|
+
|
|
166
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
167
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
168
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
169
|
+
or other liability obligations and/or rights consistent with this
|
|
170
|
+
License. However, in accepting such obligations, You may act only
|
|
171
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
172
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
173
|
+
defend, and hold each Contributor harmless for any liability
|
|
174
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
175
|
+
of your accepting any such warranty or additional liability.
|
|
176
|
+
|
|
177
|
+
END OF TERMS AND CONDITIONS
|
|
178
|
+
|
|
179
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
180
|
+
|
|
181
|
+
To apply the Apache License to your work, attach the following
|
|
182
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
183
|
+
replaced with your own identifying information. (Don't include
|
|
184
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
185
|
+
comment syntax for the file format. We also recommend that a
|
|
186
|
+
file or class name and description of purpose be included on the
|
|
187
|
+
same "printed page" as the copyright notice for easier
|
|
188
|
+
identification within third-party archives.
|
|
189
|
+
|
|
190
|
+
Copyright [yyyy] [name of copyright owner]
|
|
191
|
+
|
|
192
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
193
|
+
you may not use this file except in compliance with the License.
|
|
194
|
+
You may obtain a copy of the License at
|
|
195
|
+
|
|
196
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
197
|
+
|
|
198
|
+
Unless required by applicable law or agreed to in writing, software
|
|
199
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
200
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
201
|
+
See the License for the specific language governing permissions and
|
|
202
|
+
limitations under the License.
|