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/cli/_run.py
ADDED
|
@@ -0,0 +1,145 @@
|
|
|
1
|
+
"""Execution modes: one-shot (-p PROMPT) and interactive REPL."""
|
|
2
|
+
|
|
3
|
+
import dataclasses
|
|
4
|
+
import os
|
|
5
|
+
from pathlib import Path
|
|
6
|
+
from typing import Any
|
|
7
|
+
|
|
8
|
+
import httpx
|
|
9
|
+
import typer
|
|
10
|
+
from rich.console import Console
|
|
11
|
+
|
|
12
|
+
from ..agent import Agent
|
|
13
|
+
from ..config import AgentConfig
|
|
14
|
+
from ..hooks import MaxTurnsHook
|
|
15
|
+
from ..types import Message
|
|
16
|
+
from ._tools import build_tools
|
|
17
|
+
|
|
18
|
+
_console = Console()
|
|
19
|
+
_TOOL_RESULT_PREVIEW = 300
|
|
20
|
+
_HTTP_ERROR_BODY_PREVIEW = 500
|
|
21
|
+
|
|
22
|
+
_HTTP_HINTS: dict[int, str] = {
|
|
23
|
+
401: "Authentication failed. Check your API key.",
|
|
24
|
+
403: "Access denied. Your API key may lack permissions for this resource.",
|
|
25
|
+
404: "Endpoint not found. Check the base URL and model name.",
|
|
26
|
+
429: "Rate limited. Wait before retrying, or reduce request frequency.",
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def print_http_error(exc: httpx.HTTPStatusError) -> None:
|
|
31
|
+
status = exc.response.status_code
|
|
32
|
+
typer.echo(f"Error: HTTP {status} from {exc.request.url}", err=True)
|
|
33
|
+
body = exc.response.text[:_HTTP_ERROR_BODY_PREVIEW].strip()
|
|
34
|
+
if body:
|
|
35
|
+
typer.echo(f" {body}", err=True)
|
|
36
|
+
hint = _HTTP_HINTS.get(status) or (
|
|
37
|
+
"Server error. The provider may be temporarily unavailable." if status >= 500 else None
|
|
38
|
+
)
|
|
39
|
+
if hint:
|
|
40
|
+
typer.echo(f" Hint: {hint}", err=True)
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
async def once(agent: Agent, prompt: str, *, json_out: bool = False) -> None:
|
|
44
|
+
"""Run the agent once and print the final response."""
|
|
45
|
+
messages = [Message(role="user", content=prompt)]
|
|
46
|
+
if json_out:
|
|
47
|
+
typer.echo(messages[0].model_dump_json(exclude_none=True))
|
|
48
|
+
async for msg in agent.run(messages):
|
|
49
|
+
if not msg.partial:
|
|
50
|
+
typer.echo(msg.model_dump_json(exclude_none=True))
|
|
51
|
+
else:
|
|
52
|
+
final: str | None = None
|
|
53
|
+
async for msg in agent.run(messages):
|
|
54
|
+
if msg.role == "assistant" and not msg.partial and msg.content:
|
|
55
|
+
final = msg.content
|
|
56
|
+
if final is not None:
|
|
57
|
+
typer.echo(final)
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
async def repl(
|
|
61
|
+
agent: Agent,
|
|
62
|
+
agent_cfg: AgentConfig,
|
|
63
|
+
profile: str,
|
|
64
|
+
tools_opt: str | None,
|
|
65
|
+
searxng_url: str | None,
|
|
66
|
+
max_turns: int,
|
|
67
|
+
raw_profile: dict[str, Any] | None = None,
|
|
68
|
+
) -> None:
|
|
69
|
+
"""Run the interactive REPL until the user quits."""
|
|
70
|
+
cwd_display = Path(agent_cfg.root or os.getcwd()).resolve()
|
|
71
|
+
header = f"ma profile={profile} model={agent_cfg.model}"
|
|
72
|
+
if tools_opt:
|
|
73
|
+
header += f" tools={tools_opt} root={cwd_display}"
|
|
74
|
+
_console.print(header, style="cyan")
|
|
75
|
+
cmds = "/quit /new /model <name>"
|
|
76
|
+
if tools_opt:
|
|
77
|
+
cmds += " /root <path>"
|
|
78
|
+
_console.print(f"Commands: {cmds}\n", style="bright_black")
|
|
79
|
+
|
|
80
|
+
current_agent = agent
|
|
81
|
+
|
|
82
|
+
while True:
|
|
83
|
+
try:
|
|
84
|
+
user_input = typer.prompt("You")
|
|
85
|
+
except EOFError, KeyboardInterrupt:
|
|
86
|
+
break
|
|
87
|
+
|
|
88
|
+
cmd = user_input.strip().lower()
|
|
89
|
+
if cmd in ("/quit", "/exit", "/q"):
|
|
90
|
+
break
|
|
91
|
+
if cmd == "/new":
|
|
92
|
+
current_agent.reset()
|
|
93
|
+
_console.print("Started new conversation.", style="green")
|
|
94
|
+
continue
|
|
95
|
+
if cmd.startswith("/model "):
|
|
96
|
+
new_model = user_input[7:].strip()
|
|
97
|
+
if new_model:
|
|
98
|
+
current_agent.model = new_model
|
|
99
|
+
_console.print(f"Model changed to {new_model}", style="green")
|
|
100
|
+
continue
|
|
101
|
+
if tools_opt and cmd.startswith("/root "):
|
|
102
|
+
new_root = user_input[6:].strip()
|
|
103
|
+
if new_root:
|
|
104
|
+
new_cfg = dataclasses.replace(agent_cfg, root=new_root)
|
|
105
|
+
current_agent = Agent.from_config(
|
|
106
|
+
new_cfg,
|
|
107
|
+
hooks=MaxTurnsHook(max_turns),
|
|
108
|
+
tools=build_tools(tools_opt, new_root, searxng_url, raw_profile),
|
|
109
|
+
)
|
|
110
|
+
_console.print(f"Root changed to {Path(new_root).resolve()}", style="green")
|
|
111
|
+
continue
|
|
112
|
+
if not user_input.strip():
|
|
113
|
+
continue
|
|
114
|
+
|
|
115
|
+
messages = list(current_agent.messages) + [Message(role="user", content=user_input)]
|
|
116
|
+
typer.echo()
|
|
117
|
+
|
|
118
|
+
try:
|
|
119
|
+
async for msg in current_agent.run(messages):
|
|
120
|
+
if msg.role == "assistant":
|
|
121
|
+
if msg.tool_calls:
|
|
122
|
+
for tc in msg.tool_calls:
|
|
123
|
+
_console.print(
|
|
124
|
+
f" tool: {tc.function.name}({tc.function.arguments})",
|
|
125
|
+
style="yellow",
|
|
126
|
+
)
|
|
127
|
+
elif msg.content and not msg.partial:
|
|
128
|
+
_console.print(f" {msg.content}")
|
|
129
|
+
elif msg.role == "tool":
|
|
130
|
+
display = (msg.content or "")[:_TOOL_RESULT_PREVIEW]
|
|
131
|
+
_console.print(f" [{msg.name}] {display}", style="bright_black")
|
|
132
|
+
except httpx.HTTPStatusError as exc:
|
|
133
|
+
print_http_error(exc)
|
|
134
|
+
current_agent.reset()
|
|
135
|
+
except httpx.TimeoutException:
|
|
136
|
+
_console.print(
|
|
137
|
+
f"Error: {agent_cfg.model} did not respond within {agent_cfg.llm_timeout}s"
|
|
138
|
+
" (increase with --llm-timeout)",
|
|
139
|
+
style="red",
|
|
140
|
+
)
|
|
141
|
+
current_agent.reset()
|
|
142
|
+
except httpx.RequestError as exc:
|
|
143
|
+
_console.print(f"Error: request failed: {exc}", style="red")
|
|
144
|
+
current_agent.reset()
|
|
145
|
+
typer.echo()
|
coreloop/cli/_tools.py
ADDED
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
"""Tool construction from CLI tool names and profile config."""
|
|
2
|
+
|
|
3
|
+
from pathlib import Path
|
|
4
|
+
from typing import Any
|
|
5
|
+
|
|
6
|
+
import typer
|
|
7
|
+
|
|
8
|
+
from ..profiles import get_config
|
|
9
|
+
from ..tool_registry import ToolInfo
|
|
10
|
+
from ..tools import make_tools
|
|
11
|
+
|
|
12
|
+
_FILE_TOOL_NAMES = frozenset({"read", "ls", "edit", "grep"})
|
|
13
|
+
_WEB_TOOL_NAMES = frozenset({"web_search", "web_fetch"})
|
|
14
|
+
_BUILTIN_TOOL_NAMES = _FILE_TOOL_NAMES | {"bash"}
|
|
15
|
+
_ALL_TOOL_NAMES = _BUILTIN_TOOL_NAMES | _WEB_TOOL_NAMES
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def build_tools(
|
|
19
|
+
tools_opt: str | None,
|
|
20
|
+
root: str | None,
|
|
21
|
+
searxng_url: str | None = None,
|
|
22
|
+
profile: dict[str, Any] | None = None,
|
|
23
|
+
) -> list[ToolInfo] | None:
|
|
24
|
+
"""Build pre-scoped ToolInfo objects for the given comma-separated tool names.
|
|
25
|
+
|
|
26
|
+
Returns None if *tools_opt* is empty (lets the Agent fall back to its own defaults).
|
|
27
|
+
Exits with an error message on unknown tool names.
|
|
28
|
+
"""
|
|
29
|
+
if not tools_opt:
|
|
30
|
+
return None
|
|
31
|
+
names = {n.strip().lower() for n in tools_opt.split(",") if n.strip()}
|
|
32
|
+
unknown = names - _ALL_TOOL_NAMES
|
|
33
|
+
if unknown:
|
|
34
|
+
typer.echo(
|
|
35
|
+
f"Unknown tools: {', '.join(sorted(unknown))}. "
|
|
36
|
+
f"Available: {', '.join(sorted(_ALL_TOOL_NAMES))}",
|
|
37
|
+
err=True,
|
|
38
|
+
)
|
|
39
|
+
raise typer.Exit(1)
|
|
40
|
+
|
|
41
|
+
result: list[ToolInfo] = []
|
|
42
|
+
|
|
43
|
+
if names & _FILE_TOOL_NAMES:
|
|
44
|
+
fs_tools = make_tools(
|
|
45
|
+
allowed_root=root,
|
|
46
|
+
read_max_lines=get_config("tool.read.max_lines", profile, 100),
|
|
47
|
+
read_max_bytes=get_config("tool.read.max_bytes", profile, 10 * 1024 * 1024),
|
|
48
|
+
ls_max_entries=get_config("tool.ls.max_entries", profile, 500),
|
|
49
|
+
edit_max_bytes=get_config("tool.edit.max_bytes", profile, 10 * 1024 * 1024),
|
|
50
|
+
search_max_chars=get_config("tool.grep.max_chars", profile, 20_000),
|
|
51
|
+
search_timeout=get_config("tool.grep.timeout", profile, 30.0),
|
|
52
|
+
)
|
|
53
|
+
result.extend(t for t in fs_tools if t.name in names)
|
|
54
|
+
|
|
55
|
+
if "bash" in names:
|
|
56
|
+
from ..tools.bash import make_bash_tool
|
|
57
|
+
|
|
58
|
+
result.append(
|
|
59
|
+
make_bash_tool(
|
|
60
|
+
str(Path(root).resolve()) if root else ".",
|
|
61
|
+
max_chars=get_config("tool.bash.max_chars", profile, 10_000),
|
|
62
|
+
max_raw_bytes=get_config("tool.bash.max_raw_bytes", profile, 100 * 1024),
|
|
63
|
+
default_timeout=get_config("tool.bash.default_timeout", profile, 180),
|
|
64
|
+
max_timeout=get_config("tool.bash.max_timeout", profile, 300),
|
|
65
|
+
)
|
|
66
|
+
)
|
|
67
|
+
|
|
68
|
+
if names & _WEB_TOOL_NAMES:
|
|
69
|
+
try:
|
|
70
|
+
from ..web_tools import make_web_tools
|
|
71
|
+
|
|
72
|
+
web_tools = make_web_tools(searxng_url=searxng_url)
|
|
73
|
+
except ImportError:
|
|
74
|
+
typer.echo(
|
|
75
|
+
"To use web_search or web_fetch, install web extras: "
|
|
76
|
+
"pip install coreloop[web]",
|
|
77
|
+
err=True,
|
|
78
|
+
)
|
|
79
|
+
raise typer.Exit(1)
|
|
80
|
+
result.extend(t for t in web_tools if t.name in names)
|
|
81
|
+
|
|
82
|
+
return result
|
coreloop/config.py
ADDED
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
"""AgentConfig -- a portable, serialisable bundle of Agent constructor parameters.
|
|
2
|
+
|
|
3
|
+
Use with Agent.from_config(), or use dataclasses.replace() to derive variants:
|
|
4
|
+
|
|
5
|
+
from dataclasses import replace
|
|
6
|
+
from coreloop import AgentConfig
|
|
7
|
+
|
|
8
|
+
base = AgentConfig(model="qwen3:8b")
|
|
9
|
+
fast = replace(base, model="qwen3:0.6b", timeout=10.0)
|
|
10
|
+
agent = Agent.from_config(fast)
|
|
11
|
+
|
|
12
|
+
Hooks are intentionally excluded -- they are stateful runtime objects, not config.
|
|
13
|
+
"""
|
|
14
|
+
|
|
15
|
+
from dataclasses import dataclass, field
|
|
16
|
+
from pathlib import Path
|
|
17
|
+
from typing import Any
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
@dataclass
|
|
21
|
+
class AgentConfig:
|
|
22
|
+
"""Portable, serialisable bundle of Agent constructor parameters."""
|
|
23
|
+
model: str
|
|
24
|
+
base_url: str = "http://localhost:11434/v1"
|
|
25
|
+
api_key: str | None = None
|
|
26
|
+
system: str | None = None
|
|
27
|
+
tools: list[str] = field(default_factory=list)
|
|
28
|
+
root: str | None = None
|
|
29
|
+
http_request_timeout: float = 300.0
|
|
30
|
+
tool_timeout: float = 360.0
|
|
31
|
+
llm_timeout: float = 300.0
|
|
32
|
+
llm_extra_body: dict[str, Any] | None = None
|
|
33
|
+
cache_dir: str | None = str(Path.home() / ".cache" / "coreloop-llm-cache")
|
coreloop/coreloop.toml
ADDED
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
# coreloop configuration
|
|
2
|
+
#
|
|
3
|
+
# Profiles are named agent configurations. Every profile inherits from
|
|
4
|
+
# [profiles.default] — keys in a named profile override the default.
|
|
5
|
+
#
|
|
6
|
+
# String values can reference environment variables with {{VAR_NAME}}.
|
|
7
|
+
# Example: api_key = "{{OPENAI_API_KEY}}"
|
|
8
|
+
#
|
|
9
|
+
# Profile keys (all optional except model):
|
|
10
|
+
#
|
|
11
|
+
# model = "qwen3.5:9b"
|
|
12
|
+
# base_url = "http://localhost:11434/v1"
|
|
13
|
+
# api_key = "{{MY_API_KEY}}"
|
|
14
|
+
# system = "You are a helpful assistant."
|
|
15
|
+
# tools = ["read", "ls", "grep"]
|
|
16
|
+
# llm_extra_body = {reasoning_effort = "medium"}
|
|
17
|
+
# http_request_timeout = 120.0
|
|
18
|
+
# tool_timeout = 60.0
|
|
19
|
+
# llm_timeout = 300.0
|
|
20
|
+
# cache_dir = "~/.cache/coreloop-llm-cache"
|
|
21
|
+
|
|
22
|
+
[profiles.default]
|
|
23
|
+
base_url = "http://localhost:11434/v1"
|
|
24
|
+
model = "qwen3.5:9b"
|
|
25
|
+
|
|
26
|
+
[profiles.openai]
|
|
27
|
+
base_url = "https://api.openai.com/v1"
|
|
28
|
+
api_key = "{{OPENAI_API_KEY}}"
|
|
29
|
+
model = "gpt-4o-mini"
|
|
30
|
+
|
|
31
|
+
[profiles.together]
|
|
32
|
+
base_url = "https://api.together.xyz/v1"
|
|
33
|
+
api_key = "{{TOGETHER_API_KEY}}"
|
|
34
|
+
|
|
35
|
+
[profiles.groq]
|
|
36
|
+
base_url = "https://api.groq.com/openai/v1"
|
|
37
|
+
api_key = "{{GROQ_API_KEY}}"
|
|
38
|
+
|
|
39
|
+
[profiles.openrouter]
|
|
40
|
+
base_url = "https://openrouter.ai/api/v1"
|
|
41
|
+
api_key = "{{OPENROUTER_API_KEY}}"
|
|
42
|
+
|
|
43
|
+
[profiles.deepseek]
|
|
44
|
+
base_url = "https://api.deepseek.com/v1"
|
|
45
|
+
api_key = "{{DEEPSEEK_API_KEY}}"
|
|
46
|
+
|
|
47
|
+
# Add your own profiles below. Any OpenAI-compatible endpoint works:
|
|
48
|
+
#
|
|
49
|
+
# [profiles.lmstudio]
|
|
50
|
+
# base_url = "http://localhost:1234/v1"
|
|
51
|
+
#
|
|
52
|
+
# [profiles.vllm]
|
|
53
|
+
# base_url = "http://localhost:8000/v1"
|
|
54
|
+
#
|
|
55
|
+
# Profile-level config overrides (deep-merged with [config] below):
|
|
56
|
+
#
|
|
57
|
+
# [profiles.work.config.tool.web_search]
|
|
58
|
+
# url = "http://searxng.internal:8888"
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
# ── App / tool / UI settings ─────────────────────────────────────────────────
|
|
62
|
+
#
|
|
63
|
+
# Accessed via get_config("tool.read.max_lines", raw_profile).
|
|
64
|
+
# Profiles can override any key under [profiles.<name>.config.*].
|
|
65
|
+
|
|
66
|
+
[config.tool.read]
|
|
67
|
+
max_lines = 100
|
|
68
|
+
max_bytes = 10485760 # 10 MB
|
|
69
|
+
|
|
70
|
+
[config.tool.ls]
|
|
71
|
+
max_entries = 500
|
|
72
|
+
|
|
73
|
+
[config.tool.edit]
|
|
74
|
+
max_bytes = 10485760 # 10 MB
|
|
75
|
+
|
|
76
|
+
[config.tool.grep]
|
|
77
|
+
max_chars = 20000
|
|
78
|
+
timeout = 30.0
|
|
79
|
+
|
|
80
|
+
[config.tool.bash]
|
|
81
|
+
max_chars = 10000
|
|
82
|
+
max_raw_bytes = 102400 # 100 KB
|
|
83
|
+
default_timeout = 180
|
|
84
|
+
max_timeout = 300
|
|
85
|
+
# dangerous_patterns replaces the built-in block list entirely when set.
|
|
86
|
+
# Default patterns are in tools/bash.py:DEFAULT_DANGEROUS_PATTERNS.
|
|
87
|
+
# dangerous_patterns = [
|
|
88
|
+
# "\\brm\\s+-rf\\s+/\\b",
|
|
89
|
+
# "\\bdd\\s+if=",
|
|
90
|
+
# ":\\(\\)\\s*\\{",
|
|
91
|
+
# "\\bmkfs\\.",
|
|
92
|
+
# "\\bmkswap\\b",
|
|
93
|
+
# ]
|
|
94
|
+
# or, use an on_before_tool hook for more control
|
|
95
|
+
|
|
96
|
+
# [config.tool.web_search]
|
|
97
|
+
# url = "http://localhost:8888"
|
|
98
|
+
|
|
99
|
+
[config.ui.ma]
|
|
100
|
+
max_turns = 20
|
|
101
|
+
tool_result_preview = 300
|
coreloop/hooks.py
ADDED
|
@@ -0,0 +1,132 @@
|
|
|
1
|
+
"""AgentHooks -- lifecycle callbacks for the agent loop.
|
|
2
|
+
|
|
3
|
+
Hooks fire in this order during a single agent.run() call:
|
|
4
|
+
|
|
5
|
+
on_before_agent(agent)
|
|
6
|
+
|
|
7
|
+
for each turn:
|
|
8
|
+
on_before_turn(agent) # brackets the full LLM + tool cycle
|
|
9
|
+
|
|
10
|
+
on_before_llm(agent) -> Message | None
|
|
11
|
+
# Return a Message to inject as the response (LLM call is skipped).
|
|
12
|
+
# Return None to call the LLM normally.
|
|
13
|
+
<LLM streams response>
|
|
14
|
+
on_after_llm(agent, message) -> Message | None
|
|
15
|
+
# Return a Message to replace what gets appended to conversation
|
|
16
|
+
# history. Return None to use the message as-is.
|
|
17
|
+
# Note: the streamed content has already been yielded to the
|
|
18
|
+
# caller -- the replacement only affects conversation history.
|
|
19
|
+
|
|
20
|
+
if the LLM requested tool calls:
|
|
21
|
+
for each tool (in parallel):
|
|
22
|
+
on_before_tool(agent, name, args) -> str | None
|
|
23
|
+
# Return a str to inject as the result (tool is skipped).
|
|
24
|
+
# Return None to execute the tool normally.
|
|
25
|
+
<tool executes>
|
|
26
|
+
on_after_tool(agent, name, args, result) -> str | None
|
|
27
|
+
# Return a str to replace the result in conversation history.
|
|
28
|
+
# Return None to use the result as-is.
|
|
29
|
+
|
|
30
|
+
on_after_turn(agent) # fires every turn, with or without tools
|
|
31
|
+
|
|
32
|
+
on_after_agent(agent)
|
|
33
|
+
# NOT called after agent.abort() -- only after natural end or stop().
|
|
34
|
+
|
|
35
|
+
All hooks are called via _safe_hook, which catches and logs any exception
|
|
36
|
+
rather than propagating it. Hook bugs cannot crash the agent. To request
|
|
37
|
+
a clean exit from inside a hook, call agent.stop().
|
|
38
|
+
"""
|
|
39
|
+
|
|
40
|
+
import logging
|
|
41
|
+
from typing import TYPE_CHECKING, Any
|
|
42
|
+
|
|
43
|
+
if TYPE_CHECKING:
|
|
44
|
+
from .agent import Agent
|
|
45
|
+
from .types import Message
|
|
46
|
+
|
|
47
|
+
logger = logging.getLogger(__name__)
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
class AgentHooks:
|
|
51
|
+
"""Base class for agent lifecycle callbacks. All methods are no-ops by default."""
|
|
52
|
+
|
|
53
|
+
async def on_before_agent(self, agent: Agent) -> None:
|
|
54
|
+
"""Called once at the start of agent.run(), before any LLM call."""
|
|
55
|
+
|
|
56
|
+
async def on_after_agent(self, agent: Agent) -> None:
|
|
57
|
+
"""Called when the agent finishes cleanly (natural end or stop()).
|
|
58
|
+
Not called after agent.abort()."""
|
|
59
|
+
|
|
60
|
+
async def on_before_llm(self, agent: Agent) -> Message | None:
|
|
61
|
+
"""Called before each LLM API call.
|
|
62
|
+
|
|
63
|
+
Return a Message to inject as the response (LLM call is skipped).
|
|
64
|
+
Return None to proceed normally.
|
|
65
|
+
"""
|
|
66
|
+
return None
|
|
67
|
+
|
|
68
|
+
async def on_after_llm(self, agent: Agent, message: Message) -> Message | None:
|
|
69
|
+
"""Called after each LLM API call with the assembled response message.
|
|
70
|
+
|
|
71
|
+
Return a Message to replace the message before it is appended to
|
|
72
|
+
conversation history. Return None to use the message as-is.
|
|
73
|
+
"""
|
|
74
|
+
return None
|
|
75
|
+
|
|
76
|
+
async def on_before_tool(self, agent: Agent, name: str, args: dict[str, Any]) -> str | None:
|
|
77
|
+
"""Called before a tool executes.
|
|
78
|
+
|
|
79
|
+
Return a str to inject as the tool result (real tool is skipped).
|
|
80
|
+
Return None to proceed normally.
|
|
81
|
+
"""
|
|
82
|
+
return None
|
|
83
|
+
|
|
84
|
+
async def on_after_tool(
|
|
85
|
+
self, agent: Agent, name: str, args: dict[str, Any], result: str
|
|
86
|
+
) -> str | None:
|
|
87
|
+
"""Called after a tool executes with its result.
|
|
88
|
+
|
|
89
|
+
Return a str to replace the result that gets appended to conversation
|
|
90
|
+
history. Return None to use the result as-is.
|
|
91
|
+
"""
|
|
92
|
+
return None
|
|
93
|
+
|
|
94
|
+
async def on_before_turn(self, agent: Agent) -> None:
|
|
95
|
+
"""Called at the start of each turn, before the LLM call."""
|
|
96
|
+
|
|
97
|
+
async def on_after_turn(self, agent: Agent) -> None:
|
|
98
|
+
"""Called at the end of each turn, after tools (if any). Fires every turn."""
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
class MaxTurnsHook(AgentHooks):
|
|
102
|
+
"""Stop the agent after *n* turns within a single ``run()``.
|
|
103
|
+
|
|
104
|
+
A "turn" is one LLM call plus any tool calls it triggered. The counter
|
|
105
|
+
resets at the start of every ``run()`` (in ``on_before_agent``), so the
|
|
106
|
+
limit is per-run: reusing one hook instance across multiple runs gives
|
|
107
|
+
each run its own fresh budget rather than draining a shared one.
|
|
108
|
+
|
|
109
|
+
This is the implementation behind the CLI's ``--max-turns`` flag.
|
|
110
|
+
"""
|
|
111
|
+
|
|
112
|
+
def __init__(self, n: int) -> None:
|
|
113
|
+
self._n = n
|
|
114
|
+
self._turns = 0
|
|
115
|
+
|
|
116
|
+
async def on_before_agent(self, agent: Agent) -> None:
|
|
117
|
+
"""Reset the turn counter at the start of each run."""
|
|
118
|
+
self._turns = 0
|
|
119
|
+
|
|
120
|
+
async def on_after_turn(self, agent: Agent) -> None:
|
|
121
|
+
"""Increment the counter and stop the agent when the budget is exhausted."""
|
|
122
|
+
self._turns += 1
|
|
123
|
+
if self._turns >= self._n:
|
|
124
|
+
agent.stop()
|
|
125
|
+
|
|
126
|
+
|
|
127
|
+
async def _safe_hook(hooks: AgentHooks, method: str, *args: Any) -> Any:
|
|
128
|
+
"""Call a hook method, logging and swallowing any exceptions."""
|
|
129
|
+
try:
|
|
130
|
+
return await getattr(hooks, method)(*args)
|
|
131
|
+
except Exception as exc:
|
|
132
|
+
logger.warning("Hook %s raised %s: %s", method, type(exc).__name__, exc)
|
coreloop/profiles.py
ADDED
|
@@ -0,0 +1,176 @@
|
|
|
1
|
+
"""Configuration loaded from coreloop.toml: named profiles with default merging.
|
|
2
|
+
|
|
3
|
+
Profile resolution:
|
|
4
|
+
1. Load [profiles.default] as the base.
|
|
5
|
+
2. Merge [profiles.<name>] on top (named keys win).
|
|
6
|
+
3. Deep-merge [config] global settings with any [profiles.<name>.config] overrides.
|
|
7
|
+
4. Resolve {{VAR_NAME}} in any string value from the environment.
|
|
8
|
+
5. Strip non-AgentConfig keys and return AgentConfig.
|
|
9
|
+
|
|
10
|
+
The special name "default" is the base -- every other profile inherits from it.
|
|
11
|
+
[config] is the global settings tree; profiles can override any sub-key.
|
|
12
|
+
"""
|
|
13
|
+
|
|
14
|
+
import functools
|
|
15
|
+
import os
|
|
16
|
+
import re
|
|
17
|
+
import tomllib
|
|
18
|
+
from pathlib import Path
|
|
19
|
+
from typing import TYPE_CHECKING, Any
|
|
20
|
+
|
|
21
|
+
if TYPE_CHECKING:
|
|
22
|
+
from .config import AgentConfig
|
|
23
|
+
|
|
24
|
+
from dotenv import load_dotenv
|
|
25
|
+
|
|
26
|
+
_CONFIG_FILENAME = "coreloop.toml"
|
|
27
|
+
_TEMPLATE_RE = re.compile(r"\{\{(\w+)\}\}")
|
|
28
|
+
|
|
29
|
+
load_dotenv()
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def config_path() -> Path:
|
|
33
|
+
"""Return the path of the config file currently being used."""
|
|
34
|
+
return _CONFIG_PATH
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def _find_config_path() -> Path:
|
|
38
|
+
if env := os.environ.get("CORELOOP_CONFIG"):
|
|
39
|
+
return Path(env)
|
|
40
|
+
home_config = Path.home() / _CONFIG_FILENAME
|
|
41
|
+
if home_config.exists():
|
|
42
|
+
return home_config
|
|
43
|
+
pkg_local = Path(__file__).resolve().parent / _CONFIG_FILENAME
|
|
44
|
+
if pkg_local.exists():
|
|
45
|
+
return pkg_local
|
|
46
|
+
repo_root = Path(__file__).resolve().parent.parent.parent
|
|
47
|
+
repo_new = repo_root / _CONFIG_FILENAME
|
|
48
|
+
if repo_new.exists():
|
|
49
|
+
return repo_new
|
|
50
|
+
return repo_new
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
_CONFIG_PATH = _find_config_path()
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
@functools.lru_cache(maxsize=8)
|
|
57
|
+
def _load_config(path: Path | None = None) -> dict[str, Any]:
|
|
58
|
+
p = path or _CONFIG_PATH
|
|
59
|
+
if not p.exists():
|
|
60
|
+
msg = (
|
|
61
|
+
f"Config file not found at {p}. "
|
|
62
|
+
f"Create ~/{_CONFIG_FILENAME} or set CORELOOP_CONFIG."
|
|
63
|
+
)
|
|
64
|
+
raise FileNotFoundError(msg)
|
|
65
|
+
return tomllib.loads(p.read_bytes().decode("utf-8"))
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
def _deep_merge(base: dict[str, Any], override: dict[str, Any]) -> dict[str, Any]:
|
|
69
|
+
"""Return base with override applied recursively. Dicts merge; all other types replace."""
|
|
70
|
+
result = dict(base)
|
|
71
|
+
for k, v in override.items():
|
|
72
|
+
result[k] = (
|
|
73
|
+
_deep_merge(result[k], v)
|
|
74
|
+
if isinstance(v, dict) and isinstance(result.get(k), dict)
|
|
75
|
+
else v
|
|
76
|
+
)
|
|
77
|
+
return result
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
def _interpolate(value: Any) -> Any:
|
|
81
|
+
"""Resolve {{VAR_NAME}} in string values from the environment."""
|
|
82
|
+
if not isinstance(value, str):
|
|
83
|
+
return value
|
|
84
|
+
|
|
85
|
+
def _sub(m: re.Match) -> str:
|
|
86
|
+
var = m.group(1)
|
|
87
|
+
val = os.environ.get(var)
|
|
88
|
+
if val is None:
|
|
89
|
+
msg = f"Environment variable {var!r} referenced in config is not set"
|
|
90
|
+
raise ValueError(msg)
|
|
91
|
+
return val
|
|
92
|
+
|
|
93
|
+
return _TEMPLATE_RE.sub(_sub, value)
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
def _interpolate_strings(data: dict[str, Any]) -> dict[str, Any]:
|
|
97
|
+
return {k: _interpolate(v) for k, v in data.items()}
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
def _load_merged_profile(name: str, config_path: Path | str | None = None) -> dict[str, Any]:
|
|
101
|
+
"""Return the raw merged profile dict (default base + named overlay + config tree).
|
|
102
|
+
|
|
103
|
+
Top-level profile keys are shallow-merged (named profile wins over default).
|
|
104
|
+
The [config] tree is deep-merged: global < default profile < named profile.
|
|
105
|
+
Includes all keys -- callers that only need AgentConfig should use resolve_profile().
|
|
106
|
+
"""
|
|
107
|
+
raw = _load_config(Path(config_path) if config_path else None)
|
|
108
|
+
profiles = raw.get("profiles", {})
|
|
109
|
+
global_cfg = raw.get("config", {})
|
|
110
|
+
|
|
111
|
+
base = dict(profiles.get("default", {}))
|
|
112
|
+
base_cfg = base.pop("config", {})
|
|
113
|
+
|
|
114
|
+
if name != "default":
|
|
115
|
+
if name not in profiles:
|
|
116
|
+
known = ", ".join(sorted(k for k in profiles if k != "default"))
|
|
117
|
+
msg = f"Unknown profile {name!r}. Known: {known or '(none)'}"
|
|
118
|
+
raise KeyError(msg)
|
|
119
|
+
overlay = dict(profiles[name])
|
|
120
|
+
overlay_cfg = overlay.pop("config", {})
|
|
121
|
+
merged = {**base, **overlay}
|
|
122
|
+
profile_cfg = _deep_merge(base_cfg, overlay_cfg)
|
|
123
|
+
else:
|
|
124
|
+
merged = base
|
|
125
|
+
profile_cfg = base_cfg
|
|
126
|
+
|
|
127
|
+
merged["config"] = _deep_merge(global_cfg, profile_cfg)
|
|
128
|
+
return merged
|
|
129
|
+
|
|
130
|
+
|
|
131
|
+
def get_config(
|
|
132
|
+
key: str,
|
|
133
|
+
raw_profile: dict[str, Any] | None = None,
|
|
134
|
+
default: Any = None,
|
|
135
|
+
*,
|
|
136
|
+
config_path: Path | str | None = None,
|
|
137
|
+
) -> Any:
|
|
138
|
+
"""Look up a dot-path key in the [config] tree.
|
|
139
|
+
|
|
140
|
+
get_config("tool.web_search.url", raw) -- uses merged profile config
|
|
141
|
+
get_config("tool.web_search.url") -- uses global [config] only
|
|
142
|
+
|
|
143
|
+
{{VAR_NAME}} interpolation is applied to string values.
|
|
144
|
+
Returns default if the key is absent or the path is invalid.
|
|
145
|
+
"""
|
|
146
|
+
if raw_profile is not None:
|
|
147
|
+
node: Any = raw_profile.get("config", {})
|
|
148
|
+
else:
|
|
149
|
+
node = _load_config(Path(config_path) if config_path else None).get("config", {})
|
|
150
|
+
|
|
151
|
+
for part in key.split("."):
|
|
152
|
+
if not isinstance(node, dict):
|
|
153
|
+
return default
|
|
154
|
+
node = node.get(part)
|
|
155
|
+
if node is None:
|
|
156
|
+
return default
|
|
157
|
+
|
|
158
|
+
return _interpolate(node) if isinstance(node, str) else node
|
|
159
|
+
|
|
160
|
+
|
|
161
|
+
def resolve_profile(
|
|
162
|
+
name: str = "default", *, config_path: Path | str | None = None
|
|
163
|
+
) -> "AgentConfig":
|
|
164
|
+
"""Return an AgentConfig for the named profile.
|
|
165
|
+
|
|
166
|
+
Merges [profiles.default] as base, then [profiles.<name>] on top.
|
|
167
|
+
{{VAR_NAME}} in any string value is resolved from the environment.
|
|
168
|
+
Unknown keys (config, max_turns, searxng_url, ...) are silently ignored.
|
|
169
|
+
"""
|
|
170
|
+
import dataclasses
|
|
171
|
+
|
|
172
|
+
from .config import AgentConfig
|
|
173
|
+
|
|
174
|
+
raw = _interpolate_strings(_load_merged_profile(name, config_path=config_path))
|
|
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})
|
coreloop/py.typed
ADDED
|
File without changes
|