coreloop 0.1.4__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.4 → coreloop-0.1.5}/PKG-INFO +1 -1
- {coreloop-0.1.4 → coreloop-0.1.5}/pyproject.toml +1 -1
- {coreloop-0.1.4 → coreloop-0.1.5}/pyproject.toml.orig +1 -1
- {coreloop-0.1.4 → coreloop-0.1.5}/src/coreloop/_api_client.py +6 -5
- {coreloop-0.1.4 → coreloop-0.1.5}/src/coreloop/_tool_execution.py +2 -2
- {coreloop-0.1.4 → coreloop-0.1.5}/src/coreloop/agent.py +2 -2
- {coreloop-0.1.4 → coreloop-0.1.5}/src/coreloop/hooks.py +1 -1
- {coreloop-0.1.4 → coreloop-0.1.5}/src/coreloop/structured.py +26 -8
- {coreloop-0.1.4 → coreloop-0.1.5}/src/coreloop/tool_registry.py +2 -3
- {coreloop-0.1.4 → coreloop-0.1.5}/src/coreloop/tools/_shared.py +4 -1
- {coreloop-0.1.4 → coreloop-0.1.5}/src/coreloop/tools/bash.py +1 -1
- {coreloop-0.1.4 → coreloop-0.1.5}/src/coreloop/tools/edit.py +6 -2
- {coreloop-0.1.4 → coreloop-0.1.5}/src/coreloop/tools/grep.py +2 -2
- {coreloop-0.1.4 → coreloop-0.1.5}/src/coreloop/tools/ls.py +1 -1
- {coreloop-0.1.4 → coreloop-0.1.5}/src/coreloop/tools/read.py +7 -3
- {coreloop-0.1.4 → coreloop-0.1.5}/src/coreloop/types.py +2 -2
- {coreloop-0.1.4 → coreloop-0.1.5}/src/coreloop/web_tools.py +4 -5
- {coreloop-0.1.4 → coreloop-0.1.5}/LICENSE +0 -0
- {coreloop-0.1.4 → coreloop-0.1.5}/README.md +0 -0
- {coreloop-0.1.4 → coreloop-0.1.5}/src/coreloop/.coreloop.toml +0 -0
- {coreloop-0.1.4 → coreloop-0.1.5}/src/coreloop/__init__.py +4 -4
- {coreloop-0.1.4 → coreloop-0.1.5}/src/coreloop/__main__.py +0 -0
- {coreloop-0.1.4 → coreloop-0.1.5}/src/coreloop/_cache.py +0 -0
- {coreloop-0.1.4 → coreloop-0.1.5}/src/coreloop/_logging.py +0 -0
- {coreloop-0.1.4 → coreloop-0.1.5}/src/coreloop/cli/__init__.py +0 -0
- {coreloop-0.1.4 → coreloop-0.1.5}/src/coreloop/cli/_run.py +0 -0
- {coreloop-0.1.4 → coreloop-0.1.5}/src/coreloop/cli/_tools.py +0 -0
- {coreloop-0.1.4 → coreloop-0.1.5}/src/coreloop/complete.py +0 -0
- {coreloop-0.1.4 → coreloop-0.1.5}/src/coreloop/config.py +0 -0
- {coreloop-0.1.4 → coreloop-0.1.5}/src/coreloop/profiles.py +0 -0
- {coreloop-0.1.4 → coreloop-0.1.5}/src/coreloop/py.typed +0 -0
- {coreloop-0.1.4 → 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
|
|
@@ -17,7 +17,8 @@ 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
|
|
23
24
|
from pydantic import BaseModel
|
|
@@ -172,7 +173,7 @@ class OpenAIBackend:
|
|
|
172
173
|
continue
|
|
173
174
|
|
|
174
175
|
# --- usage (arrives in a separate no-choices chunk after finish_reason) ---
|
|
175
|
-
if
|
|
176
|
+
if chunk.get("usage"):
|
|
176
177
|
u = chunk["usage"]
|
|
177
178
|
pt = u.get("prompt_tokens", 0)
|
|
178
179
|
ct = u.get("completion_tokens", 0)
|
|
@@ -228,13 +229,13 @@ class OpenAIBackend:
|
|
|
228
229
|
"function": {"name": "", "arguments": ""},
|
|
229
230
|
},
|
|
230
231
|
)
|
|
231
|
-
if
|
|
232
|
+
if tc_delta.get("id"):
|
|
232
233
|
partial["id"] = tc_delta["id"]
|
|
233
234
|
if "function" in tc_delta:
|
|
234
235
|
fn = tc_delta["function"]
|
|
235
|
-
if
|
|
236
|
+
if fn.get("name"):
|
|
236
237
|
partial["function"]["name"] += fn["name"]
|
|
237
|
-
if
|
|
238
|
+
if fn.get("arguments"):
|
|
238
239
|
partial["function"]["arguments"] += fn["arguments"]
|
|
239
240
|
|
|
240
241
|
# --- assemble on finish, but keep reading for the usage chunk ---
|
|
@@ -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}"
|
|
@@ -3,9 +3,9 @@
|
|
|
3
3
|
import asyncio
|
|
4
4
|
import logging
|
|
5
5
|
import uuid
|
|
6
|
-
from collections.abc import Sequence
|
|
6
|
+
from collections.abc import AsyncIterator, Sequence
|
|
7
7
|
from pathlib import Path
|
|
8
|
-
from typing import TYPE_CHECKING, Any
|
|
8
|
+
from typing import TYPE_CHECKING, Any
|
|
9
9
|
|
|
10
10
|
if TYPE_CHECKING:
|
|
11
11
|
from .config import AgentConfig
|
|
@@ -142,5 +142,5 @@ async def _safe_hook(hooks: AgentHooks, method: str, *args: Any) -> Any:
|
|
|
142
142
|
"""Call a hook method, logging and swallowing any exceptions."""
|
|
143
143
|
try:
|
|
144
144
|
return await getattr(hooks, method)(*args)
|
|
145
|
-
except Exception as exc:
|
|
145
|
+
except Exception as exc: # noqa: BLE001 -- a broken hook must not abort the agent
|
|
146
146
|
logger.warning("Hook %s raised %s: %s", method, type(exc).__name__, exc)
|
|
@@ -11,6 +11,14 @@ from pydantic import BaseModel
|
|
|
11
11
|
|
|
12
12
|
__all__ = ["to_strict_schema"]
|
|
13
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
|
+
|
|
14
22
|
|
|
15
23
|
def _tighten(node: Any) -> None:
|
|
16
24
|
"""Recursively rewrite *node* in place into a strict-legal schema."""
|
|
@@ -21,15 +29,22 @@ def _tighten(node: Any) -> None:
|
|
|
21
29
|
if not isinstance(node, dict):
|
|
22
30
|
return
|
|
23
31
|
|
|
24
|
-
|
|
25
|
-
|
|
32
|
+
for keyword in _STRIP_KEYWORDS:
|
|
33
|
+
node.pop(keyword, None)
|
|
26
34
|
|
|
27
|
-
|
|
35
|
+
properties = node.get("properties")
|
|
36
|
+
if isinstance(properties, dict):
|
|
28
37
|
node["additionalProperties"] = False
|
|
29
|
-
node["required"] = list(
|
|
38
|
+
node["required"] = list(properties)
|
|
30
39
|
|
|
31
|
-
for value in node.
|
|
32
|
-
|
|
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)
|
|
33
48
|
|
|
34
49
|
|
|
35
50
|
def to_strict_schema(schema: type[BaseModel]) -> dict[str, Any]:
|
|
@@ -37,8 +52,11 @@ def to_strict_schema(schema: type[BaseModel]) -> dict[str, Any]:
|
|
|
37
52
|
|
|
38
53
|
Every object with ``properties`` gets ``additionalProperties: false`` and a
|
|
39
54
|
``required`` list naming **all** its properties; ``title`` and ``default``
|
|
40
|
-
are stripped
|
|
41
|
-
in place.
|
|
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.
|
|
42
60
|
|
|
43
61
|
``X | None`` fields keep working: Pydantic emits ``anyOf: [..., {"type":
|
|
44
62
|
"null"}]``, so the field stays formally required while remaining nullable.
|
|
@@ -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
|
|
@@ -67,9 +68,12 @@ def make_edit_tool(root: str, *, max_bytes: int = 10 * 1024 * 1024) -> ToolInfo:
|
|
|
67
68
|
f"({_fmt_size(file_size)} > {_fmt_size(max_bytes)})"
|
|
68
69
|
)
|
|
69
70
|
|
|
70
|
-
|
|
71
|
+
def _read_all() -> str:
|
|
71
72
|
with open(safe, encoding="utf-8", errors="strict") as f:
|
|
72
|
-
|
|
73
|
+
return f.read()
|
|
74
|
+
|
|
75
|
+
try:
|
|
76
|
+
content = await asyncio.to_thread(_read_all)
|
|
73
77
|
except UnicodeDecodeError:
|
|
74
78
|
return f"Error: {path!r} contains non-UTF-8 bytes; cannot edit"
|
|
75
79
|
except OSError as exc:
|
|
@@ -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,11 +129,10 @@ 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":
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
@@ -3,14 +3,14 @@
|
|
|
3
3
|
from .agent import Agent
|
|
4
4
|
from .complete import complete
|
|
5
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
|
|
6
9
|
from .tools import make_tools
|
|
7
10
|
from .tools.bash import make_bash_tool
|
|
8
11
|
from .tools.grep import make_grep_tool
|
|
9
|
-
from .hooks import AgentHooks, MaxTurnsHook
|
|
10
|
-
from .tool_registry import ToolInfo, clear_registry, get_tool, list_tools, tool
|
|
11
|
-
from .structured import to_strict_schema
|
|
12
|
-
from .web_tools import make_web_tools
|
|
13
12
|
from .types import FunctionCall, Message, ToolCall, Usage
|
|
13
|
+
from .web_tools import make_web_tools
|
|
14
14
|
|
|
15
15
|
__all__ = [
|
|
16
16
|
"Agent",
|
|
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
|