commons 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.
- commons/__init__.py +48 -0
- commons/_agent.py +655 -0
- commons/_backends.py +244 -0
- commons/_catalog/__init__.py +73 -0
- commons/_catalog/_core.py +617 -0
- commons/_catalog/_databricks.py +296 -0
- commons/_catalog/_databricks_semantic.py +485 -0
- commons/_catalog/_import.py +270 -0
- commons/_catalog/_security.py +433 -0
- commons/_catalog/_snowflake.py +174 -0
- commons/_catalog/_snowflake_semantic.py +566 -0
- commons/_citation_scan.py +320 -0
- commons/_citations.py +383 -0
- commons/_connect.py +683 -0
- commons/_context_layer.py +193 -0
- commons/_data_dictionary.py +478 -0
- commons/_data_source.py +736 -0
- commons/_definitions/__init__.py +51 -0
- commons/_definitions/_compile.py +578 -0
- commons/_definitions/_emit_duckdb.py +346 -0
- commons/_definitions/_emit_sql.py +546 -0
- commons/_definitions/_export.py +876 -0
- commons/_definitions/_expression.py +529 -0
- commons/_definitions/_registry.py +311 -0
- commons/_display.py +322 -0
- commons/_duckdb.py +62 -0
- commons/_execution/__init__.py +1 -0
- commons/_execution/_backend.py +494 -0
- commons/_execution/_driver.py +511 -0
- commons/_execution/_env.py +74 -0
- commons/_execution/_protocol.py +1318 -0
- commons/_execution/_runtime/__init__.py +10 -0
- commons/_execution/_runtime/_figure_backend.py +30 -0
- commons/_execution/_runtime/_guardrails.py +215 -0
- commons/_execution/_runtime/_landlock.py +375 -0
- commons/_execution/_runtime/_limits.py +43 -0
- commons/_execution/_runtime/_plots.py +205 -0
- commons/_execution/_runtime/_repl.py +367 -0
- commons/_execution/_runtime/_seatbelt.py +155 -0
- commons/_execution/_runtime/_seccomp.py +821 -0
- commons/_execution/_runtime/_userns.py +662 -0
- commons/_execution/_runtime/_worker.py +451 -0
- commons/_execution/_sandbox.py +202 -0
- commons/_execution/_thread.py +190 -0
- commons/_frames.py +147 -0
- commons/_handles.py +84 -0
- commons/_icons.py +56 -0
- commons/_measure_results.py +206 -0
- commons/_measures.py +893 -0
- commons/_pool.py +602 -0
- commons/_prompt.py +303 -0
- commons/_provenance.py +156 -0
- commons/_reminders.py +56 -0
- commons/_rows.py +166 -0
- commons/_run_python.py +428 -0
- commons/_semantic_models.py +943 -0
- commons/_skills.py +53 -0
- commons/_sql_guard.py +167 -0
- commons/_tools.py +1005 -0
- commons/_tracing.py +387 -0
- commons/_trajectory/__init__.py +157 -0
- commons/_trajectory/_build.py +618 -0
- commons/_trajectory/_deployment.py +337 -0
- commons/_trajectory/_otlp.py +156 -0
- commons/_trajectory/_semconv.py +154 -0
- commons/_trajectory/_source.py +263 -0
- commons/_ui/__init__.py +46 -0
- commons/_ui/_app.py +58 -0
- commons/_ui/_assets.py +52 -0
- commons/_ui/_server.py +78 -0
- commons/_ui/_theme.py +61 -0
- commons/prompts/README.md +1 -0
- commons/prompts/citation-request.md +1 -0
- commons/prompts/skills/artifacts/SKILL.md +35 -0
- commons/prompts/skills/trust-system/SKILL.md +15 -0
- commons/prompts/system-prompt.md +173 -0
- commons/py.typed +0 -0
- commons/skills/commons/SKILL.md +105 -0
- commons/skills/commons/references/data-dictionaries.md +77 -0
- commons/skills/commons/references/evaluation.md +200 -0
- commons/skills/commons/references/extracting-from-artifacts.md +62 -0
- commons/skills/commons/references/iterating-from-trajectories.md +43 -0
- commons/skills/commons/references/onboarding.md +156 -0
- commons/ui.py +5 -0
- commons/www/README.md +1 -0
- commons/www/commons-chat/commons-artifact.css +79 -0
- commons/www/commons-chat/commons-artifact.js +358 -0
- commons/www/commons-chat/commons-chat.css +716 -0
- commons/www/commons-chat/commons-chat.js +94 -0
- commons/www/commons-chat/commons-document.css +187 -0
- commons/www/commons-chat/figs/citation-definition.svg +4 -0
- commons/www/commons-chat/figs/citation-mark.svg +5 -0
- commons/www/commons-chat/figs/citation-prose.svg +4 -0
- commons/www/commons-chat/figs/citation-schema.svg +4 -0
- commons/www/commons-chat/figs/trusted-icon.svg +6 -0
- commons/www/commons-chat/figs/warning-icon.svg +7 -0
- commons/www/commons-share/commons-share.css +166 -0
- commons/www/commons-share/commons-share.js +131 -0
- commons-0.1.0.dist-info/METADATA +96 -0
- commons-0.1.0.dist-info/RECORD +102 -0
- commons-0.1.0.dist-info/WHEEL +4 -0
- commons-0.1.0.dist-info/licenses/LICENSE.md +21 -0
commons/_agent.py
ADDED
|
@@ -0,0 +1,655 @@
|
|
|
1
|
+
"""The agent: its layers, the tools they earn, and the rules a turn follows.
|
|
2
|
+
|
|
3
|
+
`pkg-r/R/commons.R` assembles the same agent for R, in the order this follows.
|
|
4
|
+
A `Commons` agent inherits directly from `chatlas.Chat`,
|
|
5
|
+
in the same way it inherits from `ellmer::Chat` in R. A `Commons` agent
|
|
6
|
+
will reject `Chat` methods it does not explicitly support to prevent
|
|
7
|
+
interaction without provenance and citation tracking.
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
from __future__ import annotations
|
|
11
|
+
|
|
12
|
+
import asyncio
|
|
13
|
+
import copy
|
|
14
|
+
import logging
|
|
15
|
+
import warnings
|
|
16
|
+
import weakref
|
|
17
|
+
from collections.abc import AsyncGenerator, Mapping, Sequence
|
|
18
|
+
from typing import Any, Literal, NoReturn
|
|
19
|
+
|
|
20
|
+
from chatlas import Chat, StreamController, Tool, Turn, UserTurn
|
|
21
|
+
from chatlas.types import ChatResponse, Content, SubmitInputArgsT
|
|
22
|
+
from pydantic import BaseModel
|
|
23
|
+
|
|
24
|
+
from ._backends import DuckDBBackend, EngineBackend
|
|
25
|
+
from ._citation_scan import CitationScanner
|
|
26
|
+
from ._citations import (
|
|
27
|
+
CitationRequest,
|
|
28
|
+
CorpusEntry,
|
|
29
|
+
build_citation_corpus,
|
|
30
|
+
turn_has_user_message,
|
|
31
|
+
)
|
|
32
|
+
from ._context_layer import ContextLayer, augment_context_layer
|
|
33
|
+
from ._data_source import DataSource
|
|
34
|
+
from ._definitions import Registry, build_registry
|
|
35
|
+
from ._execution._driver import Worker
|
|
36
|
+
from ._execution._thread import WorkerThread
|
|
37
|
+
from ._handles import HandleStore
|
|
38
|
+
from ._measures import SemanticLayer, resolve_injections, semantic_layer
|
|
39
|
+
from ._prompt import (
|
|
40
|
+
EXECUTION_TOOL,
|
|
41
|
+
check_instructions,
|
|
42
|
+
read_instructions,
|
|
43
|
+
render_system_prompt,
|
|
44
|
+
system_prompt_data,
|
|
45
|
+
system_prompt_template,
|
|
46
|
+
)
|
|
47
|
+
from ._provenance import collect_appended_tags, derive_provenance_tag, provenance_aside
|
|
48
|
+
from ._reminders import append_restored_conversation_reminder, append_turn_reminder
|
|
49
|
+
from ._run_python import run_python_description, run_python_tools
|
|
50
|
+
from ._semantic_models import semantic_registry
|
|
51
|
+
from ._tools import FirstTouch, ToolContext, build_commons_tools
|
|
52
|
+
from ._tracing import (
|
|
53
|
+
as_current,
|
|
54
|
+
check_trajectory_arguments,
|
|
55
|
+
commons_span,
|
|
56
|
+
enable_trajectory_tracing,
|
|
57
|
+
record_provenance_span,
|
|
58
|
+
start_turn_span,
|
|
59
|
+
trajectory_user,
|
|
60
|
+
)
|
|
61
|
+
|
|
62
|
+
__all__ = ["Commons"]
|
|
63
|
+
|
|
64
|
+
EchoOptions = Literal["output", "all", "none", "text"]
|
|
65
|
+
|
|
66
|
+
# The label a lone source is filed under. An agent with one source never shows
|
|
67
|
+
# the model a `source` argument and never labels its prompt sections, so this
|
|
68
|
+
# is only what the agent's own bookkeeping keys on.
|
|
69
|
+
SOLE_SOURCE = "data"
|
|
70
|
+
|
|
71
|
+
# How often a stream checks whether the stop button was pressed, in seconds.
|
|
72
|
+
STOP_POLL_INTERVAL = 0.1
|
|
73
|
+
|
|
74
|
+
# Frozen and empty, so every agent built without a semantic layer can share it.
|
|
75
|
+
_NO_MEASURES = semantic_layer()
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
logger = logging.getLogger(__name__)
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
class Commons(Chat[Any, Any]):
|
|
82
|
+
"""A trustworthy agent that answers questions about its data.
|
|
83
|
+
|
|
84
|
+
Given a `chatlas.Chat` for the provider and model, the data sources it
|
|
85
|
+
can query, and optionally a semantic layer of trusted calculations and a
|
|
86
|
+
context layer of prose, a `Commons` agent will allow for agent interactions
|
|
87
|
+
with answers classified by how they were produced.
|
|
88
|
+
|
|
89
|
+
A `Commons` agent inherits directly from `chatlas.Chat` and relies on the
|
|
90
|
+
chatlas infrastructure to set up the LLM provider and model. `Commons`
|
|
91
|
+
initializes its own chat state and system prompt to ensure provenance
|
|
92
|
+
and citation tracking. Passing a custom system prompt in the `Commons`
|
|
93
|
+
constructor is ignored with a warning; use `instructions` to add to
|
|
94
|
+
commons' prompt instead. For best results, enable thinking where the
|
|
95
|
+
provider and model support it.
|
|
96
|
+
|
|
97
|
+
`chat()` and `stream_async()` are the currently supported ways to
|
|
98
|
+
interact with a `Commons` agent. The other entry points chatlas offers
|
|
99
|
+
(`chat_async()`, `stream()`, `chat_structured()`, etc.)
|
|
100
|
+
are disabled and raise `NotImplementedError`s because they are not (yet)
|
|
101
|
+
tied in to the commons framework. The rest of chatlas's surface works as
|
|
102
|
+
it does on any chat.
|
|
103
|
+
|
|
104
|
+
`data_sources` is a `DataSource`, or a mapping of name to `DataSource`;
|
|
105
|
+
a measure can take a named source's connection as an argument named
|
|
106
|
+
after it. `instructions` is extra text placed under an
|
|
107
|
+
`## Additional instructions` heading at the end of commons' built-in
|
|
108
|
+
system prompt, as a string or the path to a text or Markdown file.
|
|
109
|
+
|
|
110
|
+
The agent can run Python code that its model writes. The code runs in a
|
|
111
|
+
separate, sandboxed Python process, which starts the first time the model
|
|
112
|
+
runs code. `network` sets whether that process can reach the network:
|
|
113
|
+
`"none"` (the default) or `"full"`. The sandbox works on Linux and macOS.
|
|
114
|
+
For local development on another system, set the
|
|
115
|
+
`COMMONS_ALLOW_UNSAFE_FALLBACK` environment variable to run the code with
|
|
116
|
+
limited checks instead. Warning! These checks are not intended to be a
|
|
117
|
+
security boundary.
|
|
118
|
+
|
|
119
|
+
`log` requests trajectory capture with OpenTelemetry (default `False`).
|
|
120
|
+
It needs the `tracing` extra (`pip install 'commons[tracing]'`), and warns
|
|
121
|
+
without it. On Posit Connect, the agent warns when the server cannot
|
|
122
|
+
record trajectories, and turns on the content's Content Observability
|
|
123
|
+
setting when the process is not yet traced. Connect must be >= 2026.09.0,
|
|
124
|
+
with `OpenTelemetry.Enabled` and `OpenTelemetry.AllowContentInstrumentation`
|
|
125
|
+
set to `true` by a server administrator. Elsewhere, the agent records only
|
|
126
|
+
when a tracer provider is already installed. Logging also records the
|
|
127
|
+
authenticated Shiny session user, when Connect supplies one, for
|
|
128
|
+
attribution. `share_with` is a sequence of Connect usernames granted
|
|
129
|
+
access to this content's trajectories once logging is live. Reading
|
|
130
|
+
traces needs editor-level access, so the named users are added as
|
|
131
|
+
collaborators on the content, which is a wider grant than trace access.
|
|
132
|
+
They need an account that can publish. `share_with` applies only when
|
|
133
|
+
`log=True`.
|
|
134
|
+
|
|
135
|
+
Construction raises a TypeError if `client` is not a `chatlas.Chat`, if
|
|
136
|
+
`log` is not a bool, if `share_with` is not a sequence of strings, if
|
|
137
|
+
an entry of `data_sources` is not a `DataSource`, or if a layer is not
|
|
138
|
+
the layer its argument claims; a ValueError if `data_sources` names no
|
|
139
|
+
source, a measure asks for an injection no named source can fill, or
|
|
140
|
+
`network` is neither `"none"` nor `"full"`; a FileNotFoundError if
|
|
141
|
+
`instructions` names a file that does not exist; and a RuntimeError if
|
|
142
|
+
this host cannot sandbox the session and the opt-in is not set.
|
|
143
|
+
"""
|
|
144
|
+
|
|
145
|
+
def __init__(
|
|
146
|
+
self,
|
|
147
|
+
client: Chat,
|
|
148
|
+
data_sources: DataSource | Mapping[str, DataSource],
|
|
149
|
+
semantic_layer: SemanticLayer | None = None,
|
|
150
|
+
context_layer: ContextLayer | None = None,
|
|
151
|
+
*,
|
|
152
|
+
instructions: str | None = None,
|
|
153
|
+
network: Literal["none", "full"] = "none",
|
|
154
|
+
log: bool = False,
|
|
155
|
+
share_with: Sequence[str] | None = None,
|
|
156
|
+
) -> None:
|
|
157
|
+
if not isinstance(client, Chat):
|
|
158
|
+
raise TypeError(
|
|
159
|
+
"client must be a chatlas.Chat, e.g. from chatlas.ChatAnthropic(), "
|
|
160
|
+
f"not {type(client).__name__}."
|
|
161
|
+
)
|
|
162
|
+
# What the client carried is warned about before any other argument
|
|
163
|
+
# is checked, as pkg-r/R/commons.R does, so a bad later argument
|
|
164
|
+
# does not eat the warning.
|
|
165
|
+
_warn_ignored_client_state(client)
|
|
166
|
+
sources = _as_data_sources(data_sources)
|
|
167
|
+
if context_layer is not None and not isinstance(context_layer, ContextLayer):
|
|
168
|
+
raise TypeError(
|
|
169
|
+
"context_layer must be a ContextLayer from commons.context_layer(), "
|
|
170
|
+
f"or None, not {type(context_layer).__name__}."
|
|
171
|
+
)
|
|
172
|
+
if semantic_layer is None:
|
|
173
|
+
semantic_layer = _NO_MEASURES
|
|
174
|
+
if not isinstance(semantic_layer, SemanticLayer):
|
|
175
|
+
raise TypeError(
|
|
176
|
+
"semantic_layer must be a SemanticLayer from "
|
|
177
|
+
f"commons.semantic_layer(), or None, not "
|
|
178
|
+
f"{type(semantic_layer).__name__}."
|
|
179
|
+
)
|
|
180
|
+
check_instructions(instructions)
|
|
181
|
+
check_trajectory_arguments(log, share_with)
|
|
182
|
+
definitions = build_registry(sources)
|
|
183
|
+
semantic = semantic_registry(sources)
|
|
184
|
+
with commons_span(
|
|
185
|
+
"commons_agent_create",
|
|
186
|
+
{
|
|
187
|
+
"commons.agent.n_data_sources": len(sources),
|
|
188
|
+
"commons.agent.has_context_layer": context_layer is not None,
|
|
189
|
+
"commons.agent.n_measures": len(semantic_layer.measures),
|
|
190
|
+
"commons.agent.n_definitions": len(definitions.records),
|
|
191
|
+
"commons.agent.n_semantic_members": len(semantic.members),
|
|
192
|
+
"commons.agent.n_calculations": len(semantic.calculations),
|
|
193
|
+
},
|
|
194
|
+
):
|
|
195
|
+
# Built here so a host that cannot sandbox the session fails now,
|
|
196
|
+
# before any model asks to run code. The process starts on first use.
|
|
197
|
+
worker = Worker(
|
|
198
|
+
network=network,
|
|
199
|
+
measure_sources=list(semantic_layer.source_text.values()),
|
|
200
|
+
)
|
|
201
|
+
|
|
202
|
+
# Share the provider, which knows the chosen model; shallow-copy
|
|
203
|
+
# the chat kwargs so later changes don't cross between the two.
|
|
204
|
+
super().__init__(
|
|
205
|
+
provider=client.provider, kwargs_chat=copy.copy(client.kwargs_chat)
|
|
206
|
+
)
|
|
207
|
+
# chatlas never generates one, so an id the caller chose is explicitly kept
|
|
208
|
+
self.conversation_id = client.conversation_id
|
|
209
|
+
_carry_model_params(self, client)
|
|
210
|
+
|
|
211
|
+
self._sources = sources
|
|
212
|
+
self._context_layer = augment_context_layer(context_layer, sources.values())
|
|
213
|
+
self._definitions = definitions
|
|
214
|
+
self._measures = semantic_layer.measures
|
|
215
|
+
# The injectables side stays here because it is the only part that
|
|
216
|
+
# knows what a DataSource is: a measure asks for a source by name and
|
|
217
|
+
# receives whatever that source is queried through.
|
|
218
|
+
self._injections = resolve_injections(
|
|
219
|
+
self._measures, _measure_injectables(data_sources, sources)
|
|
220
|
+
)
|
|
221
|
+
self._first_touch = FirstTouch()
|
|
222
|
+
self._handles = HandleStore()
|
|
223
|
+
self._citation_request = CitationRequest()
|
|
224
|
+
self._corpus = build_citation_corpus(
|
|
225
|
+
self._context_layer, self._measures.values(), sources
|
|
226
|
+
)
|
|
227
|
+
self._restore_reminder_pending = False
|
|
228
|
+
|
|
229
|
+
context = ToolContext(
|
|
230
|
+
sources=sources,
|
|
231
|
+
measures=self._measures,
|
|
232
|
+
definitions=self._definitions,
|
|
233
|
+
context_layer=self._context_layer,
|
|
234
|
+
handles=self._handles,
|
|
235
|
+
citation_request=self._citation_request,
|
|
236
|
+
injections=self._injections,
|
|
237
|
+
first_touch=self._first_touch,
|
|
238
|
+
)
|
|
239
|
+
tools = build_commons_tools(context)
|
|
240
|
+
self._python = WorkerThread(worker)
|
|
241
|
+
# Close the session's process and thread when the agent is
|
|
242
|
+
# collected or the interpreter exits. The callback names only the
|
|
243
|
+
# WorkerThread, so the finalizer never keeps the agent alive.
|
|
244
|
+
weakref.finalize(self, self._python.close)
|
|
245
|
+
self._run_python, self._run_python_sync = run_python_tools(
|
|
246
|
+
self._python,
|
|
247
|
+
context,
|
|
248
|
+
run_python_description(
|
|
249
|
+
[tool.name for tool in tools],
|
|
250
|
+
has_measures=bool(self._measures),
|
|
251
|
+
network=network,
|
|
252
|
+
),
|
|
253
|
+
network,
|
|
254
|
+
)
|
|
255
|
+
tools.append(self._run_python)
|
|
256
|
+
self.set_tools(list(tools))
|
|
257
|
+
self.system_prompt = _system_prompt(
|
|
258
|
+
sources,
|
|
259
|
+
self._definitions,
|
|
260
|
+
instructions=instructions,
|
|
261
|
+
tools=tools,
|
|
262
|
+
model=self.model,
|
|
263
|
+
)
|
|
264
|
+
|
|
265
|
+
# After construction succeeds, so a failure has changed nothing on
|
|
266
|
+
# Connect, and outside the setup span, which times only the build.
|
|
267
|
+
self._tracing = enable_trajectory_tracing(
|
|
268
|
+
log=log, share_with=share_with, stacklevel=_CALLER
|
|
269
|
+
)
|
|
270
|
+
|
|
271
|
+
def __repr__(self) -> str:
|
|
272
|
+
count = len(self._sources)
|
|
273
|
+
plural = "" if count == 1 else "s"
|
|
274
|
+
return f"A commons agent over {count} data source{plural}."
|
|
275
|
+
|
|
276
|
+
def __deepcopy__(self, memo: dict[int, Any]) -> NoReturn:
|
|
277
|
+
# chatlas Chat objects can be deep-copied to fork a conversation,
|
|
278
|
+
# Because a Commons agent may have database connections (which can't be copied)
|
|
279
|
+
# we explicitly forbid deep copying with a clear error.
|
|
280
|
+
raise NotImplementedError(
|
|
281
|
+
"A commons agent cannot be copied: it holds database connections "
|
|
282
|
+
"that copying cannot reach. Build a second agent instead."
|
|
283
|
+
)
|
|
284
|
+
|
|
285
|
+
# ---- asking it something ---------------------------------------------
|
|
286
|
+
|
|
287
|
+
def chat(
|
|
288
|
+
self,
|
|
289
|
+
*args: Content | str,
|
|
290
|
+
echo: EchoOptions = "output",
|
|
291
|
+
stream: bool = True,
|
|
292
|
+
kwargs: SubmitInputArgsT | None = None,
|
|
293
|
+
) -> ChatResponse:
|
|
294
|
+
"""Ask a question and wait for the whole answer.
|
|
295
|
+
|
|
296
|
+
A reminder queued with `queue_restore_reminder()` rides this turn,
|
|
297
|
+
and a turn that fails leaves it queued for the next one.
|
|
298
|
+
"""
|
|
299
|
+
was_pending = self._restore_reminder_pending
|
|
300
|
+
inputs = self._prepare_turn_inputs(args)
|
|
301
|
+
self._citation_request.reset()
|
|
302
|
+
# A synchronous chat cannot await an async tool, so chatlas
|
|
303
|
+
# refuses to run while the async run_python tool is registered.
|
|
304
|
+
# This workaround swaps in the sync variant of run_python for this call.
|
|
305
|
+
swap = any(tool.name == EXECUTION_TOOL for tool in self.get_tools())
|
|
306
|
+
if swap:
|
|
307
|
+
self.register_tool(self._run_python_sync, force=True)
|
|
308
|
+
turn = start_turn_span(trajectory_user()) if self._tracing else None
|
|
309
|
+
try:
|
|
310
|
+
with as_current(turn):
|
|
311
|
+
response = super().chat(
|
|
312
|
+
*inputs, echo=echo, stream=stream, kwargs=kwargs
|
|
313
|
+
)
|
|
314
|
+
finally:
|
|
315
|
+
if turn is not None:
|
|
316
|
+
turn.end()
|
|
317
|
+
if swap:
|
|
318
|
+
self.register_tool(self._run_python, force=True)
|
|
319
|
+
self._consume_restore_reminder(was_pending)
|
|
320
|
+
return response
|
|
321
|
+
|
|
322
|
+
async def stream_async(
|
|
323
|
+
self,
|
|
324
|
+
*args: Content | str,
|
|
325
|
+
content: Literal["text", "all"] = "text",
|
|
326
|
+
echo: EchoOptions = "none",
|
|
327
|
+
data_model: type[BaseModel] | None = None,
|
|
328
|
+
kwargs: SubmitInputArgsT | None = None,
|
|
329
|
+
controller: StreamController | None = None,
|
|
330
|
+
) -> AsyncGenerator[Any, None]:
|
|
331
|
+
"""Ask a question and stream the answer as it arrives.
|
|
332
|
+
|
|
333
|
+
The signature is identical to chatlas's, so a chat UI can drive this agent
|
|
334
|
+
directly and needs the attachment content, the mode, and the controller its
|
|
335
|
+
stop button cancels through.
|
|
336
|
+
|
|
337
|
+
The Commons agent does not accept `data_model`. If you pass it, this
|
|
338
|
+
method raises NotImplementedError. In chatlas, using `data_model` means
|
|
339
|
+
the chunks are JSON that the caller parses as one document. Commons adds
|
|
340
|
+
provenance markers and citations to the stream that are not compatible with
|
|
341
|
+
`data_model`, so it is explicitly forbidden.
|
|
342
|
+
"""
|
|
343
|
+
if data_model is not None:
|
|
344
|
+
raise NotImplementedError(
|
|
345
|
+
"stream_async(data_model=...) is not available on a commons "
|
|
346
|
+
"agent: the provenance marker and citations it appends would leave the "
|
|
347
|
+
"streamed JSON unparseable."
|
|
348
|
+
)
|
|
349
|
+
from_index = len(self.get_turns())
|
|
350
|
+
was_pending = self._restore_reminder_pending
|
|
351
|
+
inputs = self._prepare_turn_inputs(args)
|
|
352
|
+
self._citation_request.reset()
|
|
353
|
+
raw = await super().stream_async(
|
|
354
|
+
*inputs,
|
|
355
|
+
content=content,
|
|
356
|
+
echo=echo,
|
|
357
|
+
kwargs=kwargs,
|
|
358
|
+
controller=controller,
|
|
359
|
+
)
|
|
360
|
+
# Read now: the stream is pulled outside the session that asked.
|
|
361
|
+
user = trajectory_user() if self._tracing else None
|
|
362
|
+
return self._projected(raw, from_index, was_pending, controller, user)
|
|
363
|
+
|
|
364
|
+
# Citations are always projected, so reserved model markup cannot reach
|
|
365
|
+
# the browser whatever the display layer does with the stream.
|
|
366
|
+
async def _projected(
|
|
367
|
+
self,
|
|
368
|
+
raw: AsyncGenerator[Any, None],
|
|
369
|
+
from_index: int,
|
|
370
|
+
was_pending: bool,
|
|
371
|
+
controller: StreamController | None = None,
|
|
372
|
+
user: str | None = None,
|
|
373
|
+
) -> AsyncGenerator[str | Content, None]:
|
|
374
|
+
# `raw` is the stream chatlas returns, before citation projection.
|
|
375
|
+
turn = start_turn_span(user) if self._tracing else None
|
|
376
|
+
try:
|
|
377
|
+
scanner = CitationScanner(self._corpus)
|
|
378
|
+
# chatlas checks the controller only between chunks, so a running
|
|
379
|
+
# run_python call would otherwise finish before a stop takes effect.
|
|
380
|
+
watch = (
|
|
381
|
+
asyncio.ensure_future(self._stop_python_when(controller))
|
|
382
|
+
if controller is not None
|
|
383
|
+
else None
|
|
384
|
+
)
|
|
385
|
+
try:
|
|
386
|
+
while True:
|
|
387
|
+
# chatlas starts its spans on the first pull of `raw`,
|
|
388
|
+
# under whatever is current then. The turn span is current
|
|
389
|
+
# only while `raw` is pulled: this generator's body runs in
|
|
390
|
+
# whichever context pulls it, so a span attached across a
|
|
391
|
+
# `yield` could be detached in another.
|
|
392
|
+
with as_current(turn):
|
|
393
|
+
try:
|
|
394
|
+
chunk = await anext(raw)
|
|
395
|
+
except StopAsyncIteration:
|
|
396
|
+
break
|
|
397
|
+
# A provider's structured content passes through untouched;
|
|
398
|
+
# only the model's own text can carry the reserved dialect.
|
|
399
|
+
if not isinstance(chunk, str):
|
|
400
|
+
yield chunk
|
|
401
|
+
continue
|
|
402
|
+
projected = scanner.feed(chunk)
|
|
403
|
+
if projected:
|
|
404
|
+
yield projected
|
|
405
|
+
finally:
|
|
406
|
+
if watch is not None:
|
|
407
|
+
watch.cancel()
|
|
408
|
+
# A consumer that walks away early without cancelling still
|
|
409
|
+
# closes the provider's stream.
|
|
410
|
+
await raw.aclose()
|
|
411
|
+
|
|
412
|
+
self._consume_restore_reminder(was_pending)
|
|
413
|
+
|
|
414
|
+
tail = scanner.finish()
|
|
415
|
+
if tail:
|
|
416
|
+
yield tail
|
|
417
|
+
|
|
418
|
+
tag = derive_provenance_tag(
|
|
419
|
+
collect_appended_tags(self.get_turns(), from_index),
|
|
420
|
+
scanner.any_verified,
|
|
421
|
+
)
|
|
422
|
+
if turn is not None:
|
|
423
|
+
try:
|
|
424
|
+
record_provenance_span(turn, tag, scanner.candidates)
|
|
425
|
+
except Exception:
|
|
426
|
+
# Telemetry must not cost the user the answer.
|
|
427
|
+
logger.debug("Recording the provenance span failed", exc_info=True)
|
|
428
|
+
|
|
429
|
+
aside = provenance_aside(tag)
|
|
430
|
+
if aside:
|
|
431
|
+
yield aside
|
|
432
|
+
finally:
|
|
433
|
+
if turn is not None:
|
|
434
|
+
turn.end()
|
|
435
|
+
|
|
436
|
+
async def _stop_python_when(self, controller: StreamController) -> None:
|
|
437
|
+
"""Stop the Python session's calls once ``controller`` is cancelled."""
|
|
438
|
+
while not controller.cancelled:
|
|
439
|
+
await asyncio.sleep(STOP_POLL_INTERVAL)
|
|
440
|
+
self._python.stop_calls()
|
|
441
|
+
|
|
442
|
+
# ---- chatlas.Chat entry points a Commons agent does not support ----------------
|
|
443
|
+
|
|
444
|
+
def chat_async(self, *args: Any, **kwargs: Any) -> NoReturn:
|
|
445
|
+
raise NotImplementedError(_unrouted("chat_async"))
|
|
446
|
+
|
|
447
|
+
def stream(self, *args: Any, **kwargs: Any) -> NoReturn:
|
|
448
|
+
raise NotImplementedError(_unrouted("stream"))
|
|
449
|
+
|
|
450
|
+
def chat_structured(self, *args: Any, **kwargs: Any) -> NoReturn:
|
|
451
|
+
raise NotImplementedError(_unrouted("chat_structured"))
|
|
452
|
+
|
|
453
|
+
def chat_structured_async(self, *args: Any, **kwargs: Any) -> NoReturn:
|
|
454
|
+
raise NotImplementedError(_unrouted("chat_structured_async"))
|
|
455
|
+
|
|
456
|
+
def extract_data(self, *args: Any, **kwargs: Any) -> NoReturn:
|
|
457
|
+
raise NotImplementedError(_unrouted("extract_data"))
|
|
458
|
+
|
|
459
|
+
def extract_data_async(self, *args: Any, **kwargs: Any) -> NoReturn:
|
|
460
|
+
raise NotImplementedError(_unrouted("extract_data_async"))
|
|
461
|
+
|
|
462
|
+
def to_solver(self, *args: Any, **kwargs: Any) -> NoReturn:
|
|
463
|
+
# chatlas's solver answers each eval sample through `chat_async()` or
|
|
464
|
+
# `chat_structured_async()`, so it would raise mid-eval anyway.
|
|
465
|
+
raise NotImplementedError(
|
|
466
|
+
"A commons agent has no to_solver(): the solver it returns "
|
|
467
|
+
"answers through chat_async(), which an agent does not provide."
|
|
468
|
+
)
|
|
469
|
+
|
|
470
|
+
# ---- what the agent knows --------------------------------------------
|
|
471
|
+
|
|
472
|
+
def citation_corpus(self) -> list[CorpusEntry]:
|
|
473
|
+
"""The trusted text this agent's citations are verified against."""
|
|
474
|
+
return list(self._corpus)
|
|
475
|
+
|
|
476
|
+
def prewarm(self) -> None:
|
|
477
|
+
"""Build the caches the first question would otherwise pay for.
|
|
478
|
+
|
|
479
|
+
Failures propagate: a direct call is typically warming caches ahead
|
|
480
|
+
of a deployment, so a cold cache should fail the deploy.
|
|
481
|
+
"""
|
|
482
|
+
layer = self._context_layer
|
|
483
|
+
if layer is not None and layer.docs:
|
|
484
|
+
with commons_span(
|
|
485
|
+
"commons_context_prewarm",
|
|
486
|
+
{
|
|
487
|
+
"commons.context.n_docs": len(layer.docs),
|
|
488
|
+
"commons.context.cache_hit": layer._is_built(),
|
|
489
|
+
},
|
|
490
|
+
):
|
|
491
|
+
layer.prewarm()
|
|
492
|
+
for source in self._sources.values():
|
|
493
|
+
source.ensure_loaded()
|
|
494
|
+
|
|
495
|
+
# ---- the turn rules ---------------------------------------------------
|
|
496
|
+
|
|
497
|
+
def add_turn(self, turn: Turn) -> None:
|
|
498
|
+
"""Add a turn, restarting the citation request if a person spoke.
|
|
499
|
+
|
|
500
|
+
A user turn of nothing but tool results is the same question still
|
|
501
|
+
running, and an assistant turn is nobody asking anything.
|
|
502
|
+
"""
|
|
503
|
+
if isinstance(turn, UserTurn) and turn_has_user_message(turn):
|
|
504
|
+
self._citation_request.reset()
|
|
505
|
+
super().add_turn(turn)
|
|
506
|
+
|
|
507
|
+
def set_turns(self, turns: Sequence[Turn]) -> None:
|
|
508
|
+
"""Replace the conversation, dropping any reminder queued for it."""
|
|
509
|
+
self._restore_reminder_pending = False
|
|
510
|
+
super().set_turns(turns)
|
|
511
|
+
|
|
512
|
+
def queue_restore_reminder(self) -> None:
|
|
513
|
+
"""Tell the next turn that the session behind its history is gone."""
|
|
514
|
+
self._restore_reminder_pending = True
|
|
515
|
+
|
|
516
|
+
def _prepare_turn_inputs(
|
|
517
|
+
self, inputs: Sequence[Content | str]
|
|
518
|
+
) -> list[Content | str]:
|
|
519
|
+
prepared = append_turn_reminder(inputs, self.model)
|
|
520
|
+
if self._restore_reminder_pending:
|
|
521
|
+
prepared = append_restored_conversation_reminder(prepared)
|
|
522
|
+
return prepared
|
|
523
|
+
|
|
524
|
+
# Only a reminder that was pending when the turn started is spent, so a
|
|
525
|
+
# turn that failed, or one whose stream was never consumed, leaves the
|
|
526
|
+
# next turn to deliver it.
|
|
527
|
+
def _consume_restore_reminder(self, was_pending: bool) -> None:
|
|
528
|
+
if was_pending:
|
|
529
|
+
self._restore_reminder_pending = False
|
|
530
|
+
|
|
531
|
+
|
|
532
|
+
# The stacklevel that reaches whoever built the agent, from a function called
|
|
533
|
+
# straight from __init__: the warnings below, and trajectory logging setup.
|
|
534
|
+
_CALLER = 3
|
|
535
|
+
|
|
536
|
+
|
|
537
|
+
def _warn_ignored_client_state(client: Chat) -> None:
|
|
538
|
+
"""Warn about whatever the agent's own chat will not carry over."""
|
|
539
|
+
if client.system_prompt is not None:
|
|
540
|
+
warnings.warn(
|
|
541
|
+
"The system prompt set on client is ignored; commons builds its "
|
|
542
|
+
"own. Use `instructions` to add to commons' prompt.",
|
|
543
|
+
stacklevel=_CALLER,
|
|
544
|
+
)
|
|
545
|
+
if client.get_turns():
|
|
546
|
+
warnings.warn(
|
|
547
|
+
"An agent starts a new conversation, so the turns on client are "
|
|
548
|
+
"not carried over. Restore them with the agent's set_turns().",
|
|
549
|
+
stacklevel=_CALLER,
|
|
550
|
+
)
|
|
551
|
+
|
|
552
|
+
|
|
553
|
+
def _unrouted(name: str) -> str:
|
|
554
|
+
"""Why an inherited entry point is closed, and what to ask instead."""
|
|
555
|
+
return (
|
|
556
|
+
f"A commons agent has no {name}(): it would submit a turn outside "
|
|
557
|
+
"commons' turn handling, and the answer would carry neither the "
|
|
558
|
+
"citation scanner's work nor a provenance marker. Ask the agent "
|
|
559
|
+
"with chat() or stream_async()."
|
|
560
|
+
)
|
|
561
|
+
|
|
562
|
+
|
|
563
|
+
def _carry_model_params(agent: Chat, client: Chat) -> None:
|
|
564
|
+
"""Move whatever `set_model_params()` put on the caller's chat.
|
|
565
|
+
|
|
566
|
+
The agent brings its own system prompt and tools and starts an empty
|
|
567
|
+
conversation, as `pkg-r/R/commons.R` does when it initializes from the
|
|
568
|
+
client's provider, so the model parameters are all there is to carry.
|
|
569
|
+
"""
|
|
570
|
+
# chatlas has the setter for these and no getter, so they are read off the
|
|
571
|
+
# attribute behind it and written back through the public setter, which
|
|
572
|
+
# checks them against the provider again. An attribute that is missing, or
|
|
573
|
+
# no longer a mapping, has to be told apart from an empty one, which means
|
|
574
|
+
# nothing was set: dropping a temperature in silence is worse than saying
|
|
575
|
+
# that this chatlas does not show what was set.
|
|
576
|
+
params = getattr(client, "_standard_model_params", None)
|
|
577
|
+
if not isinstance(params, Mapping):
|
|
578
|
+
warnings.warn(
|
|
579
|
+
"Any model parameters set on client with set_model_params() are "
|
|
580
|
+
"not carried onto the agent: this version of chatlas does not "
|
|
581
|
+
"expose them.",
|
|
582
|
+
stacklevel=_CALLER,
|
|
583
|
+
)
|
|
584
|
+
elif params:
|
|
585
|
+
agent.set_model_params(**dict(params))
|
|
586
|
+
|
|
587
|
+
|
|
588
|
+
def _as_data_sources(
|
|
589
|
+
data_sources: DataSource | Mapping[str, DataSource],
|
|
590
|
+
) -> dict[str, DataSource]:
|
|
591
|
+
if isinstance(data_sources, DataSource):
|
|
592
|
+
return {SOLE_SOURCE: data_sources}
|
|
593
|
+
if not isinstance(data_sources, Mapping):
|
|
594
|
+
raise TypeError(
|
|
595
|
+
"data_sources must be a DataSource from commons.data_source(), or a "
|
|
596
|
+
f"mapping of name to DataSource, not {type(data_sources).__name__}."
|
|
597
|
+
)
|
|
598
|
+
if not data_sources:
|
|
599
|
+
raise ValueError("data_sources must name at least one DataSource.")
|
|
600
|
+
wrong = [
|
|
601
|
+
name
|
|
602
|
+
for name, source in data_sources.items()
|
|
603
|
+
if not isinstance(source, DataSource)
|
|
604
|
+
]
|
|
605
|
+
if wrong:
|
|
606
|
+
raise TypeError(
|
|
607
|
+
f"Every entry in data_sources must be a DataSource from "
|
|
608
|
+
f"commons.data_source(); {', '.join(sorted(wrong))} "
|
|
609
|
+
f"{'is' if len(wrong) == 1 else 'are'} not."
|
|
610
|
+
)
|
|
611
|
+
return dict(data_sources)
|
|
612
|
+
|
|
613
|
+
|
|
614
|
+
# A measure can take a named source's connection as an argument named after
|
|
615
|
+
# the source. A lone source passed on its own has no name to be asked for, so
|
|
616
|
+
# it offers nothing to inject, as in pkg-r/R/commons.R.
|
|
617
|
+
def _measure_injectables(
|
|
618
|
+
data_sources: DataSource | Mapping[str, DataSource],
|
|
619
|
+
sources: Mapping[str, DataSource],
|
|
620
|
+
) -> dict[str, Any]:
|
|
621
|
+
if isinstance(data_sources, DataSource):
|
|
622
|
+
return {}
|
|
623
|
+
return {name: _connection(source) for name, source in sources.items()}
|
|
624
|
+
|
|
625
|
+
|
|
626
|
+
def _connection(source: DataSource) -> Any:
|
|
627
|
+
"""What a measure queries a source through.
|
|
628
|
+
|
|
629
|
+
The engine for a caller's database and the DuckDB connection for the
|
|
630
|
+
in-process one commons builds, which is what each was queried through
|
|
631
|
+
before it reached the measure.
|
|
632
|
+
"""
|
|
633
|
+
backend = source.backend
|
|
634
|
+
if isinstance(backend, EngineBackend):
|
|
635
|
+
return backend.engine
|
|
636
|
+
if isinstance(backend, DuckDBBackend):
|
|
637
|
+
return backend.connection
|
|
638
|
+
raise TypeError(f"No connection to inject for a {type(backend).__name__}.")
|
|
639
|
+
|
|
640
|
+
|
|
641
|
+
def _system_prompt(
|
|
642
|
+
sources: Mapping[str, DataSource],
|
|
643
|
+
definitions: Registry,
|
|
644
|
+
instructions: str | None,
|
|
645
|
+
tools: Sequence[Tool],
|
|
646
|
+
model: str | None,
|
|
647
|
+
) -> str:
|
|
648
|
+
data = system_prompt_data(
|
|
649
|
+
sources,
|
|
650
|
+
definitions,
|
|
651
|
+
instructions=read_instructions(instructions),
|
|
652
|
+
tools=[tool.name for tool in tools],
|
|
653
|
+
model=model,
|
|
654
|
+
)
|
|
655
|
+
return render_system_prompt(system_prompt_template(), data)
|