agent2dashboard 0.2.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.
Files changed (79) hide show
  1. agent2dashboard/__init__.py +593 -0
  2. agent2dashboard/__main__.py +3 -0
  3. agent2dashboard/_env.py +79 -0
  4. agent2dashboard/a2ui/__init__.py +1 -0
  5. agent2dashboard/a2ui/catalogs/dashboard/v1/catalog.json +496 -0
  6. agent2dashboard/a2ui/checks.py +656 -0
  7. agent2dashboard/a2ui/express.py +349 -0
  8. agent2dashboard/a2ui/layout_actions.py +409 -0
  9. agent2dashboard/a2ui/render.py +252 -0
  10. agent2dashboard/a2ui/state.py +600 -0
  11. agent2dashboard/a2ui/surfaces.py +23 -0
  12. agent2dashboard/agent/__init__.py +83 -0
  13. agent2dashboard/agent/builtin_tools.py +258 -0
  14. agent2dashboard/agent/history.py +218 -0
  15. agent2dashboard/agent/loop.py +341 -0
  16. agent2dashboard/agent/prompt.py +66 -0
  17. agent2dashboard/agent/tools.py +162 -0
  18. agent2dashboard/agent/turn.py +201 -0
  19. agent2dashboard/auth.py +350 -0
  20. agent2dashboard/cli/__init__.py +50 -0
  21. agent2dashboard/errors.py +18 -0
  22. agent2dashboard/http/__init__.py +40 -0
  23. agent2dashboard/http/dashboards.py +100 -0
  24. agent2dashboard/http/functions.py +462 -0
  25. agent2dashboard/http/queries.py +168 -0
  26. agent2dashboard/http/revisions.py +126 -0
  27. agent2dashboard/http/router.py +353 -0
  28. agent2dashboard/http/schemas.py +102 -0
  29. agent2dashboard/llm/__init__.py +7 -0
  30. agent2dashboard/llm/_messages_api.py +123 -0
  31. agent2dashboard/llm/bedrock.py +96 -0
  32. agent2dashboard/llm/direct.py +40 -0
  33. agent2dashboard/llm/messages.py +45 -0
  34. agent2dashboard/migrations/__init__.py +383 -0
  35. agent2dashboard/migrations/versions/0001_initial.py +228 -0
  36. agent2dashboard/ports.py +538 -0
  37. agent2dashboard/py.typed +0 -0
  38. agent2dashboard/query/__init__.py +65 -0
  39. agent2dashboard/query/errors.py +39 -0
  40. agent2dashboard/query/executor.py +203 -0
  41. agent2dashboard/query/filters.py +446 -0
  42. agent2dashboard/query/governed.py +155 -0
  43. agent2dashboard/query/readonly.py +166 -0
  44. agent2dashboard/query/registry.py +213 -0
  45. agent2dashboard/query/row_filter.py +135 -0
  46. agent2dashboard/query/service.py +93 -0
  47. agent2dashboard/query/sql_guard.py +219 -0
  48. agent2dashboard/runs/__init__.py +87 -0
  49. agent2dashboard/runs/errors.py +65 -0
  50. agent2dashboard/runs/events.py +147 -0
  51. agent2dashboard/runs/hooks.py +135 -0
  52. agent2dashboard/runs/http.py +169 -0
  53. agent2dashboard/runs/memory.py +148 -0
  54. agent2dashboard/runs/redis_bus.py +219 -0
  55. agent2dashboard/runs/service.py +728 -0
  56. agent2dashboard/runs/writer.py +95 -0
  57. agent2dashboard/semantic/__init__.py +6 -0
  58. agent2dashboard/semantic/cube.py +39 -0
  59. agent2dashboard/semantic/static.py +81 -0
  60. agent2dashboard/storage/__init__.py +60 -0
  61. agent2dashboard/storage/lifecycle.py +105 -0
  62. agent2dashboard/storage/memory.py +488 -0
  63. agent2dashboard/storage/records.py +219 -0
  64. agent2dashboard/storage/sql.py +666 -0
  65. agent2dashboard/storage/tables.py +387 -0
  66. agent2dashboard/testing/__init__.py +20 -0
  67. agent2dashboard/testing/event_bus.py +10 -0
  68. agent2dashboard/testing/fake_llm.py +129 -0
  69. agent2dashboard/testing/host.py +191 -0
  70. agent2dashboard/tracing/__init__.py +36 -0
  71. agent2dashboard/tracing/db.py +143 -0
  72. agent2dashboard/tracing/fanout.py +153 -0
  73. agent2dashboard/tracing/langfuse.py +339 -0
  74. agent2dashboard/tracing/masking.py +26 -0
  75. agent2dashboard-0.2.0.dist-info/METADATA +81 -0
  76. agent2dashboard-0.2.0.dist-info/RECORD +79 -0
  77. agent2dashboard-0.2.0.dist-info/WHEEL +4 -0
  78. agent2dashboard-0.2.0.dist-info/entry_points.txt +3 -0
  79. agent2dashboard-0.2.0.dist-info/licenses/LICENSE +202 -0
