coreloop 0.1.3__tar.gz → 0.1.5__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.3 → coreloop-0.1.5}/PKG-INFO +38 -5
- {coreloop-0.1.3 → coreloop-0.1.5}/README.md +37 -4
- coreloop-0.1.5/pyproject.toml +88 -0
- coreloop-0.1.3/pyproject.toml → coreloop-0.1.5/pyproject.toml.orig +1 -1
- {coreloop-0.1.3 → coreloop-0.1.5}/src/coreloop/__init__.py +8 -4
- {coreloop-0.1.3 → coreloop-0.1.5}/src/coreloop/_api_client.py +33 -7
- {coreloop-0.1.3 → coreloop-0.1.5}/src/coreloop/_tool_execution.py +4 -4
- {coreloop-0.1.3 → coreloop-0.1.5}/src/coreloop/agent.py +16 -2
- coreloop-0.1.5/src/coreloop/complete.py +108 -0
- {coreloop-0.1.3 → coreloop-0.1.5}/src/coreloop/config.py +1 -0
- {coreloop-0.1.3 → coreloop-0.1.5}/src/coreloop/hooks.py +15 -1
- {coreloop-0.1.3 → coreloop-0.1.5}/src/coreloop/profiles.py +4 -1
- coreloop-0.1.5/src/coreloop/structured.py +66 -0
- {coreloop-0.1.3 → coreloop-0.1.5}/src/coreloop/tool_registry.py +2 -3
- {coreloop-0.1.3 → coreloop-0.1.5}/src/coreloop/tools/_shared.py +4 -1
- {coreloop-0.1.3 → coreloop-0.1.5}/src/coreloop/tools/bash.py +1 -1
- {coreloop-0.1.3 → coreloop-0.1.5}/src/coreloop/tools/edit.py +9 -39
- {coreloop-0.1.3 → coreloop-0.1.5}/src/coreloop/tools/grep.py +2 -2
- {coreloop-0.1.3 → coreloop-0.1.5}/src/coreloop/tools/ls.py +1 -1
- {coreloop-0.1.3 → coreloop-0.1.5}/src/coreloop/tools/read.py +7 -3
- {coreloop-0.1.3 → coreloop-0.1.5}/src/coreloop/types.py +2 -2
- {coreloop-0.1.3 → coreloop-0.1.5}/src/coreloop/web_tools.py +5 -6
- {coreloop-0.1.3 → coreloop-0.1.5}/LICENSE +0 -0
- {coreloop-0.1.3 → coreloop-0.1.5}/src/coreloop/.coreloop.toml +0 -0
- {coreloop-0.1.3 → coreloop-0.1.5}/src/coreloop/__main__.py +0 -0
- {coreloop-0.1.3 → coreloop-0.1.5}/src/coreloop/_cache.py +0 -0
- {coreloop-0.1.3 → coreloop-0.1.5}/src/coreloop/_logging.py +0 -0
- {coreloop-0.1.3 → coreloop-0.1.5}/src/coreloop/cli/__init__.py +0 -0
- {coreloop-0.1.3 → coreloop-0.1.5}/src/coreloop/cli/_run.py +0 -0
- {coreloop-0.1.3 → coreloop-0.1.5}/src/coreloop/cli/_tools.py +0 -0
- {coreloop-0.1.3 → coreloop-0.1.5}/src/coreloop/py.typed +0 -0
- {coreloop-0.1.3 → coreloop-0.1.5}/src/coreloop/tools/__init__.py +1 -1
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: coreloop
|
|
3
|
-
Version: 0.1.
|
|
3
|
+
Version: 0.1.5
|
|
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
|
|
@@ -83,7 +83,7 @@ async def main():
|
|
|
83
83
|
asyncio.run(main())
|
|
84
84
|
```
|
|
85
85
|
|
|
86
|
-
Or load settings from a named profile in
|
|
86
|
+
Or load settings from a named profile in `~/.coreloop.toml`:
|
|
87
87
|
|
|
88
88
|
```python
|
|
89
89
|
agent = Agent.from_profile("openai")
|
|
@@ -92,7 +92,7 @@ agent = Agent.from_profile("openai")
|
|
|
92
92
|
## CLI
|
|
93
93
|
|
|
94
94
|
`core` is a REPL / one-shot runner with profile support. On first run it copies
|
|
95
|
-
the bundled `coreloop.toml` to
|
|
95
|
+
the bundled `coreloop.toml` to `~/.coreloop.toml` — edit that file to set
|
|
96
96
|
your default model, tools, and provider credentials.
|
|
97
97
|
|
|
98
98
|
```bash
|
|
@@ -114,7 +114,7 @@ core --think -p "Explain this step by step" --model qwen3-14b
|
|
|
114
114
|
|
|
115
115
|
| Flag | Default | Description |
|
|
116
116
|
|------|---------|-------------|
|
|
117
|
-
| `--profile` | `default` | Named profile from
|
|
117
|
+
| `--profile` | `default` | Named profile from `~/.coreloop.toml` |
|
|
118
118
|
| `-m, --model` | profile value | Model name — overrides profile (`CORELOOP_MODEL`) |
|
|
119
119
|
| `--base-url` | profile value | API base URL — overrides profile (`CORELOOP_BASE_URL`) |
|
|
120
120
|
| `--api-key` | profile value | API key — overrides profile (`CORELOOP_API_KEY`) |
|
|
@@ -298,7 +298,7 @@ swallowed — they cannot crash the agent.
|
|
|
298
298
|
|
|
299
299
|
## Config profiles
|
|
300
300
|
|
|
301
|
-
`Agent.from_profile("openai")` builds an `AgentConfig` from
|
|
301
|
+
`Agent.from_profile("openai")` builds an `AgentConfig` from `~/.coreloop.toml`
|
|
302
302
|
(or `$CORELOOP_CONFIG`). Every profile inherits from `[profiles.default]`; named
|
|
303
303
|
profiles override individual keys.
|
|
304
304
|
|
|
@@ -326,6 +326,39 @@ pre-configured profiles for Ollama, OpenAI, Groq, DeepSeek, Together, and OpenRo
|
|
|
326
326
|
`dataclasses.replace(cfg, model="other")` to derive variants, or `Agent.from_config(cfg)`
|
|
327
327
|
to construct an agent from one.
|
|
328
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
|
+
|
|
329
362
|
## `Message`
|
|
330
363
|
|
|
331
364
|
| Field | Type | Description |
|
|
@@ -50,7 +50,7 @@ async def main():
|
|
|
50
50
|
asyncio.run(main())
|
|
51
51
|
```
|
|
52
52
|
|
|
53
|
-
Or load settings from a named profile in
|
|
53
|
+
Or load settings from a named profile in `~/.coreloop.toml`:
|
|
54
54
|
|
|
55
55
|
```python
|
|
56
56
|
agent = Agent.from_profile("openai")
|
|
@@ -59,7 +59,7 @@ agent = Agent.from_profile("openai")
|
|
|
59
59
|
## CLI
|
|
60
60
|
|
|
61
61
|
`core` is a REPL / one-shot runner with profile support. On first run it copies
|
|
62
|
-
the bundled `coreloop.toml` to
|
|
62
|
+
the bundled `coreloop.toml` to `~/.coreloop.toml` — edit that file to set
|
|
63
63
|
your default model, tools, and provider credentials.
|
|
64
64
|
|
|
65
65
|
```bash
|
|
@@ -81,7 +81,7 @@ core --think -p "Explain this step by step" --model qwen3-14b
|
|
|
81
81
|
|
|
82
82
|
| Flag | Default | Description |
|
|
83
83
|
|------|---------|-------------|
|
|
84
|
-
| `--profile` | `default` | Named profile from
|
|
84
|
+
| `--profile` | `default` | Named profile from `~/.coreloop.toml` |
|
|
85
85
|
| `-m, --model` | profile value | Model name — overrides profile (`CORELOOP_MODEL`) |
|
|
86
86
|
| `--base-url` | profile value | API base URL — overrides profile (`CORELOOP_BASE_URL`) |
|
|
87
87
|
| `--api-key` | profile value | API key — overrides profile (`CORELOOP_API_KEY`) |
|
|
@@ -265,7 +265,7 @@ swallowed — they cannot crash the agent.
|
|
|
265
265
|
|
|
266
266
|
## Config profiles
|
|
267
267
|
|
|
268
|
-
`Agent.from_profile("openai")` builds an `AgentConfig` from
|
|
268
|
+
`Agent.from_profile("openai")` builds an `AgentConfig` from `~/.coreloop.toml`
|
|
269
269
|
(or `$CORELOOP_CONFIG`). Every profile inherits from `[profiles.default]`; named
|
|
270
270
|
profiles override individual keys.
|
|
271
271
|
|
|
@@ -293,6 +293,39 @@ pre-configured profiles for Ollama, OpenAI, Groq, DeepSeek, Together, and OpenRo
|
|
|
293
293
|
`dataclasses.replace(cfg, model="other")` to derive variants, or `Agent.from_config(cfg)`
|
|
294
294
|
to construct an agent from one.
|
|
295
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
|
+
|
|
296
329
|
## `Message`
|
|
297
330
|
|
|
298
331
|
| Field | Type | Description |
|
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
[project]
|
|
2
|
+
name = "coreloop"
|
|
3
|
+
version = "0.1.5"
|
|
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,14 +1,16 @@
|
|
|
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
|
|
6
|
+
from .hooks import AgentHooks, MaxTurnsHook
|
|
7
|
+
from .structured import to_strict_schema
|
|
8
|
+
from .tool_registry import ToolInfo, clear_registry, get_tool, list_tools, tool
|
|
5
9
|
from .tools import make_tools
|
|
6
10
|
from .tools.bash import make_bash_tool
|
|
7
11
|
from .tools.grep import make_grep_tool
|
|
8
|
-
from .hooks import AgentHooks, MaxTurnsHook
|
|
9
|
-
from .tool_registry import ToolInfo, clear_registry, get_tool, list_tools, tool
|
|
10
|
-
from .web_tools import make_web_tools
|
|
11
12
|
from .types import FunctionCall, Message, ToolCall, Usage
|
|
13
|
+
from .web_tools import make_web_tools
|
|
12
14
|
|
|
13
15
|
__all__ = [
|
|
14
16
|
"Agent",
|
|
@@ -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
|
|
@@ -17,11 +17,14 @@ arrive at the end.
|
|
|
17
17
|
import json
|
|
18
18
|
import logging
|
|
19
19
|
import time
|
|
20
|
-
from
|
|
20
|
+
from collections.abc import AsyncIterator
|
|
21
|
+
from typing import Any, Protocol
|
|
21
22
|
|
|
22
23
|
import httpx
|
|
24
|
+
from pydantic import BaseModel
|
|
23
25
|
|
|
24
26
|
from ._cache import request_key
|
|
27
|
+
from .structured import to_strict_schema
|
|
25
28
|
from .tool_registry import ToolInfo
|
|
26
29
|
from .types import FunctionCall, Message, ToolCall, Usage, _dump_messages
|
|
27
30
|
|
|
@@ -31,7 +34,7 @@ logger = logging.getLogger(__name__)
|
|
|
31
34
|
class Backend(Protocol):
|
|
32
35
|
"""Provider-specific request shaping and stream parsing.
|
|
33
36
|
|
|
34
|
-
Implement these
|
|
37
|
+
Implement these methods to add a provider. The agent loop and
|
|
35
38
|
``stream_chat`` shell are backend-agnostic.
|
|
36
39
|
"""
|
|
37
40
|
|
|
@@ -53,6 +56,10 @@ class Backend(Protocol):
|
|
|
53
56
|
"""Serialize canonical messages + tools into the provider's request body."""
|
|
54
57
|
...
|
|
55
58
|
|
|
59
|
+
def response_format(self, schema: type[BaseModel]) -> dict[str, Any]:
|
|
60
|
+
"""Return body fields that constrain output to *schema*, or {} if unsupported."""
|
|
61
|
+
...
|
|
62
|
+
|
|
56
63
|
def parse_stream(
|
|
57
64
|
self, resp: httpx.Response, model: str, usage: Usage | None
|
|
58
65
|
) -> AsyncIterator[Message]:
|
|
@@ -126,6 +133,19 @@ class OpenAIBackend:
|
|
|
126
133
|
body[k] = v
|
|
127
134
|
return body
|
|
128
135
|
|
|
136
|
+
def response_format(self, schema: type[BaseModel]) -> dict[str, Any]:
|
|
137
|
+
"""Return the ``response_format`` body fragment constraining output to *schema*."""
|
|
138
|
+
return {
|
|
139
|
+
"response_format": {
|
|
140
|
+
"type": "json_schema",
|
|
141
|
+
"json_schema": {
|
|
142
|
+
"name": schema.__name__,
|
|
143
|
+
"strict": True,
|
|
144
|
+
"schema": to_strict_schema(schema),
|
|
145
|
+
},
|
|
146
|
+
}
|
|
147
|
+
}
|
|
148
|
+
|
|
129
149
|
async def parse_stream(
|
|
130
150
|
self, resp: httpx.Response, model: str, usage: Usage | None
|
|
131
151
|
) -> AsyncIterator[Message]:
|
|
@@ -153,7 +173,7 @@ class OpenAIBackend:
|
|
|
153
173
|
continue
|
|
154
174
|
|
|
155
175
|
# --- usage (arrives in a separate no-choices chunk after finish_reason) ---
|
|
156
|
-
if
|
|
176
|
+
if chunk.get("usage"):
|
|
157
177
|
u = chunk["usage"]
|
|
158
178
|
pt = u.get("prompt_tokens", 0)
|
|
159
179
|
ct = u.get("completion_tokens", 0)
|
|
@@ -209,13 +229,13 @@ class OpenAIBackend:
|
|
|
209
229
|
"function": {"name": "", "arguments": ""},
|
|
210
230
|
},
|
|
211
231
|
)
|
|
212
|
-
if
|
|
232
|
+
if tc_delta.get("id"):
|
|
213
233
|
partial["id"] = tc_delta["id"]
|
|
214
234
|
if "function" in tc_delta:
|
|
215
235
|
fn = tc_delta["function"]
|
|
216
|
-
if
|
|
236
|
+
if fn.get("name"):
|
|
217
237
|
partial["function"]["name"] += fn["name"]
|
|
218
|
-
if
|
|
238
|
+
if fn.get("arguments"):
|
|
219
239
|
partial["function"]["arguments"] += fn["arguments"]
|
|
220
240
|
|
|
221
241
|
# --- assemble on finish, but keep reading for the usage chunk ---
|
|
@@ -265,6 +285,7 @@ async def stream_chat(
|
|
|
265
285
|
model: str,
|
|
266
286
|
messages: list[Message],
|
|
267
287
|
tools: list[ToolInfo] | None = None,
|
|
288
|
+
schema: type[BaseModel] | None = None,
|
|
268
289
|
timeout: float = 60.0,
|
|
269
290
|
client: httpx.AsyncClient | None = None,
|
|
270
291
|
llm_extra_body: dict[str, Any] | None = None,
|
|
@@ -278,11 +299,16 @@ async def stream_chat(
|
|
|
278
299
|
serves/stores cached responses, manages the httpx connection, attaches
|
|
279
300
|
wall-clock ``duration`` to the final message, and raises on HTTP errors.
|
|
280
301
|
|
|
302
|
+
With *schema*, the backend's ``response_format`` fields are merged into the
|
|
303
|
+
body after ``build_body``, so the cache key covers the schema too.
|
|
304
|
+
|
|
281
305
|
Yields progressively richer *assistant* ``Message`` objects. The last yielded
|
|
282
306
|
message for a turn has either ``content`` set **or** ``tool_calls`` populated
|
|
283
307
|
(or both), plus ``usage`` and ``duration``.
|
|
284
308
|
"""
|
|
285
309
|
body = backend.build_body(model, messages, tools, llm_extra_body)
|
|
310
|
+
if schema is not None:
|
|
311
|
+
body.update(backend.response_format(schema))
|
|
286
312
|
|
|
287
313
|
cache_key: str | None = None
|
|
288
314
|
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:
|
|
@@ -70,11 +70,11 @@ async def run_tool(info: ToolInfo, args: dict[str, Any], timeout: float) -> str:
|
|
|
70
70
|
async with asyncio.timeout(timeout):
|
|
71
71
|
result = await info.fn(**args)
|
|
72
72
|
return str(result)
|
|
73
|
-
except
|
|
73
|
+
except TimeoutError:
|
|
74
74
|
logger.error("Tool '%s' timed out after %.1fs", info.name, timeout)
|
|
75
75
|
return f"Error: tool '{info.name}' timed out after {timeout}s"
|
|
76
76
|
except asyncio.CancelledError:
|
|
77
77
|
raise
|
|
78
|
-
except Exception as exc:
|
|
78
|
+
except Exception as exc: # noqa: BLE001 -- tool failures are reported to the LLM, not raised
|
|
79
79
|
logger.error("Tool '%s' raised %s: %s", info.name, type(exc).__name__, exc)
|
|
80
80
|
return f"Error in tool '{info.name}': {exc}"
|
|
@@ -2,9 +2,10 @@
|
|
|
2
2
|
|
|
3
3
|
import asyncio
|
|
4
4
|
import logging
|
|
5
|
-
|
|
5
|
+
import uuid
|
|
6
|
+
from collections.abc import AsyncIterator, Sequence
|
|
6
7
|
from pathlib import Path
|
|
7
|
-
from typing import TYPE_CHECKING, Any
|
|
8
|
+
from typing import TYPE_CHECKING, Any
|
|
8
9
|
|
|
9
10
|
if TYPE_CHECKING:
|
|
10
11
|
from .config import AgentConfig
|
|
@@ -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
|
|
|
@@ -128,5 +142,5 @@ async def _safe_hook(hooks: AgentHooks, method: str, *args: Any) -> Any:
|
|
|
128
142
|
"""Call a hook method, logging and swallowing any exceptions."""
|
|
129
143
|
try:
|
|
130
144
|
return await getattr(hooks, method)(*args)
|
|
131
|
-
except Exception as exc:
|
|
145
|
+
except Exception as exc: # noqa: BLE001 -- a broken hook must not abort the agent
|
|
132
146
|
logger.warning("Hook %s raised %s: %s", method, type(exc).__name__, exc)
|
|
@@ -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,66 @@
|
|
|
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
|
+
# Annotation keywords strict validators reject. Stripped from schema *nodes*
|
|
15
|
+
# only -- never from the name maps below, where these appear as field names.
|
|
16
|
+
_STRIP_KEYWORDS = ("title", "default")
|
|
17
|
+
|
|
18
|
+
# Dicts keyed by user-chosen names rather than JSON Schema keywords. Their keys
|
|
19
|
+
# are data; only their values are schema nodes to recurse into.
|
|
20
|
+
_NAME_MAPS = ("properties", "$defs", "definitions", "patternProperties")
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def _tighten(node: Any) -> None:
|
|
24
|
+
"""Recursively rewrite *node* in place into a strict-legal schema."""
|
|
25
|
+
if isinstance(node, list):
|
|
26
|
+
for item in node:
|
|
27
|
+
_tighten(item)
|
|
28
|
+
return
|
|
29
|
+
if not isinstance(node, dict):
|
|
30
|
+
return
|
|
31
|
+
|
|
32
|
+
for keyword in _STRIP_KEYWORDS:
|
|
33
|
+
node.pop(keyword, None)
|
|
34
|
+
|
|
35
|
+
properties = node.get("properties")
|
|
36
|
+
if isinstance(properties, dict):
|
|
37
|
+
node["additionalProperties"] = False
|
|
38
|
+
node["required"] = list(properties)
|
|
39
|
+
|
|
40
|
+
for key, value in node.items():
|
|
41
|
+
if key in _NAME_MAPS and isinstance(value, dict):
|
|
42
|
+
# Recurse into the definitions, not over their names. A field called
|
|
43
|
+
# "title" or "default" must survive keyword stripping.
|
|
44
|
+
for subschema in value.values():
|
|
45
|
+
_tighten(subschema)
|
|
46
|
+
else:
|
|
47
|
+
_tighten(value)
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def to_strict_schema(schema: type[BaseModel]) -> dict[str, Any]:
|
|
51
|
+
"""Return *schema*'s JSON Schema, tightened for strict structured output.
|
|
52
|
+
|
|
53
|
+
Every object with ``properties`` gets ``additionalProperties: false`` and a
|
|
54
|
+
``required`` list naming **all** its properties; ``title`` and ``default``
|
|
55
|
+
are stripped from schema nodes. ``$defs`` / ``$ref`` are preserved -- only
|
|
56
|
+
rewritten in place.
|
|
57
|
+
|
|
58
|
+
Field names are never treated as keywords: a model with a field called
|
|
59
|
+
``title`` or ``default`` keeps it.
|
|
60
|
+
|
|
61
|
+
``X | None`` fields keep working: Pydantic emits ``anyOf: [..., {"type":
|
|
62
|
+
"null"}]``, so the field stays formally required while remaining nullable.
|
|
63
|
+
"""
|
|
64
|
+
result = schema.model_json_schema()
|
|
65
|
+
_tighten(result)
|
|
66
|
+
return result
|
|
@@ -4,8 +4,9 @@ import inspect
|
|
|
4
4
|
import types
|
|
5
5
|
import typing
|
|
6
6
|
import warnings
|
|
7
|
+
from collections.abc import Callable, Coroutine
|
|
7
8
|
from dataclasses import dataclass
|
|
8
|
-
from typing import Any,
|
|
9
|
+
from typing import Any, overload
|
|
9
10
|
|
|
10
11
|
|
|
11
12
|
@dataclass
|
|
@@ -113,7 +114,6 @@ def tool(
|
|
|
113
114
|
allow_override: bool = False,
|
|
114
115
|
) -> ToolInfo:
|
|
115
116
|
"""Use as @tool directly on a function."""
|
|
116
|
-
...
|
|
117
117
|
|
|
118
118
|
|
|
119
119
|
@overload
|
|
@@ -124,7 +124,6 @@ def tool(
|
|
|
124
124
|
allow_override: bool = False,
|
|
125
125
|
) -> Callable[[Callable[..., Coroutine[Any, Any, str]]], ToolInfo]:
|
|
126
126
|
"""Use as @tool(...) with keyword arguments."""
|
|
127
|
-
...
|
|
128
127
|
|
|
129
128
|
|
|
130
129
|
def tool(
|
|
@@ -11,7 +11,10 @@ _MAX_READ_BYTES = 10 * 1024 * 1024 # 10 MB
|
|
|
11
11
|
def _resolve_safe(requested: str, root: "Path | str") -> str:
|
|
12
12
|
"""Resolve *requested* relative to *root* and raise ValueError on path traversal."""
|
|
13
13
|
if not isinstance(requested, str):
|
|
14
|
-
|
|
14
|
+
# ValueError, not TypeError: callers catch ValueError for every path failure.
|
|
15
|
+
raise ValueError( # noqa: TRY004
|
|
16
|
+
f"path must be a string, got {type(requested).__name__}"
|
|
17
|
+
)
|
|
15
18
|
|
|
16
19
|
# Normalize Windows-style separators so traversal is caught on all platforms.
|
|
17
20
|
raw = Path(requested.replace("\\", "/"))
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
"""edit.py -- atomic string-replace edit tool for text files."""
|
|
2
2
|
|
|
3
|
+
import asyncio
|
|
3
4
|
import os
|
|
4
5
|
import tempfile
|
|
5
6
|
from pathlib import Path
|
|
@@ -8,24 +9,6 @@ from ..tool_registry import ToolInfo
|
|
|
8
9
|
from ._shared import _fmt_size, _make_tool_info, _resolve_safe, _resolve_safe_strict
|
|
9
10
|
|
|
10
11
|
|
|
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
12
|
def make_edit_tool(root: str, *, max_bytes: int = 10 * 1024 * 1024) -> ToolInfo:
|
|
30
13
|
"""Build an edit tool scoped to *root* with an atomic write via a temp file."""
|
|
31
14
|
root_path = Path(root).resolve()
|
|
@@ -34,14 +17,9 @@ def make_edit_tool(root: str, *, max_bytes: int = 10 * 1024 * 1024) -> ToolInfo:
|
|
|
34
17
|
path: str,
|
|
35
18
|
old_text: str,
|
|
36
19
|
new_text: str,
|
|
37
|
-
line_hint: int | None = None,
|
|
38
20
|
) -> str:
|
|
39
21
|
"""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
22
|
|
|
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
23
|
To create a new file, pass ``old_text=""`` - the file must not already
|
|
46
24
|
exist. Parent directories are created automatically.
|
|
47
25
|
|
|
@@ -50,13 +28,10 @@ def make_edit_tool(root: str, *, max_bytes: int = 10 * 1024 * 1024) -> ToolInfo:
|
|
|
50
28
|
path :
|
|
51
29
|
Relative or absolute path to the file.
|
|
52
30
|
old_text :
|
|
53
|
-
Exact text to search for (must appear exactly once
|
|
54
|
-
|
|
31
|
+
Exact text to search for (must appear exactly once).
|
|
32
|
+
Pass ``""`` to create a new file.
|
|
55
33
|
new_text :
|
|
56
34
|
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
35
|
"""
|
|
61
36
|
if not old_text:
|
|
62
37
|
try:
|
|
@@ -93,9 +68,12 @@ def make_edit_tool(root: str, *, max_bytes: int = 10 * 1024 * 1024) -> ToolInfo:
|
|
|
93
68
|
f"({_fmt_size(file_size)} > {_fmt_size(max_bytes)})"
|
|
94
69
|
)
|
|
95
70
|
|
|
96
|
-
|
|
71
|
+
def _read_all() -> str:
|
|
97
72
|
with open(safe, encoding="utf-8", errors="strict") as f:
|
|
98
|
-
|
|
73
|
+
return f.read()
|
|
74
|
+
|
|
75
|
+
try:
|
|
76
|
+
content = await asyncio.to_thread(_read_all)
|
|
99
77
|
except UnicodeDecodeError:
|
|
100
78
|
return f"Error: {path!r} contains non-UTF-8 bytes; cannot edit"
|
|
101
79
|
except OSError as exc:
|
|
@@ -117,18 +95,10 @@ def make_edit_tool(root: str, *, max_bytes: int = 10 * 1024 * 1024) -> ToolInfo:
|
|
|
117
95
|
|
|
118
96
|
if count == 1:
|
|
119
97
|
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
98
|
else:
|
|
128
99
|
return (
|
|
129
100
|
f"Error: old_text {old_text!r} appears {count} times in "
|
|
130
|
-
f"{path!r}.
|
|
131
|
-
f"to replace."
|
|
101
|
+
f"{path!r}. Use a longer, unique excerpt as old_text."
|
|
132
102
|
)
|
|
133
103
|
|
|
134
104
|
new_content = content[:idx] + new_text + content[idx + len(old_text) :]
|
|
@@ -4,7 +4,7 @@ import asyncio
|
|
|
4
4
|
from pathlib import Path
|
|
5
5
|
|
|
6
6
|
from ..tool_registry import ToolInfo
|
|
7
|
-
from ._shared import
|
|
7
|
+
from ._shared import _make_tool_info, _resolve_safe_strict
|
|
8
8
|
|
|
9
9
|
|
|
10
10
|
def make_grep_tool(root: str, *, max_chars: int = 20_000, search_timeout: float = 30.0) -> ToolInfo:
|
|
@@ -58,7 +58,7 @@ def make_grep_tool(root: str, *, max_chars: int = 20_000, search_timeout: float
|
|
|
58
58
|
)
|
|
59
59
|
try:
|
|
60
60
|
stdout, stderr = await asyncio.wait_for(proc.communicate(), timeout=search_timeout)
|
|
61
|
-
except
|
|
61
|
+
except TimeoutError:
|
|
62
62
|
proc.kill()
|
|
63
63
|
await proc.communicate()
|
|
64
64
|
return f"Error: grep timed out after {search_timeout} seconds"
|
|
@@ -4,7 +4,7 @@ import os
|
|
|
4
4
|
from pathlib import Path
|
|
5
5
|
|
|
6
6
|
from ..tool_registry import ToolInfo
|
|
7
|
-
from ._shared import
|
|
7
|
+
from ._shared import _fmt_size, _make_tool_info, _resolve_safe, _resolve_safe_strict
|
|
8
8
|
|
|
9
9
|
|
|
10
10
|
def make_ls_tool(root: str, *, max_entries: int = 500) -> ToolInfo:
|
|
@@ -1,10 +1,11 @@
|
|
|
1
1
|
"""read.py -- line-based file reader with offset/limit pagination."""
|
|
2
2
|
|
|
3
|
+
import asyncio
|
|
3
4
|
import itertools
|
|
4
5
|
from pathlib import Path
|
|
5
6
|
|
|
6
7
|
from ..tool_registry import ToolInfo
|
|
7
|
-
from ._shared import
|
|
8
|
+
from ._shared import _fmt_size, _make_tool_info, _resolve_safe_strict
|
|
8
9
|
|
|
9
10
|
|
|
10
11
|
def make_read_tool(
|
|
@@ -49,9 +50,12 @@ def make_read_tool(
|
|
|
49
50
|
|
|
50
51
|
_stop = _offset + _limit
|
|
51
52
|
|
|
52
|
-
|
|
53
|
+
def _read_slice() -> list[str]:
|
|
53
54
|
with open(safe, encoding="utf-8", errors="replace") as f:
|
|
54
|
-
|
|
55
|
+
return list(itertools.islice(f, _offset, _stop + 1))
|
|
56
|
+
|
|
57
|
+
try:
|
|
58
|
+
lines = await asyncio.to_thread(_read_slice)
|
|
55
59
|
except OSError as exc:
|
|
56
60
|
return f"Error: cannot read {path!r}: {exc}"
|
|
57
61
|
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
"""Message and tool-call type models matching OpenAI's chat format."""
|
|
2
2
|
|
|
3
|
-
from datetime import
|
|
3
|
+
from datetime import UTC, datetime
|
|
4
4
|
|
|
5
5
|
from pydantic import BaseModel, Field
|
|
6
6
|
|
|
@@ -56,7 +56,7 @@ class Message(BaseModel):
|
|
|
56
56
|
usage: Usage | None = None
|
|
57
57
|
duration: float | None = None
|
|
58
58
|
model: str | None = None
|
|
59
|
-
timestamp: datetime = Field(default_factory=lambda: datetime.now(
|
|
59
|
+
timestamp: datetime = Field(default_factory=lambda: datetime.now(UTC))
|
|
60
60
|
|
|
61
61
|
|
|
62
62
|
def _dump_messages(messages: list[Message]) -> list[dict]:
|
|
@@ -87,7 +87,7 @@ def make_web_tools(searxng_url: str | None = None) -> list[ToolInfo]:
|
|
|
87
87
|
r = await client.get(f"{base}/search", params=params)
|
|
88
88
|
r.raise_for_status()
|
|
89
89
|
data = r.json()
|
|
90
|
-
except Exception as exc:
|
|
90
|
+
except Exception as exc: # noqa: BLE001 -- any search failure becomes a tool error string
|
|
91
91
|
msg = str(exc)
|
|
92
92
|
if "SearXNG URL not configured" in msg:
|
|
93
93
|
msg += " or set searxng_url in ~/coreloop.toml"
|
|
@@ -129,17 +129,16 @@ def make_web_tools(searxng_url: str | None = None) -> list[ToolInfo]:
|
|
|
129
129
|
) as client:
|
|
130
130
|
r = await client.get(url)
|
|
131
131
|
r.raise_for_status()
|
|
132
|
-
if cl := r.headers.get("content-length"):
|
|
133
|
-
|
|
134
|
-
return f"Error: Content too large ({cl} bytes)"
|
|
132
|
+
if (cl := r.headers.get("content-length")) and int(cl) > _MAX_CONTENT_BYTES:
|
|
133
|
+
return f"Error: Content too large ({cl} bytes)"
|
|
135
134
|
page_html = r.text
|
|
136
|
-
except Exception as exc:
|
|
135
|
+
except Exception as exc: # noqa: BLE001 -- any fetch failure becomes a tool error string
|
|
137
136
|
return f"Error: {exc}"
|
|
138
137
|
|
|
139
138
|
if extract_mode == "raw":
|
|
140
139
|
return page_html[:_MAX_RAW_CHARS]
|
|
141
140
|
if extract_mode == "metadata":
|
|
142
141
|
return _metadata(page_html)
|
|
143
|
-
return _convert(page_html).content[:_MAX_MARKDOWN_CHARS]
|
|
142
|
+
return (_convert(page_html).content or "")[:_MAX_MARKDOWN_CHARS]
|
|
144
143
|
|
|
145
144
|
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
|