coreloop 0.1.3__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.
Files changed (32) hide show
  1. {coreloop-0.1.3 → coreloop-0.1.4}/PKG-INFO +38 -5
  2. {coreloop-0.1.3 → coreloop-0.1.4}/README.md +37 -4
  3. coreloop-0.1.4/pyproject.toml +88 -0
  4. coreloop-0.1.3/pyproject.toml → coreloop-0.1.4/pyproject.toml.orig +1 -1
  5. {coreloop-0.1.3 → coreloop-0.1.4}/src/coreloop/__init__.py +5 -1
  6. {coreloop-0.1.3 → coreloop-0.1.4}/src/coreloop/_api_client.py +27 -2
  7. {coreloop-0.1.3 → coreloop-0.1.4}/src/coreloop/_tool_execution.py +2 -2
  8. {coreloop-0.1.3 → coreloop-0.1.4}/src/coreloop/agent.py +14 -0
  9. coreloop-0.1.4/src/coreloop/complete.py +108 -0
  10. {coreloop-0.1.3 → coreloop-0.1.4}/src/coreloop/config.py +1 -0
  11. {coreloop-0.1.3 → coreloop-0.1.4}/src/coreloop/hooks.py +14 -0
  12. {coreloop-0.1.3 → coreloop-0.1.4}/src/coreloop/profiles.py +4 -1
  13. coreloop-0.1.4/src/coreloop/structured.py +48 -0
  14. {coreloop-0.1.3 → coreloop-0.1.4}/src/coreloop/tools/edit.py +3 -37
  15. {coreloop-0.1.3 → coreloop-0.1.4}/src/coreloop/web_tools.py +1 -1
  16. {coreloop-0.1.3 → coreloop-0.1.4}/LICENSE +0 -0
  17. {coreloop-0.1.3 → coreloop-0.1.4}/src/coreloop/.coreloop.toml +0 -0
  18. {coreloop-0.1.3 → coreloop-0.1.4}/src/coreloop/__main__.py +0 -0
  19. {coreloop-0.1.3 → coreloop-0.1.4}/src/coreloop/_cache.py +0 -0
  20. {coreloop-0.1.3 → coreloop-0.1.4}/src/coreloop/_logging.py +0 -0
  21. {coreloop-0.1.3 → coreloop-0.1.4}/src/coreloop/cli/__init__.py +0 -0
  22. {coreloop-0.1.3 → coreloop-0.1.4}/src/coreloop/cli/_run.py +0 -0
  23. {coreloop-0.1.3 → coreloop-0.1.4}/src/coreloop/cli/_tools.py +0 -0
  24. {coreloop-0.1.3 → coreloop-0.1.4}/src/coreloop/py.typed +0 -0
  25. {coreloop-0.1.3 → coreloop-0.1.4}/src/coreloop/tool_registry.py +0 -0
  26. {coreloop-0.1.3 → coreloop-0.1.4}/src/coreloop/tools/__init__.py +0 -0
  27. {coreloop-0.1.3 → coreloop-0.1.4}/src/coreloop/tools/_shared.py +0 -0
  28. {coreloop-0.1.3 → coreloop-0.1.4}/src/coreloop/tools/bash.py +0 -0
  29. {coreloop-0.1.3 → coreloop-0.1.4}/src/coreloop/tools/grep.py +0 -0
  30. {coreloop-0.1.3 → coreloop-0.1.4}/src/coreloop/tools/ls.py +0 -0
  31. {coreloop-0.1.3 → coreloop-0.1.4}/src/coreloop/tools/read.py +0 -0
  32. {coreloop-0.1.3 → 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
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
@@ -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 `~/coreloop.toml`:
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 `~/coreloop.toml` — edit that file to set
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 `~/coreloop.toml` |
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 `~/coreloop.toml`
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 `~/coreloop.toml`:
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 `~/coreloop.toml` — edit that file to set
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 `~/coreloop.toml` |
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 `~/coreloop.toml`
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.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"
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"
@@ -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.0"
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 four ``Backend``
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 four methods to add a provider. The agent loop and
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.info("Tool call: %s(%s)", name, json.dumps(args, ensure_ascii=False) if args else "")
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.info("Tool '%s' completed in %.2fs", name, duration)
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)
@@ -31,3 +31,4 @@ class AgentConfig:
31
31
  llm_timeout: float = 300.0
32
32
  llm_extra_body: dict[str, Any] | None = None
33
33
  cache_dir: str | None = str(Path.home() / ".cache" / "coreloop-llm-cache")
34
+ system_nonce: bool = False
@@ -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
- return AgentConfig(**{k: v for k, v in raw.items() if k in known})
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
@@ -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, unless
54
- ``line_hint`` is given). Pass ``""`` to create a new file.
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}. Provide line_hint to specify which occurrence "
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) :]
@@ -140,6 +140,6 @@ def make_web_tools(searxng_url: str | None = None) -> list[ToolInfo]:
140
140
  return page_html[:_MAX_RAW_CHARS]
141
141
  if extract_mode == "metadata":
142
142
  return _metadata(page_html)
143
- return _convert(page_html).content[:_MAX_MARKDOWN_CHARS]
143
+ return (_convert(page_html).content or "")[:_MAX_MARKDOWN_CHARS]
144
144
 
145
145
  return [_make_tool_info(web_search), _make_tool_info(web_fetch)]
File without changes
File without changes
File without changes