aether-agent-framework 1.3.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.
aether/__init__.py ADDED
@@ -0,0 +1,9 @@
1
+ """Aether - a free, fully autonomous agent framework.
2
+
3
+ Plug in any OpenAI-compatible API or a local Ollama model and let the agent
4
+ plan, act (run commands, write code, browse the web), observe and iterate
5
+ until the task is done. Subtasks can be handed off to sub-agents via the
6
+ delegate_task tool; a local dashboard streams every step of the loop.
7
+ """
8
+
9
+ __version__ = "1.3.0"
aether/__main__.py ADDED
@@ -0,0 +1,4 @@
1
+ from .cli import main
2
+
3
+ if __name__ == "__main__":
4
+ raise SystemExit(main())
aether/agent.py ADDED
@@ -0,0 +1,222 @@
1
+ """The autonomous loop: plan, act (tool calls), observe, repeat, report."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ import threading
7
+
8
+ from .config import Config
9
+ from .llm import LLMClient
10
+ from .memory import Memory
11
+ from .planner import make_plan
12
+ from .tools import ToolRegistry
13
+
14
+ SYSTEM_PROMPT = """You are Aether, a fully autonomous agent running on the user's machine.
15
+
16
+ Mission: complete the user's task end-to-end using the tools available to you.
17
+ You decide your own approach. Do not ask the user questions unless the task is
18
+ literally impossible without missing information.
19
+
20
+ Operating rules:
21
+ 1. Think before acting: state what you are about to do and why (one short line).
22
+ 2. Prefer tools over guessing. Verify outcomes (run tests, re-read files, check URLs).
23
+ 3. Work inside the workspace directory. Keep files tidy and idiomatic.
24
+ 4. Tool outputs are truncated; if you need more, re-read with line ranges.
25
+ 5. If an approach fails twice, change strategy instead of repeating it.
26
+ 6. Durable facts worth keeping (user preferences, project layout) go to `remember`.
27
+ 7. When the task is fully done, reply with a concise final summary (no tool calls):
28
+ what was done, key decisions, and anything the user should check."""
29
+
30
+ ANSI = {
31
+ "reset": "\033[0m",
32
+ "dim": "\033[2m",
33
+ "cyan": "\033[36m",
34
+ "green": "\033[32m",
35
+ "yellow": "\033[33m",
36
+ }
37
+
38
+
39
+ def _canonical(arguments) -> str:
40
+ try:
41
+ if isinstance(arguments, str):
42
+ return json.dumps(json.loads(arguments), sort_keys=True)
43
+ return json.dumps(arguments, sort_keys=True)
44
+ except Exception: # noqa: BLE001
45
+ return str(arguments)
46
+
47
+
48
+ class Agent:
49
+ def __init__(
50
+ self,
51
+ config: Config,
52
+ llm: LLMClient,
53
+ registry: ToolRegistry,
54
+ memory: Memory,
55
+ color: bool = True,
56
+ on_event=None,
57
+ ):
58
+ self.config = config
59
+ self.llm = llm
60
+ self.registry = registry
61
+ self.memory = memory
62
+ self.color = color
63
+ self.conversation: list[dict] = []
64
+ # Optional observer: callable(dict) receiving structured loop events
65
+ # (used by the Web UI). Observers must never break the loop.
66
+ self.on_event = on_event
67
+ self.stop_flag = threading.Event()
68
+
69
+ # Let tools opt into agent services (stop flag, event observer).
70
+ # Used by delegate_task so sub-agents stream events to the same
71
+ # observer and stop when the parent stops.
72
+ for tool in registry.tools.values():
73
+ tool.bind_agent(self)
74
+
75
+ def request_stop(self) -> None:
76
+ """Ask the loop to halt before the next model turn / tool call."""
77
+ self.stop_flag.set()
78
+
79
+ def _emit(self, type_: str, **data) -> None:
80
+ if self.on_event is None:
81
+ return
82
+ try:
83
+ self.on_event({"type": type_, **data})
84
+ except Exception: # noqa: BLE001 - observation must not break execution
85
+ pass
86
+
87
+ # ----------------------------------------------------------------- events
88
+ def _say(self, text: str, color: str = "reset") -> None:
89
+ if self.color:
90
+ print(f"{ANSI.get(color, '')}{text}{ANSI['reset']}")
91
+ else:
92
+ print(text)
93
+
94
+ def reset(self) -> None:
95
+ self.conversation.clear()
96
+
97
+ # --------------------------------------------------------------- seeding
98
+ def _seed(self, task: str, plan: list[str]) -> None:
99
+ self.reset()
100
+ self.conversation.append({"role": "system", "content": SYSTEM_PROMPT})
101
+
102
+ notes = self.memory.load_notes_into_context()
103
+ if notes:
104
+ self.conversation.append(
105
+ {
106
+ "role": "system",
107
+ "content": "Long-term notes from previous sessions (may be relevant):\n" + notes,
108
+ }
109
+ )
110
+
111
+ content = task
112
+ if plan:
113
+ checklist = "\n".join(f"{i}. {s}" for i, s in enumerate(plan, 1))
114
+ content += f"\n\nSuggested plan (adapt freely if reality disagrees):\n{checklist}"
115
+ self.conversation.append({"role": "user", "content": content})
116
+
117
+ # ------------------------------------------------------------- single run
118
+ def run(self, task: str, use_plan: bool = True) -> str:
119
+ self.stop_flag.clear()
120
+ self.memory.log("user", task)
121
+ self._say(f"\n[TASK] {task}", "cyan")
122
+ self._emit("run_start", task=task, use_plan=use_plan)
123
+
124
+ plan = make_plan(self.llm, task) if use_plan else []
125
+ if plan:
126
+ self._say("[PLAN]", "dim")
127
+ for i, step in enumerate(plan, 1):
128
+ self._say(f" {i}. {step}", "dim")
129
+ self._emit("plan", steps=plan)
130
+
131
+ self._seed(task, plan)
132
+ return self._loop()
133
+
134
+ # ------------------------------------------------------------- multi-turn
135
+ def follow_up(self, message: str) -> str:
136
+ """Continue the current conversation (REPL mode)."""
137
+ self.stop_flag.clear()
138
+ self.memory.log("user", message)
139
+ self._emit("run_start", task=message, use_plan=False)
140
+ if not self.conversation:
141
+ self._seed(message, plan=[])
142
+ else:
143
+ self.conversation.append({"role": "user", "content": message})
144
+ return self._loop()
145
+
146
+ # ------------------------------------------------------------ the loop
147
+ def _loop(self) -> str:
148
+ recent_actions: list[str] = []
149
+ final_answer = ""
150
+
151
+ stopped = False
152
+
153
+ for step in range(1, self.config.max_iterations + 1):
154
+ if self.stop_flag.is_set():
155
+ stopped = True
156
+ break
157
+
158
+ reply = self.llm.chat(self.conversation, tools=self.registry.schemas())
159
+ content = reply.get("content")
160
+ tool_calls = reply.get("tool_calls")
161
+
162
+ if content:
163
+ self._say(f"[{step}] {content}", "dim")
164
+ self.memory.log("assistant", content)
165
+ self._emit("assistant", step=step, text=content)
166
+
167
+ if not tool_calls:
168
+ final_answer = content or "(no response)"
169
+ break
170
+
171
+ self.conversation.append(
172
+ {"role": "assistant", "content": content, "tool_calls": tool_calls}
173
+ )
174
+
175
+ for call in tool_calls:
176
+ if self.stop_flag.is_set():
177
+ # Keep the conversation valid for later follow_up() calls.
178
+ self.conversation.append(
179
+ {"role": "tool", "tool_call_id": call["id"],
180
+ "content": "(skipped: user requested stop)"}
181
+ )
182
+ continue
183
+
184
+ preview = str(call["arguments"])[:120]
185
+ self._say(f"[{step}] {call['name']}({preview})", "yellow")
186
+ self._emit("tool_call", step=step, name=call["name"],
187
+ arguments=call["arguments"])
188
+
189
+ result = self.registry.call(call["name"], call["arguments"])
190
+ first_line = result.splitlines()[0][:160] if result else "(empty)"
191
+ self._say(f" -> {first_line}", "dim")
192
+ self.memory.log("tool", f"{call['name']}: {result[:500]}")
193
+ self._emit("tool_result", step=step, name=call["name"],
194
+ result=result, ok=not result.startswith("ERROR"))
195
+
196
+ recent_actions.append(call["name"] + ":" + _canonical(call["arguments"]))
197
+
198
+ self.conversation.append(
199
+ {"role": "tool", "tool_call_id": call["id"], "content": result}
200
+ )
201
+
202
+ if len(recent_actions) >= 3 and len(set(recent_actions[-3:])) == 1:
203
+ nudge = (
204
+ "You have repeated the identical action 3 times with no "
205
+ "progress. Change approach, gather the missing information "
206
+ "differently, or finish with your best result."
207
+ )
208
+ self.conversation.append({"role": "system", "content": nudge})
209
+ self._emit("loop_warning", text=nudge)
210
+ recent_actions.clear()
211
+ else:
212
+ final_answer = (
213
+ f"Stopped after {self.config.max_iterations} iterations. "
214
+ "Raise --max-iterations or split the task into smaller pieces."
215
+ )
216
+
217
+ if stopped:
218
+ self._emit("run_stopped")
219
+ self.memory.log("final", final_answer)
220
+ self._say(f"\n[RESULT]\n{final_answer}", "green")
221
+ self._emit("run_end", result=final_answer, stopped=stopped)
222
+ return final_answer
aether/cli.py ADDED
@@ -0,0 +1,118 @@
1
+ """Command line interface: one-shot tasks and an interactive REPL."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ import sys
7
+
8
+ from .agent import Agent
9
+ from .config import load_config
10
+ from .llm import LLMClient, LLMError
11
+ from .memory import Memory
12
+ from .tools import build_default_tools
13
+
14
+ HELP = """Commands:
15
+ <any text> run it as the next instruction for the agent
16
+ /reset start a fresh conversation
17
+ /notes show long-term notes
18
+ /forget wipe long-term notes
19
+ /tools list available tools
20
+ /help this help
21
+ /exit (or Ctrl-D) quit
22
+ """
23
+
24
+
25
+ def build_parser() -> argparse.ArgumentParser:
26
+ p = argparse.ArgumentParser(
27
+ prog="aether", description="Aether - autonomous agent framework"
28
+ )
29
+ p.add_argument("task", nargs="*", help="task to run; omit to enter interactive mode")
30
+ p.add_argument("--config", help="path to config.yaml")
31
+ p.add_argument("--provider", choices=["openai_compatible", "ollama", "mock"])
32
+ p.add_argument("--base-url", help="API root, e.g. https://api.z.ai/api/paas/v4")
33
+ p.add_argument("--api-key")
34
+ p.add_argument("--model")
35
+ p.add_argument("--workspace", help="directory the agent operates in")
36
+ p.add_argument("--max-iterations", type=int)
37
+ p.add_argument("--max-delegate-depth", type=int,
38
+ help="sub-agent nesting via delegate_task (0 disables delegation)")
39
+ p.add_argument("--delegate-max-iterations", type=int,
40
+ help="loop budget for sub-agents spawned via delegate_task")
41
+ p.add_argument("--auto", action="store_true", help="skip confirmation prompts (blocklist still applies)")
42
+ p.add_argument("--no-plan", action="store_true", help="skip the planning step")
43
+ p.add_argument("--no-color", action="store_true")
44
+ return p
45
+
46
+
47
+ def main(argv: list[str] | None = None) -> int:
48
+ args = build_parser().parse_args(argv)
49
+
50
+ config = load_config(
51
+ args.config,
52
+ provider=args.provider,
53
+ base_url=args.base_url,
54
+ api_key=args.api_key,
55
+ model=args.model,
56
+ workspace=args.workspace,
57
+ max_iterations=args.max_iterations,
58
+ max_delegate_depth=args.max_delegate_depth,
59
+ delegate_max_iterations=args.delegate_max_iterations,
60
+ auto_approve=True if args.auto else None,
61
+ )
62
+
63
+ try:
64
+ llm = LLMClient(config)
65
+ memory = Memory(config.resolved_memory_dir())
66
+ registry = build_default_tools(config, memory)
67
+ agent = Agent(config, llm, registry, memory, color=not args.no_color)
68
+ except Exception as exc: # noqa: BLE001
69
+ print(f"Failed to initialise Aether: {exc}", file=sys.stderr)
70
+ return 1
71
+
72
+ task = " ".join(args.task).strip()
73
+ if task:
74
+ try:
75
+ agent.run(task, use_plan=not args.no_plan)
76
+ except LLMError as exc:
77
+ print(f"LLM error: {exc}", file=sys.stderr)
78
+ return 2
79
+ return 0
80
+
81
+ # ------------------------------------------------------------------ REPL
82
+ print("Aether interactive mode. Type /help for commands.")
83
+ while True:
84
+ try:
85
+ line = input("\naether> ").strip()
86
+ except (EOFError, KeyboardInterrupt):
87
+ print()
88
+ return 0
89
+ if not line:
90
+ continue
91
+ if line in ("/exit", "/quit"):
92
+ return 0
93
+ if line == "/reset":
94
+ agent.reset()
95
+ print("Conversation cleared.")
96
+ continue
97
+ if line == "/notes":
98
+ print(memory.recall())
99
+ continue
100
+ if line == "/forget":
101
+ memory.notes_path.write_text("", encoding="utf-8")
102
+ print("Notes wiped.")
103
+ continue
104
+ if line == "/tools":
105
+ for schema in registry.schemas():
106
+ print(f"- {schema['name']}: {schema['description'][:100]}")
107
+ continue
108
+ if line in ("/help", "/?"):
109
+ print(HELP)
110
+ continue
111
+ try:
112
+ agent.follow_up(line)
113
+ except LLMError as exc:
114
+ print(f"LLM error: {exc}", file=sys.stderr)
115
+
116
+
117
+ if __name__ == "__main__":
118
+ raise SystemExit(main())
aether/config.py ADDED
@@ -0,0 +1,98 @@
1
+ """Configuration loading: YAML file + environment variable overrides."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import os
6
+ from dataclasses import dataclass
7
+ from pathlib import Path
8
+
9
+ try:
10
+ import yaml
11
+ except ImportError: # pragma: no cover
12
+ yaml = None
13
+
14
+
15
+ @dataclass
16
+ class Config:
17
+ provider: str = "openai_compatible" # "openai_compatible" | "ollama" | "mock"
18
+ base_url: str = ""
19
+ api_key: str = ""
20
+ model: str = ""
21
+ temperature: float = 0.7
22
+ max_iterations: int = 40
23
+ auto_approve: bool = False
24
+ workspace: str = "."
25
+ max_tool_output: int = 8000
26
+ memory_dir: str = "" # defaults to <workspace>/.aether
27
+ allow_outside_workspace: bool = False
28
+ custom_tools_dir: str = "" # folder with user-defined Tool plugins (optional)
29
+ max_delegate_depth: int = 1 # 0 disables delegate_task; N allows N levels of sub-agents
30
+ delegate_max_iterations: int = 15 # loop budget for sub-agents spawned via delegate_task
31
+
32
+ def resolved_workspace(self) -> Path:
33
+ return Path(self.workspace).expanduser().resolve()
34
+
35
+ def resolved_memory_dir(self) -> Path:
36
+ if self.memory_dir:
37
+ return Path(self.memory_dir).expanduser().resolve()
38
+ return self.resolved_workspace() / ".aether"
39
+
40
+
41
+ _ENV_OVERRIDES = {
42
+ "provider": "AETHER_PROVIDER",
43
+ "base_url": "AETHER_BASE_URL",
44
+ "api_key": "AETHER_API_KEY",
45
+ "model": "AETHER_MODEL",
46
+ "max_iterations": "AETHER_MAX_ITERATIONS",
47
+ "auto_approve": "AETHER_AUTO_APPROVE",
48
+ "workspace": "AETHER_WORKSPACE",
49
+ "custom_tools_dir": "AETHER_CUSTOM_TOOLS",
50
+ "max_delegate_depth": "AETHER_MAX_DELEGATE_DEPTH",
51
+ "delegate_max_iterations": "AETHER_DELEGATE_MAX_ITERATIONS",
52
+ }
53
+
54
+
55
+ def load_config(path: str | None = None, **overrides) -> Config:
56
+ """Merge config.yaml < environment variables < explicit overrides."""
57
+ data: dict = {}
58
+ if path:
59
+ if yaml is None:
60
+ raise RuntimeError("PyYAML is required for YAML configs: pip install pyyaml")
61
+ with open(path, "r", encoding="utf-8") as fh:
62
+ data = yaml.safe_load(fh) or {}
63
+
64
+ cfg = Config()
65
+ for key, value in data.items():
66
+ if hasattr(cfg, key) and value is not None:
67
+ setattr(cfg, key, value)
68
+
69
+ for attr, env in _ENV_OVERRIDES.items():
70
+ raw = os.environ.get(env)
71
+ if raw:
72
+ current = getattr(cfg, attr)
73
+ if isinstance(current, bool):
74
+ setattr(cfg, attr, raw.lower() in ("1", "true", "yes", "on"))
75
+ elif isinstance(current, int):
76
+ setattr(cfg, attr, int(raw))
77
+ else:
78
+ setattr(cfg, attr, raw)
79
+
80
+ for key, value in overrides.items():
81
+ if value is not None and hasattr(cfg, key):
82
+ setattr(cfg, key, value)
83
+
84
+ if not cfg.base_url:
85
+ if cfg.provider == "ollama":
86
+ cfg.base_url = "http://localhost:11434"
87
+ elif cfg.provider == "mock":
88
+ cfg.base_url = "mock://local" # never used; the backend is offline
89
+ else:
90
+ cfg.base_url = "https://api.z.ai/api/paas/v4"
91
+ if not cfg.model:
92
+ cfg.model = (
93
+ "llama3.1"
94
+ if cfg.provider == "ollama"
95
+ else "aether-demo" if cfg.provider == "mock" else "glm-4.7-flash"
96
+ )
97
+
98
+ return cfg
aether/llm.py ADDED
@@ -0,0 +1,227 @@
1
+ """LLM backends.
2
+
3
+ Three providers are supported:
4
+
5
+ * ``openai_compatible`` - any server exposing POST {base_url}/chat/completions
6
+ with OpenAI-style tool calling (Z.ai, OpenRouter, Groq, vLLM, llama.cpp...).
7
+ * ``ollama`` - a local Ollama daemon (POST {base_url}/api/chat).
8
+ * ``mock`` - a built-in scripted backend that performs a small deterministic
9
+ demo (write a file, verify it, report). No network, no API key: useful to
10
+ try the agent and the Web UI offline, and for tests.
11
+
12
+ All are normalised to one internal message format:
13
+
14
+ {"role": ..., "content": str | None,
15
+ "tool_calls": [{"id", "name", "arguments"(str)}] | None}
16
+ """
17
+
18
+ from __future__ import annotations
19
+
20
+ import json
21
+ import time
22
+ import uuid
23
+
24
+ import requests
25
+
26
+ from .config import Config
27
+
28
+
29
+ class LLMError(RuntimeError):
30
+ pass
31
+
32
+
33
+ class LLMClient:
34
+ def __init__(self, config: Config):
35
+ self.config = config
36
+ self.session = requests.Session()
37
+ self._mock_step = 0
38
+
39
+ # ------------------------------------------------------------------ public
40
+ def chat(self, messages: list[dict], tools: list[dict] | None = None) -> dict:
41
+ """Send the conversation; return a normalised assistant message."""
42
+ if self.config.provider == "mock":
43
+ return self._chat_mock(messages, tools)
44
+ last_error: Exception | None = None
45
+ for attempt in range(3):
46
+ try:
47
+ if self.config.provider == "ollama":
48
+ return self._chat_ollama(messages, tools)
49
+ return self._chat_openai(messages, tools)
50
+ except (requests.RequestException, LLMError) as exc:
51
+ last_error = exc
52
+ time.sleep(1.5 * (attempt + 1))
53
+ raise LLMError(f"LLM request failed after 3 attempts: {last_error}")
54
+
55
+ # -------------------------------------------------------------------- mock
56
+ def _chat_mock(self, messages: list[dict], tools: list[dict] | None) -> dict:
57
+ """Scripted demo: plan, write a file, verify it, report."""
58
+ if tools is None:
59
+ # Called by the planner (no tools attached): return a checklist.
60
+ return {
61
+ "content": (
62
+ "1. Create a small demo file in the workspace\n"
63
+ "2. Re-read the file to verify its contents\n"
64
+ "3. Report what was done"
65
+ ),
66
+ "tool_calls": None,
67
+ }
68
+
69
+ if not any(m.get("role") == "tool" for m in messages):
70
+ self._mock_step = 0 # fresh run: replay the demo from the start
71
+ self._mock_step += 1
72
+ if self._mock_step == 1:
73
+ return {
74
+ "content": "I will create a small demo file in the workspace first.",
75
+ "tool_calls": [
76
+ {
77
+ "id": "mock_call_1",
78
+ "name": "write_file",
79
+ "arguments": json.dumps(
80
+ {
81
+ "path": "aether-demo.txt",
82
+ "content": (
83
+ "Hello from Aether!\n"
84
+ "This file was written autonomously by the"
85
+ " agent loop (mock backend demo).\n"
86
+ ),
87
+ },
88
+ indent=2,
89
+ ),
90
+ }
91
+ ],
92
+ }
93
+ if self._mock_step == 2:
94
+ return {
95
+ "content": "The file is in place; let me verify its contents.",
96
+ "tool_calls": [
97
+ {
98
+ "id": "mock_call_2",
99
+ "name": "read_file",
100
+ "arguments": json.dumps({"path": "aether-demo.txt"}),
101
+ }
102
+ ],
103
+ }
104
+ return {
105
+ "content": (
106
+ "Done. I created aether-demo.txt in the workspace with a greeting, "
107
+ "then re-read it to verify the contents. This was the offline mock "
108
+ "backend - point provider/base_url at a real model for real work."
109
+ ),
110
+ "tool_calls": None,
111
+ }
112
+
113
+ # ------------------------------------------------------- openai-compatible
114
+ def _chat_openai(self, messages: list[dict], tools: list[dict] | None) -> dict:
115
+ url = self.config.base_url.rstrip("/")
116
+ if not url.endswith("/chat/completions"):
117
+ url += "/chat/completions"
118
+
119
+ payload: dict = {
120
+ "model": self.config.model,
121
+ "messages": [_wire(m, ollama=False) for m in messages],
122
+ "temperature": self.config.temperature,
123
+ }
124
+ if tools:
125
+ payload["tools"] = [{"type": "function", "function": t} for t in tools]
126
+
127
+ resp = self.session.post(url, json=payload, headers=self._headers(), timeout=180)
128
+ if resp.status_code >= 400:
129
+ raise LLMError(f"HTTP {resp.status_code}: {resp.text[:500]}")
130
+
131
+ data = resp.json()
132
+ try:
133
+ message = data["choices"][0]["message"]
134
+ except (KeyError, IndexError) as exc:
135
+ raise LLMError(f"Unexpected response shape: {json.dumps(data)[:500]}") from exc
136
+ return _normalise(message)
137
+
138
+ # ------------------------------------------------------------------ ollama
139
+ def _chat_ollama(self, messages: list[dict], tools: list[dict] | None) -> dict:
140
+ base = self.config.base_url.rstrip("/")
141
+ if not base.endswith("/api"):
142
+ base += "/api"
143
+ url = base + "/chat"
144
+
145
+ payload: dict = {
146
+ "model": self.config.model,
147
+ "messages": [_wire(m, ollama=True) for m in messages],
148
+ "stream": False,
149
+ "options": {"temperature": self.config.temperature},
150
+ }
151
+ if tools:
152
+ payload["tools"] = [{"type": "function", "function": t} for t in tools]
153
+
154
+ resp = self.session.post(url, json=payload, timeout=600)
155
+ if resp.status_code >= 400:
156
+ raise LLMError(f"HTTP {resp.status_code}: {resp.text[:500]}")
157
+
158
+ message = resp.json().get("message", {})
159
+ tool_calls = []
160
+ for call in message.get("tool_calls") or []:
161
+ fn = call.get("function", {})
162
+ args = fn.get("arguments")
163
+ if not isinstance(args, str):
164
+ args = json.dumps(args or {})
165
+ tool_calls.append(
166
+ {
167
+ "id": call.get("id") or f"call_{uuid.uuid4().hex[:8]}",
168
+ "name": fn.get("name", ""),
169
+ "arguments": args,
170
+ }
171
+ )
172
+ return {"content": message.get("content") or None, "tool_calls": tool_calls or None}
173
+
174
+ # ----------------------------------------------------------------- helpers
175
+ def _headers(self) -> dict:
176
+ headers = {"Content-Type": "application/json"}
177
+ if self.config.api_key:
178
+ headers["Authorization"] = f"Bearer {self.config.api_key}"
179
+ return headers
180
+
181
+
182
+ def _normalise(message: dict) -> dict:
183
+ tool_calls = []
184
+ for call in message.get("tool_calls") or []:
185
+ fn = call.get("function", {})
186
+ tool_calls.append(
187
+ {
188
+ "id": call.get("id") or f"call_{uuid.uuid4().hex[:8]}",
189
+ "name": fn.get("name", ""),
190
+ "arguments": fn.get("arguments") or "{}",
191
+ }
192
+ )
193
+ return {"content": message.get("content") or None, "tool_calls": tool_calls or None}
194
+
195
+
196
+ def _wire(msg: dict, ollama: bool = False) -> dict:
197
+ """Convert the internal history format into the provider wire format."""
198
+ role = msg["role"]
199
+
200
+ if role == "assistant" and msg.get("tool_calls"):
201
+ calls = []
202
+ for call in msg["tool_calls"]:
203
+ fn = {"name": call["name"], "arguments": call["arguments"]}
204
+ if ollama:
205
+ try:
206
+ fn["arguments"] = json.loads(fn["arguments"])
207
+ except (json.JSONDecodeError, TypeError):
208
+ fn["arguments"] = {}
209
+ calls.append({"function": fn})
210
+ else:
211
+ calls.append({"id": call["id"], "type": "function", "function": fn})
212
+ return {
213
+ "role": "assistant",
214
+ "content": msg.get("content") or "",
215
+ "tool_calls": calls,
216
+ }
217
+
218
+ if role == "tool":
219
+ if ollama:
220
+ return {"role": "tool", "content": msg.get("content") or ""}
221
+ return {
222
+ "role": "tool",
223
+ "tool_call_id": msg.get("tool_call_id", ""),
224
+ "content": msg.get("content") or "",
225
+ }
226
+
227
+ return {"role": role, "content": msg.get("content") or ""}