margin-core 0.1.1__tar.gz → 0.1.2__tar.gz
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.
- {margin_core-0.1.1 → margin_core-0.1.2}/.gitignore +2 -0
- {margin_core-0.1.1 → margin_core-0.1.2}/CHANGELOG.md +14 -0
- {margin_core-0.1.1 → margin_core-0.1.2}/PKG-INFO +1 -1
- {margin_core-0.1.1 → margin_core-0.1.2}/pyproject.toml +1 -1
- {margin_core-0.1.1 → margin_core-0.1.2}/src/margin_core/__init__.py +21 -2
- {margin_core-0.1.1 → margin_core-0.1.2}/src/margin_core/agent.py +88 -4
- {margin_core-0.1.1 → margin_core-0.1.2}/src/margin_core/errors.py +4 -0
- margin_core-0.1.2/src/margin_core/models.py +321 -0
- {margin_core-0.1.1 → margin_core-0.1.2}/src/margin_core/reporting/markdown_report.py +9 -0
- {margin_core-0.1.1 → margin_core-0.1.2}/tests/test_core_skeleton.py +1 -1
- margin_core-0.1.2/tests/test_questions.py +257 -0
- margin_core-0.1.1/src/margin_core/models.py +0 -130
- {margin_core-0.1.1 → margin_core-0.1.2}/LICENSE +0 -0
- {margin_core-0.1.1 → margin_core-0.1.2}/README.md +0 -0
- {margin_core-0.1.1 → margin_core-0.1.2}/src/margin_core/_fs.py +0 -0
- {margin_core-0.1.1 → margin_core-0.1.2}/src/margin_core/config.py +0 -0
- {margin_core-0.1.1 → margin_core-0.1.2}/src/margin_core/inputs.py +0 -0
- {margin_core-0.1.1 → margin_core-0.1.2}/src/margin_core/llm/__init__.py +0 -0
- {margin_core-0.1.1 → margin_core-0.1.2}/src/margin_core/llm/_chat_completions.py +0 -0
- {margin_core-0.1.1 → margin_core-0.1.2}/src/margin_core/llm/_http.py +0 -0
- {margin_core-0.1.1 → margin_core-0.1.2}/src/margin_core/llm/anthropic.py +0 -0
- {margin_core-0.1.1 → margin_core-0.1.2}/src/margin_core/llm/base.py +0 -0
- {margin_core-0.1.1 → margin_core-0.1.2}/src/margin_core/llm/catalog.py +0 -0
- {margin_core-0.1.1 → margin_core-0.1.2}/src/margin_core/llm/factory.py +0 -0
- {margin_core-0.1.1 → margin_core-0.1.2}/src/margin_core/llm/local.py +0 -0
- {margin_core-0.1.1 → margin_core-0.1.2}/src/margin_core/llm/mock.py +0 -0
- {margin_core-0.1.1 → margin_core-0.1.2}/src/margin_core/llm/openai.py +0 -0
- {margin_core-0.1.1 → margin_core-0.1.2}/src/margin_core/llm/pricing.py +0 -0
- {margin_core-0.1.1 → margin_core-0.1.2}/src/margin_core/loaders/__init__.py +0 -0
- {margin_core-0.1.1 → margin_core-0.1.2}/src/margin_core/loaders/base.py +0 -0
- {margin_core-0.1.1 → margin_core-0.1.2}/src/margin_core/loaders/filters.py +0 -0
- {margin_core-0.1.1 → margin_core-0.1.2}/src/margin_core/loaders/git.py +0 -0
- {margin_core-0.1.1 → margin_core-0.1.2}/src/margin_core/loaders/github.py +0 -0
- {margin_core-0.1.1 → margin_core-0.1.2}/src/margin_core/loaders/local.py +0 -0
- {margin_core-0.1.1 → margin_core-0.1.2}/src/margin_core/logging.py +0 -0
- {margin_core-0.1.1 → margin_core-0.1.2}/src/margin_core/py.typed +0 -0
- {margin_core-0.1.1 → margin_core-0.1.2}/src/margin_core/registry.py +0 -0
- {margin_core-0.1.1 → margin_core-0.1.2}/src/margin_core/reporting/__init__.py +0 -0
- {margin_core-0.1.1 → margin_core-0.1.2}/src/margin_core/reporting/json_report.py +0 -0
- {margin_core-0.1.1 → margin_core-0.1.2}/src/margin_core/runner.py +0 -0
- {margin_core-0.1.1 → margin_core-0.1.2}/tests/conftest.py +0 -0
- {margin_core-0.1.1 → margin_core-0.1.2}/tests/test_agent.py +0 -0
- {margin_core-0.1.1 → margin_core-0.1.2}/tests/test_config.py +0 -0
- {margin_core-0.1.1 → margin_core-0.1.2}/tests/test_filters.py +0 -0
- {margin_core-0.1.1 → margin_core-0.1.2}/tests/test_github_loader.py +0 -0
- {margin_core-0.1.1 → margin_core-0.1.2}/tests/test_history_scope.py +0 -0
- {margin_core-0.1.1 → margin_core-0.1.2}/tests/test_inputs.py +0 -0
- {margin_core-0.1.1 → margin_core-0.1.2}/tests/test_llm.py +0 -0
- {margin_core-0.1.1 → margin_core-0.1.2}/tests/test_llm_session.py +0 -0
- {margin_core-0.1.1 → margin_core-0.1.2}/tests/test_local_llm.py +0 -0
- {margin_core-0.1.1 → margin_core-0.1.2}/tests/test_local_loader.py +0 -0
- {margin_core-0.1.1 → margin_core-0.1.2}/tests/test_models.py +0 -0
- {margin_core-0.1.1 → margin_core-0.1.2}/tests/test_preclone_check.py +0 -0
- {margin_core-0.1.1 → margin_core-0.1.2}/tests/test_registry.py +0 -0
- {margin_core-0.1.1 → margin_core-0.1.2}/tests/test_reporting.py +0 -0
- {margin_core-0.1.1 → margin_core-0.1.2}/tests/test_security.py +0 -0
- {margin_core-0.1.1 → margin_core-0.1.2}/tests/test_user_settings.py +0 -0
|
@@ -75,6 +75,8 @@ tmp/
|
|
|
75
75
|
|
|
76
76
|
# Private planning notes (kept locally, not published)
|
|
77
77
|
PLAN.md
|
|
78
|
+
# notes for Claude Code sessions; a CLAUDE.md in the repo is one of the detector's markers
|
|
79
|
+
CLAUDE.md
|
|
78
80
|
|
|
79
81
|
# the web UI bundled into margin-api at release time (scripts/build_release.py)
|
|
80
82
|
packages/api/src/margin_api/ui/
|
|
@@ -4,6 +4,20 @@ All notable changes to this package are documented here. The format follows
|
|
|
4
4
|
[Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and versions follow
|
|
5
5
|
[Semantic Versioning](https://semver.org/).
|
|
6
6
|
|
|
7
|
+
## [0.1.2] - 2026-10-29
|
|
8
|
+
|
|
9
|
+
### Added
|
|
10
|
+
- Agents can ask the person running them: `await ctx.ask(questions, title=...)` puts one or
|
|
11
|
+
more `Question`s (choice, multiple choice or text, with a default and evidence) to whoever
|
|
12
|
+
runs the agent and returns the answers. `RunContext(responder=...)` decides how they are
|
|
13
|
+
asked; without a responder, questions take their defaults.
|
|
14
|
+
- `AnswersInput`: a base input model with the standard `answers` (given up front, not asked)
|
|
15
|
+
and `assume_defaults` fields.
|
|
16
|
+
- `RunMetadata.answers` keeps every answer and who gave it (`user`, `preset` or `default`).
|
|
17
|
+
Defaults nobody confirmed are also reported as warnings. The Markdown report lists the
|
|
18
|
+
answers.
|
|
19
|
+
- `NoAnswerError` for a question that could not be answered.
|
|
20
|
+
|
|
7
21
|
## [0.1.1] - 2026-10-21
|
|
8
22
|
|
|
9
23
|
### Security
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.5
|
|
2
2
|
Name: margin-core
|
|
3
|
-
Version: 0.1.
|
|
3
|
+
Version: 0.1.2
|
|
4
4
|
Summary: The shared core of margin: the agent contract, results with evidence, model clients and code loaders.
|
|
5
5
|
Project-URL: Homepage, https://github.com/Waddah0-0/margin
|
|
6
6
|
Project-URL: Source, https://github.com/Waddah0-0/margin/tree/main/packages/core
|
|
@@ -6,7 +6,13 @@ Public API::
|
|
|
6
6
|
from margin_core import run_agent, list_agents, get_agent
|
|
7
7
|
"""
|
|
8
8
|
|
|
9
|
-
from margin_core.agent import
|
|
9
|
+
from margin_core.agent import (
|
|
10
|
+
BaseAgent,
|
|
11
|
+
CancellationToken,
|
|
12
|
+
ProgressCallback,
|
|
13
|
+
Responder,
|
|
14
|
+
RunContext,
|
|
15
|
+
)
|
|
10
16
|
from margin_core.errors import (
|
|
11
17
|
AgentLoadError,
|
|
12
18
|
AgentNotFoundError,
|
|
@@ -17,6 +23,7 @@ from margin_core.errors import (
|
|
|
17
23
|
LimitExceededError,
|
|
18
24
|
LLMError,
|
|
19
25
|
LoaderError,
|
|
26
|
+
NoAnswerError,
|
|
20
27
|
RunCancelledError,
|
|
21
28
|
TransientLLMError,
|
|
22
29
|
)
|
|
@@ -24,16 +31,21 @@ from margin_core.models import (
|
|
|
24
31
|
AgentInfo,
|
|
25
32
|
AgentInput,
|
|
26
33
|
AgentResult,
|
|
34
|
+
Answer,
|
|
35
|
+
AnswersInput,
|
|
36
|
+
Choice,
|
|
27
37
|
Evidence,
|
|
28
38
|
Finding,
|
|
29
39
|
ProgressEvent,
|
|
40
|
+
Question,
|
|
41
|
+
QuestionBatch,
|
|
30
42
|
RunMetadata,
|
|
31
43
|
TokenUsage,
|
|
32
44
|
)
|
|
33
45
|
from margin_core.registry import AgentRegistry, default_registry, get_agent, list_agents
|
|
34
46
|
from margin_core.runner import run_agent
|
|
35
47
|
|
|
36
|
-
__version__ = "0.1.
|
|
48
|
+
__version__ = "0.1.2"
|
|
37
49
|
|
|
38
50
|
__all__ = [
|
|
39
51
|
"AgentInfo",
|
|
@@ -43,9 +55,12 @@ __all__ = [
|
|
|
43
55
|
"AgentRegistry",
|
|
44
56
|
"AgentResult",
|
|
45
57
|
"AgentsLibError",
|
|
58
|
+
"Answer",
|
|
59
|
+
"AnswersInput",
|
|
46
60
|
"BaseAgent",
|
|
47
61
|
"BudgetExceededError",
|
|
48
62
|
"CancellationToken",
|
|
63
|
+
"Choice",
|
|
49
64
|
"Evidence",
|
|
50
65
|
"Finding",
|
|
51
66
|
"InputValidationError",
|
|
@@ -53,8 +68,12 @@ __all__ = [
|
|
|
53
68
|
"LLMError",
|
|
54
69
|
"LimitExceededError",
|
|
55
70
|
"LoaderError",
|
|
71
|
+
"NoAnswerError",
|
|
56
72
|
"ProgressCallback",
|
|
57
73
|
"ProgressEvent",
|
|
74
|
+
"Question",
|
|
75
|
+
"QuestionBatch",
|
|
76
|
+
"Responder",
|
|
58
77
|
"RunCancelledError",
|
|
59
78
|
"RunContext",
|
|
60
79
|
"RunMetadata",
|
|
@@ -2,23 +2,27 @@
|
|
|
2
2
|
|
|
3
3
|
from __future__ import annotations
|
|
4
4
|
|
|
5
|
+
import asyncio
|
|
5
6
|
import logging
|
|
6
7
|
import time
|
|
7
8
|
from abc import ABC, abstractmethod
|
|
8
|
-
from collections.abc import Callable, Mapping, Sequence
|
|
9
|
+
from collections.abc import Awaitable, Callable, Mapping, Sequence
|
|
9
10
|
from datetime import UTC, datetime
|
|
10
11
|
from typing import TYPE_CHECKING, Any, ClassVar
|
|
11
12
|
|
|
12
13
|
from pydantic import BaseModel, ValidationError
|
|
13
14
|
|
|
14
|
-
from margin_core.errors import InputValidationError, LLMError, RunCancelledError
|
|
15
|
+
from margin_core.errors import InputValidationError, LLMError, NoAnswerError, RunCancelledError
|
|
15
16
|
from margin_core.llm.base import LLMClient
|
|
16
17
|
from margin_core.logging import get_logger
|
|
17
18
|
from margin_core.models import (
|
|
18
19
|
AgentInfo,
|
|
19
20
|
AgentResult,
|
|
21
|
+
Answer,
|
|
20
22
|
Finding,
|
|
21
23
|
ProgressEvent,
|
|
24
|
+
Question,
|
|
25
|
+
QuestionBatch,
|
|
22
26
|
ResultStatus,
|
|
23
27
|
TokenUsage,
|
|
24
28
|
)
|
|
@@ -28,8 +32,12 @@ if TYPE_CHECKING:
|
|
|
28
32
|
from margin_core.loaders.filters import FilterConfig
|
|
29
33
|
|
|
30
34
|
ProgressCallback = Callable[[ProgressEvent], None]
|
|
35
|
+
Responder = Callable[[QuestionBatch], Awaitable[Mapping[str, Any]]]
|
|
36
|
+
"""Puts a batch of questions to a person and returns the raw answers, by question id."""
|
|
31
37
|
|
|
32
|
-
|
|
38
|
+
_CANCEL_POLL_S = 0.2
|
|
39
|
+
|
|
40
|
+
__all__ = ["BaseAgent", "CancellationToken", "ProgressCallback", "Responder", "RunContext"]
|
|
33
41
|
|
|
34
42
|
|
|
35
43
|
class CancellationToken:
|
|
@@ -51,7 +59,10 @@ class RunContext:
|
|
|
51
59
|
|
|
52
60
|
During :meth:`BaseAgent.execute`, ``llm`` is a per-run :class:`LLMSession` opened from the
|
|
53
61
|
configured client, limited by ``max_cost_usd``. Anything added with :meth:`warn` ends up in
|
|
54
|
-
the result's ``warnings``.
|
|
62
|
+
the result's ``warnings``, and every answer from :meth:`ask` in its ``metadata.answers``.
|
|
63
|
+
|
|
64
|
+
``responder`` is how :meth:`ask` reaches a person: the CLI asks in the terminal, the API
|
|
65
|
+
pauses the run until answers are posted. Without one, questions take their defaults.
|
|
55
66
|
"""
|
|
56
67
|
|
|
57
68
|
def __init__(
|
|
@@ -62,13 +73,16 @@ class RunContext:
|
|
|
62
73
|
cancel_token: CancellationToken | None = None,
|
|
63
74
|
logger: logging.Logger | None = None,
|
|
64
75
|
max_cost_usd: float | None = None,
|
|
76
|
+
responder: Responder | None = None,
|
|
65
77
|
) -> None:
|
|
66
78
|
self.llm = llm
|
|
67
79
|
self.progress = progress
|
|
68
80
|
self.cancel_token = cancel_token or CancellationToken()
|
|
69
81
|
self.logger = logger or get_logger("run")
|
|
70
82
|
self.max_cost_usd = max_cost_usd
|
|
83
|
+
self.responder = responder
|
|
71
84
|
self.warnings: list[str] = []
|
|
85
|
+
self.answers: list[Answer] = []
|
|
72
86
|
|
|
73
87
|
def warn(self, message: str) -> None:
|
|
74
88
|
"""Record a warning for the result (duplicates are ignored)."""
|
|
@@ -110,6 +124,75 @@ class RunContext:
|
|
|
110
124
|
if self.cancel_token.cancelled:
|
|
111
125
|
raise RunCancelledError("Run was cancelled")
|
|
112
126
|
|
|
127
|
+
async def ask(
|
|
128
|
+
self,
|
|
129
|
+
questions: Sequence[Question],
|
|
130
|
+
*,
|
|
131
|
+
title: str,
|
|
132
|
+
detail: str | None = None,
|
|
133
|
+
preset: Mapping[str, Any] | None = None,
|
|
134
|
+
assume_defaults: bool = False,
|
|
135
|
+
) -> dict[str, Answer]:
|
|
136
|
+
"""Ask the person running the agent, wait for the answers, and return them by id.
|
|
137
|
+
|
|
138
|
+
All the questions are asked at once. Questions answered in ``preset`` (usually an
|
|
139
|
+
``answers`` input field) are not asked. The rest go to the responder, unless there is
|
|
140
|
+
none or ``assume_defaults`` is set: then each takes its default, recorded as not
|
|
141
|
+
confirmed and reported as a warning. A required question without a default that
|
|
142
|
+
cannot be asked raises :class:`NoAnswerError`.
|
|
143
|
+
"""
|
|
144
|
+
batch = QuestionBatch(title=title, detail=detail, questions=list(questions))
|
|
145
|
+
preset = preset or {}
|
|
146
|
+
answers: dict[str, Answer] = {}
|
|
147
|
+
for question in batch.questions:
|
|
148
|
+
if question.id in preset:
|
|
149
|
+
try:
|
|
150
|
+
value = question.check(preset[question.id])
|
|
151
|
+
except ValueError as exc:
|
|
152
|
+
raise InputValidationError(
|
|
153
|
+
f"The answer given for {question.id!r} is not valid: {exc}"
|
|
154
|
+
) from exc
|
|
155
|
+
answers[question.id] = Answer.of(question, value, "preset")
|
|
156
|
+
|
|
157
|
+
remaining = [q for q in batch.questions if q.id not in answers]
|
|
158
|
+
if remaining and self.responder is not None and not assume_defaults:
|
|
159
|
+
pending = batch.model_copy(update={"questions": remaining})
|
|
160
|
+
self.check_cancelled()
|
|
161
|
+
raw = await self._wait_for_answers(self.responder(pending))
|
|
162
|
+
try:
|
|
163
|
+
answers.update(pending.resolve(raw, "user"))
|
|
164
|
+
except ValueError as exc:
|
|
165
|
+
raise InputValidationError(f"Invalid answers: {exc}") from exc
|
|
166
|
+
elif remaining:
|
|
167
|
+
unanswerable = [q.id for q in remaining if q.required and q.default is None]
|
|
168
|
+
if unanswerable:
|
|
169
|
+
raise NoAnswerError(
|
|
170
|
+
"These questions need an answer and there was no one to ask: "
|
|
171
|
+
f"{', '.join(unanswerable)}. Give the answers with the run's input."
|
|
172
|
+
)
|
|
173
|
+
for question in remaining:
|
|
174
|
+
answer = Answer.of(question, question.check(question.default), "default")
|
|
175
|
+
answers[question.id] = answer
|
|
176
|
+
if question.default is not None:
|
|
177
|
+
self.warn(f"Not confirmed: {question.prompt} Assumed: {answer.label}.")
|
|
178
|
+
|
|
179
|
+
ordered = {q.id: answers[q.id] for q in batch.questions}
|
|
180
|
+
self.answers.extend(ordered.values())
|
|
181
|
+
return ordered
|
|
182
|
+
|
|
183
|
+
async def _wait_for_answers(self, pending: Awaitable[Mapping[str, Any]]) -> Mapping[str, Any]:
|
|
184
|
+
"""Await the responder, giving up as soon as the run is cancelled."""
|
|
185
|
+
task = asyncio.ensure_future(pending)
|
|
186
|
+
try:
|
|
187
|
+
while True:
|
|
188
|
+
done, _ = await asyncio.wait({task}, timeout=_CANCEL_POLL_S)
|
|
189
|
+
if done:
|
|
190
|
+
return task.result()
|
|
191
|
+
self.check_cancelled()
|
|
192
|
+
finally:
|
|
193
|
+
if not task.done():
|
|
194
|
+
task.cancel()
|
|
195
|
+
|
|
113
196
|
def require_llm(self) -> LLMClient:
|
|
114
197
|
"""Return the LLM client or fail with a clear error if none was configured."""
|
|
115
198
|
if self.llm is None:
|
|
@@ -241,6 +324,7 @@ class BaseAgent(ABC):
|
|
|
241
324
|
"duration_s": round(time.perf_counter() - t0, 4),
|
|
242
325
|
"model": result.metadata.model or used_model,
|
|
243
326
|
"usage": session.usage if session else TokenUsage(),
|
|
327
|
+
"answers": [*result.metadata.answers, *ctx.answers],
|
|
244
328
|
}
|
|
245
329
|
)
|
|
246
330
|
return result.model_copy(update={"metadata": metadata, "warnings": warnings})
|
|
@@ -25,6 +25,10 @@ class RunCancelledError(AgentsLibError):
|
|
|
25
25
|
"""The run was cancelled through its cancellation token."""
|
|
26
26
|
|
|
27
27
|
|
|
28
|
+
class NoAnswerError(AgentsLibError):
|
|
29
|
+
"""An agent's question could not be answered: nobody to ask, or no answer in time."""
|
|
30
|
+
|
|
31
|
+
|
|
28
32
|
class LoaderError(AgentsLibError):
|
|
29
33
|
"""Base class for errors raised while loading a workspace."""
|
|
30
34
|
|
|
@@ -0,0 +1,321 @@
|
|
|
1
|
+
"""Standard Pydantic models shared by every agent.
|
|
2
|
+
|
|
3
|
+
A generic UI can render ``summary``, ``findings`` and ``evidence`` of any
|
|
4
|
+
:class:`AgentResult` without knowing anything about the agent that produced it.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import uuid
|
|
10
|
+
from collections.abc import Mapping
|
|
11
|
+
from datetime import UTC, datetime
|
|
12
|
+
from typing import Any, Literal
|
|
13
|
+
|
|
14
|
+
from pydantic import BaseModel, ConfigDict, Field, model_validator
|
|
15
|
+
|
|
16
|
+
ResultStatus = Literal["ok", "partial", "error"]
|
|
17
|
+
QuestionKind = Literal["choice", "multi_choice", "text"]
|
|
18
|
+
AnswerSource = Literal["user", "preset", "default"]
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
class _StrictModel(BaseModel):
|
|
22
|
+
model_config = ConfigDict(extra="forbid")
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
class Evidence(_StrictModel):
|
|
26
|
+
"""A single, checkable piece of evidence supporting a finding."""
|
|
27
|
+
|
|
28
|
+
kind: str = Field(description='Evidence type, e.g. "file", "commit", "config", "metric".')
|
|
29
|
+
location: str | None = Field(
|
|
30
|
+
default=None, description='Where to look, e.g. "src/utils.py:10-42" or a commit SHA.'
|
|
31
|
+
)
|
|
32
|
+
detail: str = Field(description="Human-readable explanation.")
|
|
33
|
+
weight: float | None = Field(
|
|
34
|
+
default=None, description="Contribution to the score, if applicable."
|
|
35
|
+
)
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
class Finding(_StrictModel):
|
|
39
|
+
"""A titled conclusion backed by evidence."""
|
|
40
|
+
|
|
41
|
+
title: str
|
|
42
|
+
severity_or_score: float | None = None
|
|
43
|
+
summary: str
|
|
44
|
+
evidence: list[Evidence] = Field(default_factory=list)
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
class TokenUsage(_StrictModel):
|
|
48
|
+
"""Aggregated LLM usage and estimated cost."""
|
|
49
|
+
|
|
50
|
+
llm_calls: int = 0
|
|
51
|
+
input_tokens: int = 0
|
|
52
|
+
output_tokens: int = 0
|
|
53
|
+
cost_usd: float = 0.0
|
|
54
|
+
|
|
55
|
+
def __add__(self, other: TokenUsage) -> TokenUsage:
|
|
56
|
+
return TokenUsage(
|
|
57
|
+
llm_calls=self.llm_calls + other.llm_calls,
|
|
58
|
+
input_tokens=self.input_tokens + other.input_tokens,
|
|
59
|
+
output_tokens=self.output_tokens + other.output_tokens,
|
|
60
|
+
cost_usd=self.cost_usd + other.cost_usd,
|
|
61
|
+
)
|
|
62
|
+
|
|
63
|
+
def __sub__(self, other: TokenUsage) -> TokenUsage:
|
|
64
|
+
return TokenUsage(
|
|
65
|
+
llm_calls=self.llm_calls - other.llm_calls,
|
|
66
|
+
input_tokens=self.input_tokens - other.input_tokens,
|
|
67
|
+
output_tokens=self.output_tokens - other.output_tokens,
|
|
68
|
+
cost_usd=max(0.0, self.cost_usd - other.cost_usd),
|
|
69
|
+
)
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
class Choice(_StrictModel):
|
|
73
|
+
"""One option of a :class:`Question`."""
|
|
74
|
+
|
|
75
|
+
value: str | int | float | bool = Field(description="What the agent gets when this is picked.")
|
|
76
|
+
label: str = Field(description="What the person sees.")
|
|
77
|
+
detail: str | None = Field(default=None, description="A short explanation of the option.")
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
def _same(a: Any, b: Any) -> bool:
|
|
81
|
+
# True == 1 in Python, but an answer of 1 must not pick a choice whose value is True
|
|
82
|
+
return bool(a == b) and isinstance(a, bool) == isinstance(b, bool)
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
class Question(_StrictModel):
|
|
86
|
+
"""Something an agent asks the person running it, with the evidence behind the question.
|
|
87
|
+
|
|
88
|
+
``choice`` takes one of ``choices`` (or any text, with ``allow_other``), ``multi_choice``
|
|
89
|
+
takes a list of them, and ``text`` takes free text.
|
|
90
|
+
"""
|
|
91
|
+
|
|
92
|
+
id: str = Field(
|
|
93
|
+
min_length=1, max_length=200, description='Stable key, e.g. "date_format:order_date".'
|
|
94
|
+
)
|
|
95
|
+
prompt: str = Field(min_length=1, description="The question, as one sentence.")
|
|
96
|
+
detail: str | None = Field(default=None, description="Why the agent is asking.")
|
|
97
|
+
kind: QuestionKind = "choice"
|
|
98
|
+
choices: list[Choice] = Field(default_factory=list)
|
|
99
|
+
allow_other: bool = Field(
|
|
100
|
+
default=False, description="choice only: any text is accepted besides the choices."
|
|
101
|
+
)
|
|
102
|
+
default: Any = Field(
|
|
103
|
+
default=None, description="Used when the question is not asked; the suggested answer."
|
|
104
|
+
)
|
|
105
|
+
required: bool = Field(default=True, description="Whether an empty answer is refused.")
|
|
106
|
+
section: str | None = Field(default=None, description="A heading to group questions under.")
|
|
107
|
+
evidence: list[Evidence] = Field(default_factory=list)
|
|
108
|
+
|
|
109
|
+
@model_validator(mode="after")
|
|
110
|
+
def _consistent(self) -> Question:
|
|
111
|
+
if self.kind == "text":
|
|
112
|
+
if self.choices or self.allow_other:
|
|
113
|
+
raise ValueError("a text question takes no choices")
|
|
114
|
+
else:
|
|
115
|
+
if not self.choices:
|
|
116
|
+
raise ValueError(f"a {self.kind} question needs at least one choice")
|
|
117
|
+
values = [c.value for c in self.choices]
|
|
118
|
+
if any(_same(v, w) for i, v in enumerate(values) for w in values[i + 1 :]):
|
|
119
|
+
raise ValueError("choice values must be unique")
|
|
120
|
+
if self.kind == "multi_choice" and self.allow_other:
|
|
121
|
+
raise ValueError("allow_other only applies to choice questions")
|
|
122
|
+
if self.default is not None:
|
|
123
|
+
self.default = self.check(self.default)
|
|
124
|
+
return self
|
|
125
|
+
|
|
126
|
+
def _choice(self, value: Any) -> Choice | None:
|
|
127
|
+
return next((c for c in self.choices if _same(c.value, value)), None)
|
|
128
|
+
|
|
129
|
+
def check(self, value: Any) -> Any:
|
|
130
|
+
"""Return ``value`` in its normal form, or raise ``ValueError`` if it is not accepted."""
|
|
131
|
+
if self.kind == "multi_choice":
|
|
132
|
+
if value is None:
|
|
133
|
+
value = []
|
|
134
|
+
if not isinstance(value, list | tuple):
|
|
135
|
+
raise ValueError("expected a list of choices")
|
|
136
|
+
unknown = [v for v in value if self._choice(v) is None]
|
|
137
|
+
if unknown:
|
|
138
|
+
raise ValueError(f"not among the choices: {', '.join(map(repr, unknown))}")
|
|
139
|
+
if not value and self.required:
|
|
140
|
+
raise ValueError("pick at least one")
|
|
141
|
+
return [c.value for c in self.choices if any(_same(c.value, v) for v in value)]
|
|
142
|
+
|
|
143
|
+
if value is None or (isinstance(value, str) and not value.strip()):
|
|
144
|
+
if self.required:
|
|
145
|
+
raise ValueError("an answer is required")
|
|
146
|
+
return None
|
|
147
|
+
if self.kind == "text":
|
|
148
|
+
if not isinstance(value, str):
|
|
149
|
+
raise ValueError("expected text")
|
|
150
|
+
return value.strip()
|
|
151
|
+
choice = self._choice(value)
|
|
152
|
+
if choice is not None:
|
|
153
|
+
return choice.value
|
|
154
|
+
if self.allow_other and isinstance(value, str):
|
|
155
|
+
return value.strip()
|
|
156
|
+
raise ValueError(f"{value!r} is not one of the choices")
|
|
157
|
+
|
|
158
|
+
def describe(self, value: Any) -> str:
|
|
159
|
+
"""A readable form of an answer to this question."""
|
|
160
|
+
if value is None or value == []:
|
|
161
|
+
return "(no answer)"
|
|
162
|
+
if self.kind == "text":
|
|
163
|
+
return str(value)
|
|
164
|
+
values = value if isinstance(value, list) else [value]
|
|
165
|
+
labels = []
|
|
166
|
+
for v in values:
|
|
167
|
+
choice = self._choice(v)
|
|
168
|
+
labels.append(choice.label if choice is not None else str(v))
|
|
169
|
+
return ", ".join(labels)
|
|
170
|
+
|
|
171
|
+
|
|
172
|
+
class Answer(_StrictModel):
|
|
173
|
+
"""How one question was answered, kept with the result so every choice can be traced.
|
|
174
|
+
|
|
175
|
+
``source`` says who decided: ``user`` (answered when asked), ``preset`` (given with the
|
|
176
|
+
run's input) or ``default`` (the question's default was assumed; nobody confirmed it).
|
|
177
|
+
"""
|
|
178
|
+
|
|
179
|
+
question_id: str
|
|
180
|
+
prompt: str
|
|
181
|
+
value: Any = None
|
|
182
|
+
label: str = Field(description="The answer in readable form.")
|
|
183
|
+
source: AnswerSource
|
|
184
|
+
|
|
185
|
+
@classmethod
|
|
186
|
+
def of(cls, question: Question, value: Any, source: AnswerSource) -> Answer:
|
|
187
|
+
return cls(
|
|
188
|
+
question_id=question.id,
|
|
189
|
+
prompt=question.prompt,
|
|
190
|
+
value=value,
|
|
191
|
+
label=question.describe(value),
|
|
192
|
+
source=source,
|
|
193
|
+
)
|
|
194
|
+
|
|
195
|
+
|
|
196
|
+
class QuestionBatch(_StrictModel):
|
|
197
|
+
"""Questions asked together, at one point of a run."""
|
|
198
|
+
|
|
199
|
+
id: str = Field(default_factory=lambda: uuid.uuid4().hex)
|
|
200
|
+
title: str = Field(min_length=1, description='What is being decided, e.g. "Check the plan".')
|
|
201
|
+
detail: str | None = None
|
|
202
|
+
questions: list[Question] = Field(min_length=1)
|
|
203
|
+
|
|
204
|
+
@model_validator(mode="after")
|
|
205
|
+
def _unique_ids(self) -> QuestionBatch:
|
|
206
|
+
ids = [q.id for q in self.questions]
|
|
207
|
+
duplicates = sorted({i for i in ids if ids.count(i) > 1})
|
|
208
|
+
if duplicates:
|
|
209
|
+
raise ValueError(f"question ids must be unique: {', '.join(duplicates)}")
|
|
210
|
+
return self
|
|
211
|
+
|
|
212
|
+
def resolve(self, raw: Mapping[str, Any], source: AnswerSource) -> dict[str, Answer]:
|
|
213
|
+
"""Turn raw answers into :class:`Answer` objects, in question order.
|
|
214
|
+
|
|
215
|
+
A question left out takes its default (recorded as ``default``). Raises
|
|
216
|
+
``ValueError`` listing every problem: unknown ids, missing or invalid answers.
|
|
217
|
+
"""
|
|
218
|
+
known = {q.id for q in self.questions}
|
|
219
|
+
problems = [f"{key}: no such question" for key in raw if key not in known]
|
|
220
|
+
answers: dict[str, Answer] = {}
|
|
221
|
+
for question in self.questions:
|
|
222
|
+
if question.id in raw:
|
|
223
|
+
try:
|
|
224
|
+
value = question.check(raw[question.id])
|
|
225
|
+
except ValueError as exc:
|
|
226
|
+
problems.append(f"{question.id}: {exc}")
|
|
227
|
+
continue
|
|
228
|
+
answers[question.id] = Answer.of(question, value, source)
|
|
229
|
+
elif question.default is not None or not question.required:
|
|
230
|
+
default = question.check(question.default)
|
|
231
|
+
answers[question.id] = Answer.of(question, default, "default")
|
|
232
|
+
else:
|
|
233
|
+
problems.append(f"{question.id}: an answer is required")
|
|
234
|
+
if problems:
|
|
235
|
+
raise ValueError("; ".join(problems))
|
|
236
|
+
return answers
|
|
237
|
+
|
|
238
|
+
|
|
239
|
+
class RunMetadata(_StrictModel):
|
|
240
|
+
"""Execution metadata attached to every result."""
|
|
241
|
+
|
|
242
|
+
started_at: datetime | None = None
|
|
243
|
+
finished_at: datetime | None = None
|
|
244
|
+
duration_s: float | None = None
|
|
245
|
+
model: str | None = None
|
|
246
|
+
usage: TokenUsage = Field(default_factory=TokenUsage)
|
|
247
|
+
answers: list[Answer] = Field(
|
|
248
|
+
default_factory=list, description="Questions the agent asked, and how each was answered."
|
|
249
|
+
)
|
|
250
|
+
extra: dict[str, Any] = Field(default_factory=dict)
|
|
251
|
+
|
|
252
|
+
|
|
253
|
+
class AgentInput(_StrictModel):
|
|
254
|
+
"""Base class for agent input models. Unknown fields are rejected."""
|
|
255
|
+
|
|
256
|
+
|
|
257
|
+
class AnswersInput(AgentInput):
|
|
258
|
+
"""Base class for the input of an agent that asks questions (``RunContext.ask``).
|
|
259
|
+
|
|
260
|
+
The two fields have the same names in every such agent, so a run can be repeated with
|
|
261
|
+
the answers of an earlier one, and scripts can answer up front.
|
|
262
|
+
"""
|
|
263
|
+
|
|
264
|
+
answers: dict[str, Any] = Field(
|
|
265
|
+
default_factory=dict,
|
|
266
|
+
description="Answers to the agent's questions, by question id. These are not asked.",
|
|
267
|
+
)
|
|
268
|
+
assume_defaults: bool = Field(
|
|
269
|
+
default=False,
|
|
270
|
+
description="Ask nothing: every question takes its suggested answer, marked unconfirmed.",
|
|
271
|
+
)
|
|
272
|
+
|
|
273
|
+
|
|
274
|
+
class AgentResult(_StrictModel):
|
|
275
|
+
"""The standard result returned by every agent.
|
|
276
|
+
|
|
277
|
+
``status`` semantics:
|
|
278
|
+
|
|
279
|
+
- ``ok``: everything requested was done. ``error`` is null.
|
|
280
|
+
- ``partial``: a usable result, but some requested work was skipped (a budget or time cap
|
|
281
|
+
was hit, some files were unreadable, an optional step was unavailable). Each skipped
|
|
282
|
+
part has an entry in ``warnings``. ``data`` is complete in shape but may hold fewer
|
|
283
|
+
items. ``error`` is null.
|
|
284
|
+
- ``error``: no usable result. ``data`` is empty and ``error`` holds the message.
|
|
285
|
+
"""
|
|
286
|
+
|
|
287
|
+
agent_id: str
|
|
288
|
+
agent_version: str
|
|
289
|
+
status: ResultStatus
|
|
290
|
+
summary: str = Field(description="2-3 sentence human summary.")
|
|
291
|
+
data: dict[str, Any] = Field(
|
|
292
|
+
default_factory=dict, description="Agent-specific payload, validated by its OutputModel."
|
|
293
|
+
)
|
|
294
|
+
findings: list[Finding] = Field(default_factory=list)
|
|
295
|
+
warnings: list[str] = Field(default_factory=list)
|
|
296
|
+
error: str | None = Field(default=None, description="Error message when status is 'error'.")
|
|
297
|
+
metadata: RunMetadata = Field(default_factory=RunMetadata)
|
|
298
|
+
|
|
299
|
+
|
|
300
|
+
class ProgressEvent(_StrictModel):
|
|
301
|
+
"""A progress update emitted during a run (consumed by CLI/UI)."""
|
|
302
|
+
|
|
303
|
+
stage: str
|
|
304
|
+
message: str = ""
|
|
305
|
+
fraction: float | None = Field(default=None, ge=0.0, le=1.0)
|
|
306
|
+
timestamp: datetime = Field(default_factory=lambda: datetime.now(UTC))
|
|
307
|
+
|
|
308
|
+
|
|
309
|
+
class AgentInfo(_StrictModel):
|
|
310
|
+
"""Static description of an agent, including its JSON schemas."""
|
|
311
|
+
|
|
312
|
+
id: str
|
|
313
|
+
name: str
|
|
314
|
+
description: str
|
|
315
|
+
version: str
|
|
316
|
+
input_schema: dict[str, Any]
|
|
317
|
+
output_schema: dict[str, Any]
|
|
318
|
+
primary_input: str | None = Field(
|
|
319
|
+
default=None, description="Input field filled by a positional CLI argument."
|
|
320
|
+
)
|
|
321
|
+
uses_llm: bool = Field(default=False, description="Whether runs normally call a model.")
|
|
@@ -7,6 +7,7 @@ from pathlib import Path
|
|
|
7
7
|
from margin_core.models import AgentResult, Evidence
|
|
8
8
|
|
|
9
9
|
_STATUS_LABEL = {"ok": "ok", "partial": "partial", "error": "error"}
|
|
10
|
+
_ANSWERED_BY = {"user": "you", "preset": "the run's input", "default": "default, not confirmed"}
|
|
10
11
|
|
|
11
12
|
|
|
12
13
|
def _cell(text: object) -> str:
|
|
@@ -56,6 +57,14 @@ def to_markdown(result: AgentResult) -> str:
|
|
|
56
57
|
md.append("")
|
|
57
58
|
|
|
58
59
|
meta = result.metadata
|
|
60
|
+
if meta.answers:
|
|
61
|
+
md += ["## Answers", "", "| Question | Answer | Given by |", "|---|---|---|"]
|
|
62
|
+
md += [
|
|
63
|
+
f"| {_cell(a.prompt)} | {_cell(a.label)} | {_ANSWERED_BY.get(a.source, a.source)} |"
|
|
64
|
+
for a in meta.answers
|
|
65
|
+
]
|
|
66
|
+
md.append("")
|
|
67
|
+
|
|
59
68
|
rows: list[tuple[str, object]] = []
|
|
60
69
|
if meta.duration_s is not None:
|
|
61
70
|
rows.append(("Duration", f"{meta.duration_s:.2f}s"))
|
|
@@ -0,0 +1,257 @@
|
|
|
1
|
+
"""Questions an agent asks during a run: the models, ``RunContext.ask`` and the report."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import asyncio
|
|
6
|
+
from collections.abc import Mapping
|
|
7
|
+
from typing import Any
|
|
8
|
+
|
|
9
|
+
import pytest
|
|
10
|
+
from margin_core import (
|
|
11
|
+
AgentResult,
|
|
12
|
+
Answer,
|
|
13
|
+
AnswersInput,
|
|
14
|
+
BaseAgent,
|
|
15
|
+
CancellationToken,
|
|
16
|
+
Choice,
|
|
17
|
+
Evidence,
|
|
18
|
+
InputValidationError,
|
|
19
|
+
NoAnswerError,
|
|
20
|
+
Question,
|
|
21
|
+
QuestionBatch,
|
|
22
|
+
RunContext,
|
|
23
|
+
)
|
|
24
|
+
from margin_core.reporting import to_markdown
|
|
25
|
+
from pydantic import BaseModel, ValidationError
|
|
26
|
+
|
|
27
|
+
FORMAT = Question(
|
|
28
|
+
id="date_format",
|
|
29
|
+
prompt="Which date format does order_date use?",
|
|
30
|
+
choices=[Choice(value="mdy", label="MM/DD/YYYY"), Choice(value="dmy", label="DD/MM/YYYY")],
|
|
31
|
+
default="mdy",
|
|
32
|
+
evidence=[Evidence(kind="sample", location="order_date", detail="01/02/2024, 03/04/2024")],
|
|
33
|
+
)
|
|
34
|
+
COLUMNS = Question(
|
|
35
|
+
id="columns",
|
|
36
|
+
prompt="Which columns matter?",
|
|
37
|
+
kind="multi_choice",
|
|
38
|
+
choices=[Choice(value=c, label=c.title()) for c in ("revenue", "cost", "units")],
|
|
39
|
+
default=["revenue"],
|
|
40
|
+
)
|
|
41
|
+
CONTEXT = Question(id="context", prompt="Anything we should know?", kind="text", required=False)
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
# ---- the models -------------------------------------------------------------------------
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def test_questions_must_be_consistent() -> None:
|
|
48
|
+
with pytest.raises(ValidationError, match="at least one choice"):
|
|
49
|
+
Question(id="q", prompt="?")
|
|
50
|
+
with pytest.raises(ValidationError, match="takes no choices"):
|
|
51
|
+
Question(id="q", prompt="?", kind="text", choices=[Choice(value=1, label="one")])
|
|
52
|
+
with pytest.raises(ValidationError, match="unique"):
|
|
53
|
+
Question(
|
|
54
|
+
id="q", prompt="?", choices=[Choice(value=1, label="a"), Choice(value=1, label="b")]
|
|
55
|
+
)
|
|
56
|
+
with pytest.raises(ValidationError, match="not one of the choices"):
|
|
57
|
+
Question(id="q", prompt="?", choices=[Choice(value="a", label="A")], default="b")
|
|
58
|
+
with pytest.raises(ValidationError, match="unique"):
|
|
59
|
+
QuestionBatch(title="t", questions=[FORMAT, FORMAT])
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def test_check_normalises_answers() -> None:
|
|
63
|
+
assert FORMAT.check("dmy") == "dmy"
|
|
64
|
+
with pytest.raises(ValueError, match="required"):
|
|
65
|
+
FORMAT.check(None)
|
|
66
|
+
with pytest.raises(ValueError, match="not one of"):
|
|
67
|
+
FORMAT.check("ymd")
|
|
68
|
+
|
|
69
|
+
# lists come back in the order of the choices, whatever order they were given in
|
|
70
|
+
assert COLUMNS.check(["units", "revenue"]) == ["revenue", "units"]
|
|
71
|
+
with pytest.raises(ValueError, match="at least one"):
|
|
72
|
+
COLUMNS.check([])
|
|
73
|
+
with pytest.raises(ValueError, match="not among"):
|
|
74
|
+
COLUMNS.check(["profit"])
|
|
75
|
+
|
|
76
|
+
assert CONTEXT.check(" a promo in Q3 ") == "a promo in Q3"
|
|
77
|
+
assert CONTEXT.check("") is None # optional
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
def test_true_is_not_one() -> None:
|
|
81
|
+
flag = Question(
|
|
82
|
+
id="q", prompt="?", choices=[Choice(value=True, label="Yes"), Choice(value=0, label="Zero")]
|
|
83
|
+
)
|
|
84
|
+
with pytest.raises(ValueError):
|
|
85
|
+
flag.check(1)
|
|
86
|
+
assert flag.check(True) is True and flag.check(0) == 0
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
def test_other_text_is_accepted_only_when_allowed() -> None:
|
|
90
|
+
grain = Question(
|
|
91
|
+
id="grain", prompt="One row is one what?", allow_other=True,
|
|
92
|
+
choices=[Choice(value="order", label="An order")],
|
|
93
|
+
) # fmt: skip
|
|
94
|
+
assert grain.check("order line") == "order line"
|
|
95
|
+
assert grain.describe("order") == "An order"
|
|
96
|
+
assert grain.describe("order line") == "order line"
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
def test_resolve_fills_defaults_and_lists_every_problem() -> None:
|
|
100
|
+
batch = QuestionBatch(title="Check", questions=[FORMAT, COLUMNS, CONTEXT])
|
|
101
|
+
answers = batch.resolve({"date_format": "dmy"}, "user")
|
|
102
|
+
assert [a.source for a in answers.values()] == ["user", "default", "default"]
|
|
103
|
+
assert answers["columns"].label == "Revenue"
|
|
104
|
+
assert answers["context"].value is None and answers["context"].label == "(no answer)"
|
|
105
|
+
|
|
106
|
+
# an optional list left out is an empty list, whichever way it was left out
|
|
107
|
+
optional = COLUMNS.model_copy(update={"required": False, "default": None})
|
|
108
|
+
skipped = QuestionBatch(title="Check", questions=[optional]).resolve({}, "user")
|
|
109
|
+
assert skipped["columns"].value == [] and optional.check(None) == []
|
|
110
|
+
|
|
111
|
+
strict = QuestionBatch(title="Check", questions=[Question(id="x", prompt="?", kind="text")])
|
|
112
|
+
with pytest.raises(ValueError) as problem:
|
|
113
|
+
strict.resolve({"nope": 1}, "user")
|
|
114
|
+
assert "nope: no such question" in str(problem.value)
|
|
115
|
+
assert "x: an answer is required" in str(problem.value)
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
# ---- RunContext.ask ---------------------------------------------------------------------
|
|
119
|
+
|
|
120
|
+
|
|
121
|
+
class AskInput(AnswersInput):
|
|
122
|
+
text_question: bool = False
|
|
123
|
+
|
|
124
|
+
|
|
125
|
+
class AskOutput(BaseModel):
|
|
126
|
+
answers: dict[str, Any]
|
|
127
|
+
|
|
128
|
+
|
|
129
|
+
class Asker(BaseAgent):
|
|
130
|
+
id = "asker"
|
|
131
|
+
name = "Asker"
|
|
132
|
+
description = "Asks, then reports what it was told."
|
|
133
|
+
version = "0.0.1"
|
|
134
|
+
InputModel = AskInput
|
|
135
|
+
OutputModel = AskOutput
|
|
136
|
+
|
|
137
|
+
async def run(self, input: AskInput, ctx: RunContext) -> AgentResult:
|
|
138
|
+
questions = [FORMAT, COLUMNS, CONTEXT]
|
|
139
|
+
if input.text_question:
|
|
140
|
+
questions.append(Question(id="must", prompt="Required, no default", kind="text"))
|
|
141
|
+
answers = await ctx.ask(
|
|
142
|
+
questions,
|
|
143
|
+
title="Check the data",
|
|
144
|
+
preset=input.answers,
|
|
145
|
+
assume_defaults=input.assume_defaults,
|
|
146
|
+
)
|
|
147
|
+
return self.make_result(
|
|
148
|
+
summary="asked", output=AskOutput(answers={k: a.value for k, a in answers.items()})
|
|
149
|
+
)
|
|
150
|
+
|
|
151
|
+
|
|
152
|
+
class Scripted:
|
|
153
|
+
"""A responder that records what it was asked and answers from a script."""
|
|
154
|
+
|
|
155
|
+
def __init__(self, reply: Mapping[str, Any], delay: float = 0.0) -> None:
|
|
156
|
+
self.reply = reply
|
|
157
|
+
self.delay = delay
|
|
158
|
+
self.batches: list[QuestionBatch] = []
|
|
159
|
+
|
|
160
|
+
async def __call__(self, batch: QuestionBatch) -> Mapping[str, Any]:
|
|
161
|
+
self.batches.append(batch)
|
|
162
|
+
await asyncio.sleep(self.delay)
|
|
163
|
+
return self.reply
|
|
164
|
+
|
|
165
|
+
|
|
166
|
+
async def test_ask_puts_everything_to_the_responder_at_once() -> None:
|
|
167
|
+
responder = Scripted({"date_format": "dmy", "columns": ["cost"], "context": "promo"})
|
|
168
|
+
result = await Asker().execute({}, RunContext(responder=responder))
|
|
169
|
+
assert result.status == "ok"
|
|
170
|
+
assert result.data["answers"] == {"date_format": "dmy", "columns": ["cost"], "context": "promo"}
|
|
171
|
+
(batch,) = responder.batches
|
|
172
|
+
assert batch.title == "Check the data" and len(batch.questions) == 3
|
|
173
|
+
assert [a.source for a in result.metadata.answers] == ["user", "user", "user"]
|
|
174
|
+
assert result.warnings == []
|
|
175
|
+
|
|
176
|
+
|
|
177
|
+
async def test_preset_answers_are_not_asked() -> None:
|
|
178
|
+
responder = Scripted({"columns": ["units"]})
|
|
179
|
+
preset = {"date_format": "dmy", "context": "promo"}
|
|
180
|
+
result = await Asker().execute({"answers": preset}, RunContext(responder=responder))
|
|
181
|
+
assert [q.id for q in responder.batches[0].questions] == ["columns"]
|
|
182
|
+
sources = {a.question_id: a.source for a in result.metadata.answers}
|
|
183
|
+
assert sources == {"date_format": "preset", "columns": "user", "context": "preset"}
|
|
184
|
+
|
|
185
|
+
|
|
186
|
+
async def test_without_anyone_to_ask_defaults_are_assumed_and_flagged() -> None:
|
|
187
|
+
result = await Asker().execute({})
|
|
188
|
+
assert result.status == "ok"
|
|
189
|
+
assert result.data["answers"] == {"date_format": "mdy", "columns": ["revenue"], "context": None}
|
|
190
|
+
assert all(a.source == "default" for a in result.metadata.answers)
|
|
191
|
+
assert result.warnings == [
|
|
192
|
+
"Not confirmed: Which date format does order_date use? Assumed: MM/DD/YYYY.",
|
|
193
|
+
"Not confirmed: Which columns matter? Assumed: Revenue.",
|
|
194
|
+
]
|
|
195
|
+
|
|
196
|
+
|
|
197
|
+
async def test_assume_defaults_skips_the_responder() -> None:
|
|
198
|
+
responder = Scripted({})
|
|
199
|
+
result = await Asker().execute({"assume_defaults": True}, RunContext(responder=responder))
|
|
200
|
+
assert result.status == "ok" and responder.batches == []
|
|
201
|
+
|
|
202
|
+
|
|
203
|
+
async def test_a_question_nobody_can_answer_fails_the_run() -> None:
|
|
204
|
+
result = await Asker().execute({"text_question": True})
|
|
205
|
+
assert result.status == "error"
|
|
206
|
+
assert "NoAnswerError" in (result.error or "") and "must" in (result.error or "")
|
|
207
|
+
# but it can be answered up front
|
|
208
|
+
ok = await Asker().execute({"text_question": True, "answers": {"must": "yes"}})
|
|
209
|
+
assert ok.status == "ok"
|
|
210
|
+
|
|
211
|
+
|
|
212
|
+
async def test_invalid_answers_are_refused() -> None:
|
|
213
|
+
preset = await Asker().execute({"answers": {"date_format": "ymd"}})
|
|
214
|
+
assert preset.status == "error" and "not valid" in (preset.error or "")
|
|
215
|
+
|
|
216
|
+
replied = await Asker().execute({}, RunContext(responder=Scripted({"date_format": "ymd"})))
|
|
217
|
+
assert replied.status == "error" and "Invalid answers" in (replied.error or "")
|
|
218
|
+
|
|
219
|
+
|
|
220
|
+
async def test_cancelling_while_waiting_stops_the_run_promptly() -> None:
|
|
221
|
+
token = CancellationToken()
|
|
222
|
+
responder = Scripted({}, delay=30)
|
|
223
|
+
run = asyncio.ensure_future(
|
|
224
|
+
Asker().execute({}, RunContext(responder=responder, cancel_token=token))
|
|
225
|
+
)
|
|
226
|
+
await asyncio.sleep(0.05)
|
|
227
|
+
token.cancel()
|
|
228
|
+
result = await asyncio.wait_for(run, timeout=2)
|
|
229
|
+
assert result.status == "error" and result.error == "Run was cancelled"
|
|
230
|
+
|
|
231
|
+
|
|
232
|
+
async def test_no_answer_error_is_part_of_the_public_api() -> None:
|
|
233
|
+
async def gives_up(batch: QuestionBatch) -> Mapping[str, Any]:
|
|
234
|
+
raise NoAnswerError("nobody answered in time")
|
|
235
|
+
|
|
236
|
+
result = await Asker().execute({}, RunContext(responder=gives_up))
|
|
237
|
+
assert result.status == "error" and "nobody answered in time" in (result.error or "")
|
|
238
|
+
|
|
239
|
+
|
|
240
|
+
def test_invalid_answers_field_is_an_input_error() -> None:
|
|
241
|
+
with pytest.raises(InputValidationError):
|
|
242
|
+
Asker.parse_input({"answers": "not a mapping"})
|
|
243
|
+
|
|
244
|
+
|
|
245
|
+
# ---- reporting --------------------------------------------------------------------------
|
|
246
|
+
|
|
247
|
+
|
|
248
|
+
def test_markdown_lists_answers_and_who_gave_them() -> None:
|
|
249
|
+
result = AgentResult(agent_id="asker", agent_version="1", status="ok", summary="s")
|
|
250
|
+
result.metadata.answers = [
|
|
251
|
+
Answer.of(FORMAT, "dmy", "user"),
|
|
252
|
+
Answer.of(COLUMNS, ["revenue"], "default"),
|
|
253
|
+
]
|
|
254
|
+
md = to_markdown(result)
|
|
255
|
+
assert "## Answers" in md
|
|
256
|
+
assert "| Which date format does order_date use? | DD/MM/YYYY | you |" in md
|
|
257
|
+
assert "| Which columns matter? | Revenue | default, not confirmed |" in md
|
|
@@ -1,130 +0,0 @@
|
|
|
1
|
-
"""Standard Pydantic models shared by every agent.
|
|
2
|
-
|
|
3
|
-
A generic UI can render ``summary``, ``findings`` and ``evidence`` of any
|
|
4
|
-
:class:`AgentResult` without knowing anything about the agent that produced it.
|
|
5
|
-
"""
|
|
6
|
-
|
|
7
|
-
from __future__ import annotations
|
|
8
|
-
|
|
9
|
-
from datetime import UTC, datetime
|
|
10
|
-
from typing import Any, Literal
|
|
11
|
-
|
|
12
|
-
from pydantic import BaseModel, ConfigDict, Field
|
|
13
|
-
|
|
14
|
-
ResultStatus = Literal["ok", "partial", "error"]
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
class _StrictModel(BaseModel):
|
|
18
|
-
model_config = ConfigDict(extra="forbid")
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
class Evidence(_StrictModel):
|
|
22
|
-
"""A single, checkable piece of evidence supporting a finding."""
|
|
23
|
-
|
|
24
|
-
kind: str = Field(description='Evidence type, e.g. "file", "commit", "config", "metric".')
|
|
25
|
-
location: str | None = Field(
|
|
26
|
-
default=None, description='Where to look, e.g. "src/utils.py:10-42" or a commit SHA.'
|
|
27
|
-
)
|
|
28
|
-
detail: str = Field(description="Human-readable explanation.")
|
|
29
|
-
weight: float | None = Field(
|
|
30
|
-
default=None, description="Contribution to the score, if applicable."
|
|
31
|
-
)
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
class Finding(_StrictModel):
|
|
35
|
-
"""A titled conclusion backed by evidence."""
|
|
36
|
-
|
|
37
|
-
title: str
|
|
38
|
-
severity_or_score: float | None = None
|
|
39
|
-
summary: str
|
|
40
|
-
evidence: list[Evidence] = Field(default_factory=list)
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
class TokenUsage(_StrictModel):
|
|
44
|
-
"""Aggregated LLM usage and estimated cost."""
|
|
45
|
-
|
|
46
|
-
llm_calls: int = 0
|
|
47
|
-
input_tokens: int = 0
|
|
48
|
-
output_tokens: int = 0
|
|
49
|
-
cost_usd: float = 0.0
|
|
50
|
-
|
|
51
|
-
def __add__(self, other: TokenUsage) -> TokenUsage:
|
|
52
|
-
return TokenUsage(
|
|
53
|
-
llm_calls=self.llm_calls + other.llm_calls,
|
|
54
|
-
input_tokens=self.input_tokens + other.input_tokens,
|
|
55
|
-
output_tokens=self.output_tokens + other.output_tokens,
|
|
56
|
-
cost_usd=self.cost_usd + other.cost_usd,
|
|
57
|
-
)
|
|
58
|
-
|
|
59
|
-
def __sub__(self, other: TokenUsage) -> TokenUsage:
|
|
60
|
-
return TokenUsage(
|
|
61
|
-
llm_calls=self.llm_calls - other.llm_calls,
|
|
62
|
-
input_tokens=self.input_tokens - other.input_tokens,
|
|
63
|
-
output_tokens=self.output_tokens - other.output_tokens,
|
|
64
|
-
cost_usd=max(0.0, self.cost_usd - other.cost_usd),
|
|
65
|
-
)
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
class RunMetadata(_StrictModel):
|
|
69
|
-
"""Execution metadata attached to every result."""
|
|
70
|
-
|
|
71
|
-
started_at: datetime | None = None
|
|
72
|
-
finished_at: datetime | None = None
|
|
73
|
-
duration_s: float | None = None
|
|
74
|
-
model: str | None = None
|
|
75
|
-
usage: TokenUsage = Field(default_factory=TokenUsage)
|
|
76
|
-
extra: dict[str, Any] = Field(default_factory=dict)
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
class AgentInput(_StrictModel):
|
|
80
|
-
"""Base class for agent input models. Unknown fields are rejected."""
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
class AgentResult(_StrictModel):
|
|
84
|
-
"""The standard result returned by every agent.
|
|
85
|
-
|
|
86
|
-
``status`` semantics:
|
|
87
|
-
|
|
88
|
-
- ``ok``: everything requested was done. ``error`` is null.
|
|
89
|
-
- ``partial``: a usable result, but some requested work was skipped (a budget or time cap
|
|
90
|
-
was hit, some files were unreadable, an optional step was unavailable). Each skipped
|
|
91
|
-
part has an entry in ``warnings``. ``data`` is complete in shape but may hold fewer
|
|
92
|
-
items. ``error`` is null.
|
|
93
|
-
- ``error``: no usable result. ``data`` is empty and ``error`` holds the message.
|
|
94
|
-
"""
|
|
95
|
-
|
|
96
|
-
agent_id: str
|
|
97
|
-
agent_version: str
|
|
98
|
-
status: ResultStatus
|
|
99
|
-
summary: str = Field(description="2-3 sentence human summary.")
|
|
100
|
-
data: dict[str, Any] = Field(
|
|
101
|
-
default_factory=dict, description="Agent-specific payload, validated by its OutputModel."
|
|
102
|
-
)
|
|
103
|
-
findings: list[Finding] = Field(default_factory=list)
|
|
104
|
-
warnings: list[str] = Field(default_factory=list)
|
|
105
|
-
error: str | None = Field(default=None, description="Error message when status is 'error'.")
|
|
106
|
-
metadata: RunMetadata = Field(default_factory=RunMetadata)
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
class ProgressEvent(_StrictModel):
|
|
110
|
-
"""A progress update emitted during a run (consumed by CLI/UI)."""
|
|
111
|
-
|
|
112
|
-
stage: str
|
|
113
|
-
message: str = ""
|
|
114
|
-
fraction: float | None = Field(default=None, ge=0.0, le=1.0)
|
|
115
|
-
timestamp: datetime = Field(default_factory=lambda: datetime.now(UTC))
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
class AgentInfo(_StrictModel):
|
|
119
|
-
"""Static description of an agent, including its JSON schemas."""
|
|
120
|
-
|
|
121
|
-
id: str
|
|
122
|
-
name: str
|
|
123
|
-
description: str
|
|
124
|
-
version: str
|
|
125
|
-
input_schema: dict[str, Any]
|
|
126
|
-
output_schema: dict[str, Any]
|
|
127
|
-
primary_input: str | None = Field(
|
|
128
|
-
default=None, description="Input field filled by a positional CLI argument."
|
|
129
|
-
)
|
|
130
|
-
uses_llm: bool = Field(default=False, description="Whether runs normally call a model.")
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|