coreloop 0.1.0__py3-none-any.whl

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/__init__.py ADDED
@@ -0,0 +1,33 @@
1
+ """coreloop: a minimal LLM agent with tool-calling support."""
2
+
3
+ from .agent import Agent
4
+ from .config import AgentConfig
5
+ from .tools import make_tools
6
+ from .tools.bash import make_bash_tool
7
+ 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
+ from .types import FunctionCall, Message, ToolCall, Usage
12
+
13
+ __all__ = [
14
+ "Agent",
15
+ "AgentConfig",
16
+ "AgentHooks",
17
+ "FunctionCall",
18
+ "MaxTurnsHook",
19
+ "Message",
20
+ "ToolCall",
21
+ "ToolInfo",
22
+ "Usage",
23
+ "clear_registry",
24
+ "get_tool",
25
+ "list_tools",
26
+ "make_bash_tool",
27
+ "make_grep_tool",
28
+ "make_tools",
29
+ "make_web_tools",
30
+ "tool",
31
+ ]
32
+
33
+ __version__ = "0.1.0"
coreloop/__main__.py ADDED
@@ -0,0 +1,5 @@
1
+ """Allow ``python -m coreloop`` to invoke the CLI."""
2
+
3
+ from .cli import app
4
+
5
+ app()
@@ -0,0 +1,330 @@
1
+ """HTTP streaming client and the pluggable :class:`Backend` seam.
2
+
3
+ A *backend* owns everything provider-specific: the endpoint path, auth headers,
4
+ request-body shape (message + tool serialization), and the wire-stream parser
5
+ that turns raw response lines into canonical ``Message`` objects. ``stream_chat``
6
+ is the shared shell around any backend -- it owns the httpx connection, response
7
+ caching, timing, and HTTP error handling.
8
+
9
+ Only one backend ships today (:class:`OpenAIBackend`, OpenAI-compatible chat
10
+ completions). Adding another provider means implementing the four ``Backend``
11
+ methods; nothing else in the agent loop needs to change.
12
+
13
+ Note: Ollama via the OpenAI endpoint does not stream thinking models. They
14
+ arrive at the end.
15
+ """
16
+
17
+ import json
18
+ import logging
19
+ import time
20
+ from typing import Any, AsyncIterator, Protocol
21
+
22
+ import httpx
23
+
24
+ from ._cache import request_key
25
+ from .tool_registry import ToolInfo
26
+ from .types import FunctionCall, Message, ToolCall, Usage, _dump_messages
27
+
28
+ logger = logging.getLogger(__name__)
29
+
30
+
31
+ class Backend(Protocol):
32
+ """Provider-specific request shaping and stream parsing.
33
+
34
+ Implement these four methods to add a provider. The agent loop and
35
+ ``stream_chat`` shell are backend-agnostic.
36
+ """
37
+
38
+ def endpoint(self, base_url: str) -> str:
39
+ """Return the full URL to POST to."""
40
+ ...
41
+
42
+ def headers(self, api_key: str | None) -> dict[str, str]:
43
+ """Return request headers (content type, accept, auth)."""
44
+ ...
45
+
46
+ def build_body(
47
+ self,
48
+ model: str,
49
+ messages: list[Message],
50
+ tools: list[ToolInfo] | None,
51
+ extra: dict[str, Any] | None,
52
+ ) -> dict[str, Any]:
53
+ """Serialize canonical messages + tools into the provider's request body."""
54
+ ...
55
+
56
+ def parse_stream(
57
+ self, resp: httpx.Response, model: str, usage: Usage | None
58
+ ) -> AsyncIterator[Message]:
59
+ """Parse the streaming response into progressively richer ``Message`` objects.
60
+
61
+ Yields ``partial=True`` messages as content/reasoning stream in, and
62
+ exactly one final ``partial=False`` message (with ``usage`` populated)
63
+ at the end. ``duration`` is left unset -- the shell attaches wall-clock
64
+ timing. If *usage* is given, token counts are accumulated into it.
65
+ """
66
+ ...
67
+
68
+
69
+ def _tool_schemas(tools: list[ToolInfo] | None) -> list[dict[str, Any]] | None:
70
+ """Wrap tools in the OpenAI ``{type: function, function: {...}}`` schema."""
71
+ if not tools:
72
+ return None
73
+ return [
74
+ {
75
+ "type": "function",
76
+ "function": {
77
+ "name": t.name,
78
+ "description": t.description,
79
+ "parameters": t.parameters,
80
+ },
81
+ }
82
+ for t in tools
83
+ ]
84
+
85
+
86
+ class OpenAIBackend:
87
+ """OpenAI-compatible chat-completions backend (the default)."""
88
+
89
+ _CHAT_PATH = "/chat/completions"
90
+ _PROTECTED = frozenset({"model", "messages", "stream", "tools", "stream_options"})
91
+
92
+ def endpoint(self, base_url: str) -> str:
93
+ """Return the full chat-completions URL for the given base URL."""
94
+ return f"{base_url.rstrip('/')}{self._CHAT_PATH}"
95
+
96
+ def headers(self, api_key: str | None) -> dict[str, str]:
97
+ """Return content-type, accept, and optional Bearer auth headers."""
98
+ headers = {
99
+ "Content-Type": "application/json",
100
+ "Accept": "text/event-stream",
101
+ }
102
+ if api_key:
103
+ headers["Authorization"] = f"Bearer {api_key}"
104
+ return headers
105
+
106
+ def build_body(
107
+ self,
108
+ model: str,
109
+ messages: list[Message],
110
+ tools: list[ToolInfo] | None,
111
+ extra: dict[str, Any] | None,
112
+ ) -> dict[str, Any]:
113
+ """Serialize messages and tools into an OpenAI-compatible request body."""
114
+ body: dict[str, Any] = {
115
+ "model": model,
116
+ "messages": _dump_messages(messages),
117
+ "stream": True,
118
+ }
119
+ schemas = _tool_schemas(tools)
120
+ if schemas:
121
+ body["tools"] = schemas
122
+ body["stream_options"] = {"include_usage": True}
123
+ if extra:
124
+ for k, v in extra.items():
125
+ if k not in self._PROTECTED:
126
+ body[k] = v
127
+ return body
128
+
129
+ async def parse_stream(
130
+ self, resp: httpx.Response, model: str, usage: Usage | None
131
+ ) -> AsyncIterator[Message]:
132
+ """Parse an OpenAI SSE stream into progressive then final Message objects."""
133
+ accumulated_content: str | None = ""
134
+ accumulated_reasoning: str | None = ""
135
+ accumulated_tool_calls: list[ToolCall] | None = None
136
+ # For incremental tool-call building: index -> partial ToolCall
137
+ partials: dict[int, dict[str, Any]] = {}
138
+ captured_usage: Usage | None = None
139
+ # Assembled on finish_reason; held until [DONE] so usage chunk can arrive first
140
+ pending_message: Message | None = None
141
+
142
+ async for line in resp.aiter_lines():
143
+ line = line.strip()
144
+ if not line or not line.startswith("data: "):
145
+ continue
146
+ payload = line.removeprefix("data: ")
147
+ if payload == "[DONE]":
148
+ break
149
+
150
+ try:
151
+ chunk = json.loads(payload)
152
+ except json.JSONDecodeError:
153
+ continue
154
+
155
+ # --- usage (arrives in a separate no-choices chunk after finish_reason) ---
156
+ if "usage" in chunk and chunk["usage"]:
157
+ u = chunk["usage"]
158
+ pt = u.get("prompt_tokens", 0)
159
+ ct = u.get("completion_tokens", 0)
160
+ tt = u.get("total_tokens", 0)
161
+ captured_usage = Usage(prompt_tokens=pt, completion_tokens=ct, total_tokens=tt)
162
+ if usage is not None:
163
+ usage.prompt_tokens += pt
164
+ usage.completion_tokens += ct
165
+ usage.total_tokens += tt
166
+
167
+ choices = chunk.get("choices", [])
168
+ if not choices:
169
+ continue
170
+
171
+ delta = choices[0].get("delta", {})
172
+ finish_reason = choices[0].get("finish_reason")
173
+
174
+ # --- reasoning delta (thinking tokens, streamed as partials) ---
175
+ reasoning_delta = delta.get("reasoning") or delta.get("reasoning_content")
176
+ if reasoning_delta:
177
+ accumulated_reasoning = (accumulated_reasoning or "") + reasoning_delta
178
+ yield Message(
179
+ role="assistant",
180
+ content=accumulated_content or None,
181
+ reasoning=accumulated_reasoning,
182
+ partial=True,
183
+ model=model,
184
+ )
185
+
186
+ # --- content delta ---
187
+ if delta.get("content"):
188
+ accumulated_content = (accumulated_content or "") + delta["content"]
189
+ yield Message(
190
+ role="assistant",
191
+ content=accumulated_content,
192
+ reasoning=accumulated_reasoning or None,
193
+ partial=True,
194
+ model=model,
195
+ )
196
+
197
+ # --- tool call deltas ---
198
+ raw_tool_calls = delta.get("tool_calls")
199
+ if raw_tool_calls:
200
+ if accumulated_tool_calls is None:
201
+ accumulated_tool_calls = []
202
+ for tc_delta in raw_tool_calls:
203
+ idx = tc_delta.get("index", 0)
204
+ partial = partials.setdefault(
205
+ idx,
206
+ {
207
+ "id": "",
208
+ "type": "function",
209
+ "function": {"name": "", "arguments": ""},
210
+ },
211
+ )
212
+ if "id" in tc_delta and tc_delta["id"]:
213
+ partial["id"] = tc_delta["id"]
214
+ if "function" in tc_delta:
215
+ fn = tc_delta["function"]
216
+ if "name" in fn and fn["name"]:
217
+ partial["function"]["name"] += fn["name"]
218
+ if "arguments" in fn and fn["arguments"]:
219
+ partial["function"]["arguments"] += fn["arguments"]
220
+
221
+ # --- assemble on finish, but keep reading for the usage chunk ---
222
+ if finish_reason:
223
+ if partials:
224
+ accumulated_tool_calls = [
225
+ ToolCall(
226
+ id=p["id"],
227
+ type=p["type"],
228
+ function=FunctionCall(
229
+ name=p["function"]["name"],
230
+ arguments=p["function"]["arguments"],
231
+ ),
232
+ )
233
+ for _idx, p in sorted(partials.items())
234
+ ]
235
+ partials.clear()
236
+ pending_message = Message(
237
+ role="assistant",
238
+ content=accumulated_content or None,
239
+ tool_calls=accumulated_tool_calls,
240
+ reasoning=accumulated_reasoning or None,
241
+ model=model,
242
+ )
243
+
244
+ if pending_message is not None:
245
+ yield pending_message.model_copy(update={"usage": captured_usage})
246
+ else:
247
+ yield Message(
248
+ role="assistant",
249
+ content=accumulated_content or None,
250
+ tool_calls=accumulated_tool_calls,
251
+ reasoning=accumulated_reasoning or None,
252
+ usage=captured_usage,
253
+ model=model,
254
+ )
255
+
256
+
257
+ OPENAI_BACKEND: Backend = OpenAIBackend()
258
+ """The default backend: OpenAI-compatible chat completions."""
259
+
260
+
261
+ async def stream_chat(
262
+ *,
263
+ base_url: str,
264
+ api_key: str | None,
265
+ model: str,
266
+ messages: list[Message],
267
+ tools: list[ToolInfo] | None = None,
268
+ timeout: float = 60.0,
269
+ client: httpx.AsyncClient | None = None,
270
+ llm_extra_body: dict[str, Any] | None = None,
271
+ usage: Usage | None = None,
272
+ cache: Any = None,
273
+ backend: Backend = OPENAI_BACKEND,
274
+ ) -> AsyncIterator[Message]:
275
+ """Stream chat completion chunks from *backend*, yielding ``Message`` objects.
276
+
277
+ The shared shell around any :class:`Backend`: builds the request body,
278
+ serves/stores cached responses, manages the httpx connection, attaches
279
+ wall-clock ``duration`` to the final message, and raises on HTTP errors.
280
+
281
+ Yields progressively richer *assistant* ``Message`` objects. The last yielded
282
+ message for a turn has either ``content`` set **or** ``tool_calls`` populated
283
+ (or both), plus ``usage`` and ``duration``.
284
+ """
285
+ body = backend.build_body(model, messages, tools, llm_extra_body)
286
+
287
+ cache_key: str | None = None
288
+ if cache is not None:
289
+ cache_key = request_key(base_url, body)
290
+ cached = cache.get(cache_key)
291
+ if cached is not None:
292
+ logger.debug("Cache hit for model=%s messages=%d", model, len(messages))
293
+ yield Message.model_validate_json(cached)
294
+ return
295
+
296
+ url = backend.endpoint(base_url)
297
+ headers = backend.headers(api_key)
298
+
299
+ _owned = client is None
300
+ _session = client or httpx.AsyncClient(timeout=httpx.Timeout(timeout))
301
+ _t0 = time.perf_counter()
302
+ logger.info("POST %s model=%s messages=%d", url, model, len(messages))
303
+ try:
304
+ async with _session.stream("POST", url, headers=headers, json=body) as resp:
305
+ if resp.status_code >= 400:
306
+ await resp.aread()
307
+ detail = resp.text[:500]
308
+ msg = f"HTTP {resp.status_code} from {url}"
309
+ if detail:
310
+ msg += f": {detail}"
311
+ raise httpx.HTTPStatusError(msg, request=resp.request, response=resp)
312
+
313
+ final: Message | None = None
314
+ async for chunk in backend.parse_stream(resp, model, usage):
315
+ if chunk.partial:
316
+ yield chunk
317
+ else:
318
+ final = chunk
319
+
320
+ if final is None:
321
+ return
322
+ _duration = time.perf_counter() - _t0
323
+ final = final.model_copy(update={"duration": _duration})
324
+ logger.debug("Response from %s in %.2fs -- usage: %s", model, _duration, final.usage)
325
+ if cache is not None and cache_key is not None:
326
+ cache.set(cache_key, final.model_dump_json())
327
+ yield final
328
+ finally:
329
+ if _owned:
330
+ await _session.aclose()
coreloop/_cache.py ADDED
@@ -0,0 +1,19 @@
1
+ """Disk-based cache for LLM responses, keyed by a hash of the request."""
2
+
3
+ import hashlib
4
+ import json
5
+ from pathlib import Path
6
+ from typing import Any
7
+
8
+ import diskcache
9
+
10
+
11
+ def make_cache(path: str | Path) -> diskcache.Cache:
12
+ """Open (or create) a disk cache at the given directory path."""
13
+ return diskcache.Cache(str(path))
14
+
15
+
16
+ def request_key(base_url: str, body: dict[str, Any]) -> str:
17
+ """Return a hex SHA-256 key for the full request (endpoint + body)."""
18
+ payload = {"base_url": base_url, "body": body}
19
+ return hashlib.sha256(json.dumps(payload, sort_keys=True).encode()).hexdigest()
coreloop/_logging.py ADDED
@@ -0,0 +1,23 @@
1
+ """Logging configuration for coreloop."""
2
+
3
+ import logging
4
+
5
+ from rich.logging import RichHandler
6
+
7
+ _LOGGER_NAME = "coreloop"
8
+
9
+
10
+ def setup_logging(level: str | int = logging.WARNING) -> None:
11
+ """Configure the coreloop logger with a RichHandler."""
12
+ logger = logging.getLogger(_LOGGER_NAME)
13
+ if logger.handlers:
14
+ return # already configured
15
+
16
+ handler = RichHandler(
17
+ rich_tracebacks=True,
18
+ show_path=False,
19
+ markup=False, # avoid misinterpreting brackets/arrows in log messages
20
+ )
21
+ logger.addHandler(handler)
22
+ logger.setLevel(level)
23
+ logger.propagate = False
@@ -0,0 +1,80 @@
1
+ """Tool execution -- argument validation, timeout handling, and error formatting."""
2
+
3
+ import asyncio
4
+ import json
5
+ import logging
6
+ import time
7
+ from typing import TYPE_CHECKING, Any
8
+
9
+ from .hooks import _safe_hook
10
+ from .tool_registry import ToolInfo
11
+ from .types import ToolCall
12
+
13
+ if TYPE_CHECKING:
14
+ from .agent import Agent
15
+
16
+ logger = logging.getLogger(__name__)
17
+
18
+
19
+ async def exec_tool(tc: ToolCall, agent: "Agent") -> tuple[ToolCall, str, float]:
20
+ """Execute a single tool call and return (call, result, duration)."""
21
+ name = tc.function.name
22
+ try:
23
+ args: dict[str, Any] = json.loads(tc.function.arguments) if tc.function.arguments else {}
24
+ except json.JSONDecodeError as exc:
25
+ logger.warning("Failed to parse arguments for tool '%s': %s", name, exc)
26
+ return tc, f"Error: failed to parse arguments for '{name}': {exc}", 0.0
27
+
28
+ injected = await _safe_hook(agent.hooks, "on_before_tool", agent, name, args)
29
+ if injected is not None:
30
+ logger.debug("Tool '%s' result injected by on_before_tool hook", name)
31
+ replacement = await _safe_hook(agent.hooks, "on_after_tool", agent, name, args, injected)
32
+ return tc, replacement if replacement is not None else injected, 0.0
33
+
34
+ info = agent._resolve_tool(name)
35
+ if info is None:
36
+ logger.warning("Unknown tool requested: '%s'", name)
37
+ result = (
38
+ f"Error: unknown tool '{name}'. "
39
+ f"Available tools: {', '.join(t.name for t in agent._all_tools())}"
40
+ )
41
+ replacement = await _safe_hook(agent.hooks, "on_after_tool", agent, name, args, result)
42
+ return tc, replacement if replacement is not None else result, 0.0
43
+
44
+ logger.info("Tool call: %s(%s)", name, json.dumps(args, ensure_ascii=False) if args else "")
45
+ t0 = time.perf_counter()
46
+ result = await run_tool(info, args, agent.tool_timeout)
47
+ duration = time.perf_counter() - t0
48
+ logger.info("Tool '%s' completed in %.2fs", name, duration)
49
+
50
+ replacement = await _safe_hook(agent.hooks, "on_after_tool", agent, name, args, result)
51
+ if replacement is not None:
52
+ result = replacement
53
+ return tc, result, duration
54
+
55
+
56
+ async def run_tool(info: ToolInfo, args: dict[str, Any], timeout: float) -> str:
57
+ """Validate arguments and execute a tool with timeout."""
58
+ allowed = set(info.parameters.get("properties", {}).keys())
59
+ required = set(info.parameters.get("required", []))
60
+ missing = required - set(args.keys())
61
+ unknown = set(args.keys()) - allowed
62
+ if missing:
63
+ return f"Error: tool '{info.name}' missing required arguments: {', '.join(sorted(missing))}"
64
+ if unknown:
65
+ return (
66
+ f"Error: tool '{info.name}' received unexpected arguments: {', '.join(sorted(unknown))}"
67
+ )
68
+
69
+ try:
70
+ async with asyncio.timeout(timeout):
71
+ result = await info.fn(**args)
72
+ return str(result)
73
+ except asyncio.TimeoutError:
74
+ logger.error("Tool '%s' timed out after %.1fs", info.name, timeout)
75
+ return f"Error: tool '{info.name}' timed out after {timeout}s"
76
+ except asyncio.CancelledError:
77
+ raise
78
+ except Exception as exc:
79
+ logger.error("Tool '%s' raised %s: %s", info.name, type(exc).__name__, exc)
80
+ return f"Error in tool '{info.name}': {exc}"