@@ -0,0 +1,387 @@
1
+ """The SDK's own tables (design §4.1), built for a host's `TableNames`.
2
+
3
+ Physical names are only known at runtime (`csops_ad_run`, `xora_a2d_run`, ...), so the tables
4
+ are SQLAlchemy Core `Table`s built by `build_tables`, not declarative classes. Every
5
+ constraint and index is named explicitly from the physical table name, and
6
+ `migrations/versions/0001_initial.py` creates exactly the same objects;
7
+ `agent2dashboard.migrations.assert_models_match_migrations` checks that they agree.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ from dataclasses import dataclass, fields
13
+ from typing import Literal
14
+
15
+ from sqlalchemy import (
16
+ BigInteger,
17
+ CheckConstraint,
18
+ Column,
19
+ DateTime,
20
+ ForeignKey,
21
+ Identity,
22
+ Index,
23
+ Integer,
24
+ MetaData,
25
+ PrimaryKeyConstraint,
26
+ String,
27
+ Table,
28
+ Text,
29
+ UniqueConstraint,
30
+ Uuid,
31
+ func,
32
+ text,
33
+ )
34
+ from sqlalchemy.dialects.postgresql import JSONB
35
+ from sqlalchemy.sql.elements import conv
36
+ from sqlalchemy.types import TypeEngine
37
+
38
+ from agent2dashboard.ports import RunStatus
39
+
40
+ __all__ = [
41
+ "ACTIVE_RUN_STATUSES",
42
+ "LOGICAL_TABLES",
43
+ "PrincipalColumn",
44
+ "REVISION_SOURCES",
45
+ "StorageTables",
46
+ "TableNames",
47
+ "build_tables",
48
+ ]
49
+
50
+ LOGICAL_TABLES = (
51
+ "conversation",
52
+ "message",
53
+ "run",
54
+ "dashboard",
55
+ "dashboard_revision",
56
+ "llm_call",
57
+ )
58
+ # Who stored a dashboard revision (`dashboard_revision.source`).
59
+ REVISION_SOURCES = ("agent", "layout", "restore")
60
+ ACTIVE_RUN_STATUSES = (RunStatus.QUEUED, RunStatus.RUNNING)
61
+ _POSTGRES_MAX_IDENTIFIER = 63
62
+
63
+
64
+ @dataclass(frozen=True)
65
+ class TableNames:
66
+ """Physical name of each SDK table. Default `<prefix><logical>`; any one can be overridden,
67
+ e.g. `dataclasses.replace(TableNames.prefixed("csops_ad_"), run="csops_ad_agent_run")`."""
68
+
69
+ conversation: str = "conversation"
70
+ message: str = "message"
71
+ run: str = "run"
72
+ dashboard: str = "dashboard"
73
+ dashboard_revision: str = "dashboard_revision"
74
+ llm_call: str = "llm_call"
75
+
76
+ @classmethod
77
+ def prefixed(cls, prefix: str) -> TableNames:
78
+ return cls(**{name: f"{prefix}{name}" for name in LOGICAL_TABLES})
79
+
80
+ def __post_init__(self) -> None:
81
+ names = [getattr(self, f.name) for f in fields(self)]
82
+ if len(set(names)) != len(names):
83
+ raise ValueError(f"TableNames must be distinct: {names}")
84
+ for name in names:
85
+ # Derived constraint/index names add at most 21 characters to the table name.
86
+ if not name or len(name) + 21 > _POSTGRES_MAX_IDENTIFIER:
87
+ raise ValueError(f"table name {name!r} is empty or too long for Postgres")
88
+
89
+ def all(self) -> tuple[str, ...]:
90
+ """Every physical name, in creation order (parents first)."""
91
+ return tuple(getattr(self, name) for name in LOGICAL_TABLES)
92
+
93
+
94
+ @dataclass(frozen=True)
95
+ class PrincipalColumn:
96
+ """How `principal_id` is stored. Default `String(128)` with no foreign key, matching the
97
+ opaque `Principal.id`. A host may store it as `UUID` with a foreign key to its user table
98
+ (XoraOps: `PrincipalColumn(type="uuid", foreign_key="user.id")`). Repositories always take
99
+ and return the principal id as `str`."""
100
+
101
+ type: Literal["string", "uuid"] = "string"
102
+ # "<table>.<column>" or "<schema>.<table>.<column>"; requires type="uuid". When the SDK
103
+ # tables have their own schema, name the host table's schema ("public.user.id").
104
+ foreign_key: str | None = None
105
+ ondelete: str = "CASCADE"
106
+
107
+ def __post_init__(self) -> None:
108
+ if self.type not in ("string", "uuid"):
109
+ raise ValueError(f"unknown principal column type {self.type!r}")
110
+ if self.foreign_key is not None:
111
+ if self.type != "uuid":
112
+ raise ValueError("a principal foreign key requires type='uuid'")
113
+ if self.foreign_key.count(".") not in (1, 2):
114
+ raise ValueError(
115
+ "foreign_key must be '<table>.<column>' or '<schema>.<table>.<column>'"
116
+ )
117
+
118
+ def sql_type(self) -> TypeEngine:
119
+ return Uuid(as_uuid=False) if self.type == "uuid" else String(128)
120
+
121
+
122
+ @dataclass(frozen=True)
123
+ class StorageTables:
124
+ names: TableNames
125
+ principal: PrincipalColumn
126
+ metadata: MetaData
127
+ conversation: Table
128
+ message: Table
129
+ run: Table
130
+ dashboard: Table
131
+ dashboard_revision: Table
132
+ llm_call: Table
133
+
134
+ @property
135
+ def schema(self) -> str | None:
136
+ """The Postgres schema the tables live in (None: the connection's default)."""
137
+ return self.metadata.schema
138
+
139
+ @property
140
+ def active_run_index(self) -> str:
141
+ return active_run_index_name(self.names)
142
+
143
+
144
+ def active_run_index_name(names: TableNames) -> str:
145
+ return f"uq_{names.run}_one_active"
146
+
147
+
148
+ def client_message_constraint_name(names: TableNames) -> str:
149
+ return f"uq_{names.message}_client_message"
150
+
151
+
152
+ def _principal_column(principal: PrincipalColumn, table: str) -> Column:
153
+ args = []
154
+ if principal.foreign_key is not None:
155
+ args.append(
156
+ ForeignKey(
157
+ principal.foreign_key,
158
+ ondelete=principal.ondelete,
159
+ name=f"fk_{table}_principal",
160
+ )
161
+ )
162
+ return Column("principal_id", principal.sql_type(), *args, nullable=False)
163
+
164
+
165
+ def build_tables(
166
+ names: TableNames | None = None,
167
+ principal: PrincipalColumn | None = None,
168
+ metadata: MetaData | None = None,
169
+ *,
170
+ schema: str | None = None,
171
+ ) -> StorageTables:
172
+ """Build the SDK tables on `metadata` (a fresh `MetaData` by default), in `schema` (the
173
+ connection's default schema when None)."""
174
+ names = names or TableNames()
175
+ principal = principal or PrincipalColumn()
176
+ if metadata is not None and schema is not None and metadata.schema != schema:
177
+ raise ValueError("pass the schema on the MetaData, or a schema without a MetaData")
178
+ md = metadata if metadata is not None else MetaData(schema=schema)
179
+ t = names
180
+
181
+ conversation = Table(
182
+ t.conversation,
183
+ md,
184
+ Column("id", Uuid(as_uuid=False), nullable=False),
185
+ _principal_column(principal, t.conversation),
186
+ Column("title", String(255), nullable=True),
187
+ Column("created_at", DateTime(timezone=True), server_default=func.now(), nullable=False),
188
+ Column("updated_at", DateTime(timezone=True), server_default=func.now(), nullable=False),
189
+ Column(
190
+ "last_message_at", DateTime(timezone=True), server_default=func.now(), nullable=False
191
+ ),
192
+ PrimaryKeyConstraint("id", name=f"pk_{t.conversation}"),
193
+ Index(f"ix_{t.conversation}_principal_last", "principal_id", "last_message_at"),
194
+ Index(f"ix_{t.conversation}_last_message_at", "last_message_at"),
195
+ )
196
+
197
+ message = Table(
198
+ t.message,
199
+ md,
200
+ Column("id", BigInteger, Identity(), nullable=False),
201
+ Column(
202
+ "conversation_id",
203
+ Uuid(as_uuid=False),
204
+ ForeignKey(
205
+ f"{t.conversation}.id", ondelete="CASCADE", name=f"fk_{t.message}_conversation"
206
+ ),
207
+ nullable=False,
208
+ ),
209
+ Column("role", String(16), nullable=False),
210
+ Column("content", Text, nullable=False),
211
+ Column("stop_reason", String(32), nullable=True),
212
+ Column("input_tokens", Integer, nullable=True),
213
+ Column("output_tokens", Integer, nullable=True),
214
+ # The run that wrote this assistant message (or that this user message started). No
215
+ # foreign key: `run` already references `message`, and the pair would be circular.
216
+ Column("run_id", Uuid(as_uuid=False), nullable=True),
217
+ # The A2UI Express the model wrote this turn; history replays it, never rows.
218
+ Column("a2ui", Text, nullable=True),
219
+ # The dashboard revision this turn's accepted `render_dashboard` produced.
220
+ Column("revision", Integer, nullable=True),
221
+ Column("tool_trace", JSONB(none_as_null=True), nullable=True),
222
+ # A note written by a layout action or a restore: `{code, params}` the UI translates;
223
+ # `content` holds the English fallback.
224
+ Column("note", JSONB(none_as_null=True), nullable=True),
225
+ # User turns only: the browser's idempotency key, unique per conversation (§5.3).
226
+ Column("client_message_id", String(64), nullable=True),
227
+ Column("created_at", DateTime(timezone=True), server_default=func.now(), nullable=False),
228
+ PrimaryKeyConstraint("id", name=f"pk_{t.message}"),
229
+ UniqueConstraint(
230
+ "conversation_id", "client_message_id", name=client_message_constraint_name(t)
231
+ ),
232
+ Index(f"ix_{t.message}_conversation", "conversation_id", "id"),
233
+ )
234
+
235
+ statuses = ", ".join(f"'{s.value}'" for s in RunStatus)
236
+ active = ", ".join(f"'{s.value}'" for s in ACTIVE_RUN_STATUSES)
237
+ run = Table(
238
+ t.run,
239
+ md,
240
+ Column("id", Uuid(as_uuid=False), nullable=False),
241
+ Column(
242
+ "conversation_id",
243
+ Uuid(as_uuid=False),
244
+ ForeignKey(f"{t.conversation}.id", ondelete="CASCADE", name=f"fk_{t.run}_conversation"),
245
+ nullable=False,
246
+ ),
247
+ _principal_column(principal, t.run),
248
+ Column(
249
+ "user_message_id",
250
+ BigInteger,
251
+ ForeignKey(f"{t.message}.id", ondelete="CASCADE", name=f"fk_{t.run}_user_message"),
252
+ nullable=False,
253
+ ),
254
+ Column(
255
+ "assistant_message_id",
256
+ BigInteger,
257
+ ForeignKey(
258
+ f"{t.message}.id", ondelete="SET NULL", name=f"fk_{t.run}_assistant_message"
259
+ ),
260
+ nullable=True,
261
+ ),
262
+ Column("status", String(16), nullable=False),
263
+ Column("cancel_requested_at", DateTime(timezone=True), nullable=True),
264
+ Column("owner_instance", String(128), nullable=True),
265
+ Column("heartbeat_at", DateTime(timezone=True), nullable=True),
266
+ Column("started_at", DateTime(timezone=True), nullable=True),
267
+ Column("finished_at", DateTime(timezone=True), nullable=True),
268
+ Column("error_code", String(64), nullable=True),
269
+ Column("trace_id", String(128), nullable=True),
270
+ Column("model_id", String(128), nullable=True),
271
+ Column("input_tokens", Integer, nullable=True),
272
+ Column("output_tokens", Integer, nullable=True),
273
+ Column("last_event_id", String(64), nullable=True),
274
+ Column("created_at", DateTime(timezone=True), server_default=func.now(), nullable=False),
275
+ PrimaryKeyConstraint("id", name=f"pk_{t.run}"),
276
+ # conv(): a final name, as the migration's op.f(), whatever the metadata's convention.
277
+ CheckConstraint(f"status IN ({statuses})", name=conv(f"ck_{t.run}_status")),
278
+ # One active run per conversation (§5.3).
279
+ Index(
280
+ active_run_index_name(t),
281
+ "conversation_id",
282
+ unique=True,
283
+ postgresql_where=text(f"status IN ({active})"),
284
+ ),
285
+ Index(f"ix_{t.run}_conversation", "conversation_id", "created_at"),
286
+ Index(f"ix_{t.run}_principal_status", "principal_id", "status"),
287
+ Index(f"ix_{t.run}_user_message", "user_message_id"),
288
+ )
289
+
290
+ dashboard = Table(
291
+ t.dashboard,
292
+ md,
293
+ Column(
294
+ "conversation_id",
295
+ Uuid(as_uuid=False),
296
+ ForeignKey(
297
+ f"{t.conversation}.id", ondelete="CASCADE", name=f"fk_{t.dashboard}_conversation"
298
+ ),
299
+ nullable=False,
300
+ ),
301
+ Column("catalog_id", String(255), nullable=False),
302
+ Column("surface", JSONB, nullable=False),
303
+ Column("queries", JSONB, nullable=False),
304
+ Column("revision", Integer, nullable=False),
305
+ Column("updated_at", DateTime(timezone=True), server_default=func.now(), nullable=False),
306
+ PrimaryKeyConstraint("conversation_id", name=f"pk_{t.dashboard}"),
307
+ )
308
+
309
+ sources = ", ".join(f"'{s}'" for s in REVISION_SOURCES)
310
+ dashboard_revision = Table(
311
+ t.dashboard_revision,
312
+ md,
313
+ Column(
314
+ "conversation_id",
315
+ Uuid(as_uuid=False),
316
+ ForeignKey(
317
+ f"{t.conversation}.id",
318
+ ondelete="CASCADE",
319
+ name=f"fk_{t.dashboard_revision}_conversation",
320
+ ),
321
+ nullable=False,
322
+ ),
323
+ Column("revision", Integer, nullable=False),
324
+ # The Express block that produced this revision (the model's, or the generated one of a
325
+ # layout action or restore).
326
+ Column("express", Text, nullable=False),
327
+ # The surface document and the query registry exactly as stored at this revision.
328
+ Column("surface", JSONB, nullable=False),
329
+ Column("queries", JSONB, nullable=False),
330
+ # The message that records it; set when that message is written (end of the turn).
331
+ Column(
332
+ "message_id",
333
+ BigInteger,
334
+ ForeignKey(
335
+ f"{t.message}.id", ondelete="SET NULL", name=f"fk_{t.dashboard_revision}_message"
336
+ ),
337
+ nullable=True,
338
+ ),
339
+ # The run that stored it (agent renders); no foreign key, like `message.run_id`.
340
+ Column("run_id", Uuid(as_uuid=False), nullable=True),
341
+ Column("source", String(16), nullable=False),
342
+ Column("created_at", DateTime(timezone=True), server_default=func.now(), nullable=False),
343
+ PrimaryKeyConstraint("conversation_id", "revision", name=f"pk_{t.dashboard_revision}"),
344
+ CheckConstraint(f"source IN ({sources})", name=conv(f"ck_{t.dashboard_revision}_source")),
345
+ Index(f"ix_{t.dashboard_revision}_run", "run_id"),
346
+ Index(f"ix_{t.dashboard_revision}_message", "message_id"),
347
+ )
348
+
349
+ llm_call = Table(
350
+ t.llm_call,
351
+ md,
352
+ Column("id", BigInteger, Identity(), nullable=False),
353
+ Column(
354
+ "run_id",
355
+ Uuid(as_uuid=False),
356
+ ForeignKey(f"{t.run}.id", ondelete="CASCADE", name=f"fk_{t.llm_call}_run"),
357
+ nullable=True,
358
+ ),
359
+ Column("purpose", String(128), nullable=False),
360
+ Column("model", String(128), nullable=False),
361
+ Column("status", String(16), nullable=False),
362
+ Column("max_tokens", Integer, nullable=True),
363
+ Column("system_sha256", String(64), nullable=True),
364
+ Column("input", Text, nullable=False),
365
+ Column("output", Text, nullable=True),
366
+ Column("stop_reason", String(32), nullable=True),
367
+ Column("input_tokens", Integer, nullable=True),
368
+ Column("output_tokens", Integer, nullable=True),
369
+ Column("latency_ms", Integer, nullable=False),
370
+ Column("error", Text, nullable=True),
371
+ Column("created_at", DateTime(timezone=True), server_default=func.now(), nullable=False),
372
+ PrimaryKeyConstraint("id", name=f"pk_{t.llm_call}"),
373
+ Index(f"ix_{t.llm_call}_run", "run_id"),
374
+ Index(f"ix_{t.llm_call}_purpose", "purpose"),
375
+ )
376
+
377
+ return StorageTables(
378
+ names=names,
379
+ principal=principal,
380
+ metadata=md,
381
+ conversation=conversation,
382
+ message=message,
383
+ run=run,
384
+ dashboard=dashboard,
385
+ dashboard_revision=dashboard_revision,
386
+ llm_call=llm_call,
387
+ )
@@ -0,0 +1,20 @@
1
+ """Test doubles for SDK and host test suites. No network, no model calls."""
2
+
3
+ from agent2dashboard.testing.event_bus import BusEvent, InMemoryEventBus
4
+ from agent2dashboard.testing.fake_llm import (
5
+ FakeLLM,
6
+ FakeLLMExhausted,
7
+ LLMRequest,
8
+ ScriptedToolUse,
9
+ ScriptedTurn,
10
+ )
11
+
12
+ __all__ = [
13
+ "BusEvent",
14
+ "FakeLLM",
15
+ "FakeLLMExhausted",
16
+ "InMemoryEventBus",
17
+ "LLMRequest",
18
+ "ScriptedToolUse",
19
+ "ScriptedTurn",
20
+ ]
@@ -0,0 +1,10 @@
1
+ """`InMemoryEventBus`: single-instance stand-in for the Redis Streams bus (design §5).
2
+
3
+ The contract and the implementation live in `agent2dashboard.runs`; this module keeps the
4
+ `agent2dashboard.testing` import path.
5
+ """
6
+
7
+ from agent2dashboard.runs.events import BusEvent
8
+ from agent2dashboard.runs.memory import InMemoryEventBus
9
+
10
+ __all__ = ["BusEvent", "InMemoryEventBus"]
@@ -0,0 +1,129 @@
1
+ """`FakeLLM`: an `LLMProvider` that replays scripted turns and records what it was asked."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import copy
6
+ from collections.abc import AsyncIterator, Mapping, Sequence
7
+ from dataclasses import dataclass, field
8
+ from typing import Any, Literal
9
+
10
+ from agent2dashboard.ports import ChatMessage, ModelResult, ModelTurn, ToolDef, ToolUse, Usage
11
+
12
+
13
+ @dataclass(frozen=True)
14
+ class ScriptedToolUse:
15
+ name: str
16
+ input: Mapping[str, Any] = field(default_factory=dict)
17
+ id: str | None = None # generated ("toolu_fake_<n>") when omitted
18
+
19
+
20
+ @dataclass(frozen=True)
21
+ class ScriptedTurn:
22
+ """One model round to replay. `stop_reason` defaults to "tool_use" when the turn has tool
23
+ calls and "end_turn" otherwise. `error` is raised from `stream()` instead of replying."""
24
+
25
+ text: Sequence[str] = ()
26
+ tool_uses: Sequence[ScriptedToolUse] = ()
27
+ stop_reason: str | None = None
28
+ usage: Usage = field(default_factory=lambda: Usage(input_tokens=10, output_tokens=5))
29
+ error: BaseException | None = None
30
+
31
+ @classmethod
32
+ def say(cls, *deltas: str, **kwargs: Any) -> ScriptedTurn:
33
+ return cls(text=deltas, **kwargs)
34
+
35
+ @classmethod
36
+ def call(cls, name: str, input: Mapping[str, Any] | None = None, **kwargs: Any) -> ScriptedTurn:
37
+ return cls(tool_uses=(ScriptedToolUse(name, dict(input or {})),), **kwargs)
38
+
39
+
40
+ @dataclass(frozen=True)
41
+ class LLMRequest:
42
+ """What a caller passed to `stream()`, deep-copied at call time."""
43
+
44
+ system: str
45
+ messages: list[ChatMessage]
46
+ tools: list[ToolDef]
47
+ max_tokens: int
48
+ tool_choice: Literal["auto", "none"]
49
+
50
+ @property
51
+ def tool_names(self) -> list[str]:
52
+ return [tool.name for tool in self.tools]
53
+
54
+
55
+ class FakeLLMExhausted(AssertionError):
56
+ """`stream()` was called more times than there are scripted turns."""
57
+
58
+
59
+ class FakeLLM:
60
+ """Replays `turns` in order, one per `stream()` call, and records each request.
61
+
62
+ >>> llm = FakeLLM([ScriptedTurn.call("describe_table", {"name": "ticket"}),
63
+ ... ScriptedTurn.say("Here ", "you go.")])
64
+ """
65
+
66
+ def __init__(self, turns: Sequence[ScriptedTurn] = (), *, model_id: str = "fake-llm") -> None:
67
+ self.model_id = model_id
68
+ self._turns = list(turns)
69
+ self._next = 0
70
+ self._tool_ids = 0
71
+ self.requests: list[LLMRequest] = []
72
+
73
+ def add_turns(self, *turns: ScriptedTurn) -> None:
74
+ self._turns.extend(turns)
75
+
76
+ @property
77
+ def remaining(self) -> int:
78
+ return len(self._turns) - self._next
79
+
80
+ async def stream(
81
+ self,
82
+ *,
83
+ system: str,
84
+ messages: list[ChatMessage],
85
+ tools: list[ToolDef],
86
+ max_tokens: int,
87
+ tool_choice: Literal["auto", "none"] = "auto",
88
+ ) -> ModelTurn:
89
+ self.requests.append(
90
+ LLMRequest(
91
+ system=system,
92
+ messages=copy.deepcopy(messages),
93
+ tools=list(tools),
94
+ max_tokens=max_tokens,
95
+ tool_choice=tool_choice,
96
+ )
97
+ )
98
+ if self._next >= len(self._turns):
99
+ raise FakeLLMExhausted(
100
+ f"FakeLLM got call {self._next + 1} but only {len(self._turns)} turns are scripted"
101
+ )
102
+ turn = self._turns[self._next]
103
+ self._next += 1
104
+ if turn.error is not None:
105
+ raise turn.error
106
+
107
+ tool_uses = tuple(self._tool_use(t) for t in turn.tool_uses)
108
+ stop_reason = turn.stop_reason or ("tool_use" if tool_uses else "end_turn")
109
+ result = ModelResult(
110
+ tool_uses=tool_uses,
111
+ stop_reason=stop_reason,
112
+ usage=turn.usage,
113
+ text="".join(turn.text),
114
+ )
115
+ deltas = tuple(turn.text)
116
+
117
+ async def text_deltas() -> AsyncIterator[str]:
118
+ for delta in deltas:
119
+ yield delta
120
+
121
+ async def result_fn() -> ModelResult:
122
+ return result
123
+
124
+ return ModelTurn(text_deltas=text_deltas(), result_fn=result_fn)
125
+
126
+ def _tool_use(self, scripted: ScriptedToolUse) -> ToolUse:
127
+ self._tool_ids += 1
128
+ tool_id = scripted.id or f"toolu_fake_{self._tool_ids}"
129
+ return ToolUse(id=tool_id, name=scripted.name, input=copy.deepcopy(dict(scripted.input)))