reactifact 0.20.2__py3-none-any.whl → 0.22.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.
- reactifact/__init__.py +22 -4
- reactifact/a2a/remote.py +1 -1
- reactifact/agents.py +29 -1
- reactifact/artifacts.py +20 -0
- reactifact/branching/__init__.py +2 -0
- reactifact/branching/ops.py +38 -5
- reactifact/chat.py +37 -15
- reactifact/cli/__init__.py +37 -14
- reactifact/cli/doctor.py +159 -0
- reactifact/cli/graph.py +27 -0
- reactifact/cli/new.py +97 -0
- reactifact/cli/replay.py +14 -2
- reactifact/commit.py +31 -0
- reactifact/context/context.py +110 -19
- reactifact/context/pending.py +18 -5
- reactifact/effects.py +45 -11
- reactifact/experiments.py +240 -0
- reactifact/interrupt.py +81 -3
- reactifact/knowledge/__init__.py +143 -0
- reactifact/knowledge/_closers.py +25 -0
- reactifact/knowledge/bridge.py +169 -0
- reactifact/knowledge/chunk.py +212 -0
- reactifact/knowledge/connectors.py +137 -0
- reactifact/knowledge/docstore.py +228 -0
- reactifact/knowledge/embed.py +253 -0
- reactifact/knowledge/errors.py +31 -0
- reactifact/knowledge/extract.py +124 -0
- reactifact/knowledge/http.py +189 -0
- reactifact/knowledge/indexes/__init__.py +25 -0
- reactifact/knowledge/indexes/acl.py +24 -0
- reactifact/knowledge/indexes/base.py +69 -0
- reactifact/knowledge/indexes/chroma.py +266 -0
- reactifact/knowledge/indexes/fusion.py +36 -0
- reactifact/knowledge/indexes/keyword.py +57 -0
- reactifact/knowledge/indexes/math.py +21 -0
- reactifact/knowledge/indexes/memory.py +137 -0
- reactifact/knowledge/indexes/pgvector.py +331 -0
- reactifact/knowledge/indexes/qdrant.py +359 -0
- reactifact/knowledge/indexes/sqlite.py +218 -0
- reactifact/knowledge/models.py +132 -0
- reactifact/knowledge/pipeline.py +523 -0
- reactifact/knowledge/rerank.py +212 -0
- reactifact/knowledge/templates/knowledge.html +125 -0
- reactifact/knowledge/web.py +95 -0
- reactifact/operations.py +8 -1
- reactifact/patches.py +27 -4
- reactifact/policy.py +65 -0
- reactifact/produce.py +2 -1
- reactifact/recipes/__init__.py +25 -0
- reactifact/recipes/map_reduce.py +262 -0
- reactifact/recipes/memory_store.py +448 -0
- reactifact/recipes/supervisor.py +1 -1
- reactifact/recipes/swarm.py +186 -0
- reactifact/replay.py +107 -1
- reactifact/resources.py +10 -0
- reactifact/runtime/events.py +196 -0
- reactifact/runtime/patch.py +44 -1
- reactifact/runtime/runtime.py +344 -48
- reactifact/session.py +60 -0
- reactifact/step/core.py +13 -0
- reactifact/step/decorator.py +2 -0
- reactifact/streaming.py +284 -1
- reactifact/subflow.py +142 -0
- reactifact/templates/__init__.py +0 -0
- reactifact/templates/daemon/.env.example +32 -0
- reactifact/templates/daemon/.gitignore +7 -0
- reactifact/templates/daemon/Dockerfile +12 -0
- reactifact/templates/daemon/README.md +47 -0
- reactifact/templates/daemon/app/__init__.py +0 -0
- reactifact/templates/daemon/app/config.py +96 -0
- reactifact/templates/daemon/app/llm.py +64 -0
- reactifact/templates/daemon/app/llm_presets.py +63 -0
- reactifact/templates/daemon/app/main.py +55 -0
- reactifact/templates/daemon/app/models.py +22 -0
- reactifact/templates/daemon/app/monitor.py +53 -0
- reactifact/templates/daemon/app/prompts.py +10 -0
- reactifact/templates/daemon/app/resources.py +19 -0
- reactifact/templates/daemon/app/runner.py +46 -0
- reactifact/templates/daemon/pyproject.toml +40 -0
- reactifact/templates/daemon/tests/__init__.py +0 -0
- reactifact/templates/daemon/tests/test_daemon.py +41 -0
- reactifact/templates/fastapi_chat/.env.example +60 -0
- reactifact/templates/fastapi_chat/.gitignore +7 -0
- reactifact/templates/fastapi_chat/Dockerfile +14 -0
- reactifact/templates/fastapi_chat/README.md +120 -0
- reactifact/templates/fastapi_chat/app/__init__.py +0 -0
- reactifact/templates/fastapi_chat/app/agent/__init__.py +0 -0
- reactifact/templates/fastapi_chat/app/agent/pipeline.py +83 -0
- reactifact/templates/fastapi_chat/app/agent/prompts.py +14 -0
- reactifact/templates/fastapi_chat/app/agent/resources.py +29 -0
- reactifact/templates/fastapi_chat/app/agent/steps/__init__.py +3 -0
- reactifact/templates/fastapi_chat/app/agent/steps/answer.py +35 -0
- reactifact/templates/fastapi_chat/app/api/__init__.py +0 -0
- reactifact/templates/fastapi_chat/app/api/deps.py +21 -0
- reactifact/templates/fastapi_chat/app/api/routes/__init__.py +0 -0
- reactifact/templates/fastapi_chat/app/api/routes/chat.py +86 -0
- reactifact/templates/fastapi_chat/app/authz.py +28 -0
- reactifact/templates/fastapi_chat/app/bootstrap.py +88 -0
- reactifact/templates/fastapi_chat/app/config.py +135 -0
- reactifact/templates/fastapi_chat/app/llm.py +60 -0
- reactifact/templates/fastapi_chat/app/llm_presets.py +63 -0
- reactifact/templates/fastapi_chat/app/main.py +71 -0
- reactifact/templates/fastapi_chat/app/models.py +33 -0
- reactifact/templates/fastapi_chat/app/security.py +74 -0
- reactifact/templates/fastapi_chat/pyproject.toml +48 -0
- reactifact/templates/fastapi_chat/tests/__init__.py +0 -0
- reactifact/templates/fastapi_chat/tests/conftest.py +32 -0
- reactifact/templates/fastapi_chat/tests/test_auth_sessions.py +36 -0
- reactifact/templates/fastapi_chat/tests/test_chat_sse.py +52 -0
- reactifact/templates/fastapi_chat/tests/test_settings.py +75 -0
- reactifact/tools/base.py +103 -24
- reactifact/tools/use/hitl.py +8 -15
- reactifact/tracing/_shared.py +3 -0
- reactifact/tracing/models.py +7 -0
- reactifact/tracing/postgres.py +48 -20
- reactifact/tracing/store.py +49 -20
- reactifact/tracing/tracer.py +278 -11
- reactifact/tracing/web.py +6 -1
- reactifact/validate.py +273 -0
- reactifact/viz.py +29 -25
- {reactifact-0.20.2.dist-info → reactifact-0.22.0.dist-info}/METADATA +112 -4
- {reactifact-0.20.2.dist-info → reactifact-0.22.0.dist-info}/RECORD +126 -43
- {reactifact-0.20.2.dist-info → reactifact-0.22.0.dist-info}/WHEEL +0 -0
- {reactifact-0.20.2.dist-info → reactifact-0.22.0.dist-info}/entry_points.txt +0 -0
- {reactifact-0.20.2.dist-info → reactifact-0.22.0.dist-info}/licenses/LICENSE +0 -0
- {reactifact-0.20.2.dist-info → reactifact-0.22.0.dist-info}/top_level.txt +0 -0
reactifact/__init__.py
CHANGED
|
@@ -25,9 +25,10 @@ from importlib.metadata import PackageNotFoundError as _PackageNotFoundError
|
|
|
25
25
|
from importlib.metadata import version as _distribution_version
|
|
26
26
|
|
|
27
27
|
from .agents import Agent, create_agent
|
|
28
|
-
from .artifacts import Artifact
|
|
28
|
+
from .artifacts import Artifact, ArtifactConflict
|
|
29
29
|
from .branching import MergeConflict
|
|
30
30
|
from .budget import Budget, BudgetTracker, RunOutcome, RunStats
|
|
31
|
+
from .commit import ContextCheckpoint
|
|
31
32
|
from .consume import Consume, consume
|
|
32
33
|
from .context import Context, View
|
|
33
34
|
from .effects import Effects, Handle
|
|
@@ -35,6 +36,10 @@ from .events import Event, EventType
|
|
|
35
36
|
from .interrupt import PendingAction, PendingQuestion
|
|
36
37
|
from .logging import bind, configure_logging, get_logger
|
|
37
38
|
from .patches import Create, Delete, Link, Patch, Relation, Unlink, Update
|
|
39
|
+
from .policy import RetryPolicy
|
|
40
|
+
|
|
41
|
+
# Deprecated 0.1.x aliases: importable for the compatibility window, but kept
|
|
42
|
+
# out of `__all__` (the public surface) until their removal.
|
|
38
43
|
from .produce import Produce, ProduceCall, produce
|
|
39
44
|
from .providers import (
|
|
40
45
|
EmbeddingProvider,
|
|
@@ -51,9 +56,16 @@ from .resources import ResourceKey, ResourceScope, RuntimeResources
|
|
|
51
56
|
from .runtime import Runtime
|
|
52
57
|
from .session import Session, SessionStore
|
|
53
58
|
from .step import Latest, Scope, Step, StepCall, Wakes, When, step
|
|
59
|
+
from .subflow import SubflowResult, run_subflow
|
|
54
60
|
from .tools import FunctionTool, Tool, ToolError, ToolOutput, tool
|
|
55
61
|
from .triggers import Trigger
|
|
56
62
|
from .types import register as register_type
|
|
63
|
+
from .validate import (
|
|
64
|
+
ValidationError,
|
|
65
|
+
ValidationIssue,
|
|
66
|
+
ValidationReport,
|
|
67
|
+
validate_agents,
|
|
68
|
+
)
|
|
57
69
|
|
|
58
70
|
try:
|
|
59
71
|
__version__ = _distribution_version("reactifact")
|
|
@@ -63,10 +75,12 @@ except _PackageNotFoundError: # source checkout without an installed distributi
|
|
|
63
75
|
__all__ = [
|
|
64
76
|
"Agent",
|
|
65
77
|
"Artifact",
|
|
78
|
+
"ArtifactConflict",
|
|
66
79
|
"Budget",
|
|
67
80
|
"BudgetTracker",
|
|
68
81
|
"Consume",
|
|
69
82
|
"Context",
|
|
83
|
+
"ContextCheckpoint",
|
|
70
84
|
"Create",
|
|
71
85
|
"Delete",
|
|
72
86
|
"EmbeddingProvider",
|
|
@@ -84,13 +98,13 @@ __all__ = [
|
|
|
84
98
|
"Patch",
|
|
85
99
|
"PendingAction",
|
|
86
100
|
"PendingQuestion",
|
|
87
|
-
"Produce",
|
|
88
|
-
"ProduceCall",
|
|
89
101
|
"Step",
|
|
90
102
|
"StepCall",
|
|
103
|
+
"SubflowResult",
|
|
91
104
|
"Relation",
|
|
92
105
|
"ResourceKey",
|
|
93
106
|
"ResourceScope",
|
|
107
|
+
"RetryPolicy",
|
|
94
108
|
"RunOutcome",
|
|
95
109
|
"RunStats",
|
|
96
110
|
"Scope",
|
|
@@ -108,6 +122,9 @@ __all__ = [
|
|
|
108
122
|
"Trigger",
|
|
109
123
|
"Unlink",
|
|
110
124
|
"Update",
|
|
125
|
+
"ValidationError",
|
|
126
|
+
"ValidationIssue",
|
|
127
|
+
"ValidationReport",
|
|
111
128
|
"View",
|
|
112
129
|
"Wakes",
|
|
113
130
|
"When",
|
|
@@ -117,8 +134,9 @@ __all__ = [
|
|
|
117
134
|
"create_agent",
|
|
118
135
|
"current_request",
|
|
119
136
|
"get_logger",
|
|
120
|
-
"produce",
|
|
121
137
|
"register_type",
|
|
138
|
+
"run_subflow",
|
|
122
139
|
"step",
|
|
123
140
|
"tool",
|
|
141
|
+
"validate_agents",
|
|
124
142
|
]
|
reactifact/a2a/remote.py
CHANGED
|
@@ -115,7 +115,7 @@ class A2ARemoteProduce(Step[Any]):
|
|
|
115
115
|
)
|
|
116
116
|
source = original.data if original is not None else data
|
|
117
117
|
result = await self._client.send(
|
|
118
|
-
data.
|
|
118
|
+
data.answer_text(),
|
|
119
119
|
task_id=notes.get("a2a_task_id"),
|
|
120
120
|
context_id=notes.get("a2a_context_id"),
|
|
121
121
|
)
|
reactifact/agents.py
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
from __future__ import annotations
|
|
2
2
|
|
|
3
|
+
import asyncio
|
|
3
4
|
import time
|
|
4
5
|
from abc import ABC
|
|
5
6
|
from collections.abc import Callable, Sequence
|
|
@@ -13,6 +14,7 @@ from .context import Context
|
|
|
13
14
|
from .effects import current_effects
|
|
14
15
|
from .events import Event, EventType
|
|
15
16
|
from .patches import Patch
|
|
17
|
+
from .policy import RetryPolicy
|
|
16
18
|
from .step import (
|
|
17
19
|
Step,
|
|
18
20
|
StepCall,
|
|
@@ -83,6 +85,12 @@ class Agent(ABC): # noqa: B024 — interface without abstract methods, run() ha
|
|
|
83
85
|
# the runtime default (max_concurrency). Use it to throttle LLM-bound
|
|
84
86
|
# producers (rate limits) independently of cheap I/O (file reads).
|
|
85
87
|
concurrency_limit: int | None = None
|
|
88
|
+
#: Retry policy for this agent's execution (class or instance level).
|
|
89
|
+
#: A retry gets a fresh `Effects` slot; only the successful patch commits.
|
|
90
|
+
retry: RetryPolicy | None = None
|
|
91
|
+
#: Hard per-execution deadline, in seconds. The runtime cancels the agent
|
|
92
|
+
#: when it passes; `asyncio.TimeoutError` then follows the retry policy.
|
|
93
|
+
timeout: float | None = None
|
|
86
94
|
#: Whether the runtime auto-schedules this agent from matching events.
|
|
87
95
|
#: `False` keeps it out of reactive scheduling (run it explicitly).
|
|
88
96
|
wakes: bool | Callable[[Event, Context | None], bool] = True
|
|
@@ -101,12 +109,24 @@ class Agent(ABC): # noqa: B024 — interface without abstract methods, run() ha
|
|
|
101
109
|
*,
|
|
102
110
|
steps: Sequence[Step[Any]] | None = None,
|
|
103
111
|
wakes: bool | Callable[[Event, Context | None], bool] | None = None,
|
|
112
|
+
retry: RetryPolicy | None = None,
|
|
113
|
+
timeout: float | None = None,
|
|
104
114
|
):
|
|
105
115
|
self.name = name or self.name or self.__class__.__name__
|
|
106
116
|
|
|
107
117
|
self.priority = (
|
|
108
118
|
priority if priority is not None else getattr(self.__class__, "priority", 0)
|
|
109
119
|
)
|
|
120
|
+
self.retry = (
|
|
121
|
+
retry if retry is not None else getattr(self.__class__, "retry", None)
|
|
122
|
+
)
|
|
123
|
+
self.timeout = (
|
|
124
|
+
timeout if timeout is not None else getattr(self.__class__, "timeout", None)
|
|
125
|
+
)
|
|
126
|
+
if self.retry is not None and not isinstance(self.retry, RetryPolicy):
|
|
127
|
+
raise TypeError("Agent.retry must be a RetryPolicy or None")
|
|
128
|
+
if self.timeout is not None and self.timeout <= 0:
|
|
129
|
+
raise ValueError("Agent.timeout must be > 0")
|
|
110
130
|
|
|
111
131
|
existing_steps = self.__dict__.get("steps")
|
|
112
132
|
existing_produces = self.__dict__.get("produces")
|
|
@@ -307,7 +327,11 @@ class Agent(ABC): # noqa: B024 — interface without abstract methods, run() ha
|
|
|
307
327
|
context_token = set_step_context(context)
|
|
308
328
|
call_token = set_step_call(call)
|
|
309
329
|
try:
|
|
310
|
-
|
|
330
|
+
if p.timeout is not None:
|
|
331
|
+
async with asyncio.timeout(p.timeout):
|
|
332
|
+
result = await invoke_step(p, call)
|
|
333
|
+
else:
|
|
334
|
+
result = await invoke_step(p, call)
|
|
311
335
|
p._apply_result(result, call.effects)
|
|
312
336
|
if trigger_cursor:
|
|
313
337
|
context._step_cursors[cursor_key] = trigger_cursor
|
|
@@ -392,6 +416,8 @@ def create_agent(
|
|
|
392
416
|
concurrency_limit: int | None = None,
|
|
393
417
|
triggers: list[Trigger] | None = None,
|
|
394
418
|
wakes: bool | Callable[[Event, Context | None], bool] = True,
|
|
419
|
+
retry: RetryPolicy | None = None,
|
|
420
|
+
timeout: float | None = None,
|
|
395
421
|
) -> Agent:
|
|
396
422
|
"""Builds an Agent instance without subclassing.
|
|
397
423
|
|
|
@@ -423,6 +449,8 @@ def create_agent(
|
|
|
423
449
|
priority=priority,
|
|
424
450
|
steps=resolved_steps,
|
|
425
451
|
wakes=wakes,
|
|
452
|
+
retry=retry,
|
|
453
|
+
timeout=timeout,
|
|
426
454
|
)
|
|
427
455
|
if consumes is not None:
|
|
428
456
|
agent.consumes = consumes
|
reactifact/artifacts.py
CHANGED
|
@@ -36,6 +36,26 @@ def blob_key(data_type: str, content_hash: str) -> str:
|
|
|
36
36
|
return f"{data_type}:{content_hash}"
|
|
37
37
|
|
|
38
38
|
|
|
39
|
+
class ArtifactConflict(RuntimeError):
|
|
40
|
+
"""An optimistic-concurrency update expected a different artifact version.
|
|
41
|
+
|
|
42
|
+
Raised by `effects.update(..., expected_version=...)`, `Context.update`, or
|
|
43
|
+
the runtime before a commit when a patch would overwrite a version another
|
|
44
|
+
writer already moved. The runtime validates the whole generation first, so
|
|
45
|
+
no patch from that generation is applied.
|
|
46
|
+
"""
|
|
47
|
+
|
|
48
|
+
def __init__(self, artifact_id: str, expected: int, actual: int | None) -> None:
|
|
49
|
+
self.artifact_id = artifact_id
|
|
50
|
+
self.expected = expected
|
|
51
|
+
self.actual = actual
|
|
52
|
+
actual_text = actual if actual is not None else "absent"
|
|
53
|
+
super().__init__(
|
|
54
|
+
f"artifact {artifact_id!r} version conflict: expected {expected}, "
|
|
55
|
+
f"actual {actual_text}"
|
|
56
|
+
)
|
|
57
|
+
|
|
58
|
+
|
|
39
59
|
@dataclass(frozen=True)
|
|
40
60
|
class ArtifactVersion:
|
|
41
61
|
"""One immutable artifact revision, addressed by content hash.
|
reactifact/branching/__init__.py
CHANGED
|
@@ -2,6 +2,7 @@
|
|
|
2
2
|
|
|
3
3
|
from .ops import (
|
|
4
4
|
MergeConflict,
|
|
5
|
+
MergePolicy,
|
|
5
6
|
clone_context,
|
|
6
7
|
fork_context,
|
|
7
8
|
merge_context_from,
|
|
@@ -12,6 +13,7 @@ from .store import BranchStore
|
|
|
12
13
|
__all__ = [
|
|
13
14
|
"BranchStore",
|
|
14
15
|
"MergeConflict",
|
|
16
|
+
"MergePolicy",
|
|
15
17
|
"clone_context",
|
|
16
18
|
"fork_context",
|
|
17
19
|
"merge_context_from",
|
reactifact/branching/ops.py
CHANGED
|
@@ -25,6 +25,7 @@ backend (matching the constitution: semantics live in Context operations).
|
|
|
25
25
|
|
|
26
26
|
from __future__ import annotations
|
|
27
27
|
|
|
28
|
+
from collections.abc import Callable, Mapping
|
|
28
29
|
from typing import TYPE_CHECKING, Any
|
|
29
30
|
|
|
30
31
|
from pydantic import BaseModel
|
|
@@ -50,6 +51,12 @@ class MergeConflict(Exception):
|
|
|
50
51
|
self.conflicts = conflicts or []
|
|
51
52
|
|
|
52
53
|
|
|
54
|
+
#: Resolves a diverged artifact in `Context.merge`: given the target and the
|
|
55
|
+
#: incoming data, return the merged data (same model type). Opt-in, per type;
|
|
56
|
+
#: without a policy the merge stays fail-loud with `MergeConflict`.
|
|
57
|
+
MergePolicy = Callable[[Any, Any], BaseModel]
|
|
58
|
+
|
|
59
|
+
|
|
53
60
|
def clone_context(source: Context) -> Context:
|
|
54
61
|
"""Deep copy of `source`'s live state (artifacts, log, relations)."""
|
|
55
62
|
new_ws = source.__class__()
|
|
@@ -142,7 +149,11 @@ def _kind_short(signature: Any) -> str:
|
|
|
142
149
|
|
|
143
150
|
|
|
144
151
|
def merge_contexts(
|
|
145
|
-
target: Context,
|
|
152
|
+
target: Context,
|
|
153
|
+
other: Context,
|
|
154
|
+
*,
|
|
155
|
+
message: str = "Merged branch",
|
|
156
|
+
policies: Mapping[type[BaseModel], MergePolicy] | None = None,
|
|
146
157
|
) -> None:
|
|
147
158
|
"""Merges `other` into `target` with explicit conflicts, atomically (§40).
|
|
148
159
|
|
|
@@ -157,6 +168,9 @@ def merge_contexts(
|
|
|
157
168
|
|
|
158
169
|
So a change adopted from `other` never silently overwrites a change made
|
|
159
170
|
on `target` since the fork (§40: the framework must not choose silently).
|
|
171
|
+
`policies` can opt a specific model type into a deterministic resolution:
|
|
172
|
+
the callable receives `(target_data, other_data)` and returns merged data of
|
|
173
|
+
the same type; a policy that raises or returns a wrong type still fails.
|
|
160
174
|
"""
|
|
161
175
|
base = other._base if other._base is not None else target._base
|
|
162
176
|
if base is None:
|
|
@@ -204,10 +218,28 @@ def merge_contexts(
|
|
|
204
218
|
else Update(artifact_id, other_art.data)
|
|
205
219
|
)
|
|
206
220
|
else:
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
221
|
+
policy = None
|
|
222
|
+
if (
|
|
223
|
+
policies is not None
|
|
224
|
+
and target_art is not None
|
|
225
|
+
and other_art is not None
|
|
226
|
+
):
|
|
227
|
+
policy = policies.get(type(target_art.data))
|
|
228
|
+
if policy is not None:
|
|
229
|
+
assert target_art is not None and other_art is not None
|
|
230
|
+
merged = policy(target_art.data, other_art.data)
|
|
231
|
+
if not isinstance(merged, type(target_art.data)):
|
|
232
|
+
raise TypeError(
|
|
233
|
+
f"merge policy for {type(target_art.data).__name__} "
|
|
234
|
+
f"returned {type(merged).__name__}"
|
|
235
|
+
)
|
|
236
|
+
pending[artifact_id] = merged
|
|
237
|
+
operations.append(Update(artifact_id, merged))
|
|
238
|
+
else:
|
|
239
|
+
conflicts.append(
|
|
240
|
+
f"{artifact_id} diverged since the fork "
|
|
241
|
+
f"(target={_kind_short(st)}, other={_kind_short(so)})"
|
|
242
|
+
)
|
|
211
243
|
|
|
212
244
|
if conflicts:
|
|
213
245
|
raise MergeConflict(
|
|
@@ -258,6 +290,7 @@ def merge_contexts(
|
|
|
258
290
|
|
|
259
291
|
__all__ = [
|
|
260
292
|
"MergeConflict",
|
|
293
|
+
"MergePolicy",
|
|
261
294
|
"clone_context",
|
|
262
295
|
"fork_context",
|
|
263
296
|
"merge_context_from",
|
reactifact/chat.py
CHANGED
|
@@ -217,18 +217,22 @@ def _accepts_arg(func: Callable[..., Any], count: int) -> bool:
|
|
|
217
217
|
return len(params) >= count
|
|
218
218
|
|
|
219
219
|
|
|
220
|
-
def _resolve_with_session(
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
220
|
+
def _resolve_with_session(
|
|
221
|
+
value: Any,
|
|
222
|
+
session_id: str,
|
|
223
|
+
request: Mapping[str, Any] | None = None,
|
|
224
|
+
) -> Any:
|
|
225
|
+
"""Like `_resolve`, but passes `session_id` (and optionally `request`) when
|
|
226
|
+
the factory declares the extra parameters — the per-request resource shape
|
|
227
|
+
(`resources=lambda session_id, request: build_resources(...)`) alongside
|
|
228
|
+
the pre-existing one-arg (`resources=lambda session_id: ...`) and zero-arg
|
|
229
|
+
forms, which keep working unchanged. `ChatAssistant` already knows the
|
|
230
|
+
session and turn request at this point; a factory can opt into either.
|
|
229
231
|
"""
|
|
230
232
|
if not callable(value):
|
|
231
233
|
return value
|
|
234
|
+
if _accepts_arg(value, 2):
|
|
235
|
+
return value(session_id, request or {})
|
|
232
236
|
return value(session_id) if _accepts_arg(value, 1) else value()
|
|
233
237
|
|
|
234
238
|
|
|
@@ -461,14 +465,26 @@ class ChatAssistant:
|
|
|
461
465
|
self._lock_refs.pop(session_id, None)
|
|
462
466
|
self._session_locks.pop(session_id, None)
|
|
463
467
|
|
|
464
|
-
async def _open(
|
|
465
|
-
|
|
468
|
+
async def _open(
|
|
469
|
+
self,
|
|
470
|
+
session_id: str,
|
|
471
|
+
request: Mapping[str, Any] | None = None,
|
|
472
|
+
*,
|
|
473
|
+
build_resources: bool = True,
|
|
474
|
+
) -> Session:
|
|
475
|
+
resources: RuntimeResources | None = None
|
|
476
|
+
if build_resources:
|
|
477
|
+
resources = _resolve_with_session(self._resources, session_id, request)
|
|
478
|
+
elif not callable(self._resources):
|
|
479
|
+
# A shared instance is harmless to attach; a per-turn factory is
|
|
480
|
+
# deliberately not invoked for a read-only open (history()).
|
|
481
|
+
resources = self._resources
|
|
466
482
|
try:
|
|
467
483
|
return await self.store.open(session_id, resources=resources)
|
|
468
484
|
except Exception:
|
|
469
485
|
# A callable `resources=` built a fresh per-turn instance; if the
|
|
470
486
|
# store fails to open the session nothing else will close it.
|
|
471
|
-
if callable(self._resources):
|
|
487
|
+
if build_resources and callable(self._resources) and resources is not None:
|
|
472
488
|
with suppress(Exception):
|
|
473
489
|
await resources.aclose()
|
|
474
490
|
raise
|
|
@@ -560,7 +576,7 @@ class ChatAssistant:
|
|
|
560
576
|
async with self._locked_session(session_id):
|
|
561
577
|
session: Session | None = None
|
|
562
578
|
try:
|
|
563
|
-
session = await self._open(session_id)
|
|
579
|
+
session = await self._open(session_id, request)
|
|
564
580
|
runtime = self._build_runtime(session)
|
|
565
581
|
except Exception:
|
|
566
582
|
logger.exception(
|
|
@@ -631,9 +647,15 @@ class ChatAssistant:
|
|
|
631
647
|
return message
|
|
632
648
|
|
|
633
649
|
async def history(self, session_id: str = "") -> dict[str, Any]:
|
|
634
|
-
"""Reconstruct the chat thread of a persisted session.
|
|
650
|
+
"""Reconstruct the chat thread of a persisted session.
|
|
651
|
+
|
|
652
|
+
Read-only: a per-turn `resources=` factory is not invoked (no provider
|
|
653
|
+
or user scope is built just to read artifacts). A shared
|
|
654
|
+
`RuntimeResources` instance is attached as usual, so a custom
|
|
655
|
+
`session_state` can still read it.
|
|
656
|
+
"""
|
|
635
657
|
try:
|
|
636
|
-
session = await self._open(session_id)
|
|
658
|
+
session = await self._open(session_id, build_resources=False)
|
|
637
659
|
except Exception:
|
|
638
660
|
logger.exception("chat.ChatAssistant: history open failed %r", session_id)
|
|
639
661
|
return {"messages": []}
|
reactifact/cli/__init__.py
CHANGED
|
@@ -2,6 +2,8 @@
|
|
|
2
2
|
|
|
3
3
|
Subcommands:
|
|
4
4
|
|
|
5
|
+
new create a project (FastAPI chat or scheduled daemon)
|
|
6
|
+
doctor check app settings and common boundaries
|
|
5
7
|
graph static agent blueprint from a module path ("pkg.mod:Attr")
|
|
6
8
|
context live provenance graph from a saved session (KV backend)
|
|
7
9
|
trace run diagram from a trace store (SQLite)
|
|
@@ -13,13 +15,16 @@ Subcommands:
|
|
|
13
15
|
|
|
14
16
|
Examples:
|
|
15
17
|
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
18
|
+
reactifact new app my-app
|
|
19
|
+
reactifact new daemon my-worker
|
|
20
|
+
reactifact doctor
|
|
21
|
+
reactifact graph examples.knowledge.agents
|
|
22
|
+
reactifact context examples/knowledge/sessions/traces.sqlite3
|
|
23
|
+
reactifact trace traces.db
|
|
24
|
+
reactifact skills install --target both
|
|
20
25
|
|
|
21
|
-
|
|
22
|
-
mermaid.live.
|
|
26
|
+
Inspection commands print Mermaid source to stdout — paste it into GitHub,
|
|
27
|
+
Notion or mermaid.live.
|
|
23
28
|
"""
|
|
24
29
|
|
|
25
30
|
from __future__ import annotations
|
|
@@ -28,7 +33,7 @@ import argparse
|
|
|
28
33
|
import sys
|
|
29
34
|
|
|
30
35
|
from .. import __version__
|
|
31
|
-
from . import branch, context, eval, graph, replay, scenario, skills, trace
|
|
36
|
+
from . import branch, context, doctor, eval, graph, new, replay, scenario, skills, trace
|
|
32
37
|
|
|
33
38
|
|
|
34
39
|
def build_parser() -> argparse.ArgumentParser:
|
|
@@ -44,7 +49,18 @@ def build_parser() -> argparse.ArgumentParser:
|
|
|
44
49
|
)
|
|
45
50
|
sub = parser.add_subparsers(dest="command")
|
|
46
51
|
|
|
47
|
-
for module in (
|
|
52
|
+
for module in (
|
|
53
|
+
graph,
|
|
54
|
+
context,
|
|
55
|
+
trace,
|
|
56
|
+
replay,
|
|
57
|
+
branch,
|
|
58
|
+
scenario,
|
|
59
|
+
skills,
|
|
60
|
+
eval,
|
|
61
|
+
new,
|
|
62
|
+
doctor,
|
|
63
|
+
):
|
|
48
64
|
module.add_parser(sub)
|
|
49
65
|
|
|
50
66
|
return parser
|
|
@@ -62,17 +78,24 @@ def main(argv: list[str] | None = None) -> int:
|
|
|
62
78
|
f"reactifact {__version__} — inspect & visualize agents, contexts and"
|
|
63
79
|
" traces as Mermaid.\n"
|
|
64
80
|
)
|
|
65
|
-
print("
|
|
81
|
+
print("Start here:")
|
|
82
|
+
print(" reactifact new app <dir> FastAPI chat template")
|
|
83
|
+
print(" reactifact new daemon <dir> scheduled agent loop")
|
|
84
|
+
print(" reactifact doctor check an app's settings")
|
|
85
|
+
print(" reactifact skills install add agent skills to your project\n")
|
|
86
|
+
print("Inspect a run:")
|
|
66
87
|
print(" reactifact graph <module:Agent> static blueprint")
|
|
67
|
-
print(" reactifact trace <trace.db> run diagram")
|
|
88
|
+
print(" reactifact trace <trace.db> run diagram\n")
|
|
89
|
+
print("Advanced:")
|
|
68
90
|
print(" reactifact context <sessions.sqlite3> live provenance graph")
|
|
69
91
|
print(" reactifact replay <sessions.sqlite3> deterministic replay")
|
|
70
92
|
print(" reactifact branch <path> <session> <action> persistent forks")
|
|
71
|
-
print(" reactifact scenario <module> run reactifact.testing scenarios
|
|
72
|
-
print(" reactifact skills install add agent skills to your project\n")
|
|
93
|
+
print(" reactifact scenario <module> run reactifact.testing scenarios")
|
|
73
94
|
print(" reactifact eval <traces.db> online-evaluate finished runs\n")
|
|
74
|
-
print("
|
|
75
|
-
print(" uv
|
|
95
|
+
print("Install into an app:")
|
|
96
|
+
print(" uv add reactifact core + CLI")
|
|
97
|
+
print(" uv add 'reactifact[web]' + FastAPI/uvicorn")
|
|
98
|
+
print("Run 'reactifact <command> --help' for details.")
|
|
76
99
|
parser.print_help()
|
|
77
100
|
return 0
|
|
78
101
|
return int(args.func(args))
|
reactifact/cli/doctor.py
ADDED
|
@@ -0,0 +1,159 @@
|
|
|
1
|
+
"""`reactifact doctor` — configuration and common-boundary checks.
|
|
2
|
+
|
|
3
|
+
It is advisory by design: it inspects a settings/app factory by duck typing and
|
|
4
|
+
scans the project for a few common mistakes. It never starts the server.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import argparse
|
|
10
|
+
import importlib
|
|
11
|
+
import inspect
|
|
12
|
+
import os
|
|
13
|
+
from collections.abc import Iterator
|
|
14
|
+
from dataclasses import dataclass
|
|
15
|
+
from pathlib import Path
|
|
16
|
+
from typing import Any
|
|
17
|
+
|
|
18
|
+
_DEFAULTS = "app.config:get_settings"
|
|
19
|
+
_SKIP_DIRS = {
|
|
20
|
+
".git",
|
|
21
|
+
".venv",
|
|
22
|
+
"__pycache__",
|
|
23
|
+
".mypy_cache",
|
|
24
|
+
".pytest_cache",
|
|
25
|
+
".ruff_cache",
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
@dataclass
|
|
30
|
+
class Finding:
|
|
31
|
+
level: str # "OK" | "WARN" | "ERROR"
|
|
32
|
+
message: str
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def _is_set(value: Any) -> bool:
|
|
36
|
+
if value is None:
|
|
37
|
+
return False
|
|
38
|
+
if hasattr(value, "get_secret_value"):
|
|
39
|
+
return bool(value.get_secret_value())
|
|
40
|
+
return bool(str(value))
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def _load_target(spec: str) -> Any:
|
|
44
|
+
module_name, _, attr = spec.partition(":")
|
|
45
|
+
module = importlib.import_module(module_name)
|
|
46
|
+
target = getattr(module, attr) if attr else module
|
|
47
|
+
if callable(target) and not inspect.signature(target).parameters:
|
|
48
|
+
target = target()
|
|
49
|
+
state = getattr(target, "state", None)
|
|
50
|
+
if state is not None and hasattr(state, "settings"):
|
|
51
|
+
return state.settings
|
|
52
|
+
return target
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def _py_files(root: Path) -> Iterator[Path]:
|
|
56
|
+
for path in root.rglob("*.py"):
|
|
57
|
+
if any(part in _SKIP_DIRS for part in path.parts):
|
|
58
|
+
continue
|
|
59
|
+
yield path
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def check_settings(settings: Any, *, root: Path) -> list[Finding]:
|
|
63
|
+
findings: list[Finding] = []
|
|
64
|
+
|
|
65
|
+
def add(level: str, message: str) -> None:
|
|
66
|
+
findings.append(Finding(level, message))
|
|
67
|
+
|
|
68
|
+
env = getattr(settings, "env", "dev")
|
|
69
|
+
auth = getattr(settings, "auth_token", None)
|
|
70
|
+
if not _is_set(auth):
|
|
71
|
+
add("ERROR", "auth token is not configured (fail-closed web app)")
|
|
72
|
+
else:
|
|
73
|
+
add("OK", "auth token is configured")
|
|
74
|
+
|
|
75
|
+
session_backend = getattr(settings, "session_backend", None)
|
|
76
|
+
if env == "prod" and session_backend == "memory":
|
|
77
|
+
add("ERROR", "session_backend=memory is not allowed in prod")
|
|
78
|
+
elif session_backend:
|
|
79
|
+
add("OK", f"session backend: {session_backend}")
|
|
80
|
+
|
|
81
|
+
trace_backend = getattr(settings, "trace_backend", None)
|
|
82
|
+
if env == "prod" and trace_backend in {None, "memory"}:
|
|
83
|
+
add("ERROR", "trace store must be persistent in prod")
|
|
84
|
+
elif trace_backend:
|
|
85
|
+
add("OK", f"trace backend: {trace_backend}")
|
|
86
|
+
|
|
87
|
+
provider = str(getattr(settings, "llm_provider", "none"))
|
|
88
|
+
model = getattr(settings, "llm_model", None)
|
|
89
|
+
if provider == "none":
|
|
90
|
+
add("OK", "llm_provider=none (offline/fallback mode)")
|
|
91
|
+
elif not model:
|
|
92
|
+
add("ERROR", f"llm_provider={provider!r} but no llm_model")
|
|
93
|
+
else:
|
|
94
|
+
add("OK", f"llm: {provider} / {model}")
|
|
95
|
+
key_env = getattr(settings, "llm_api_key_env", None)
|
|
96
|
+
if key_env and not os.getenv(str(key_env)):
|
|
97
|
+
add("ERROR", f"{key_env} is not set")
|
|
98
|
+
|
|
99
|
+
budget_values = [
|
|
100
|
+
getattr(settings, f"budget_max_{name}", None)
|
|
101
|
+
for name in ("runs", "iterations", "seconds", "tool_calls", "tokens", "cost")
|
|
102
|
+
]
|
|
103
|
+
if not any(value is not None for value in budget_values):
|
|
104
|
+
add("WARN", "no budget limits configured")
|
|
105
|
+
else:
|
|
106
|
+
add("OK", "budget limits configured")
|
|
107
|
+
|
|
108
|
+
if (
|
|
109
|
+
getattr(settings, "chat_memory_keep", None) is None
|
|
110
|
+
and getattr(settings, "chat_memory_commits", None) is None
|
|
111
|
+
):
|
|
112
|
+
add("WARN", "chat history is unbounded (no ChatMemory policy)")
|
|
113
|
+
|
|
114
|
+
sources = list(_py_files(root))
|
|
115
|
+
if sources:
|
|
116
|
+
text = "\n".join(path.read_text(errors="ignore") for path in sources)
|
|
117
|
+
if "scope_session" not in text and "session_key" not in text:
|
|
118
|
+
add(
|
|
119
|
+
"WARN",
|
|
120
|
+
"no session scoping helper found (client id may be a storage key)",
|
|
121
|
+
)
|
|
122
|
+
if "lifespan" not in text and "aclose" not in text:
|
|
123
|
+
add("WARN", "no lifespan/resource cleanup found")
|
|
124
|
+
if "@produce" in text or "Produce" in text:
|
|
125
|
+
add("WARN", "deprecated Produce/@produce usage found")
|
|
126
|
+
|
|
127
|
+
return findings
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
def cmd_doctor(args: argparse.Namespace) -> int:
|
|
131
|
+
try:
|
|
132
|
+
target = _load_target(args.target)
|
|
133
|
+
except Exception as exc: # noqa: BLE001 - a doctor reports, it does not raise
|
|
134
|
+
print(f"reactifact doctor: cannot load {args.target!r}: {exc}")
|
|
135
|
+
return 1
|
|
136
|
+
|
|
137
|
+
findings = check_settings(target, root=Path(args.path).expanduser().resolve())
|
|
138
|
+
print(f"reactifact doctor — {args.target}")
|
|
139
|
+
for finding in findings:
|
|
140
|
+
print(f" {finding.level:<5} {finding.message}")
|
|
141
|
+
errors = sum(finding.level == "ERROR" for finding in findings)
|
|
142
|
+
warnings = sum(finding.level == "WARN" for finding in findings)
|
|
143
|
+
print(f"\n{errors} error(s), {warnings} warning(s)")
|
|
144
|
+
return 1 if errors else 0
|
|
145
|
+
|
|
146
|
+
|
|
147
|
+
def add_parser(sub: argparse._SubParsersAction[argparse.ArgumentParser]) -> None:
|
|
148
|
+
p = sub.add_parser("doctor", help="check app settings and common boundaries")
|
|
149
|
+
p.add_argument(
|
|
150
|
+
"target",
|
|
151
|
+
nargs="?",
|
|
152
|
+
default=_DEFAULTS,
|
|
153
|
+
help=f"module:factory (default: {_DEFAULTS})",
|
|
154
|
+
)
|
|
155
|
+
p.add_argument("--path", default=".", help="project directory to scan")
|
|
156
|
+
p.set_defaults(func=cmd_doctor)
|
|
157
|
+
|
|
158
|
+
|
|
159
|
+
__all__ = ["Finding", "add_parser", "check_settings"]
|