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 +33 -0
- coreloop/__main__.py +5 -0
- coreloop/_api_client.py +330 -0
- coreloop/_cache.py +19 -0
- coreloop/_logging.py +23 -0
- coreloop/_tool_execution.py +80 -0
- coreloop/agent.py +368 -0
- coreloop/cli/__init__.py +269 -0
- coreloop/cli/_run.py +145 -0
- coreloop/cli/_tools.py +82 -0
- coreloop/config.py +33 -0
- coreloop/coreloop.toml +101 -0
- coreloop/hooks.py +132 -0
- coreloop/profiles.py +176 -0
- coreloop/py.typed +0 -0
- coreloop/tool_registry.py +188 -0
- coreloop/tools/__init__.py +31 -0
- coreloop/tools/_shared.py +59 -0
- coreloop/tools/bash.py +252 -0
- coreloop/tools/edit.py +154 -0
- coreloop/tools/grep.py +86 -0
- coreloop/tools/ls.py +62 -0
- coreloop/tools/read.py +70 -0
- coreloop/types.py +86 -0
- coreloop/web_tools.py +98 -0
- coreloop-0.1.0.dist-info/METADATA +350 -0
- coreloop-0.1.0.dist-info/RECORD +30 -0
- coreloop-0.1.0.dist-info/WHEEL +4 -0
- coreloop-0.1.0.dist-info/entry_points.txt +3 -0
- coreloop-0.1.0.dist-info/licenses/LICENSE +21 -0
coreloop/agent.py
ADDED
|
@@ -0,0 +1,368 @@
|
|
|
1
|
+
"""The Agent -- orchestrates the LLM loop with tool execution."""
|
|
2
|
+
|
|
3
|
+
import asyncio
|
|
4
|
+
import logging
|
|
5
|
+
from collections.abc import Sequence
|
|
6
|
+
from pathlib import Path
|
|
7
|
+
from typing import TYPE_CHECKING, Any, AsyncIterator
|
|
8
|
+
|
|
9
|
+
if TYPE_CHECKING:
|
|
10
|
+
from .config import AgentConfig
|
|
11
|
+
|
|
12
|
+
from ._api_client import OPENAI_BACKEND, Backend, stream_chat
|
|
13
|
+
from ._cache import make_cache
|
|
14
|
+
from ._tool_execution import exec_tool
|
|
15
|
+
from .hooks import AgentHooks, _safe_hook
|
|
16
|
+
from .tool_registry import ToolInfo, get_tool
|
|
17
|
+
from .types import Message, ToolCall, Usage
|
|
18
|
+
|
|
19
|
+
logger = logging.getLogger(__name__)
|
|
20
|
+
|
|
21
|
+
_DEFAULT_CACHE_DIR = Path.home() / ".cache" / "coreloop-llm-cache"
|
|
22
|
+
|
|
23
|
+
_FILE_TOOL_NAMES = frozenset({"read", "ls", "edit", "grep"})
|
|
24
|
+
_WEB_TOOL_NAMES = frozenset({"web_search", "web_fetch"})
|
|
25
|
+
_BASH_TOOL_NAME = "bash"
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def _resolve_tools(
|
|
29
|
+
tools: "Sequence[str | ToolInfo]", root: str | Path | None
|
|
30
|
+
) -> dict[str, ToolInfo]:
|
|
31
|
+
"""Resolve a mixed list of tool names and ``ToolInfo`` objects.
|
|
32
|
+
|
|
33
|
+
Names resolve, in order, to built-in file tools (scoped to *root*), built-in
|
|
34
|
+
web tools, then globally registered ``@tool`` functions. ``ToolInfo`` objects
|
|
35
|
+
(including ``@tool``-decorated functions) are used as-is. Later entries win on
|
|
36
|
+
name collisions. Raises ``ValueError`` for an unknown name.
|
|
37
|
+
"""
|
|
38
|
+
resolved: dict[str, ToolInfo] = {}
|
|
39
|
+
file_tools: dict[str, ToolInfo] | None = None
|
|
40
|
+
web_tools: dict[str, ToolInfo] | None = None
|
|
41
|
+
bash_tool: ToolInfo | None = None
|
|
42
|
+
|
|
43
|
+
for item in tools:
|
|
44
|
+
if isinstance(item, ToolInfo):
|
|
45
|
+
resolved[item.name] = item
|
|
46
|
+
continue
|
|
47
|
+
name = item
|
|
48
|
+
if name in _FILE_TOOL_NAMES:
|
|
49
|
+
if file_tools is None:
|
|
50
|
+
from .tools import make_tools
|
|
51
|
+
|
|
52
|
+
file_tools = {t.name: t for t in make_tools(root)}
|
|
53
|
+
resolved[name] = file_tools[name]
|
|
54
|
+
elif name in _WEB_TOOL_NAMES:
|
|
55
|
+
if web_tools is None:
|
|
56
|
+
from .web_tools import make_web_tools
|
|
57
|
+
|
|
58
|
+
web_tools = {t.name: t for t in make_web_tools()}
|
|
59
|
+
resolved[name] = web_tools[name]
|
|
60
|
+
elif name == _BASH_TOOL_NAME:
|
|
61
|
+
if bash_tool is None:
|
|
62
|
+
from .tools.bash import make_bash_tool
|
|
63
|
+
|
|
64
|
+
bash_tool = make_bash_tool(str(root) if root else ".")
|
|
65
|
+
resolved[name] = bash_tool
|
|
66
|
+
else:
|
|
67
|
+
info = get_tool(name)
|
|
68
|
+
if info is None:
|
|
69
|
+
builtins = ", ".join(sorted(_FILE_TOOL_NAMES | _WEB_TOOL_NAMES | {_BASH_TOOL_NAME}))
|
|
70
|
+
raise ValueError(
|
|
71
|
+
f"Unknown tool {name!r}. Built-ins: {builtins}; or register one with @tool."
|
|
72
|
+
)
|
|
73
|
+
resolved[name] = info
|
|
74
|
+
return resolved
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
class Agent:
|
|
78
|
+
"""A minimal agent that calls an LLM, executes tools, and loops.
|
|
79
|
+
|
|
80
|
+
Usage::
|
|
81
|
+
|
|
82
|
+
agent = Agent(
|
|
83
|
+
model="gpt-4o-mini",
|
|
84
|
+
base_url="https://api.openai.com/v1",
|
|
85
|
+
api_key=os.environ["OPENAI_API_KEY"],
|
|
86
|
+
system="You are a helpful assistant.",
|
|
87
|
+
timeout=30,
|
|
88
|
+
)
|
|
89
|
+
|
|
90
|
+
async for msg in agent.run([Message(role="user", content="Hello!")]):
|
|
91
|
+
print(msg)
|
|
92
|
+
|
|
93
|
+
After ``run()`` completes (or is stopped), the full message history --
|
|
94
|
+
including system prompt, assistant responses, and tool results -- is
|
|
95
|
+
available via ``agent.messages``. You can copy it to a new agent to
|
|
96
|
+
restart::
|
|
97
|
+
|
|
98
|
+
# agent.messages contains every message the LLM saw
|
|
99
|
+
new_agent = Agent(model="better-model", ...)
|
|
100
|
+
async for msg in new_agent.run(agent.messages):
|
|
101
|
+
...
|
|
102
|
+
|
|
103
|
+
The agent core has no built-in turn limit; to bound a run, attach a hook
|
|
104
|
+
that calls ``agent.stop()`` (see ``MaxTurnsHook`` in the examples).
|
|
105
|
+
"""
|
|
106
|
+
|
|
107
|
+
def __init__(
|
|
108
|
+
self,
|
|
109
|
+
model: str,
|
|
110
|
+
base_url: str = "http://localhost:11434/v1",
|
|
111
|
+
api_key: str | None = None,
|
|
112
|
+
system: str | None = None,
|
|
113
|
+
tools: Sequence[str | ToolInfo] | None = None,
|
|
114
|
+
root: str | Path | None = None,
|
|
115
|
+
http_request_timeout: float = 300.0,
|
|
116
|
+
tool_timeout: float = 360.0,
|
|
117
|
+
llm_timeout: float = 300.0,
|
|
118
|
+
hooks: AgentHooks | None = None,
|
|
119
|
+
llm_extra_body: dict[str, Any] | None = None,
|
|
120
|
+
cache_dir: Path | str | None = _DEFAULT_CACHE_DIR,
|
|
121
|
+
backend: Backend | None = None,
|
|
122
|
+
) -> None:
|
|
123
|
+
# Public -- safe to read/write between runs
|
|
124
|
+
self.model = model
|
|
125
|
+
self.system = system
|
|
126
|
+
self.root = root
|
|
127
|
+
self.http_request_timeout = http_request_timeout
|
|
128
|
+
self.tool_timeout = tool_timeout
|
|
129
|
+
self.llm_timeout = llm_timeout
|
|
130
|
+
self.hooks = hooks if hooks is not None else AgentHooks()
|
|
131
|
+
self.llm_extra_body = llm_extra_body
|
|
132
|
+
self.backend = backend if backend is not None else OPENAI_BACKEND
|
|
133
|
+
self._cache = make_cache(cache_dir) if cache_dir is not None else None
|
|
134
|
+
|
|
135
|
+
self._base_url = base_url.rstrip("/")
|
|
136
|
+
self._api_key = api_key
|
|
137
|
+
self._messages: list[Message] = []
|
|
138
|
+
|
|
139
|
+
# Resolve names ('read', 'web_search', a registered @tool) and ToolInfo
|
|
140
|
+
# objects into this agent's tool set. The agent only has the tools listed
|
|
141
|
+
# here -- there is no implicit inclusion of the global registry.
|
|
142
|
+
self._tools: dict[str, ToolInfo] = _resolve_tools(tools, root) if tools else {}
|
|
143
|
+
|
|
144
|
+
self._stop_event = asyncio.Event()
|
|
145
|
+
self._current_task: asyncio.Task[None] | None = None
|
|
146
|
+
self._aborted = False
|
|
147
|
+
# Last message produced by the current LLM turn; set in _stream_llm_response.
|
|
148
|
+
self._llm_last_chunk: Message | None = None
|
|
149
|
+
|
|
150
|
+
@classmethod
|
|
151
|
+
def from_profile(
|
|
152
|
+
cls,
|
|
153
|
+
name: str = "default",
|
|
154
|
+
*,
|
|
155
|
+
config_path: "str | Path | None" = None,
|
|
156
|
+
hooks: AgentHooks | None = None,
|
|
157
|
+
tools: "Sequence[str | ToolInfo] | None" = None,
|
|
158
|
+
backend: Backend | None = None,
|
|
159
|
+
) -> "Agent":
|
|
160
|
+
"""Create an Agent from a named profile in coreloop.toml.
|
|
161
|
+
|
|
162
|
+
config_path overrides the default config file location
|
|
163
|
+
(~/coreloop.toml or CORELOOP_CONFIG env var).
|
|
164
|
+
"""
|
|
165
|
+
from .profiles import resolve_profile
|
|
166
|
+
|
|
167
|
+
return cls.from_config(
|
|
168
|
+
resolve_profile(name, config_path=config_path),
|
|
169
|
+
hooks=hooks,
|
|
170
|
+
tools=tools,
|
|
171
|
+
backend=backend,
|
|
172
|
+
)
|
|
173
|
+
|
|
174
|
+
@classmethod
|
|
175
|
+
def from_config(
|
|
176
|
+
cls,
|
|
177
|
+
cfg: "AgentConfig",
|
|
178
|
+
*,
|
|
179
|
+
hooks: AgentHooks | None = None,
|
|
180
|
+
tools: "Sequence[str | ToolInfo] | None" = None,
|
|
181
|
+
backend: Backend | None = None,
|
|
182
|
+
) -> "Agent":
|
|
183
|
+
"""Create an Agent from an AgentConfig.
|
|
184
|
+
|
|
185
|
+
Equivalent to ``Agent(**dataclasses.asdict(cfg), hooks=hooks)``.
|
|
186
|
+
Pass ``tools`` to override with pre-built ``ToolInfo`` objects (e.g.
|
|
187
|
+
root-scoped instances that cannot be expressed as plain names in config).
|
|
188
|
+
``backend`` and ``hooks`` are stateful runtime objects, kept out of
|
|
189
|
+
``AgentConfig`` and passed here instead.
|
|
190
|
+
"""
|
|
191
|
+
import dataclasses
|
|
192
|
+
|
|
193
|
+
kwargs = dataclasses.asdict(cfg)
|
|
194
|
+
if tools is not None:
|
|
195
|
+
kwargs["tools"] = tools
|
|
196
|
+
return cls(**kwargs, hooks=hooks, backend=backend)
|
|
197
|
+
|
|
198
|
+
# -- public API ------------------------------------------------
|
|
199
|
+
|
|
200
|
+
@property
|
|
201
|
+
def messages(self) -> list[Message]:
|
|
202
|
+
"""The message history from the last ``run()`` call (shallow copy)."""
|
|
203
|
+
return list(self._messages)
|
|
204
|
+
|
|
205
|
+
def reset(self) -> None:
|
|
206
|
+
"""Clear message history and reset the stop flag."""
|
|
207
|
+
self._messages.clear()
|
|
208
|
+
self._stop_event.clear()
|
|
209
|
+
|
|
210
|
+
def stop(self) -> None:
|
|
211
|
+
"""Signal the agent to finish the current turn and stop cleanly.
|
|
212
|
+
|
|
213
|
+
Safe to call from inside a tool or hook -- sets the stop flag without
|
|
214
|
+
cancelling the task, so the current turn completes normally and
|
|
215
|
+
``on_after_agent`` is called before the loop exits.
|
|
216
|
+
"""
|
|
217
|
+
self._stop_event.set()
|
|
218
|
+
|
|
219
|
+
def abort(self) -> None:
|
|
220
|
+
"""Halt immediately, abandoning in-flight tools.
|
|
221
|
+
|
|
222
|
+
Cancels the current task. ``on_after_agent`` is NOT called. Use ``stop()``
|
|
223
|
+
for a clean exit.
|
|
224
|
+
"""
|
|
225
|
+
self._aborted = True
|
|
226
|
+
self._stop_event.set()
|
|
227
|
+
if self._current_task is not None and not self._current_task.done():
|
|
228
|
+
self._current_task.cancel()
|
|
229
|
+
|
|
230
|
+
@property
|
|
231
|
+
def stopped(self) -> bool:
|
|
232
|
+
"""Whether stop() or abort() has been called."""
|
|
233
|
+
return self._stop_event.is_set()
|
|
234
|
+
|
|
235
|
+
async def run(
|
|
236
|
+
self,
|
|
237
|
+
messages: list[Message],
|
|
238
|
+
*,
|
|
239
|
+
usage: Usage | None = None,
|
|
240
|
+
) -> AsyncIterator[Message]:
|
|
241
|
+
"""Run the agent loop, yielding messages as they are produced.
|
|
242
|
+
|
|
243
|
+
The loop:
|
|
244
|
+
1. Sends the message history to the LLM (streaming).
|
|
245
|
+
2. If the LLM returns tool calls, executes each (with timeout).
|
|
246
|
+
3. Appends results and repeats.
|
|
247
|
+
4. Stops when the LLM returns a non-tool-call response.
|
|
248
|
+
|
|
249
|
+
Streaming notes:
|
|
250
|
+
- Intermediate content delta messages have ``partial=True``.
|
|
251
|
+
- The final assembled message for each LLM turn has ``partial=False``.
|
|
252
|
+
- Tool result messages always have ``partial=False``.
|
|
253
|
+
"""
|
|
254
|
+
self._stop_event.clear()
|
|
255
|
+
self._aborted = False
|
|
256
|
+
self._current_task = asyncio.current_task()
|
|
257
|
+
self._messages = list(messages)
|
|
258
|
+
|
|
259
|
+
if self.system and not (self._messages and self._messages[0].role == "system"):
|
|
260
|
+
self._messages.insert(0, Message(role="system", content=self.system))
|
|
261
|
+
|
|
262
|
+
logger.debug("Agent.run starting: model=%s base_url=%s", self.model, self._base_url)
|
|
263
|
+
await _safe_hook(self.hooks, "on_before_agent", self)
|
|
264
|
+
try:
|
|
265
|
+
while not self._stop_event.is_set():
|
|
266
|
+
await _safe_hook(self.hooks, "on_before_turn", self)
|
|
267
|
+
|
|
268
|
+
async for msg in self._stream_llm_response(usage):
|
|
269
|
+
yield msg
|
|
270
|
+
|
|
271
|
+
if self._stop_event.is_set() or self._llm_last_chunk is None:
|
|
272
|
+
await _safe_hook(self.hooks, "on_after_turn", self)
|
|
273
|
+
return
|
|
274
|
+
|
|
275
|
+
assistant_msg = self._llm_last_chunk
|
|
276
|
+
self._messages.append(assistant_msg)
|
|
277
|
+
|
|
278
|
+
if not assistant_msg.tool_calls:
|
|
279
|
+
logger.debug("LLM finished without tool calls")
|
|
280
|
+
await _safe_hook(self.hooks, "on_after_turn", self)
|
|
281
|
+
return
|
|
282
|
+
|
|
283
|
+
logger.debug(
|
|
284
|
+
"LLM requested %d tool call(s): %s",
|
|
285
|
+
len(assistant_msg.tool_calls),
|
|
286
|
+
[tc.function.name for tc in assistant_msg.tool_calls],
|
|
287
|
+
)
|
|
288
|
+
results = await asyncio.gather(
|
|
289
|
+
*[exec_tool(tc, self) for tc in assistant_msg.tool_calls]
|
|
290
|
+
)
|
|
291
|
+
|
|
292
|
+
async for msg in self._emit_tool_results(results):
|
|
293
|
+
yield msg
|
|
294
|
+
|
|
295
|
+
await _safe_hook(self.hooks, "on_after_turn", self)
|
|
296
|
+
|
|
297
|
+
except asyncio.CancelledError:
|
|
298
|
+
if self._stop_event.is_set():
|
|
299
|
+
pass # abort() -- swallow
|
|
300
|
+
else:
|
|
301
|
+
raise
|
|
302
|
+
finally:
|
|
303
|
+
if not self._aborted:
|
|
304
|
+
await _safe_hook(self.hooks, "on_after_agent", self)
|
|
305
|
+
self._current_task = None
|
|
306
|
+
|
|
307
|
+
# -- tool registry ---------------------------------------------
|
|
308
|
+
|
|
309
|
+
def _all_tools(self) -> list[ToolInfo]:
|
|
310
|
+
return list(self._tools.values())
|
|
311
|
+
|
|
312
|
+
def _resolve_tool(self, name: str) -> ToolInfo | None:
|
|
313
|
+
return self._tools.get(name)
|
|
314
|
+
|
|
315
|
+
# -- loop helpers ----------------------------------------------
|
|
316
|
+
|
|
317
|
+
async def _emit_tool_results(
|
|
318
|
+
self, results: list[tuple[ToolCall, str, float]]
|
|
319
|
+
) -> AsyncIterator[Message]:
|
|
320
|
+
for tc, result_content, tool_duration in results:
|
|
321
|
+
tool_msg = Message(
|
|
322
|
+
role="tool",
|
|
323
|
+
content=result_content,
|
|
324
|
+
tool_call_id=tc.id,
|
|
325
|
+
name=tc.function.name,
|
|
326
|
+
duration=tool_duration,
|
|
327
|
+
)
|
|
328
|
+
self._messages.append(tool_msg)
|
|
329
|
+
yield tool_msg
|
|
330
|
+
|
|
331
|
+
async def _stream_llm_response(self, usage: Usage | None) -> AsyncIterator[Message]:
|
|
332
|
+
self._llm_last_chunk = None
|
|
333
|
+
injected = await _safe_hook(self.hooks, "on_before_llm", self)
|
|
334
|
+
if injected is not None:
|
|
335
|
+
self._llm_last_chunk = injected
|
|
336
|
+
yield injected
|
|
337
|
+
replacement = await _safe_hook(self.hooks, "on_after_llm", self, injected)
|
|
338
|
+
if replacement is not None:
|
|
339
|
+
self._llm_last_chunk = replacement
|
|
340
|
+
return
|
|
341
|
+
try:
|
|
342
|
+
async with asyncio.timeout(self.llm_timeout):
|
|
343
|
+
async for chunk in stream_chat(
|
|
344
|
+
base_url=self._base_url,
|
|
345
|
+
api_key=self._api_key,
|
|
346
|
+
model=self.model,
|
|
347
|
+
messages=self._messages,
|
|
348
|
+
tools=self._all_tools() or None,
|
|
349
|
+
timeout=self.http_request_timeout,
|
|
350
|
+
llm_extra_body=self.llm_extra_body,
|
|
351
|
+
usage=usage,
|
|
352
|
+
cache=self._cache,
|
|
353
|
+
backend=self.backend,
|
|
354
|
+
):
|
|
355
|
+
if self._stop_event.is_set():
|
|
356
|
+
return
|
|
357
|
+
self._llm_last_chunk = chunk
|
|
358
|
+
if chunk.partial:
|
|
359
|
+
yield chunk
|
|
360
|
+
else:
|
|
361
|
+
yield chunk.model_copy()
|
|
362
|
+
replacement = await _safe_hook(self.hooks, "on_after_llm", self, chunk)
|
|
363
|
+
if replacement is not None:
|
|
364
|
+
self._llm_last_chunk = replacement
|
|
365
|
+
except asyncio.CancelledError:
|
|
366
|
+
if self._stop_event.is_set():
|
|
367
|
+
return
|
|
368
|
+
raise
|
coreloop/cli/__init__.py
ADDED
|
@@ -0,0 +1,269 @@
|
|
|
1
|
+
"""ma: minimal LLM agent CLI."""
|
|
2
|
+
|
|
3
|
+
import asyncio
|
|
4
|
+
import json
|
|
5
|
+
import os
|
|
6
|
+
from pathlib import Path
|
|
7
|
+
|
|
8
|
+
import httpx
|
|
9
|
+
import typer
|
|
10
|
+
|
|
11
|
+
from .. import __version__
|
|
12
|
+
from .._logging import setup_logging
|
|
13
|
+
from ..agent import Agent
|
|
14
|
+
from ..hooks import MaxTurnsHook
|
|
15
|
+
from ..profiles import _load_merged_profile, config_path, get_config, resolve_profile
|
|
16
|
+
from ._run import once, print_http_error, repl
|
|
17
|
+
from ._tools import _ALL_TOOL_NAMES, build_tools
|
|
18
|
+
|
|
19
|
+
app = typer.Typer(
|
|
20
|
+
name="ma",
|
|
21
|
+
invoke_without_command=True,
|
|
22
|
+
rich_markup_mode="rich",
|
|
23
|
+
no_args_is_help=False,
|
|
24
|
+
)
|
|
25
|
+
|
|
26
|
+
_P = "Provider"
|
|
27
|
+
_T = "Tools"
|
|
28
|
+
_A = "Advanced"
|
|
29
|
+
_O = "Output"
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def _version_callback(value: bool) -> None:
|
|
33
|
+
if value:
|
|
34
|
+
typer.echo(f"coreloop {__version__}")
|
|
35
|
+
raise typer.Exit()
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def _ensure_home_config() -> None:
|
|
39
|
+
dst = Path.home() / "coreloop.toml"
|
|
40
|
+
if dst.exists():
|
|
41
|
+
return
|
|
42
|
+
src = config_path()
|
|
43
|
+
if src == dst:
|
|
44
|
+
return
|
|
45
|
+
dst.parent.mkdir(parents=True, exist_ok=True)
|
|
46
|
+
header = (
|
|
47
|
+
f"# Originally installed by coreloop from {src}\n"
|
|
48
|
+
"# Edit this file to configure profiles and default tools.\n\n"
|
|
49
|
+
)
|
|
50
|
+
dst.write_text(header + src.read_text())
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
@app.callback(invoke_without_command=True)
|
|
54
|
+
def main(
|
|
55
|
+
ctx: typer.Context,
|
|
56
|
+
# -- run mode ------------------------------------------------------------------
|
|
57
|
+
prompt: str | None = typer.Option(
|
|
58
|
+
None, "--prompt", "-p", help="Run once and print result (non-interactive)"
|
|
59
|
+
),
|
|
60
|
+
max_turns: int | None = typer.Option(
|
|
61
|
+
None, "--max-turns", "-n", help="Maximum agent loop iterations"
|
|
62
|
+
),
|
|
63
|
+
system: str | None = typer.Option(None, "--system", "-s", help="System prompt"),
|
|
64
|
+
think: bool | None = typer.Option(
|
|
65
|
+
None, "--think/--no-think", help="Set reasoning_effort to medium / none"
|
|
66
|
+
),
|
|
67
|
+
llm_extra_body: str | None = typer.Option(
|
|
68
|
+
None, "--extra", "-e", help="Extra JSON merged into the API request body"
|
|
69
|
+
),
|
|
70
|
+
# -- provider ------------------------------------------------------------------
|
|
71
|
+
profile: str = typer.Option(
|
|
72
|
+
"default", "--profile", help="Named profile from ~/coreloop.toml", rich_help_panel=_P
|
|
73
|
+
),
|
|
74
|
+
model: str | None = typer.Option(
|
|
75
|
+
None,
|
|
76
|
+
"--model",
|
|
77
|
+
"-m",
|
|
78
|
+
help="Model name (overrides profile)",
|
|
79
|
+
envvar="CORELOOP_MODEL",
|
|
80
|
+
rich_help_panel=_P,
|
|
81
|
+
),
|
|
82
|
+
base_url: str | None = typer.Option(
|
|
83
|
+
None,
|
|
84
|
+
"--base-url",
|
|
85
|
+
help="API base URL (overrides profile)",
|
|
86
|
+
envvar="CORELOOP_BASE_URL",
|
|
87
|
+
rich_help_panel=_P,
|
|
88
|
+
),
|
|
89
|
+
api_key: str | None = typer.Option(
|
|
90
|
+
None,
|
|
91
|
+
"--api-key",
|
|
92
|
+
help="API key (overrides profile)",
|
|
93
|
+
envvar="CORELOOP_API_KEY",
|
|
94
|
+
rich_help_panel=_P,
|
|
95
|
+
),
|
|
96
|
+
# -- tools ---------------------------------------------------------------------
|
|
97
|
+
tools: str | None = typer.Option(
|
|
98
|
+
None,
|
|
99
|
+
"--tools",
|
|
100
|
+
metavar="TOOLS",
|
|
101
|
+
help=f"Comma-separated: {', '.join(sorted(_ALL_TOOL_NAMES))}",
|
|
102
|
+
rich_help_panel=_T,
|
|
103
|
+
),
|
|
104
|
+
root: str | None = typer.Option(
|
|
105
|
+
None, "--root", "-r", help="Allowed root for file tools (default: cwd)", rich_help_panel=_T
|
|
106
|
+
),
|
|
107
|
+
searxng_url: str | None = typer.Option(
|
|
108
|
+
None,
|
|
109
|
+
"--searxng-url",
|
|
110
|
+
help="SearXNG base URL for web_search/web_fetch",
|
|
111
|
+
envvar="SEARXNG_URL",
|
|
112
|
+
rich_help_panel=_T,
|
|
113
|
+
),
|
|
114
|
+
# -- advanced ------------------------------------------------------------------
|
|
115
|
+
llm_timeout: float | None = typer.Option(
|
|
116
|
+
None,
|
|
117
|
+
"--llm-timeout",
|
|
118
|
+
"-t",
|
|
119
|
+
help="Asyncio wall-clock timeout per LLM turn (seconds)",
|
|
120
|
+
rich_help_panel=_A,
|
|
121
|
+
),
|
|
122
|
+
tool_timeout: float | None = typer.Option(
|
|
123
|
+
None, "--tool-timeout", help="Hard timeout per tool call (seconds)", rich_help_panel=_A
|
|
124
|
+
),
|
|
125
|
+
http_request_timeout: float | None = typer.Option(
|
|
126
|
+
None,
|
|
127
|
+
"--http-request-timeout",
|
|
128
|
+
help="httpx per-chunk read timeout (seconds)",
|
|
129
|
+
rich_help_panel=_A,
|
|
130
|
+
),
|
|
131
|
+
cache_dir: str | None = typer.Option(
|
|
132
|
+
None, "--cache-dir", help="LLM response cache directory", rich_help_panel=_A
|
|
133
|
+
),
|
|
134
|
+
no_cache: bool = typer.Option(
|
|
135
|
+
False, "--no-cache", help="Disable LLM response caching", rich_help_panel=_A
|
|
136
|
+
),
|
|
137
|
+
# -- output --------------------------------------------------------------------
|
|
138
|
+
json_out: bool = typer.Option(
|
|
139
|
+
False, "--json", help="Output all non-partial messages as JSONL", rich_help_panel=_O
|
|
140
|
+
),
|
|
141
|
+
log_level: str | None = typer.Option(
|
|
142
|
+
None,
|
|
143
|
+
"--log-level",
|
|
144
|
+
"-l",
|
|
145
|
+
help="Logging level: DEBUG, INFO, WARNING, ERROR",
|
|
146
|
+
metavar="LEVEL",
|
|
147
|
+
rich_help_panel=_O,
|
|
148
|
+
),
|
|
149
|
+
_version: bool = typer.Option(
|
|
150
|
+
False,
|
|
151
|
+
"--version",
|
|
152
|
+
"-V",
|
|
153
|
+
callback=_version_callback,
|
|
154
|
+
is_eager=True,
|
|
155
|
+
help="Show version and exit",
|
|
156
|
+
rich_help_panel=_O,
|
|
157
|
+
),
|
|
158
|
+
) -> None:
|
|
159
|
+
"""A minimal LLM agent -- interactive REPL or one-shot with [bold]-p PROMPT[/bold].
|
|
160
|
+
|
|
161
|
+
On first run, [cyan]~/coreloop.toml[/cyan] is created from the bundled default.
|
|
162
|
+
Edit it to set your provider credentials and default tools.
|
|
163
|
+
|
|
164
|
+
[bold]Examples[/bold]
|
|
165
|
+
ma REPL with default profile (Ollama)
|
|
166
|
+
ma --profile openai -p "Hello" one-shot with a named profile
|
|
167
|
+
ma -m gpt-4o --tools read,ls,grep --root . override model and add file tools
|
|
168
|
+
ma --base-url http://localhost:11434/v1 -m qwen direct endpoint, no config needed
|
|
169
|
+
"""
|
|
170
|
+
if ctx.invoked_subcommand is not None:
|
|
171
|
+
return
|
|
172
|
+
|
|
173
|
+
if log_level is not None:
|
|
174
|
+
_valid_levels = {"DEBUG", "INFO", "WARNING", "ERROR", "CRITICAL"}
|
|
175
|
+
level_upper = log_level.upper()
|
|
176
|
+
if level_upper not in _valid_levels:
|
|
177
|
+
typer.echo(
|
|
178
|
+
f"Error: invalid log level {log_level!r}. "
|
|
179
|
+
f"Valid levels: {', '.join(sorted(_valid_levels))}",
|
|
180
|
+
err=True,
|
|
181
|
+
)
|
|
182
|
+
raise typer.Exit(1)
|
|
183
|
+
setup_logging(level_upper)
|
|
184
|
+
|
|
185
|
+
_ensure_home_config()
|
|
186
|
+
|
|
187
|
+
try:
|
|
188
|
+
agent_cfg = resolve_profile(profile)
|
|
189
|
+
raw = _load_merged_profile(profile)
|
|
190
|
+
except (FileNotFoundError, KeyError, ValueError) as exc:
|
|
191
|
+
typer.echo(f"Error: {exc}", err=True)
|
|
192
|
+
raise typer.Exit(1)
|
|
193
|
+
|
|
194
|
+
# CLI flags override profile values
|
|
195
|
+
if model is not None:
|
|
196
|
+
agent_cfg.model = model
|
|
197
|
+
if base_url is not None:
|
|
198
|
+
agent_cfg.base_url = base_url
|
|
199
|
+
if api_key is not None:
|
|
200
|
+
agent_cfg.api_key = api_key
|
|
201
|
+
if system is not None:
|
|
202
|
+
agent_cfg.system = system
|
|
203
|
+
if root is not None:
|
|
204
|
+
agent_cfg.root = root
|
|
205
|
+
if llm_timeout is not None:
|
|
206
|
+
agent_cfg.llm_timeout = llm_timeout
|
|
207
|
+
if tool_timeout is not None:
|
|
208
|
+
agent_cfg.tool_timeout = tool_timeout
|
|
209
|
+
if http_request_timeout is not None:
|
|
210
|
+
agent_cfg.http_request_timeout = http_request_timeout
|
|
211
|
+
if no_cache:
|
|
212
|
+
agent_cfg.cache_dir = None
|
|
213
|
+
elif cache_dir is not None:
|
|
214
|
+
agent_cfg.cache_dir = cache_dir
|
|
215
|
+
|
|
216
|
+
extra_body: dict | None = None
|
|
217
|
+
if llm_extra_body:
|
|
218
|
+
try:
|
|
219
|
+
extra_body = json.loads(llm_extra_body)
|
|
220
|
+
except json.JSONDecodeError as exc:
|
|
221
|
+
typer.echo(f"Error: --extra must be valid JSON: {exc}", err=True)
|
|
222
|
+
raise typer.Exit(1)
|
|
223
|
+
if think is not None:
|
|
224
|
+
extra_body = (extra_body or {}) | {"reasoning_effort": "medium" if think else "none"}
|
|
225
|
+
if extra_body is not None:
|
|
226
|
+
agent_cfg.llm_extra_body = extra_body
|
|
227
|
+
|
|
228
|
+
# Resolve tools: --tools flag overrides profile tools list
|
|
229
|
+
tools_opt = tools
|
|
230
|
+
if tools_opt is None and agent_cfg.tools:
|
|
231
|
+
tools_opt = ",".join(agent_cfg.tools)
|
|
232
|
+
if searxng_url is None:
|
|
233
|
+
searxng_url = get_config("tool.web_search.url", raw) or os.environ.get("SEARXNG_URL")
|
|
234
|
+
built_tools = build_tools(tools_opt, agent_cfg.root, searxng_url, raw)
|
|
235
|
+
|
|
236
|
+
if max_turns is None:
|
|
237
|
+
max_turns = int(get_config("ui.ma.max_turns", raw, 20))
|
|
238
|
+
|
|
239
|
+
try:
|
|
240
|
+
agent = Agent.from_config(agent_cfg, hooks=MaxTurnsHook(max_turns), tools=built_tools)
|
|
241
|
+
except (KeyError, ValueError) as exc:
|
|
242
|
+
typer.echo(f"Error: {exc}", err=True)
|
|
243
|
+
raise typer.Exit(1)
|
|
244
|
+
|
|
245
|
+
if prompt is not None:
|
|
246
|
+
try:
|
|
247
|
+
asyncio.run(once(agent, prompt, json_out=json_out))
|
|
248
|
+
except httpx.HTTPStatusError as exc:
|
|
249
|
+
print_http_error(exc)
|
|
250
|
+
raise typer.Exit(1)
|
|
251
|
+
except httpx.TimeoutException:
|
|
252
|
+
typer.echo(
|
|
253
|
+
f"Error: {agent_cfg.model} did not respond within {agent_cfg.llm_timeout}s"
|
|
254
|
+
" (increase with --llm-timeout)",
|
|
255
|
+
err=True,
|
|
256
|
+
)
|
|
257
|
+
raise typer.Exit(1)
|
|
258
|
+
except httpx.RequestError as exc:
|
|
259
|
+
typer.echo(f"Error: request failed: {exc}", err=True)
|
|
260
|
+
raise typer.Exit(1)
|
|
261
|
+
else:
|
|
262
|
+
try:
|
|
263
|
+
asyncio.run(repl(agent, agent_cfg, profile, tools_opt, searxng_url, max_turns, raw))
|
|
264
|
+
except httpx.HTTPStatusError as exc:
|
|
265
|
+
print_http_error(exc)
|
|
266
|
+
raise typer.Exit(1)
|
|
267
|
+
except httpx.RequestError as exc:
|
|
268
|
+
typer.echo(f"Error: request failed: {exc}", err=True)
|
|
269
|
+
raise typer.Exit(1)
|