lewtun's picture
lewtun HF Staff
harness: agent loop
1159ab0 verified
Raw History Blame Contribute Delete
3.89 kB
"""Shared worker-agent harness for the GitSwarm Appendix C replication.
Worker LLM: moonshotai/Kimi-K3 via HF Inference Providers (OpenAI-compatible).
Tool protocol: every assistant reply must be a single JSON object
{"tool": "<name>", "args": {...}}. The harness executes the tool and returns
the result as the next user message.
"""
import json
import os
import re
import time
from huggingface_hub import InferenceClient
MODEL_ID = os.environ.get("WORKER_MODEL", "moonshotai/Kimi-K3")
PROVIDER = os.environ.get("HF_PROVIDER") or None
def make_client():
kwargs = {"model": MODEL_ID}
if PROVIDER:
kwargs["provider"] = PROVIDER
return InferenceClient(**kwargs)
TOOL_RE = re.compile(r"\{.*\}", re.DOTALL)
def parse_tool_call(text):
"""Extract the first JSON object from a reply; return (tool, args) or None."""
if text is None:
return None
# strip markdown fences if present
m = TOOL_RE.search(text)
if not m:
return None
try:
obj = json.loads(m.group(0))
except json.JSONDecodeError:
return None
if not isinstance(obj, dict) or "tool" not in obj:
return None
args = obj.get("args", {})
if not isinstance(args, dict):
args = {}
return obj["tool"], args
class Usage:
"""Accumulates token usage across a run so we can report API cost."""
def __init__(self):
self.calls = 0
self.prompt_tokens = 0
self.completion_tokens = 0
def add(self, usage):
self.calls += 1
if usage is not None:
self.prompt_tokens += getattr(usage, "prompt_tokens", 0) or 0
self.completion_tokens += getattr(usage, "completion_tokens", 0) or 0
def run_worker_episode(system_prompt, tools, max_turns=250, temperature=0.0,
usage=None, client=None, max_retries=5):
"""Run one worker episode. tools: {name: fn(args) -> (result_str, done)}.
Returns the name of the tool that ended the episode (or "max_turns").
"""
if client is None:
client = make_client()
messages = [{"role": "system", "content": system_prompt}]
done_tool = None
for turn in range(max_turns):
reply = None
for attempt in range(max_retries):
try:
resp = client.chat.completions.create(
model=MODEL_ID,
messages=messages,
max_tokens=2048,
temperature=temperature,
)
reply = resp.choices[0].message.content
if usage is not None:
usage.add(getattr(resp, "usage", None))
break
except Exception as e: # provider hiccups: back off and retry
if attempt == max_retries - 1:
raise
time.sleep(min(60, 5 * (2 ** attempt)))
call = parse_tool_call(reply)
if call is None:
messages.append({"role": "assistant", "content": reply or ""})
messages.append({"role": "user", "content": (
'Your reply was not a valid tool call. Reply with exactly one '
'JSON object: {"tool": "<tool name>", "args": {...}}')})
continue
name, args = call
messages.append({"role": "assistant", "content": json.dumps({"tool": name, "args": args})})
if name not in tools:
messages.append({"role": "user", "content": (
f"ERROR: unknown tool '{name}'. Valid tools: {sorted(tools)}.")})
continue
try:
result, done = tools[name](args)
except Exception as e:
result, done = f"ERROR: tool '{name}' failed: {e}", False
if done:
done_tool = name
break
messages.append({"role": "user", "content": result})
return done_tool or "max_turns"