agent-runloop 0.1.0__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.
- agent_runloop-0.1.0/.gitignore +10 -0
- agent_runloop-0.1.0/LICENSE +21 -0
- agent_runloop-0.1.0/PKG-INFO +230 -0
- agent_runloop-0.1.0/README.md +203 -0
- agent_runloop-0.1.0/agent_loop/__init__.py +32 -0
- agent_runloop-0.1.0/agent_loop/_trace.py +15 -0
- agent_runloop-0.1.0/agent_loop/backend.py +17 -0
- agent_runloop-0.1.0/agent_loop/compose.py +441 -0
- agent_runloop-0.1.0/agent_loop/hooks.py +73 -0
- agent_runloop-0.1.0/agent_loop/loop.py +657 -0
- agent_runloop-0.1.0/agent_loop/ollama.py +43 -0
- agent_runloop-0.1.0/agent_loop/prompts.py +21 -0
- agent_runloop-0.1.0/agent_loop/py.typed +0 -0
- agent_runloop-0.1.0/agent_loop/runs.py +122 -0
- agent_runloop-0.1.0/agent_loop/usage.py +30 -0
- agent_runloop-0.1.0/pyproject.toml +40 -0
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Kirill Ostapenko
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
@@ -0,0 +1,230 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: agent-runloop
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Explicit, durable agent loop: validated tool calls, human approval, budgets, crash recovery, and composable router / waterfall / parallel / handoff / refine blocks.
|
|
5
|
+
Project-URL: Homepage, https://github.com/kroq86/agent-loop
|
|
6
|
+
Project-URL: Repository, https://github.com/kroq86/agent-loop
|
|
7
|
+
Project-URL: Issues, https://github.com/kroq86/agent-loop/issues
|
|
8
|
+
Author-email: KirillOstapenko <djkroq@gmail.com>
|
|
9
|
+
License-Expression: MIT
|
|
10
|
+
License-File: LICENSE
|
|
11
|
+
Keywords: LLM,agent,durable,human-in-the-loop,multi-agent,ollama,router,tool-calling
|
|
12
|
+
Classifier: Development Status :: 3 - Alpha
|
|
13
|
+
Classifier: Framework :: AsyncIO
|
|
14
|
+
Classifier: Intended Audience :: Developers
|
|
15
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
16
|
+
Classifier: Programming Language :: Python :: 3
|
|
17
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
18
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
19
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
20
|
+
Classifier: Programming Language :: Python :: 3.14
|
|
21
|
+
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
|
|
22
|
+
Requires-Python: >=3.11
|
|
23
|
+
Requires-Dist: pydantic>=2.5
|
|
24
|
+
Provides-Extra: trace
|
|
25
|
+
Requires-Dist: flow-xray>=0.4.0; extra == 'trace'
|
|
26
|
+
Description-Content-Type: text/markdown
|
|
27
|
+
|
|
28
|
+
# agent-runloop
|
|
29
|
+
|
|
30
|
+
`pip install agent-runloop`, then `import agent_loop`.
|
|
31
|
+
|
|
32
|
+
An explicit agent loop for tool-using LLM agents, and blocks to compose
|
|
33
|
+
agents into routers, waterfalls, parallel fan-outs, handoffs and
|
|
34
|
+
review loops.
|
|
35
|
+
|
|
36
|
+
The model never calls anything. On every turn it returns one JSON
|
|
37
|
+
decision: "call this tool with these arguments" or "here is the final
|
|
38
|
+
answer". The rest is ordinary code:
|
|
39
|
+
|
|
40
|
+
```
|
|
41
|
+
generate -> parse JSON -> validate decision -> look up tool -> validate arguments
|
|
42
|
+
-> reject duplicates -> check budget, precondition, authorization
|
|
43
|
+
-> execute (timeout) -> feed result back as delimited, untrusted data -> generate ...
|
|
44
|
+
```
|
|
45
|
+
|
|
46
|
+
Every rejection (bad JSON, unknown tool, invalid arguments, duplicate
|
|
47
|
+
call, tool exception) becomes an observation the model sees on its next
|
|
48
|
+
turn. None of them execute anything.
|
|
49
|
+
|
|
50
|
+
```bash
|
|
51
|
+
pip install agent-runloop # core: pydantic only
|
|
52
|
+
pip install "agent-runloop[trace]" # + flow-xray call-tree tracing
|
|
53
|
+
```
|
|
54
|
+
|
|
55
|
+
Python 3.11+.
|
|
56
|
+
|
|
57
|
+
## What the loop does
|
|
58
|
+
|
|
59
|
+
- **Validated tool calls.** Tool arguments are pydantic models. Invalid
|
|
60
|
+
calls go back to the model as structured errors, never to your code.
|
|
61
|
+
- **Human approval for writes.** A tool with `writes=True` never runs on
|
|
62
|
+
the model's word. The run pauses as `awaiting_approval` with the
|
|
63
|
+
proposed call. `resume_agent(run_id, approved=True|False)` continues
|
|
64
|
+
it, from another request or another process. The approve step is a
|
|
65
|
+
compare-and-set, so two approvals cannot both execute.
|
|
66
|
+
- **Budgets.** Hard limits per run on model turns, executed tool calls,
|
|
67
|
+
tokens actually used and wall time. They carry across pause and resume.
|
|
68
|
+
- **Crash recovery.** The loop saves a checkpoint to SQLite with a lease
|
|
69
|
+
before every model turn. If the process dies, `recover_agent(run_id)`
|
|
70
|
+
continues from the last checkpoint once the lease expires.
|
|
71
|
+
- **Authorization and preconditions.** These come from trusted run
|
|
72
|
+
context, never from model output. They are checked when a call is
|
|
73
|
+
proposed (a human is never asked to approve a forbidden action) and
|
|
74
|
+
again at execution.
|
|
75
|
+
- **Idempotency.** `current_call_id` gives each tool call a stable id
|
|
76
|
+
(run id + hash of the validated call). A write tool can use it as an
|
|
77
|
+
idempotency key.
|
|
78
|
+
- **Prompt-injection hygiene.** Tool output goes back delimited and
|
|
79
|
+
labelled as data, with the original task restated after it. The
|
|
80
|
+
system message starts with a fixed instruction-hierarchy policy.
|
|
81
|
+
- **Audit and versions.** One audit row per tool execution. Every result
|
|
82
|
+
records the model and a hash of the whole system prompt (instructions,
|
|
83
|
+
protocol, tool catalog).
|
|
84
|
+
- **Live events.** Pass an `asyncio.Queue` to stream steps, for example
|
|
85
|
+
over SSE.
|
|
86
|
+
|
|
87
|
+
## Quick start
|
|
88
|
+
|
|
89
|
+
```python
|
|
90
|
+
import asyncio
|
|
91
|
+
from pydantic import BaseModel
|
|
92
|
+
from agent_loop import Budget, SqliteAgentRunStore, ToolSpec, run_agent
|
|
93
|
+
from agent_loop.ollama import OllamaBackend
|
|
94
|
+
|
|
95
|
+
class SearchArgs(BaseModel):
|
|
96
|
+
query: str
|
|
97
|
+
|
|
98
|
+
async def search(args: SearchArgs, trace_id: str):
|
|
99
|
+
return [{"doc_id": "refunds", "text": "Refunds take 5 to 7 business days."}]
|
|
100
|
+
|
|
101
|
+
result = asyncio.run(run_agent(
|
|
102
|
+
"How long does a refund take?",
|
|
103
|
+
"You are a support agent. Answer only from search results.",
|
|
104
|
+
[ToolSpec("search_knowledge_base", "Search the knowledge base.", SearchArgs, search)],
|
|
105
|
+
backend=OllamaBackend("llama3.2:3b"),
|
|
106
|
+
run_store=SqliteAgentRunStore("runs.sqlite3"),
|
|
107
|
+
budget=Budget(max_iterations=4, max_tool_calls=4, max_tokens=8000, max_seconds=60),
|
|
108
|
+
))
|
|
109
|
+
print(result.status, result.answer, result.usage)
|
|
110
|
+
```
|
|
111
|
+
|
|
112
|
+
`result.status` is one of `answered`, `awaiting_approval`, `max_iterations`,
|
|
113
|
+
`budget_exceeded`, `timeout`, `rejected_final`, `model_unavailable` or
|
|
114
|
+
`cancelled`. `result.steps` lists every step, including rejected ones.
|
|
115
|
+
|
|
116
|
+
### Human approval
|
|
117
|
+
|
|
118
|
+
```python
|
|
119
|
+
TICKET = ToolSpec("create_ticket", "Open a support ticket.", TicketArgs, create_ticket, writes=True,
|
|
120
|
+
authorize=lambda ctx: ctx.get("role") == "customer")
|
|
121
|
+
|
|
122
|
+
r = await run_agent(task, instructions, [SEARCH, TICKET], backend=b, run_store=store, context={"role": "customer"})
|
|
123
|
+
if r.status == "awaiting_approval":
|
|
124
|
+
print(r.pending_call) # {"tool": "create_ticket", "arguments": {...}}
|
|
125
|
+
r = await resume_agent(r.run_id, True, [SEARCH, TICKET], store, backend=b)
|
|
126
|
+
```
|
|
127
|
+
|
|
128
|
+
### Other hooks
|
|
129
|
+
|
|
130
|
+
- `final_check(answer, citations, steps) -> reason | None` accepts or
|
|
131
|
+
rejects the final answer, for example "every citation must be a
|
|
132
|
+
doc_id a tool returned".
|
|
133
|
+
- `prefetch=[("search_knowledge_base", {"query": task})]` runs read
|
|
134
|
+
tools before the first model turn.
|
|
135
|
+
- `ToolSpec(precondition=...)` is a deterministic business rule checked
|
|
136
|
+
on a proposed call.
|
|
137
|
+
|
|
138
|
+
## Composing agents
|
|
139
|
+
|
|
140
|
+
Every block is a step, `async (task, ctx) -> Outcome`, so blocks nest
|
|
141
|
+
freely.
|
|
142
|
+
|
|
143
|
+
| Block | What it does |
|
|
144
|
+
|---|---|
|
|
145
|
+
| `Agent` | One run of the loop: instructions, tools, model, budget, final check. |
|
|
146
|
+
| `Sequence` | Waterfall: each step's answer becomes part of the next task. Stops at the first step that does not answer. |
|
|
147
|
+
| `Router` | A classifier picks one route. The classifier is any function (keyword rules, embeddings) or `LLMClassifier`, which constrains the model to the route names. |
|
|
148
|
+
| `Parallel` | Branches run concurrently. Results are merged with `join_answers`, `majority_vote`, your own function, or an aggregator agent. |
|
|
149
|
+
| `Handoff` | The source agent gets a `handoff_to_<target>` tool. The target sees only the structured note, not the conversation. At most one hop. |
|
|
150
|
+
| `Refine` | Evaluator-optimizer: the worker answers, a critic reviews, the worker revises, up to `max_rounds`. The critic is a rule function or `LLMCritic`. |
|
|
151
|
+
| `Fallback` | Tries steps in order; the first that answers wins. |
|
|
152
|
+
| `Timeout` | A wall-time limit around any step. |
|
|
153
|
+
| `step(fn)` | Any `async (task, ctx) -> str \| Outcome` function as a step. |
|
|
154
|
+
|
|
155
|
+
```python
|
|
156
|
+
from agent_loop import (Agent, Context, Fallback, Handoff, LLMClassifier, LLMCritic, Parallel, Refine, Router,
|
|
157
|
+
Sequence, Timeout, majority_vote)
|
|
158
|
+
|
|
159
|
+
billing = Agent("billing", "You are the billing agent. Answer only from search results.", [SEARCH])
|
|
160
|
+
technical = Agent("technical", "You are technical support. Answer only from search results.", [SEARCH])
|
|
161
|
+
writer = Agent("writer", "Rewrite the previous result as one polite sentence.")
|
|
162
|
+
|
|
163
|
+
pipeline = Timeout(
|
|
164
|
+
Router(
|
|
165
|
+
{"billing": Sequence(billing, writer), # waterfall inside a route
|
|
166
|
+
"technical": Refine(technical, LLMCritic("Must give concrete steps."), max_rounds=2)},
|
|
167
|
+
LLMClassifier({"billing": "payments, refunds, plans", "technical": "bugs and errors"}),
|
|
168
|
+
default="technical",
|
|
169
|
+
),
|
|
170
|
+
seconds=120,
|
|
171
|
+
)
|
|
172
|
+
|
|
173
|
+
ctx = Context(backend=OllamaBackend("llama3.2:3b"), run_store=SqliteAgentRunStore("runs.sqlite3"),
|
|
174
|
+
context={"subject": "user-42"})
|
|
175
|
+
outcome = await pipeline("When will my refund arrive?", ctx)
|
|
176
|
+
print(outcome.status, outcome.answer, outcome.data["route"], len(outcome.runs))
|
|
177
|
+
```
|
|
178
|
+
|
|
179
|
+
`Outcome` has `status`, `answer`, `runs` (every `AgentResult` inside, in
|
|
180
|
+
order) and `data`, which records what each block decided: the route, the
|
|
181
|
+
votes, review rounds, which fallback answered.
|
|
182
|
+
|
|
183
|
+
`examples/patterns.py` runs every block against a local model and
|
|
184
|
+
captures each run as a flow-xray trace.
|
|
185
|
+
|
|
186
|
+
### Limits
|
|
187
|
+
|
|
188
|
+
- When an agent inside a composite pauses for approval, the composite
|
|
189
|
+
stops and returns `awaiting_approval`. Resuming that agent run does
|
|
190
|
+
not continue the rest of the composite.
|
|
191
|
+
- Token and tool budgets apply per agent run. Use `Timeout` for a
|
|
192
|
+
deadline across a whole composite.
|
|
193
|
+
- `majority_vote` compares exact answers, so use it for labels and
|
|
194
|
+
numbers, not free text.
|
|
195
|
+
- The run store is SQLite: one host, or a shared file system with
|
|
196
|
+
working file locks.
|
|
197
|
+
- Recovering after a crash during an approved write re-executes that
|
|
198
|
+
write. It is safe only if the tool is idempotent across processes
|
|
199
|
+
(`current_call_id`).
|
|
200
|
+
|
|
201
|
+
## Backends
|
|
202
|
+
|
|
203
|
+
The loop needs any object with:
|
|
204
|
+
|
|
205
|
+
```python
|
|
206
|
+
async def generate(self, messages, format=None, options=None, trace_id=None) -> str
|
|
207
|
+
```
|
|
208
|
+
|
|
209
|
+
`format` is a JSON schema the reply must follow. A backend should report
|
|
210
|
+
tokens with `agent_loop.usage.add(prompt, completion)`, or `max_tokens`
|
|
211
|
+
is not enforced. `agent_loop.ollama.OllamaBackend` is a dependency-free
|
|
212
|
+
reference backend with no retries. For production, wrap your client with
|
|
213
|
+
retries and a circuit breaker.
|
|
214
|
+
|
|
215
|
+
## Observability
|
|
216
|
+
|
|
217
|
+
- **flow-xray**: with `agent-runloop[trace]` installed, `run_agent`, each tool
|
|
218
|
+
execution, each composite block and each model call become nodes in a
|
|
219
|
+
flow-xray call tree, with inputs, outputs, tokens and latency.
|
|
220
|
+
- **Step events**: by default they go to the `agent_loop` logger at
|
|
221
|
+
DEBUG. To send them to your own logging and trace-id binding:
|
|
222
|
+
|
|
223
|
+
```python
|
|
224
|
+
from agent_loop import hooks
|
|
225
|
+
hooks.configure(log=my_log_step, bind_trace=my_bind_trace) # log(trace_id, step, **fields)
|
|
226
|
+
```
|
|
227
|
+
|
|
228
|
+
## License
|
|
229
|
+
|
|
230
|
+
MIT
|
|
@@ -0,0 +1,203 @@
|
|
|
1
|
+
# agent-runloop
|
|
2
|
+
|
|
3
|
+
`pip install agent-runloop`, then `import agent_loop`.
|
|
4
|
+
|
|
5
|
+
An explicit agent loop for tool-using LLM agents, and blocks to compose
|
|
6
|
+
agents into routers, waterfalls, parallel fan-outs, handoffs and
|
|
7
|
+
review loops.
|
|
8
|
+
|
|
9
|
+
The model never calls anything. On every turn it returns one JSON
|
|
10
|
+
decision: "call this tool with these arguments" or "here is the final
|
|
11
|
+
answer". The rest is ordinary code:
|
|
12
|
+
|
|
13
|
+
```
|
|
14
|
+
generate -> parse JSON -> validate decision -> look up tool -> validate arguments
|
|
15
|
+
-> reject duplicates -> check budget, precondition, authorization
|
|
16
|
+
-> execute (timeout) -> feed result back as delimited, untrusted data -> generate ...
|
|
17
|
+
```
|
|
18
|
+
|
|
19
|
+
Every rejection (bad JSON, unknown tool, invalid arguments, duplicate
|
|
20
|
+
call, tool exception) becomes an observation the model sees on its next
|
|
21
|
+
turn. None of them execute anything.
|
|
22
|
+
|
|
23
|
+
```bash
|
|
24
|
+
pip install agent-runloop # core: pydantic only
|
|
25
|
+
pip install "agent-runloop[trace]" # + flow-xray call-tree tracing
|
|
26
|
+
```
|
|
27
|
+
|
|
28
|
+
Python 3.11+.
|
|
29
|
+
|
|
30
|
+
## What the loop does
|
|
31
|
+
|
|
32
|
+
- **Validated tool calls.** Tool arguments are pydantic models. Invalid
|
|
33
|
+
calls go back to the model as structured errors, never to your code.
|
|
34
|
+
- **Human approval for writes.** A tool with `writes=True` never runs on
|
|
35
|
+
the model's word. The run pauses as `awaiting_approval` with the
|
|
36
|
+
proposed call. `resume_agent(run_id, approved=True|False)` continues
|
|
37
|
+
it, from another request or another process. The approve step is a
|
|
38
|
+
compare-and-set, so two approvals cannot both execute.
|
|
39
|
+
- **Budgets.** Hard limits per run on model turns, executed tool calls,
|
|
40
|
+
tokens actually used and wall time. They carry across pause and resume.
|
|
41
|
+
- **Crash recovery.** The loop saves a checkpoint to SQLite with a lease
|
|
42
|
+
before every model turn. If the process dies, `recover_agent(run_id)`
|
|
43
|
+
continues from the last checkpoint once the lease expires.
|
|
44
|
+
- **Authorization and preconditions.** These come from trusted run
|
|
45
|
+
context, never from model output. They are checked when a call is
|
|
46
|
+
proposed (a human is never asked to approve a forbidden action) and
|
|
47
|
+
again at execution.
|
|
48
|
+
- **Idempotency.** `current_call_id` gives each tool call a stable id
|
|
49
|
+
(run id + hash of the validated call). A write tool can use it as an
|
|
50
|
+
idempotency key.
|
|
51
|
+
- **Prompt-injection hygiene.** Tool output goes back delimited and
|
|
52
|
+
labelled as data, with the original task restated after it. The
|
|
53
|
+
system message starts with a fixed instruction-hierarchy policy.
|
|
54
|
+
- **Audit and versions.** One audit row per tool execution. Every result
|
|
55
|
+
records the model and a hash of the whole system prompt (instructions,
|
|
56
|
+
protocol, tool catalog).
|
|
57
|
+
- **Live events.** Pass an `asyncio.Queue` to stream steps, for example
|
|
58
|
+
over SSE.
|
|
59
|
+
|
|
60
|
+
## Quick start
|
|
61
|
+
|
|
62
|
+
```python
|
|
63
|
+
import asyncio
|
|
64
|
+
from pydantic import BaseModel
|
|
65
|
+
from agent_loop import Budget, SqliteAgentRunStore, ToolSpec, run_agent
|
|
66
|
+
from agent_loop.ollama import OllamaBackend
|
|
67
|
+
|
|
68
|
+
class SearchArgs(BaseModel):
|
|
69
|
+
query: str
|
|
70
|
+
|
|
71
|
+
async def search(args: SearchArgs, trace_id: str):
|
|
72
|
+
return [{"doc_id": "refunds", "text": "Refunds take 5 to 7 business days."}]
|
|
73
|
+
|
|
74
|
+
result = asyncio.run(run_agent(
|
|
75
|
+
"How long does a refund take?",
|
|
76
|
+
"You are a support agent. Answer only from search results.",
|
|
77
|
+
[ToolSpec("search_knowledge_base", "Search the knowledge base.", SearchArgs, search)],
|
|
78
|
+
backend=OllamaBackend("llama3.2:3b"),
|
|
79
|
+
run_store=SqliteAgentRunStore("runs.sqlite3"),
|
|
80
|
+
budget=Budget(max_iterations=4, max_tool_calls=4, max_tokens=8000, max_seconds=60),
|
|
81
|
+
))
|
|
82
|
+
print(result.status, result.answer, result.usage)
|
|
83
|
+
```
|
|
84
|
+
|
|
85
|
+
`result.status` is one of `answered`, `awaiting_approval`, `max_iterations`,
|
|
86
|
+
`budget_exceeded`, `timeout`, `rejected_final`, `model_unavailable` or
|
|
87
|
+
`cancelled`. `result.steps` lists every step, including rejected ones.
|
|
88
|
+
|
|
89
|
+
### Human approval
|
|
90
|
+
|
|
91
|
+
```python
|
|
92
|
+
TICKET = ToolSpec("create_ticket", "Open a support ticket.", TicketArgs, create_ticket, writes=True,
|
|
93
|
+
authorize=lambda ctx: ctx.get("role") == "customer")
|
|
94
|
+
|
|
95
|
+
r = await run_agent(task, instructions, [SEARCH, TICKET], backend=b, run_store=store, context={"role": "customer"})
|
|
96
|
+
if r.status == "awaiting_approval":
|
|
97
|
+
print(r.pending_call) # {"tool": "create_ticket", "arguments": {...}}
|
|
98
|
+
r = await resume_agent(r.run_id, True, [SEARCH, TICKET], store, backend=b)
|
|
99
|
+
```
|
|
100
|
+
|
|
101
|
+
### Other hooks
|
|
102
|
+
|
|
103
|
+
- `final_check(answer, citations, steps) -> reason | None` accepts or
|
|
104
|
+
rejects the final answer, for example "every citation must be a
|
|
105
|
+
doc_id a tool returned".
|
|
106
|
+
- `prefetch=[("search_knowledge_base", {"query": task})]` runs read
|
|
107
|
+
tools before the first model turn.
|
|
108
|
+
- `ToolSpec(precondition=...)` is a deterministic business rule checked
|
|
109
|
+
on a proposed call.
|
|
110
|
+
|
|
111
|
+
## Composing agents
|
|
112
|
+
|
|
113
|
+
Every block is a step, `async (task, ctx) -> Outcome`, so blocks nest
|
|
114
|
+
freely.
|
|
115
|
+
|
|
116
|
+
| Block | What it does |
|
|
117
|
+
|---|---|
|
|
118
|
+
| `Agent` | One run of the loop: instructions, tools, model, budget, final check. |
|
|
119
|
+
| `Sequence` | Waterfall: each step's answer becomes part of the next task. Stops at the first step that does not answer. |
|
|
120
|
+
| `Router` | A classifier picks one route. The classifier is any function (keyword rules, embeddings) or `LLMClassifier`, which constrains the model to the route names. |
|
|
121
|
+
| `Parallel` | Branches run concurrently. Results are merged with `join_answers`, `majority_vote`, your own function, or an aggregator agent. |
|
|
122
|
+
| `Handoff` | The source agent gets a `handoff_to_<target>` tool. The target sees only the structured note, not the conversation. At most one hop. |
|
|
123
|
+
| `Refine` | Evaluator-optimizer: the worker answers, a critic reviews, the worker revises, up to `max_rounds`. The critic is a rule function or `LLMCritic`. |
|
|
124
|
+
| `Fallback` | Tries steps in order; the first that answers wins. |
|
|
125
|
+
| `Timeout` | A wall-time limit around any step. |
|
|
126
|
+
| `step(fn)` | Any `async (task, ctx) -> str \| Outcome` function as a step. |
|
|
127
|
+
|
|
128
|
+
```python
|
|
129
|
+
from agent_loop import (Agent, Context, Fallback, Handoff, LLMClassifier, LLMCritic, Parallel, Refine, Router,
|
|
130
|
+
Sequence, Timeout, majority_vote)
|
|
131
|
+
|
|
132
|
+
billing = Agent("billing", "You are the billing agent. Answer only from search results.", [SEARCH])
|
|
133
|
+
technical = Agent("technical", "You are technical support. Answer only from search results.", [SEARCH])
|
|
134
|
+
writer = Agent("writer", "Rewrite the previous result as one polite sentence.")
|
|
135
|
+
|
|
136
|
+
pipeline = Timeout(
|
|
137
|
+
Router(
|
|
138
|
+
{"billing": Sequence(billing, writer), # waterfall inside a route
|
|
139
|
+
"technical": Refine(technical, LLMCritic("Must give concrete steps."), max_rounds=2)},
|
|
140
|
+
LLMClassifier({"billing": "payments, refunds, plans", "technical": "bugs and errors"}),
|
|
141
|
+
default="technical",
|
|
142
|
+
),
|
|
143
|
+
seconds=120,
|
|
144
|
+
)
|
|
145
|
+
|
|
146
|
+
ctx = Context(backend=OllamaBackend("llama3.2:3b"), run_store=SqliteAgentRunStore("runs.sqlite3"),
|
|
147
|
+
context={"subject": "user-42"})
|
|
148
|
+
outcome = await pipeline("When will my refund arrive?", ctx)
|
|
149
|
+
print(outcome.status, outcome.answer, outcome.data["route"], len(outcome.runs))
|
|
150
|
+
```
|
|
151
|
+
|
|
152
|
+
`Outcome` has `status`, `answer`, `runs` (every `AgentResult` inside, in
|
|
153
|
+
order) and `data`, which records what each block decided: the route, the
|
|
154
|
+
votes, review rounds, which fallback answered.
|
|
155
|
+
|
|
156
|
+
`examples/patterns.py` runs every block against a local model and
|
|
157
|
+
captures each run as a flow-xray trace.
|
|
158
|
+
|
|
159
|
+
### Limits
|
|
160
|
+
|
|
161
|
+
- When an agent inside a composite pauses for approval, the composite
|
|
162
|
+
stops and returns `awaiting_approval`. Resuming that agent run does
|
|
163
|
+
not continue the rest of the composite.
|
|
164
|
+
- Token and tool budgets apply per agent run. Use `Timeout` for a
|
|
165
|
+
deadline across a whole composite.
|
|
166
|
+
- `majority_vote` compares exact answers, so use it for labels and
|
|
167
|
+
numbers, not free text.
|
|
168
|
+
- The run store is SQLite: one host, or a shared file system with
|
|
169
|
+
working file locks.
|
|
170
|
+
- Recovering after a crash during an approved write re-executes that
|
|
171
|
+
write. It is safe only if the tool is idempotent across processes
|
|
172
|
+
(`current_call_id`).
|
|
173
|
+
|
|
174
|
+
## Backends
|
|
175
|
+
|
|
176
|
+
The loop needs any object with:
|
|
177
|
+
|
|
178
|
+
```python
|
|
179
|
+
async def generate(self, messages, format=None, options=None, trace_id=None) -> str
|
|
180
|
+
```
|
|
181
|
+
|
|
182
|
+
`format` is a JSON schema the reply must follow. A backend should report
|
|
183
|
+
tokens with `agent_loop.usage.add(prompt, completion)`, or `max_tokens`
|
|
184
|
+
is not enforced. `agent_loop.ollama.OllamaBackend` is a dependency-free
|
|
185
|
+
reference backend with no retries. For production, wrap your client with
|
|
186
|
+
retries and a circuit breaker.
|
|
187
|
+
|
|
188
|
+
## Observability
|
|
189
|
+
|
|
190
|
+
- **flow-xray**: with `agent-runloop[trace]` installed, `run_agent`, each tool
|
|
191
|
+
execution, each composite block and each model call become nodes in a
|
|
192
|
+
flow-xray call tree, with inputs, outputs, tokens and latency.
|
|
193
|
+
- **Step events**: by default they go to the `agent_loop` logger at
|
|
194
|
+
DEBUG. To send them to your own logging and trace-id binding:
|
|
195
|
+
|
|
196
|
+
```python
|
|
197
|
+
from agent_loop import hooks
|
|
198
|
+
hooks.configure(log=my_log_step, bind_trace=my_bind_trace) # log(trace_id, step, **fields)
|
|
199
|
+
```
|
|
200
|
+
|
|
201
|
+
## License
|
|
202
|
+
|
|
203
|
+
MIT
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
"""agent-runloop: an explicit, durable agent loop and blocks to compose agents.
|
|
2
|
+
|
|
3
|
+
The model proposes one JSON decision per turn; this code validates and
|
|
4
|
+
executes it. Write tools pause for human approval; runs checkpoint to
|
|
5
|
+
SQLite and can be resumed or recovered in another process.
|
|
6
|
+
"""
|
|
7
|
+
from importlib.metadata import PackageNotFoundError, version
|
|
8
|
+
|
|
9
|
+
from agent_loop import hooks, usage
|
|
10
|
+
from agent_loop.backend import LLMBackend
|
|
11
|
+
from agent_loop.compose import (
|
|
12
|
+
Agent, Context, Fallback, Handoff, HandoffNote, LLMClassifier, LLMCritic, Outcome, Parallel, Refine, Router,
|
|
13
|
+
Sequence, Step, Timeout, Verdict, chain_task, join_answers, majority_vote, step,
|
|
14
|
+
)
|
|
15
|
+
from agent_loop.loop import (
|
|
16
|
+
AgentDecision, AgentResult, AgentStep, Budget, EventSink, FinalCheck, Status, ToolSpec, cancel_agent,
|
|
17
|
+
current_call_id, recover_agent, resume_agent, run_agent, tool_error,
|
|
18
|
+
)
|
|
19
|
+
from agent_loop.runs import SqliteAgentRunStore
|
|
20
|
+
|
|
21
|
+
try:
|
|
22
|
+
__version__ = version("agent-runloop")
|
|
23
|
+
except PackageNotFoundError: # running from a source checkout
|
|
24
|
+
__version__ = "0.0.0"
|
|
25
|
+
|
|
26
|
+
__all__ = [
|
|
27
|
+
"Agent", "AgentDecision", "AgentResult", "AgentStep", "Budget", "Context", "EventSink", "Fallback", "FinalCheck",
|
|
28
|
+
"Handoff", "HandoffNote", "LLMBackend", "LLMClassifier", "LLMCritic", "Outcome", "Parallel", "Refine", "Router",
|
|
29
|
+
"Sequence", "SqliteAgentRunStore", "Status", "Step", "Timeout", "ToolSpec", "Verdict", "cancel_agent",
|
|
30
|
+
"chain_task", "current_call_id", "hooks", "join_answers", "majority_vote", "recover_agent", "resume_agent",
|
|
31
|
+
"run_agent", "step", "tool_error", "usage",
|
|
32
|
+
]
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
"""flow-xray tracing when it is installed (`pip install agent-runloop[trace]`),
|
|
2
|
+
otherwise a no-op with the same surface."""
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
try:
|
|
6
|
+
from flow_xray import trace
|
|
7
|
+
except ImportError: # pragma: no cover - depends on the environment
|
|
8
|
+
class _NoTrace:
|
|
9
|
+
def __call__(self, fn):
|
|
10
|
+
return fn
|
|
11
|
+
|
|
12
|
+
def meta(self, **fields) -> None:
|
|
13
|
+
pass
|
|
14
|
+
|
|
15
|
+
trace = _NoTrace() # type: ignore[assignment]
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
"""The one interface the loop needs from a model."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
from typing import Protocol, runtime_checkable
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
@runtime_checkable
|
|
8
|
+
class LLMBackend(Protocol):
|
|
9
|
+
"""`generate` returns the model's reply text for a chat `messages`
|
|
10
|
+
list. `format` is a JSON schema the reply must follow (the loop always
|
|
11
|
+
passes one); `options` carries sampling settings. A backend should
|
|
12
|
+
raise after its own retries when the model is unavailable, and report
|
|
13
|
+
token usage with `agent_loop.usage.add` for token budgets to work.
|
|
14
|
+
An optional `model` attribute names the model in run versions."""
|
|
15
|
+
|
|
16
|
+
async def generate(self, messages: list[dict], format: str | dict | None = None,
|
|
17
|
+
options: dict | None = None, trace_id: str | None = None) -> str: ...
|