coreloop 0.1.2__tar.gz → 0.1.4__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.
- {coreloop-0.1.2 → coreloop-0.1.4}/PKG-INFO +45 -8
- {coreloop-0.1.2 → coreloop-0.1.4}/README.md +40 -5
- coreloop-0.1.4/pyproject.toml +88 -0
- coreloop-0.1.2/pyproject.toml → coreloop-0.1.4/pyproject.toml.orig +6 -4
- {coreloop-0.1.2 → coreloop-0.1.4}/src/coreloop/__init__.py +5 -1
- {coreloop-0.1.2 → coreloop-0.1.4}/src/coreloop/_api_client.py +27 -2
- {coreloop-0.1.2 → coreloop-0.1.4}/src/coreloop/_tool_execution.py +2 -2
- {coreloop-0.1.2 → coreloop-0.1.4}/src/coreloop/agent.py +14 -0
- {coreloop-0.1.2 → coreloop-0.1.4}/src/coreloop/cli/_run.py +1 -1
- coreloop-0.1.4/src/coreloop/complete.py +108 -0
- {coreloop-0.1.2 → coreloop-0.1.4}/src/coreloop/config.py +1 -0
- {coreloop-0.1.2 → coreloop-0.1.4}/src/coreloop/hooks.py +14 -0
- {coreloop-0.1.2 → coreloop-0.1.4}/src/coreloop/profiles.py +4 -1
- coreloop-0.1.4/src/coreloop/structured.py +48 -0
- {coreloop-0.1.2 → coreloop-0.1.4}/src/coreloop/tools/_shared.py +2 -1
- {coreloop-0.1.2 → coreloop-0.1.4}/src/coreloop/tools/bash.py +2 -2
- {coreloop-0.1.2 → coreloop-0.1.4}/src/coreloop/tools/edit.py +3 -37
- coreloop-0.1.4/src/coreloop/web_tools.py +145 -0
- coreloop-0.1.2/src/coreloop/web_tools.py +0 -98
- {coreloop-0.1.2 → coreloop-0.1.4}/LICENSE +0 -0
- {coreloop-0.1.2 → coreloop-0.1.4}/src/coreloop/.coreloop.toml +0 -0
- {coreloop-0.1.2 → coreloop-0.1.4}/src/coreloop/__main__.py +0 -0
- {coreloop-0.1.2 → coreloop-0.1.4}/src/coreloop/_cache.py +0 -0
- {coreloop-0.1.2 → coreloop-0.1.4}/src/coreloop/_logging.py +0 -0
- {coreloop-0.1.2 → coreloop-0.1.4}/src/coreloop/cli/__init__.py +0 -0
- {coreloop-0.1.2 → coreloop-0.1.4}/src/coreloop/cli/_tools.py +0 -0
- {coreloop-0.1.2 → coreloop-0.1.4}/src/coreloop/py.typed +0 -0
- {coreloop-0.1.2 → coreloop-0.1.4}/src/coreloop/tool_registry.py +0 -0
- {coreloop-0.1.2 → coreloop-0.1.4}/src/coreloop/tools/__init__.py +0 -0
- {coreloop-0.1.2 → coreloop-0.1.4}/src/coreloop/tools/grep.py +0 -0
- {coreloop-0.1.2 → coreloop-0.1.4}/src/coreloop/tools/ls.py +0 -0
- {coreloop-0.1.2 → coreloop-0.1.4}/src/coreloop/tools/read.py +0 -0
- {coreloop-0.1.2 → coreloop-0.1.4}/src/coreloop/types.py +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: coreloop
|
|
3
|
-
Version: 0.1.
|
|
3
|
+
Version: 0.1.4
|
|
4
4
|
Summary: A lightweight async tool-calling agent for any OpenAI-compatible API, usable as a library or CLI
|
|
5
5
|
Keywords: llm,agent,tool-calling,openai,ollama,cli,async,streaming,hooks,httpx,local-models
|
|
6
6
|
Author: Chris Kilner
|
|
@@ -11,6 +11,8 @@ Classifier: Development Status :: 4 - Beta
|
|
|
11
11
|
Classifier: Intended Audience :: Developers
|
|
12
12
|
Classifier: License :: OSI Approved :: MIT License
|
|
13
13
|
Classifier: Programming Language :: Python :: 3
|
|
14
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
15
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
14
16
|
Classifier: Programming Language :: Python :: 3.14
|
|
15
17
|
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
|
|
16
18
|
Classifier: Topic :: Software Development :: Libraries :: Python Modules
|
|
@@ -21,8 +23,8 @@ Requires-Dist: pydantic>=2.0,<3
|
|
|
21
23
|
Requires-Dist: diskcache>=5.6.3
|
|
22
24
|
Requires-Dist: python-dotenv>=1.0.1
|
|
23
25
|
Requires-Dist: rich>=13.0.0
|
|
24
|
-
Requires-Dist:
|
|
25
|
-
Requires-Python: >=3.
|
|
26
|
+
Requires-Dist: html-to-markdown>=3.5 ; extra == 'web'
|
|
27
|
+
Requires-Python: >=3.12
|
|
26
28
|
Project-URL: Homepage, https://github.com/rhiza-fr/coreloop
|
|
27
29
|
Project-URL: Repository, https://github.com/rhiza-fr/coreloop
|
|
28
30
|
Project-URL: Issues, https://github.com/rhiza-fr/coreloop/issues
|
|
@@ -52,6 +54,8 @@ and `web_fetch` (via the `[web]` extra).
|
|
|
52
54
|
|
|
53
55
|
## Install
|
|
54
56
|
|
|
57
|
+
Requires Python 3.12+.
|
|
58
|
+
|
|
55
59
|
```bash
|
|
56
60
|
pip install coreloop
|
|
57
61
|
pip install "coreloop[web]" # adds web_search and web_fetch
|
|
@@ -79,7 +83,7 @@ async def main():
|
|
|
79
83
|
asyncio.run(main())
|
|
80
84
|
```
|
|
81
85
|
|
|
82
|
-
Or load settings from a named profile in
|
|
86
|
+
Or load settings from a named profile in `~/.coreloop.toml`:
|
|
83
87
|
|
|
84
88
|
```python
|
|
85
89
|
agent = Agent.from_profile("openai")
|
|
@@ -88,7 +92,7 @@ agent = Agent.from_profile("openai")
|
|
|
88
92
|
## CLI
|
|
89
93
|
|
|
90
94
|
`core` is a REPL / one-shot runner with profile support. On first run it copies
|
|
91
|
-
the bundled `coreloop.toml` to
|
|
95
|
+
the bundled `coreloop.toml` to `~/.coreloop.toml` — edit that file to set
|
|
92
96
|
your default model, tools, and provider credentials.
|
|
93
97
|
|
|
94
98
|
```bash
|
|
@@ -110,7 +114,7 @@ core --think -p "Explain this step by step" --model qwen3-14b
|
|
|
110
114
|
|
|
111
115
|
| Flag | Default | Description |
|
|
112
116
|
|------|---------|-------------|
|
|
113
|
-
| `--profile` | `default` | Named profile from
|
|
117
|
+
| `--profile` | `default` | Named profile from `~/.coreloop.toml` |
|
|
114
118
|
| `-m, --model` | profile value | Model name — overrides profile (`CORELOOP_MODEL`) |
|
|
115
119
|
| `--base-url` | profile value | API base URL — overrides profile (`CORELOOP_BASE_URL`) |
|
|
116
120
|
| `--api-key` | profile value | API key — overrides profile (`CORELOOP_API_KEY`) |
|
|
@@ -211,7 +215,7 @@ docker run -d -p 8080:8080 searxng/searxng
|
|
|
211
215
|
| Tool | Description |
|
|
212
216
|
|------|-------------|
|
|
213
217
|
| `web_search` | Search via SearXNG; returns titles, URLs, snippets; supports `max_results`, `domain_filter`, `recency` |
|
|
214
|
-
| `web_fetch` | Fetch a URL; `extract_mode`: `markdown` (default), `
|
|
218
|
+
| `web_fetch` | Fetch a URL; `extract_mode`: `markdown` (default), `raw`, `metadata` |
|
|
215
219
|
|
|
216
220
|
## Custom tools
|
|
217
221
|
|
|
@@ -294,7 +298,7 @@ swallowed — they cannot crash the agent.
|
|
|
294
298
|
|
|
295
299
|
## Config profiles
|
|
296
300
|
|
|
297
|
-
`Agent.from_profile("openai")` builds an `AgentConfig` from
|
|
301
|
+
`Agent.from_profile("openai")` builds an `AgentConfig` from `~/.coreloop.toml`
|
|
298
302
|
(or `$CORELOOP_CONFIG`). Every profile inherits from `[profiles.default]`; named
|
|
299
303
|
profiles override individual keys.
|
|
300
304
|
|
|
@@ -322,6 +326,39 @@ pre-configured profiles for Ollama, OpenAI, Groq, DeepSeek, Together, and OpenRo
|
|
|
322
326
|
`dataclasses.replace(cfg, model="other")` to derive variants, or `Agent.from_config(cfg)`
|
|
323
327
|
to construct an agent from one.
|
|
324
328
|
|
|
329
|
+
## Structured output
|
|
330
|
+
|
|
331
|
+
`complete()` is a one-shot call — no tools, no loop. With `schema`, output is constrained
|
|
332
|
+
via `response_format: {"type": "json_schema"}` and validated before it is returned.
|
|
333
|
+
|
|
334
|
+
```python
|
|
335
|
+
from pydantic import BaseModel
|
|
336
|
+
from coreloop import complete
|
|
337
|
+
|
|
338
|
+
class Triage(BaseModel):
|
|
339
|
+
category: str
|
|
340
|
+
urgent: bool
|
|
341
|
+
|
|
342
|
+
result = await complete("Kettle broke again.", model="qwen3:8b", schema=Triage)
|
|
343
|
+
# -> Triage(category='...', urgent=True)
|
|
344
|
+
```
|
|
345
|
+
|
|
346
|
+
Without `schema` it returns the final `Message`. `ValidationError` propagates to the
|
|
347
|
+
caller, so retry policy stays yours.
|
|
348
|
+
|
|
349
|
+
`prompt` also accepts a message list, which makes "loop, then extract" compose:
|
|
350
|
+
|
|
351
|
+
```python
|
|
352
|
+
async for _ in agent.run([Message(role="user", content="Check the logs and triage.")]):
|
|
353
|
+
pass
|
|
354
|
+
|
|
355
|
+
record = await complete(agent.messages, model="qwen3:8b", schema=Triage)
|
|
356
|
+
```
|
|
357
|
+
|
|
358
|
+
It is deliberately not an `Agent` parameter: constrained decoding and tool-calling cannot
|
|
359
|
+
coexist in one turn, so the loop stays unconstrained and `complete()` is the terminal
|
|
360
|
+
extraction step.
|
|
361
|
+
|
|
325
362
|
## `Message`
|
|
326
363
|
|
|
327
364
|
| Field | Type | Description |
|
|
@@ -21,6 +21,8 @@ and `web_fetch` (via the `[web]` extra).
|
|
|
21
21
|
|
|
22
22
|
## Install
|
|
23
23
|
|
|
24
|
+
Requires Python 3.12+.
|
|
25
|
+
|
|
24
26
|
```bash
|
|
25
27
|
pip install coreloop
|
|
26
28
|
pip install "coreloop[web]" # adds web_search and web_fetch
|
|
@@ -48,7 +50,7 @@ async def main():
|
|
|
48
50
|
asyncio.run(main())
|
|
49
51
|
```
|
|
50
52
|
|
|
51
|
-
Or load settings from a named profile in
|
|
53
|
+
Or load settings from a named profile in `~/.coreloop.toml`:
|
|
52
54
|
|
|
53
55
|
```python
|
|
54
56
|
agent = Agent.from_profile("openai")
|
|
@@ -57,7 +59,7 @@ agent = Agent.from_profile("openai")
|
|
|
57
59
|
## CLI
|
|
58
60
|
|
|
59
61
|
`core` is a REPL / one-shot runner with profile support. On first run it copies
|
|
60
|
-
the bundled `coreloop.toml` to
|
|
62
|
+
the bundled `coreloop.toml` to `~/.coreloop.toml` — edit that file to set
|
|
61
63
|
your default model, tools, and provider credentials.
|
|
62
64
|
|
|
63
65
|
```bash
|
|
@@ -79,7 +81,7 @@ core --think -p "Explain this step by step" --model qwen3-14b
|
|
|
79
81
|
|
|
80
82
|
| Flag | Default | Description |
|
|
81
83
|
|------|---------|-------------|
|
|
82
|
-
| `--profile` | `default` | Named profile from
|
|
84
|
+
| `--profile` | `default` | Named profile from `~/.coreloop.toml` |
|
|
83
85
|
| `-m, --model` | profile value | Model name — overrides profile (`CORELOOP_MODEL`) |
|
|
84
86
|
| `--base-url` | profile value | API base URL — overrides profile (`CORELOOP_BASE_URL`) |
|
|
85
87
|
| `--api-key` | profile value | API key — overrides profile (`CORELOOP_API_KEY`) |
|
|
@@ -180,7 +182,7 @@ docker run -d -p 8080:8080 searxng/searxng
|
|
|
180
182
|
| Tool | Description |
|
|
181
183
|
|------|-------------|
|
|
182
184
|
| `web_search` | Search via SearXNG; returns titles, URLs, snippets; supports `max_results`, `domain_filter`, `recency` |
|
|
183
|
-
| `web_fetch` | Fetch a URL; `extract_mode`: `markdown` (default), `
|
|
185
|
+
| `web_fetch` | Fetch a URL; `extract_mode`: `markdown` (default), `raw`, `metadata` |
|
|
184
186
|
|
|
185
187
|
## Custom tools
|
|
186
188
|
|
|
@@ -263,7 +265,7 @@ swallowed — they cannot crash the agent.
|
|
|
263
265
|
|
|
264
266
|
## Config profiles
|
|
265
267
|
|
|
266
|
-
`Agent.from_profile("openai")` builds an `AgentConfig` from
|
|
268
|
+
`Agent.from_profile("openai")` builds an `AgentConfig` from `~/.coreloop.toml`
|
|
267
269
|
(or `$CORELOOP_CONFIG`). Every profile inherits from `[profiles.default]`; named
|
|
268
270
|
profiles override individual keys.
|
|
269
271
|
|
|
@@ -291,6 +293,39 @@ pre-configured profiles for Ollama, OpenAI, Groq, DeepSeek, Together, and OpenRo
|
|
|
291
293
|
`dataclasses.replace(cfg, model="other")` to derive variants, or `Agent.from_config(cfg)`
|
|
292
294
|
to construct an agent from one.
|
|
293
295
|
|
|
296
|
+
## Structured output
|
|
297
|
+
|
|
298
|
+
`complete()` is a one-shot call — no tools, no loop. With `schema`, output is constrained
|
|
299
|
+
via `response_format: {"type": "json_schema"}` and validated before it is returned.
|
|
300
|
+
|
|
301
|
+
```python
|
|
302
|
+
from pydantic import BaseModel
|
|
303
|
+
from coreloop import complete
|
|
304
|
+
|
|
305
|
+
class Triage(BaseModel):
|
|
306
|
+
category: str
|
|
307
|
+
urgent: bool
|
|
308
|
+
|
|
309
|
+
result = await complete("Kettle broke again.", model="qwen3:8b", schema=Triage)
|
|
310
|
+
# -> Triage(category='...', urgent=True)
|
|
311
|
+
```
|
|
312
|
+
|
|
313
|
+
Without `schema` it returns the final `Message`. `ValidationError` propagates to the
|
|
314
|
+
caller, so retry policy stays yours.
|
|
315
|
+
|
|
316
|
+
`prompt` also accepts a message list, which makes "loop, then extract" compose:
|
|
317
|
+
|
|
318
|
+
```python
|
|
319
|
+
async for _ in agent.run([Message(role="user", content="Check the logs and triage.")]):
|
|
320
|
+
pass
|
|
321
|
+
|
|
322
|
+
record = await complete(agent.messages, model="qwen3:8b", schema=Triage)
|
|
323
|
+
```
|
|
324
|
+
|
|
325
|
+
It is deliberately not an `Agent` parameter: constrained decoding and tool-calling cannot
|
|
326
|
+
coexist in one turn, so the loop stays unconstrained and `complete()` is the terminal
|
|
327
|
+
extraction step.
|
|
328
|
+
|
|
294
329
|
## `Message`
|
|
295
330
|
|
|
296
331
|
| Field | Type | Description |
|
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
[project]
|
|
2
|
+
name = "coreloop"
|
|
3
|
+
version = "0.1.4"
|
|
4
|
+
description = "A lightweight async tool-calling agent for any OpenAI-compatible API, usable as a library or CLI"
|
|
5
|
+
readme = "README.md"
|
|
6
|
+
license = "MIT"
|
|
7
|
+
license-files = ["LICENSE"]
|
|
8
|
+
keywords = [
|
|
9
|
+
"llm",
|
|
10
|
+
"agent",
|
|
11
|
+
"tool-calling",
|
|
12
|
+
"openai",
|
|
13
|
+
"ollama",
|
|
14
|
+
"cli",
|
|
15
|
+
"async",
|
|
16
|
+
"streaming",
|
|
17
|
+
"hooks",
|
|
18
|
+
"httpx",
|
|
19
|
+
"local-models",
|
|
20
|
+
]
|
|
21
|
+
classifiers = [
|
|
22
|
+
"Development Status :: 4 - Beta",
|
|
23
|
+
"Intended Audience :: Developers",
|
|
24
|
+
"License :: OSI Approved :: MIT License",
|
|
25
|
+
"Programming Language :: Python :: 3",
|
|
26
|
+
"Programming Language :: Python :: 3.12",
|
|
27
|
+
"Programming Language :: Python :: 3.13",
|
|
28
|
+
"Programming Language :: Python :: 3.14",
|
|
29
|
+
"Topic :: Scientific/Engineering :: Artificial Intelligence",
|
|
30
|
+
"Topic :: Software Development :: Libraries :: Python Modules",
|
|
31
|
+
"Typing :: Typed",
|
|
32
|
+
]
|
|
33
|
+
requires-python = ">=3.12"
|
|
34
|
+
dependencies = [
|
|
35
|
+
"httpx>=0.28.1",
|
|
36
|
+
"typer>=0.26.1",
|
|
37
|
+
"pydantic>=2.0,<3",
|
|
38
|
+
"diskcache>=5.6.3",
|
|
39
|
+
"python-dotenv>=1.0.1",
|
|
40
|
+
"rich>=13.0.0",
|
|
41
|
+
]
|
|
42
|
+
|
|
43
|
+
[[project.authors]]
|
|
44
|
+
name = "Chris Kilner"
|
|
45
|
+
email = "chris@rhiza.fr"
|
|
46
|
+
|
|
47
|
+
[project.urls]
|
|
48
|
+
Homepage = "https://github.com/rhiza-fr/coreloop"
|
|
49
|
+
Repository = "https://github.com/rhiza-fr/coreloop"
|
|
50
|
+
Issues = "https://github.com/rhiza-fr/coreloop/issues"
|
|
51
|
+
|
|
52
|
+
[project.optional-dependencies]
|
|
53
|
+
web = ["html-to-markdown>=3.5"]
|
|
54
|
+
|
|
55
|
+
[project.scripts]
|
|
56
|
+
core = "coreloop.cli:app"
|
|
57
|
+
|
|
58
|
+
[build-system]
|
|
59
|
+
requires = ["uv_build>=0.11.2,<0.12.0"]
|
|
60
|
+
build-backend = "uv_build"
|
|
61
|
+
|
|
62
|
+
[dependency-groups]
|
|
63
|
+
dev = [
|
|
64
|
+
"pytest>=9.0.3",
|
|
65
|
+
"pytest-asyncio>=0.25.0",
|
|
66
|
+
"pytest-cov>=7.1.0",
|
|
67
|
+
"ruff>=0.15.14",
|
|
68
|
+
]
|
|
69
|
+
|
|
70
|
+
[tool.ruff]
|
|
71
|
+
target-version = "py312"
|
|
72
|
+
line-length = 100
|
|
73
|
+
|
|
74
|
+
[tool.pytest.ini_options]
|
|
75
|
+
addopts = "-m 'not slow' --strict-markers"
|
|
76
|
+
markers = ["slow: tests that require a running Ollama instance or provider connection"]
|
|
77
|
+
|
|
78
|
+
[tool.cq.thresholds.radon-hal]
|
|
79
|
+
warning = 0.45
|
|
80
|
+
error = 0.25
|
|
81
|
+
|
|
82
|
+
[tool.interrogate]
|
|
83
|
+
ignore-init-method = true
|
|
84
|
+
ignore-init-module = false
|
|
85
|
+
ignore-semiprivate = true
|
|
86
|
+
ignore-private = true
|
|
87
|
+
ignore-magic = true
|
|
88
|
+
exclude = [".claude"]
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
[project]
|
|
2
2
|
name = "coreloop"
|
|
3
|
-
version = "0.1.
|
|
3
|
+
version = "0.1.4"
|
|
4
4
|
description = "A lightweight async tool-calling agent for any OpenAI-compatible API, usable as a library or CLI"
|
|
5
5
|
readme = "README.md"
|
|
6
6
|
license = "MIT"
|
|
@@ -14,12 +14,14 @@ classifiers = [
|
|
|
14
14
|
"Intended Audience :: Developers",
|
|
15
15
|
"License :: OSI Approved :: MIT License",
|
|
16
16
|
"Programming Language :: Python :: 3",
|
|
17
|
+
"Programming Language :: Python :: 3.12",
|
|
18
|
+
"Programming Language :: Python :: 3.13",
|
|
17
19
|
"Programming Language :: Python :: 3.14",
|
|
18
20
|
"Topic :: Scientific/Engineering :: Artificial Intelligence",
|
|
19
21
|
"Topic :: Software Development :: Libraries :: Python Modules",
|
|
20
22
|
"Typing :: Typed",
|
|
21
23
|
]
|
|
22
|
-
requires-python = ">=3.
|
|
24
|
+
requires-python = ">=3.12"
|
|
23
25
|
dependencies = [
|
|
24
26
|
"httpx>=0.28.1",
|
|
25
27
|
"typer>=0.26.1",
|
|
@@ -35,7 +37,7 @@ Repository = "https://github.com/rhiza-fr/coreloop"
|
|
|
35
37
|
Issues = "https://github.com/rhiza-fr/coreloop/issues"
|
|
36
38
|
|
|
37
39
|
[project.optional-dependencies]
|
|
38
|
-
web = ["
|
|
40
|
+
web = ["html-to-markdown>=3.5"]
|
|
39
41
|
|
|
40
42
|
[project.scripts]
|
|
41
43
|
core = "coreloop.cli:app"
|
|
@@ -53,7 +55,7 @@ dev = [
|
|
|
53
55
|
]
|
|
54
56
|
|
|
55
57
|
[tool.ruff]
|
|
56
|
-
target-version = "
|
|
58
|
+
target-version = "py312"
|
|
57
59
|
line-length = 100
|
|
58
60
|
|
|
59
61
|
[tool.pytest.ini_options]
|
|
@@ -1,12 +1,14 @@
|
|
|
1
1
|
"""coreloop: a minimal LLM agent with tool-calling support."""
|
|
2
2
|
|
|
3
3
|
from .agent import Agent
|
|
4
|
+
from .complete import complete
|
|
4
5
|
from .config import AgentConfig
|
|
5
6
|
from .tools import make_tools
|
|
6
7
|
from .tools.bash import make_bash_tool
|
|
7
8
|
from .tools.grep import make_grep_tool
|
|
8
9
|
from .hooks import AgentHooks, MaxTurnsHook
|
|
9
10
|
from .tool_registry import ToolInfo, clear_registry, get_tool, list_tools, tool
|
|
11
|
+
from .structured import to_strict_schema
|
|
10
12
|
from .web_tools import make_web_tools
|
|
11
13
|
from .types import FunctionCall, Message, ToolCall, Usage
|
|
12
14
|
|
|
@@ -21,13 +23,15 @@ __all__ = [
|
|
|
21
23
|
"ToolInfo",
|
|
22
24
|
"Usage",
|
|
23
25
|
"clear_registry",
|
|
26
|
+
"complete",
|
|
24
27
|
"get_tool",
|
|
25
28
|
"list_tools",
|
|
26
29
|
"make_bash_tool",
|
|
27
30
|
"make_grep_tool",
|
|
28
31
|
"make_tools",
|
|
29
32
|
"make_web_tools",
|
|
33
|
+
"to_strict_schema",
|
|
30
34
|
"tool",
|
|
31
35
|
]
|
|
32
36
|
|
|
33
|
-
__version__ = "0.1.
|
|
37
|
+
__version__ = "0.1.4"
|
|
@@ -7,7 +7,7 @@ is the shared shell around any backend -- it owns the httpx connection, response
|
|
|
7
7
|
caching, timing, and HTTP error handling.
|
|
8
8
|
|
|
9
9
|
Only one backend ships today (:class:`OpenAIBackend`, OpenAI-compatible chat
|
|
10
|
-
completions). Adding another provider means implementing the
|
|
10
|
+
completions). Adding another provider means implementing the ``Backend``
|
|
11
11
|
methods; nothing else in the agent loop needs to change.
|
|
12
12
|
|
|
13
13
|
Note: Ollama via the OpenAI endpoint does not stream thinking models. They
|
|
@@ -20,8 +20,10 @@ import time
|
|
|
20
20
|
from typing import Any, AsyncIterator, Protocol
|
|
21
21
|
|
|
22
22
|
import httpx
|
|
23
|
+
from pydantic import BaseModel
|
|
23
24
|
|
|
24
25
|
from ._cache import request_key
|
|
26
|
+
from .structured import to_strict_schema
|
|
25
27
|
from .tool_registry import ToolInfo
|
|
26
28
|
from .types import FunctionCall, Message, ToolCall, Usage, _dump_messages
|
|
27
29
|
|
|
@@ -31,7 +33,7 @@ logger = logging.getLogger(__name__)
|
|
|
31
33
|
class Backend(Protocol):
|
|
32
34
|
"""Provider-specific request shaping and stream parsing.
|
|
33
35
|
|
|
34
|
-
Implement these
|
|
36
|
+
Implement these methods to add a provider. The agent loop and
|
|
35
37
|
``stream_chat`` shell are backend-agnostic.
|
|
36
38
|
"""
|
|
37
39
|
|
|
@@ -53,6 +55,10 @@ class Backend(Protocol):
|
|
|
53
55
|
"""Serialize canonical messages + tools into the provider's request body."""
|
|
54
56
|
...
|
|
55
57
|
|
|
58
|
+
def response_format(self, schema: type[BaseModel]) -> dict[str, Any]:
|
|
59
|
+
"""Return body fields that constrain output to *schema*, or {} if unsupported."""
|
|
60
|
+
...
|
|
61
|
+
|
|
56
62
|
def parse_stream(
|
|
57
63
|
self, resp: httpx.Response, model: str, usage: Usage | None
|
|
58
64
|
) -> AsyncIterator[Message]:
|
|
@@ -126,6 +132,19 @@ class OpenAIBackend:
|
|
|
126
132
|
body[k] = v
|
|
127
133
|
return body
|
|
128
134
|
|
|
135
|
+
def response_format(self, schema: type[BaseModel]) -> dict[str, Any]:
|
|
136
|
+
"""Return the ``response_format`` body fragment constraining output to *schema*."""
|
|
137
|
+
return {
|
|
138
|
+
"response_format": {
|
|
139
|
+
"type": "json_schema",
|
|
140
|
+
"json_schema": {
|
|
141
|
+
"name": schema.__name__,
|
|
142
|
+
"strict": True,
|
|
143
|
+
"schema": to_strict_schema(schema),
|
|
144
|
+
},
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
|
|
129
148
|
async def parse_stream(
|
|
130
149
|
self, resp: httpx.Response, model: str, usage: Usage | None
|
|
131
150
|
) -> AsyncIterator[Message]:
|
|
@@ -265,6 +284,7 @@ async def stream_chat(
|
|
|
265
284
|
model: str,
|
|
266
285
|
messages: list[Message],
|
|
267
286
|
tools: list[ToolInfo] | None = None,
|
|
287
|
+
schema: type[BaseModel] | None = None,
|
|
268
288
|
timeout: float = 60.0,
|
|
269
289
|
client: httpx.AsyncClient | None = None,
|
|
270
290
|
llm_extra_body: dict[str, Any] | None = None,
|
|
@@ -278,11 +298,16 @@ async def stream_chat(
|
|
|
278
298
|
serves/stores cached responses, manages the httpx connection, attaches
|
|
279
299
|
wall-clock ``duration`` to the final message, and raises on HTTP errors.
|
|
280
300
|
|
|
301
|
+
With *schema*, the backend's ``response_format`` fields are merged into the
|
|
302
|
+
body after ``build_body``, so the cache key covers the schema too.
|
|
303
|
+
|
|
281
304
|
Yields progressively richer *assistant* ``Message`` objects. The last yielded
|
|
282
305
|
message for a turn has either ``content`` set **or** ``tool_calls`` populated
|
|
283
306
|
(or both), plus ``usage`` and ``duration``.
|
|
284
307
|
"""
|
|
285
308
|
body = backend.build_body(model, messages, tools, llm_extra_body)
|
|
309
|
+
if schema is not None:
|
|
310
|
+
body.update(backend.response_format(schema))
|
|
286
311
|
|
|
287
312
|
cache_key: str | None = None
|
|
288
313
|
if cache is not None:
|
|
@@ -41,11 +41,11 @@ async def exec_tool(tc: ToolCall, agent: "Agent") -> tuple[ToolCall, str, float]
|
|
|
41
41
|
replacement = await _safe_hook(agent.hooks, "on_after_tool", agent, name, args, result)
|
|
42
42
|
return tc, replacement if replacement is not None else result, 0.0
|
|
43
43
|
|
|
44
|
-
logger.
|
|
44
|
+
logger.debug("Tool call: %s(%s)", name, json.dumps(args, ensure_ascii=False) if args else "")
|
|
45
45
|
t0 = time.perf_counter()
|
|
46
46
|
result = await run_tool(info, args, agent.tool_timeout)
|
|
47
47
|
duration = time.perf_counter() - t0
|
|
48
|
-
logger.
|
|
48
|
+
logger.debug("Tool '%s' completed in %.2fs", name, duration)
|
|
49
49
|
|
|
50
50
|
replacement = await _safe_hook(agent.hooks, "on_after_tool", agent, name, args, result)
|
|
51
51
|
if replacement is not None:
|
|
@@ -2,6 +2,7 @@
|
|
|
2
2
|
|
|
3
3
|
import asyncio
|
|
4
4
|
import logging
|
|
5
|
+
import uuid
|
|
5
6
|
from collections.abc import Sequence
|
|
6
7
|
from pathlib import Path
|
|
7
8
|
from typing import TYPE_CHECKING, Any, AsyncIterator
|
|
@@ -119,11 +120,13 @@ class Agent:
|
|
|
119
120
|
llm_extra_body: dict[str, Any] | None = None,
|
|
120
121
|
cache_dir: Path | str | None = _DEFAULT_CACHE_DIR,
|
|
121
122
|
backend: Backend | None = None,
|
|
123
|
+
system_nonce: bool = False,
|
|
122
124
|
) -> None:
|
|
123
125
|
# Public -- safe to read/write between runs
|
|
124
126
|
self.model = model
|
|
125
127
|
self.system = system
|
|
126
128
|
self.root = root
|
|
129
|
+
self.system_nonce = system_nonce
|
|
127
130
|
self.http_request_timeout = http_request_timeout
|
|
128
131
|
self.tool_timeout = tool_timeout
|
|
129
132
|
self.llm_timeout = llm_timeout
|
|
@@ -259,6 +262,16 @@ class Agent:
|
|
|
259
262
|
if self.system and not (self._messages and self._messages[0].role == "system"):
|
|
260
263
|
self._messages.insert(0, Message(role="system", content=self.system))
|
|
261
264
|
|
|
265
|
+
# Prepend a per-run nonce to the system prompt so each run has a unique
|
|
266
|
+
# prefix. This defeats Ollama's cross-request prompt-cache reuse (slot
|
|
267
|
+
# selection by longest-common-prefix similarity), which can corrupt KV
|
|
268
|
+
# state across independent requests that share a system prompt. The
|
|
269
|
+
# nonce is constant within a run, so intra-conversation caching is kept.
|
|
270
|
+
if self.system_nonce and self._messages and self._messages[0].role == "system":
|
|
271
|
+
sys0 = self._messages[0]
|
|
272
|
+
nonce = f"[run:{uuid.uuid4().hex}]\n"
|
|
273
|
+
self._messages[0] = sys0.model_copy(update={"content": nonce + (sys0.content or "")})
|
|
274
|
+
|
|
262
275
|
logger.debug("Agent.run starting: model=%s base_url=%s", self.model, self._base_url)
|
|
263
276
|
await _safe_hook(self.hooks, "on_before_agent", self)
|
|
264
277
|
try:
|
|
@@ -356,6 +369,7 @@ class Agent:
|
|
|
356
369
|
return
|
|
357
370
|
self._llm_last_chunk = chunk
|
|
358
371
|
if chunk.partial:
|
|
372
|
+
await _safe_hook(self.hooks, "on_stream_chunk", self, chunk)
|
|
359
373
|
yield chunk
|
|
360
374
|
else:
|
|
361
375
|
yield chunk.model_copy()
|
|
@@ -0,0 +1,108 @@
|
|
|
1
|
+
"""One-shot, schema-constrained completion -- no tools, no loop."""
|
|
2
|
+
|
|
3
|
+
from pathlib import Path
|
|
4
|
+
from typing import Any, overload
|
|
5
|
+
|
|
6
|
+
from pydantic import BaseModel
|
|
7
|
+
|
|
8
|
+
from ._api_client import OPENAI_BACKEND, Backend, stream_chat
|
|
9
|
+
from ._cache import make_cache
|
|
10
|
+
from .agent import _DEFAULT_CACHE_DIR
|
|
11
|
+
from .types import Message, Usage
|
|
12
|
+
|
|
13
|
+
__all__ = ["complete"]
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
@overload
|
|
17
|
+
async def complete[T: BaseModel](
|
|
18
|
+
prompt: str | list[Message],
|
|
19
|
+
*,
|
|
20
|
+
model: str,
|
|
21
|
+
schema: type[T],
|
|
22
|
+
base_url: str = ...,
|
|
23
|
+
api_key: str | None = ...,
|
|
24
|
+
system: str | None = ...,
|
|
25
|
+
timeout: float = ...,
|
|
26
|
+
llm_extra_body: dict[str, Any] | None = ...,
|
|
27
|
+
usage: Usage | None = ...,
|
|
28
|
+
cache_dir: Path | str | None = ...,
|
|
29
|
+
backend: Backend = ...,
|
|
30
|
+
) -> T: ...
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
@overload
|
|
34
|
+
async def complete[T: BaseModel](
|
|
35
|
+
prompt: str | list[Message],
|
|
36
|
+
*,
|
|
37
|
+
model: str,
|
|
38
|
+
schema: None = None,
|
|
39
|
+
base_url: str = ...,
|
|
40
|
+
api_key: str | None = ...,
|
|
41
|
+
system: str | None = ...,
|
|
42
|
+
timeout: float = ...,
|
|
43
|
+
llm_extra_body: dict[str, Any] | None = ...,
|
|
44
|
+
usage: Usage | None = ...,
|
|
45
|
+
cache_dir: Path | str | None = ...,
|
|
46
|
+
backend: Backend = ...,
|
|
47
|
+
) -> Message: ...
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
async def complete[T: BaseModel](
|
|
51
|
+
prompt: str | list[Message],
|
|
52
|
+
*,
|
|
53
|
+
model: str,
|
|
54
|
+
base_url: str = "http://localhost:11434/v1",
|
|
55
|
+
api_key: str | None = None,
|
|
56
|
+
system: str | None = None,
|
|
57
|
+
schema: type[T] | None = None,
|
|
58
|
+
timeout: float = 300.0,
|
|
59
|
+
llm_extra_body: dict[str, Any] | None = None,
|
|
60
|
+
usage: Usage | None = None,
|
|
61
|
+
cache_dir: Path | str | None = _DEFAULT_CACHE_DIR,
|
|
62
|
+
backend: Backend = OPENAI_BACKEND,
|
|
63
|
+
) -> Message | T:
|
|
64
|
+
"""One LLM call, no tools, no loop. With *schema*, returns a validated instance.
|
|
65
|
+
|
|
66
|
+
*prompt* is either a string (wrapped into a single user message) or a list of
|
|
67
|
+
``Message`` objects sent as-is -- the latter is the "extract from
|
|
68
|
+
``agent.messages``" path. *system*, when given, is prepended as a system message.
|
|
69
|
+
|
|
70
|
+
With *schema*, output is constrained via the backend's ``response_format``
|
|
71
|
+
and the final content is validated with ``schema.model_validate_json``.
|
|
72
|
+
``ValidationError`` and ``json.JSONDecodeError`` propagate to the caller.
|
|
73
|
+
|
|
74
|
+
Note: a provider may silently ignore request fields it does not know
|
|
75
|
+
(Ollama's ``/v1`` endpoint drops unknown keys with HTTP 200), so anything
|
|
76
|
+
passed through *llm_extra_body* should be verified against observed
|
|
77
|
+
behaviour rather than assumed to take effect.
|
|
78
|
+
"""
|
|
79
|
+
messages = [Message(role="user", content=prompt)] if isinstance(prompt, str) else list(prompt)
|
|
80
|
+
if system is not None:
|
|
81
|
+
messages = [Message(role="system", content=system), *messages]
|
|
82
|
+
|
|
83
|
+
cache = make_cache(cache_dir) if cache_dir is not None else None
|
|
84
|
+
|
|
85
|
+
final: Message | None = None
|
|
86
|
+
async for msg in stream_chat(
|
|
87
|
+
base_url=base_url,
|
|
88
|
+
api_key=api_key,
|
|
89
|
+
model=model,
|
|
90
|
+
messages=messages,
|
|
91
|
+
tools=None,
|
|
92
|
+
schema=schema,
|
|
93
|
+
timeout=timeout,
|
|
94
|
+
llm_extra_body=llm_extra_body,
|
|
95
|
+
usage=usage,
|
|
96
|
+
cache=cache,
|
|
97
|
+
backend=backend,
|
|
98
|
+
):
|
|
99
|
+
if not msg.partial:
|
|
100
|
+
final = msg
|
|
101
|
+
|
|
102
|
+
if final is None:
|
|
103
|
+
raise ValueError(f"No response from {model}")
|
|
104
|
+
if schema is None:
|
|
105
|
+
return final
|
|
106
|
+
if not final.content:
|
|
107
|
+
raise ValueError(f"Empty response content from {model} while a schema was set")
|
|
108
|
+
return schema.model_validate_json(final.content)
|
|
@@ -11,6 +11,10 @@ Hooks fire in this order during a single agent.run() call:
|
|
|
11
11
|
# Return a Message to inject as the response (LLM call is skipped).
|
|
12
12
|
# Return None to call the LLM normally.
|
|
13
13
|
<LLM streams response>
|
|
14
|
+
on_stream_chunk(agent, chunk) -> None
|
|
15
|
+
# Called for each partial Message chunk as it arrives from the
|
|
16
|
+
# LLM stream. chunk.partial is True. Return value is ignored.
|
|
17
|
+
# Use for progress display, token counting, or early abort.
|
|
14
18
|
on_after_llm(agent, message) -> Message | None
|
|
15
19
|
# Return a Message to replace what gets appended to conversation
|
|
16
20
|
# history. Return None to use the message as-is.
|
|
@@ -37,6 +41,8 @@ rather than propagating it. Hook bugs cannot crash the agent. To request
|
|
|
37
41
|
a clean exit from inside a hook, call agent.stop().
|
|
38
42
|
"""
|
|
39
43
|
|
|
44
|
+
from __future__ import annotations
|
|
45
|
+
|
|
40
46
|
import logging
|
|
41
47
|
from typing import TYPE_CHECKING, Any
|
|
42
48
|
|
|
@@ -91,6 +97,14 @@ class AgentHooks:
|
|
|
91
97
|
"""
|
|
92
98
|
return None
|
|
93
99
|
|
|
100
|
+
async def on_stream_chunk(self, agent: Agent, chunk: Message) -> None:
|
|
101
|
+
"""Called for each partial chunk as it arrives from the LLM stream.
|
|
102
|
+
|
|
103
|
+
``chunk.partial`` is always ``True``. The return value is ignored.
|
|
104
|
+
Use this for real-time progress display, per-token logging, or calling
|
|
105
|
+
``agent.stop()`` to abort the stream early.
|
|
106
|
+
"""
|
|
107
|
+
|
|
94
108
|
async def on_before_turn(self, agent: Agent) -> None:
|
|
95
109
|
"""Called at the start of each turn, before the LLM call."""
|
|
96
110
|
|
|
@@ -173,4 +173,7 @@ def resolve_profile(
|
|
|
173
173
|
|
|
174
174
|
raw = _interpolate_strings(_load_merged_profile(name, config_path=config_path))
|
|
175
175
|
known = {f.name for f in dataclasses.fields(AgentConfig)}
|
|
176
|
-
|
|
176
|
+
filtered = {k: v for k, v in raw.items() if k in known}
|
|
177
|
+
if isinstance(filtered.get("tools"), str):
|
|
178
|
+
filtered["tools"] = [t.strip() for t in filtered["tools"].split(",") if t.strip()]
|
|
179
|
+
return AgentConfig(**filtered)
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
"""JSON Schema tightening for strict structured output.
|
|
2
|
+
|
|
3
|
+
Pydantic's ``model_json_schema()`` is not accepted as-is by strict validators
|
|
4
|
+
(OpenAI's ``json_schema`` mode in particular). :func:`to_strict_schema` rewrites
|
|
5
|
+
the tree into a strict-legal shape.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from typing import Any
|
|
9
|
+
|
|
10
|
+
from pydantic import BaseModel
|
|
11
|
+
|
|
12
|
+
__all__ = ["to_strict_schema"]
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def _tighten(node: Any) -> None:
|
|
16
|
+
"""Recursively rewrite *node* in place into a strict-legal schema."""
|
|
17
|
+
if isinstance(node, list):
|
|
18
|
+
for item in node:
|
|
19
|
+
_tighten(item)
|
|
20
|
+
return
|
|
21
|
+
if not isinstance(node, dict):
|
|
22
|
+
return
|
|
23
|
+
|
|
24
|
+
node.pop("title", None)
|
|
25
|
+
node.pop("default", None)
|
|
26
|
+
|
|
27
|
+
if isinstance(node.get("properties"), dict):
|
|
28
|
+
node["additionalProperties"] = False
|
|
29
|
+
node["required"] = list(node["properties"])
|
|
30
|
+
|
|
31
|
+
for value in node.values():
|
|
32
|
+
_tighten(value)
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def to_strict_schema(schema: type[BaseModel]) -> dict[str, Any]:
|
|
36
|
+
"""Return *schema*'s JSON Schema, tightened for strict structured output.
|
|
37
|
+
|
|
38
|
+
Every object with ``properties`` gets ``additionalProperties: false`` and a
|
|
39
|
+
``required`` list naming **all** its properties; ``title`` and ``default``
|
|
40
|
+
are stripped everywhere. ``$defs`` / ``$ref`` are preserved -- only rewritten
|
|
41
|
+
in place.
|
|
42
|
+
|
|
43
|
+
``X | None`` fields keep working: Pydantic emits ``anyOf: [..., {"type":
|
|
44
|
+
"null"}]``, so the field stays formally required while remaining nullable.
|
|
45
|
+
"""
|
|
46
|
+
result = schema.model_json_schema()
|
|
47
|
+
_tighten(result)
|
|
48
|
+
return result
|
|
@@ -13,7 +13,8 @@ def _resolve_safe(requested: str, root: "Path | str") -> str:
|
|
|
13
13
|
if not isinstance(requested, str):
|
|
14
14
|
raise ValueError(f"path must be a string, got {type(requested).__name__}")
|
|
15
15
|
|
|
16
|
-
|
|
16
|
+
# Normalize Windows-style separators so traversal is caught on all platforms.
|
|
17
|
+
raw = Path(requested.replace("\\", "/"))
|
|
17
18
|
root_path = Path(root)
|
|
18
19
|
if not raw.is_absolute():
|
|
19
20
|
raw = root_path / raw
|
|
@@ -200,7 +200,7 @@ def _kill_process_group(proc: asyncio.subprocess.Process) -> None:
|
|
|
200
200
|
try:
|
|
201
201
|
pgid = os.getpgid(proc.pid)
|
|
202
202
|
os.killpg(pgid, signal.SIGTERM)
|
|
203
|
-
except ProcessLookupError, PermissionError, OSError:
|
|
203
|
+
except (ProcessLookupError, PermissionError, OSError):
|
|
204
204
|
proc.kill()
|
|
205
205
|
return
|
|
206
206
|
|
|
@@ -208,7 +208,7 @@ def _kill_process_group(proc: asyncio.subprocess.Process) -> None:
|
|
|
208
208
|
def _force_kill() -> None:
|
|
209
209
|
try:
|
|
210
210
|
os.killpg(pgid, signal.SIGKILL)
|
|
211
|
-
except ProcessLookupError, OSError:
|
|
211
|
+
except (ProcessLookupError, OSError):
|
|
212
212
|
pass
|
|
213
213
|
|
|
214
214
|
import threading
|
|
@@ -8,24 +8,6 @@ from ..tool_registry import ToolInfo
|
|
|
8
8
|
from ._shared import _fmt_size, _make_tool_info, _resolve_safe, _resolve_safe_strict
|
|
9
9
|
|
|
10
10
|
|
|
11
|
-
def _character_line(content: str, pos: int) -> int:
|
|
12
|
-
"""Return the 1-based line number for character position *pos* in *content*."""
|
|
13
|
-
return content[:pos].count("\n") + 1
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
def _find_occurrence_near_line(content: str, old_text: str, target_line: int) -> int:
|
|
17
|
-
"""Find the first occurrence of *old_text* whose 1-based line number
|
|
18
|
-
matches *target_line*. Returns the character index or ``-1``."""
|
|
19
|
-
idx = -1
|
|
20
|
-
while True:
|
|
21
|
-
idx = content.find(old_text, idx + 1)
|
|
22
|
-
if idx < 0:
|
|
23
|
-
break
|
|
24
|
-
if _character_line(content, idx) == target_line:
|
|
25
|
-
return idx
|
|
26
|
-
return -1
|
|
27
|
-
|
|
28
|
-
|
|
29
11
|
def make_edit_tool(root: str, *, max_bytes: int = 10 * 1024 * 1024) -> ToolInfo:
|
|
30
12
|
"""Build an edit tool scoped to *root* with an atomic write via a temp file."""
|
|
31
13
|
root_path = Path(root).resolve()
|
|
@@ -34,14 +16,9 @@ def make_edit_tool(root: str, *, max_bytes: int = 10 * 1024 * 1024) -> ToolInfo:
|
|
|
34
16
|
path: str,
|
|
35
17
|
old_text: str,
|
|
36
18
|
new_text: str,
|
|
37
|
-
line_hint: int | None = None,
|
|
38
19
|
) -> str:
|
|
39
20
|
"""Use this to make a targeted edit to a file by replacing an exact string. To create a new file, pass old_text as an empty string.
|
|
40
21
|
|
|
41
|
-
If *old_text* appears multiple times, ``line_hint`` is required to
|
|
42
|
-
disambiguate. Pass the 1-based line number where the text to
|
|
43
|
-
replace appears.
|
|
44
|
-
|
|
45
22
|
To create a new file, pass ``old_text=""`` - the file must not already
|
|
46
23
|
exist. Parent directories are created automatically.
|
|
47
24
|
|
|
@@ -50,13 +27,10 @@ def make_edit_tool(root: str, *, max_bytes: int = 10 * 1024 * 1024) -> ToolInfo:
|
|
|
50
27
|
path :
|
|
51
28
|
Relative or absolute path to the file.
|
|
52
29
|
old_text :
|
|
53
|
-
Exact text to search for (must appear exactly once
|
|
54
|
-
|
|
30
|
+
Exact text to search for (must appear exactly once).
|
|
31
|
+
Pass ``""`` to create a new file.
|
|
55
32
|
new_text :
|
|
56
33
|
Replacement text (or full content when creating a new file).
|
|
57
|
-
line_hint :
|
|
58
|
-
Optional 1-based line number that *old_text* appears on.
|
|
59
|
-
Required when *old_text* appears more than once.
|
|
60
34
|
"""
|
|
61
35
|
if not old_text:
|
|
62
36
|
try:
|
|
@@ -117,18 +91,10 @@ def make_edit_tool(root: str, *, max_bytes: int = 10 * 1024 * 1024) -> ToolInfo:
|
|
|
117
91
|
|
|
118
92
|
if count == 1:
|
|
119
93
|
idx = content.find(old_text)
|
|
120
|
-
elif line_hint is not None:
|
|
121
|
-
idx = _find_occurrence_near_line(content, old_text, line_hint)
|
|
122
|
-
if idx < 0:
|
|
123
|
-
return (
|
|
124
|
-
f"Error: old_text {old_text!r} appears {count} times in "
|
|
125
|
-
f"{path!r} but none are on line {line_hint}"
|
|
126
|
-
)
|
|
127
94
|
else:
|
|
128
95
|
return (
|
|
129
96
|
f"Error: old_text {old_text!r} appears {count} times in "
|
|
130
|
-
f"{path!r}.
|
|
131
|
-
f"to replace."
|
|
97
|
+
f"{path!r}. Use a longer, unique excerpt as old_text."
|
|
132
98
|
)
|
|
133
99
|
|
|
134
100
|
new_content = content[:idx] + new_text + content[idx + len(old_text) :]
|
|
@@ -0,0 +1,145 @@
|
|
|
1
|
+
"""Optional web tools: ``web_search`` and ``web_fetch``.
|
|
2
|
+
|
|
3
|
+
Requires the ``web`` extra: ``pip install coreloop[web]``
|
|
4
|
+
"""
|
|
5
|
+
|
|
6
|
+
import html as _html
|
|
7
|
+
import os
|
|
8
|
+
import re
|
|
9
|
+
from typing import Literal
|
|
10
|
+
|
|
11
|
+
import httpx
|
|
12
|
+
|
|
13
|
+
from .tool_registry import ToolInfo
|
|
14
|
+
from .tools._shared import _make_tool_info
|
|
15
|
+
|
|
16
|
+
_DEFAULT_TIMEOUT = 15.0
|
|
17
|
+
_MAX_CONTENT_BYTES = 1_000_000
|
|
18
|
+
_MAX_MARKDOWN_CHARS = 100_000
|
|
19
|
+
_MAX_RAW_CHARS = 50_000
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def _searxng_base(override: str | None) -> str:
|
|
23
|
+
url = override or os.environ.get("SEARXNG_URL", "")
|
|
24
|
+
if not url:
|
|
25
|
+
raise RuntimeError("SearXNG URL not configured (set SEARXNG_URL env var)")
|
|
26
|
+
return url.rstrip("/")
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def _metadata(html_content: str) -> str:
|
|
30
|
+
meta: dict[str, str] = {}
|
|
31
|
+
if m := re.search(r"<title[^>]*>(.*?)</title>", html_content, re.IGNORECASE | re.DOTALL):
|
|
32
|
+
meta["title"] = _html.unescape(m.group(1).strip())
|
|
33
|
+
if m := re.search(
|
|
34
|
+
r'<meta[^>]*name=["\']description["\'][^>]*content=["\']([^"\']*)["\']',
|
|
35
|
+
html_content, re.IGNORECASE,
|
|
36
|
+
):
|
|
37
|
+
meta["description"] = _html.unescape(m.group(1).strip())
|
|
38
|
+
for prop, value in re.findall(
|
|
39
|
+
r'<meta[^>]*property=["\']og:(\w+)["\'][^>]*content=["\']([^"\']*)["\']',
|
|
40
|
+
html_content, re.IGNORECASE,
|
|
41
|
+
):
|
|
42
|
+
meta[f"og_{prop}"] = _html.unescape(value.strip())
|
|
43
|
+
return "\n".join(f"{k}: {v}" for k, v in meta.items())
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def make_web_tools(searxng_url: str | None = None) -> list[ToolInfo]:
|
|
47
|
+
"""Build web search and fetch tools.
|
|
48
|
+
|
|
49
|
+
Parameters
|
|
50
|
+
----------
|
|
51
|
+
searxng_url:
|
|
52
|
+
Base URL of your SearXNG instance. Falls back to ``SEARXNG_URL`` env var.
|
|
53
|
+
"""
|
|
54
|
+
try:
|
|
55
|
+
from html_to_markdown import convert as _convert
|
|
56
|
+
except ImportError as exc:
|
|
57
|
+
raise ImportError(
|
|
58
|
+
"Web tools require 'html-to-markdown'. Install with: pip install coreloop[web]"
|
|
59
|
+
) from exc
|
|
60
|
+
|
|
61
|
+
async def web_search(
|
|
62
|
+
query: str,
|
|
63
|
+
max_results: int = 5,
|
|
64
|
+
domain_filter: str | None = None,
|
|
65
|
+
recency: Literal["all_time", "day", "week", "month", "year"] = "all_time",
|
|
66
|
+
) -> str:
|
|
67
|
+
"""Use this to find information on the web. Returns titles, URLs, and snippets for relevant pages.
|
|
68
|
+
|
|
69
|
+
Parameters
|
|
70
|
+
----------
|
|
71
|
+
query:
|
|
72
|
+
Search query string.
|
|
73
|
+
max_results:
|
|
74
|
+
Maximum number of results to return.
|
|
75
|
+
domain_filter:
|
|
76
|
+
Restrict results to a specific domain (e.g. ``"github.com"``).
|
|
77
|
+
recency:
|
|
78
|
+
Time filter: ``all_time``, ``day``, ``week``, ``month``, or ``year``.
|
|
79
|
+
"""
|
|
80
|
+
try:
|
|
81
|
+
base = _searxng_base(searxng_url)
|
|
82
|
+
q = f"site:{domain_filter} {query}" if domain_filter else query
|
|
83
|
+
params: dict[str, str | int] = {"q": q, "format": "json", "categories": "general"}
|
|
84
|
+
if recency != "all_time":
|
|
85
|
+
params["time_range"] = recency
|
|
86
|
+
async with httpx.AsyncClient(timeout=_DEFAULT_TIMEOUT) as client:
|
|
87
|
+
r = await client.get(f"{base}/search", params=params)
|
|
88
|
+
r.raise_for_status()
|
|
89
|
+
data = r.json()
|
|
90
|
+
except Exception as exc:
|
|
91
|
+
msg = str(exc)
|
|
92
|
+
if "SearXNG URL not configured" in msg:
|
|
93
|
+
msg += " or set searxng_url in ~/coreloop.toml"
|
|
94
|
+
return f"Error: {msg}"
|
|
95
|
+
|
|
96
|
+
results = data.get("results", [])[:max_results]
|
|
97
|
+
if not results:
|
|
98
|
+
return "No results found."
|
|
99
|
+
|
|
100
|
+
lines: list[str] = []
|
|
101
|
+
for item in results:
|
|
102
|
+
lines.append(f"**{item.get('title', '')}**")
|
|
103
|
+
lines.append(item.get("url", ""))
|
|
104
|
+
if snippet := item.get("content", ""):
|
|
105
|
+
lines.append(snippet)
|
|
106
|
+
if date := item.get("publishedDate"):
|
|
107
|
+
lines.append(f"Published: {date}")
|
|
108
|
+
lines.append("")
|
|
109
|
+
return "\n".join(lines).rstrip()
|
|
110
|
+
|
|
111
|
+
async def web_fetch(
|
|
112
|
+
url: str,
|
|
113
|
+
extract_mode: Literal["markdown", "raw", "metadata"] = "markdown",
|
|
114
|
+
) -> str:
|
|
115
|
+
"""Use this to read a specific web page when you already have its URL.
|
|
116
|
+
|
|
117
|
+
Parameters
|
|
118
|
+
----------
|
|
119
|
+
url:
|
|
120
|
+
HTTP/HTTPS URL to fetch.
|
|
121
|
+
extract_mode:
|
|
122
|
+
How to extract content: ``markdown`` (default), ``raw`` (HTML), or ``metadata``.
|
|
123
|
+
"""
|
|
124
|
+
try:
|
|
125
|
+
async with httpx.AsyncClient(
|
|
126
|
+
timeout=_DEFAULT_TIMEOUT,
|
|
127
|
+
follow_redirects=True,
|
|
128
|
+
headers={"User-Agent": "coreloop/web (https://github.com/rhiza-fr/coreloop)"},
|
|
129
|
+
) as client:
|
|
130
|
+
r = await client.get(url)
|
|
131
|
+
r.raise_for_status()
|
|
132
|
+
if cl := r.headers.get("content-length"):
|
|
133
|
+
if int(cl) > _MAX_CONTENT_BYTES:
|
|
134
|
+
return f"Error: Content too large ({cl} bytes)"
|
|
135
|
+
page_html = r.text
|
|
136
|
+
except Exception as exc:
|
|
137
|
+
return f"Error: {exc}"
|
|
138
|
+
|
|
139
|
+
if extract_mode == "raw":
|
|
140
|
+
return page_html[:_MAX_RAW_CHARS]
|
|
141
|
+
if extract_mode == "metadata":
|
|
142
|
+
return _metadata(page_html)
|
|
143
|
+
return (_convert(page_html).content or "")[:_MAX_MARKDOWN_CHARS]
|
|
144
|
+
|
|
145
|
+
return [_make_tool_info(web_search), _make_tool_info(web_fetch)]
|
|
@@ -1,98 +0,0 @@
|
|
|
1
|
-
"""Optional web tools: ``web_search`` and ``web_fetch``.
|
|
2
|
-
|
|
3
|
-
Requires the ``web`` extra: ``pip install coreloop[web]``
|
|
4
|
-
"""
|
|
5
|
-
|
|
6
|
-
from typing import Literal
|
|
7
|
-
|
|
8
|
-
from .tool_registry import ToolInfo
|
|
9
|
-
from .tools._shared import _make_tool_info
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
def make_web_tools(searxng_url: str | None = None) -> list[ToolInfo]:
|
|
13
|
-
"""Build web search and fetch tools.
|
|
14
|
-
|
|
15
|
-
Parameters
|
|
16
|
-
----------
|
|
17
|
-
searxng_url:
|
|
18
|
-
Base URL of your SearXNG instance (e.g. ``"http://localhost:8080"``).
|
|
19
|
-
Falls back to the ``SEARXNG_URL`` environment variable or pvl-webtools'
|
|
20
|
-
own default if ``None``.
|
|
21
|
-
"""
|
|
22
|
-
try:
|
|
23
|
-
from pvlwebtools import web_fetch as _web_fetch
|
|
24
|
-
from pvlwebtools import web_search as _web_search
|
|
25
|
-
except ImportError as exc:
|
|
26
|
-
raise ImportError(
|
|
27
|
-
"Web tools require 'pvl-webtools'. Install with: pip install coreloop[web]"
|
|
28
|
-
) from exc
|
|
29
|
-
|
|
30
|
-
async def web_search(
|
|
31
|
-
query: str,
|
|
32
|
-
max_results: int = 5,
|
|
33
|
-
domain_filter: str | None = None,
|
|
34
|
-
recency: Literal["all_time", "day", "week", "month", "year"] = "all_time",
|
|
35
|
-
) -> str:
|
|
36
|
-
"""Use this to find information on the web. Returns titles, URLs, and snippets for relevant pages.
|
|
37
|
-
|
|
38
|
-
Parameters
|
|
39
|
-
----------
|
|
40
|
-
query:
|
|
41
|
-
Search query string.
|
|
42
|
-
max_results:
|
|
43
|
-
Maximum number of results to return.
|
|
44
|
-
domain_filter:
|
|
45
|
-
Restrict results to a specific domain (e.g. ``"github.com"``).
|
|
46
|
-
recency:
|
|
47
|
-
Time filter: ``all_time``, ``day``, ``week``, ``month``, or ``year``.
|
|
48
|
-
"""
|
|
49
|
-
try:
|
|
50
|
-
results = await _web_search(
|
|
51
|
-
query=query,
|
|
52
|
-
max_results=max_results,
|
|
53
|
-
domain_filter=domain_filter or None,
|
|
54
|
-
recency=recency,
|
|
55
|
-
searxng_url=searxng_url,
|
|
56
|
-
)
|
|
57
|
-
except Exception as exc:
|
|
58
|
-
msg = str(exc)
|
|
59
|
-
if "SearXNG URL not configured" in msg:
|
|
60
|
-
msg += " or set searxng_url in ~/coreloop.toml"
|
|
61
|
-
return f"Error: {msg}"
|
|
62
|
-
|
|
63
|
-
if not results:
|
|
64
|
-
return "No results found."
|
|
65
|
-
|
|
66
|
-
lines: list[str] = []
|
|
67
|
-
for r in results:
|
|
68
|
-
lines.append(f"**{r.title}**")
|
|
69
|
-
lines.append(r.url)
|
|
70
|
-
if r.snippet:
|
|
71
|
-
lines.append(r.snippet)
|
|
72
|
-
if r.published_date:
|
|
73
|
-
lines.append(f"Published: {r.published_date}")
|
|
74
|
-
lines.append("")
|
|
75
|
-
return "\n".join(lines).rstrip()
|
|
76
|
-
|
|
77
|
-
async def web_fetch(
|
|
78
|
-
url: str,
|
|
79
|
-
extract_mode: Literal["markdown", "article", "raw", "metadata"] = "markdown",
|
|
80
|
-
) -> str:
|
|
81
|
-
"""Use this to read a specific web page when you already have its URL.
|
|
82
|
-
|
|
83
|
-
Parameters
|
|
84
|
-
----------
|
|
85
|
-
url:
|
|
86
|
-
HTTP/HTTPS URL to fetch.
|
|
87
|
-
extract_mode:
|
|
88
|
-
How to extract content: ``markdown`` (full page as markdown),
|
|
89
|
-
``article`` (main article text only), ``raw`` (raw HTML),
|
|
90
|
-
or ``metadata`` (title, description, etc.).
|
|
91
|
-
"""
|
|
92
|
-
try:
|
|
93
|
-
result = await _web_fetch(url=url, extract_mode=extract_mode)
|
|
94
|
-
except Exception as exc:
|
|
95
|
-
return f"Error: {exc}"
|
|
96
|
-
return result.content
|
|
97
|
-
|
|
98
|
-
return [_make_tool_info(web_search), _make_tool_info(web_fetch)]
|
|
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
|