Datasets:
Upload folder using huggingface_hub
Browse files- rlm_haiku/repl.py +6 -4
- rlm_haiku/rlm_repl.py +5 -2
- rlm_haiku/utils/llm.py +92 -0
rlm_haiku/repl.py
CHANGED
|
@@ -27,12 +27,13 @@ TERSE_SYSTEM = (
|
|
| 27 |
class Sub_RLM(RLM):
|
| 28 |
"""Depth-1 LM callee for the REPL environment."""
|
| 29 |
|
| 30 |
-
def __init__(self, model: str = "haiku", usage=None, terse: bool = False
|
| 31 |
-
|
|
|
|
| 32 |
|
| 33 |
self.model = model
|
| 34 |
self.terse = terse
|
| 35 |
-
self.client =
|
| 36 |
|
| 37 |
def completion(self, prompt) -> str:
|
| 38 |
"""Single sub-LM call. Errors are returned as text so REPL code can react."""
|
|
@@ -83,6 +84,7 @@ class REPLEnv:
|
|
| 83 |
usage=None,
|
| 84 |
max_workers: int = 8,
|
| 85 |
terse: bool = False,
|
|
|
|
| 86 |
):
|
| 87 |
self.max_workers = max_workers
|
| 88 |
# Store the original working directory
|
|
@@ -93,7 +95,7 @@ class REPLEnv:
|
|
| 93 |
|
| 94 |
|
| 95 |
# Initialize minimal RLM / LM client. Change this to support more depths.
|
| 96 |
-
self.sub_rlm: RLM = Sub_RLM(model=recursive_model, usage=usage, terse=terse)
|
| 97 |
|
| 98 |
# Create safe globals with only string-safe built-ins
|
| 99 |
self.globals = {
|
|
|
|
| 27 |
class Sub_RLM(RLM):
|
| 28 |
"""Depth-1 LM callee for the REPL environment."""
|
| 29 |
|
| 30 |
+
def __init__(self, model: str = "haiku", usage=None, terse: bool = False,
|
| 31 |
+
backend: str = "claude"):
|
| 32 |
+
from rlm_haiku.utils.llm import make_client
|
| 33 |
|
| 34 |
self.model = model
|
| 35 |
self.terse = terse
|
| 36 |
+
self.client = make_client(model, usage=usage, backend=backend)
|
| 37 |
|
| 38 |
def completion(self, prompt) -> str:
|
| 39 |
"""Single sub-LM call. Errors are returned as text so REPL code can react."""
|
|
|
|
| 84 |
usage=None,
|
| 85 |
max_workers: int = 8,
|
| 86 |
terse: bool = False,
|
| 87 |
+
backend: str = "claude",
|
| 88 |
):
|
| 89 |
self.max_workers = max_workers
|
| 90 |
# Store the original working directory
|
|
|
|
| 95 |
|
| 96 |
|
| 97 |
# Initialize minimal RLM / LM client. Change this to support more depths.
|
| 98 |
+
self.sub_rlm: RLM = Sub_RLM(model=recursive_model, usage=usage, terse=terse, backend=backend)
|
| 99 |
|
| 100 |
# Create safe globals with only string-safe built-ins
|
| 101 |
self.globals = {
|
rlm_haiku/rlm_repl.py
CHANGED
|
@@ -6,7 +6,7 @@ from typing import Dict, List, Optional, Any
|
|
| 6 |
|
| 7 |
from rlm_haiku import RLM
|
| 8 |
from rlm_haiku.repl import REPLEnv
|
| 9 |
-
from rlm_haiku.utils.llm import
|
| 10 |
from rlm_haiku.utils.prompts import DEFAULT_QUERY, next_action_prompt, build_system_prompt
|
| 11 |
import rlm_haiku.utils.utils as utils
|
| 12 |
|
|
@@ -30,7 +30,9 @@ class RLM_REPL(RLM):
|
|
| 30 |
max_workers: int = 8,
|
| 31 |
terse: bool = False,
|
| 32 |
require_repl: bool = False,
|
|
|
|
| 33 |
):
|
|
|
|
| 34 |
self.terse = terse
|
| 35 |
self.require_repl = require_repl
|
| 36 |
self.api_key = api_key
|
|
@@ -38,7 +40,7 @@ class RLM_REPL(RLM):
|
|
| 38 |
self.recursive_model = recursive_model
|
| 39 |
self.usage = usage if usage is not None else Usage()
|
| 40 |
self.max_workers = max_workers
|
| 41 |
-
self.llm =
|
| 42 |
|
| 43 |
# Track recursive call depth to prevent infinite loops
|
| 44 |
self.repl_env = None
|
|
@@ -80,6 +82,7 @@ class RLM_REPL(RLM):
|
|
| 80 |
usage=self.usage,
|
| 81 |
max_workers=self.max_workers,
|
| 82 |
terse=self.terse,
|
|
|
|
| 83 |
)
|
| 84 |
|
| 85 |
return self.messages
|
|
|
|
| 6 |
|
| 7 |
from rlm_haiku import RLM
|
| 8 |
from rlm_haiku.repl import REPLEnv
|
| 9 |
+
from rlm_haiku.utils.llm import Usage, make_client
|
| 10 |
from rlm_haiku.utils.prompts import DEFAULT_QUERY, next_action_prompt, build_system_prompt
|
| 11 |
import rlm_haiku.utils.utils as utils
|
| 12 |
|
|
|
|
| 30 |
max_workers: int = 8,
|
| 31 |
terse: bool = False,
|
| 32 |
require_repl: bool = False,
|
| 33 |
+
backend: str = "claude",
|
| 34 |
):
|
| 35 |
+
self.backend = backend
|
| 36 |
self.terse = terse
|
| 37 |
self.require_repl = require_repl
|
| 38 |
self.api_key = api_key
|
|
|
|
| 40 |
self.recursive_model = recursive_model
|
| 41 |
self.usage = usage if usage is not None else Usage()
|
| 42 |
self.max_workers = max_workers
|
| 43 |
+
self.llm = make_client(model, usage=self.usage, backend=backend)
|
| 44 |
|
| 45 |
# Track recursive call depth to prevent infinite loops
|
| 46 |
self.repl_env = None
|
|
|
|
| 82 |
usage=self.usage,
|
| 83 |
max_workers=self.max_workers,
|
| 84 |
terse=self.terse,
|
| 85 |
+
backend=self.backend,
|
| 86 |
)
|
| 87 |
|
| 88 |
return self.messages
|
rlm_haiku/utils/llm.py
CHANGED
|
@@ -192,3 +192,95 @@ if __name__ == "__main__":
|
|
| 192 |
assert "391" in out, out
|
| 193 |
assert usage.calls == 1 and usage.cost_usd > 0, usage.as_dict()
|
| 194 |
print("ok:", out.strip(), usage.as_dict())
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 192 |
assert "391" in out, out
|
| 193 |
assert usage.calls == 1 and usage.cost_usd > 0, usage.as_dict()
|
| 194 |
print("ok:", out.strip(), usage.as_dict())
|
| 195 |
+
|
| 196 |
+
|
| 197 |
+
class OllamaClient:
|
| 198 |
+
"""Same interface as ClaudeCodeClient, backed by a local Ollama model.
|
| 199 |
+
|
| 200 |
+
Lets the RLM loop run on local weights instead of the Claude Code CLI. Uses
|
| 201 |
+
Ollama's Anthropic-compatible /v1/messages so message handling matches the
|
| 202 |
+
CLI backend exactly.
|
| 203 |
+
"""
|
| 204 |
+
|
| 205 |
+
def __init__(
|
| 206 |
+
self,
|
| 207 |
+
model: str = "gemma4:e4b",
|
| 208 |
+
usage: Optional[Usage] = None,
|
| 209 |
+
base_url: str = "http://127.0.0.1:11434",
|
| 210 |
+
timeout: int = 900,
|
| 211 |
+
max_retries: int = 3,
|
| 212 |
+
max_prompt_chars: int | None = None,
|
| 213 |
+
max_tokens: int = 4096,
|
| 214 |
+
):
|
| 215 |
+
self.model = model
|
| 216 |
+
self.usage = usage if usage is not None else Usage()
|
| 217 |
+
self.base_url = base_url.rstrip("/")
|
| 218 |
+
self.timeout = timeout
|
| 219 |
+
self.max_retries = max_retries
|
| 220 |
+
# Local models have far smaller windows than the hosted ones, and Ollama
|
| 221 |
+
# silently truncates past num_ctx rather than erroring.
|
| 222 |
+
self.max_prompt_chars = max_prompt_chars or 60_000
|
| 223 |
+
self.max_tokens = max_tokens
|
| 224 |
+
|
| 225 |
+
def completion(self, messages, **_) -> str:
|
| 226 |
+
import json as _json
|
| 227 |
+
import urllib.error
|
| 228 |
+
import urllib.request
|
| 229 |
+
|
| 230 |
+
system_prompt, prompt = ClaudeCodeClient._split(messages)
|
| 231 |
+
if len(prompt) > self.max_prompt_chars:
|
| 232 |
+
dropped = len(prompt) - self.max_prompt_chars
|
| 233 |
+
prompt = prompt[: self.max_prompt_chars] + (
|
| 234 |
+
f"\n\n[TRUNCATED: {dropped} characters dropped, over the "
|
| 235 |
+
f"{self.max_prompt_chars}-character limit. Use smaller chunks.]"
|
| 236 |
+
)
|
| 237 |
+
|
| 238 |
+
body: dict = {
|
| 239 |
+
"model": self.model,
|
| 240 |
+
"max_tokens": self.max_tokens,
|
| 241 |
+
"messages": [{"role": "user", "content": prompt}],
|
| 242 |
+
}
|
| 243 |
+
if system_prompt:
|
| 244 |
+
body["system"] = system_prompt
|
| 245 |
+
|
| 246 |
+
last_error = ""
|
| 247 |
+
for attempt in range(self.max_retries):
|
| 248 |
+
start = time.time()
|
| 249 |
+
try:
|
| 250 |
+
req = urllib.request.Request(
|
| 251 |
+
f"{self.base_url}/v1/messages",
|
| 252 |
+
data=_json.dumps(body).encode(),
|
| 253 |
+
headers={"content-type": "application/json"},
|
| 254 |
+
)
|
| 255 |
+
with urllib.request.urlopen(req, timeout=self.timeout) as r:
|
| 256 |
+
payload = _json.loads(r.read())
|
| 257 |
+
if "error" in payload:
|
| 258 |
+
raise RuntimeError(str(payload["error"])[:300])
|
| 259 |
+
text = "".join(
|
| 260 |
+
b.get("text", "") for b in payload.get("content", [])
|
| 261 |
+
if b.get("type") == "text"
|
| 262 |
+
)
|
| 263 |
+
u = payload.get("usage", {}) or {}
|
| 264 |
+
self.usage.add(
|
| 265 |
+
{"usage": {"input_tokens": u.get("input_tokens", 0),
|
| 266 |
+
"output_tokens": u.get("output_tokens", 0)},
|
| 267 |
+
"total_cost_usd": 0.0}, # local weights: no marginal cost
|
| 268 |
+
time.time() - start,
|
| 269 |
+
)
|
| 270 |
+
return text
|
| 271 |
+
except Exception as e: # noqa: BLE001
|
| 272 |
+
last_error = f"{type(e).__name__}: {e}"
|
| 273 |
+
if attempt < self.max_retries - 1:
|
| 274 |
+
time.sleep(2 ** attempt * 2)
|
| 275 |
+
|
| 276 |
+
self.usage.add_error()
|
| 277 |
+
raise RuntimeError(f"ollama failed after {self.max_retries} attempts: {last_error}")
|
| 278 |
+
|
| 279 |
+
|
| 280 |
+
def make_client(model: str, usage=None, backend: str = "claude", **kw):
|
| 281 |
+
"""Pick an LM backend. `claude` = Claude Code CLI, `ollama` = local weights."""
|
| 282 |
+
if backend == "ollama":
|
| 283 |
+
return OllamaClient(model=model, usage=usage, **kw)
|
| 284 |
+
if backend == "claude":
|
| 285 |
+
return ClaudeCodeClient(model=model, usage=usage, **kw)
|
| 286 |
+
raise ValueError(f"unknown backend {backend!r}")
|