File size: 3,390 Bytes
73f7e6f | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 | """Minimal agent loop for a model fine-tuned with `train/sft_trl.py --with-tools`.
from transformers import AutoModelForCausalLM, AutoTokenizer
from opusdb.agent import Agent
agent = Agent.from_pretrained("./opus55-4b-dpo")
print(agent.run("How many days are there between 2026-01-01 and 2026-12-25? Then convert that to weeks."))
The tool definitions are placed in the system prompt in the same Hermes format used in training,
so this works with any chat template. Add your own tools with `Agent.register(spec, fn)`.
"""
import json
from .agent_tools import IMPL, TOOL_SPECS, parse_tool_calls
from .tool_formats import hermes_system_prompt
class Agent:
def __init__(self, model, tokenizer, tools=None, impl=None, max_steps=6, max_new_tokens=512):
self.model, self.tok = model, tokenizer
self.tools = list(tools or TOOL_SPECS)
self.impl = dict(impl or IMPL)
self.max_steps, self.max_new_tokens = max_steps, max_new_tokens
@classmethod
def from_pretrained(cls, path, **kw):
import torch
from transformers import AutoModelForCausalLM, AutoTokenizer
tok = AutoTokenizer.from_pretrained(path)
model = AutoModelForCausalLM.from_pretrained(path, dtype=torch.bfloat16 if torch.cuda.is_available() else torch.float32,
device_map="auto" if torch.cuda.is_available() else None)
return cls(model.eval(), tok, **kw)
def register(self, spec, fn):
"""Add a tool: spec is an OpenAI-style {"type": "function", "function": {...}}; fn(**arguments) -> JSON-able."""
self.tools.append(spec)
self.impl[spec["function"]["name"]] = fn
def _generate(self, messages):
import torch
text = self.tok.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)
enc = self.tok(text, return_tensors="pt", add_special_tokens=False).to(self.model.device)
with torch.no_grad():
out = self.model.generate(**enc, max_new_tokens=self.max_new_tokens, do_sample=False)
return self.tok.decode(out[0][enc["input_ids"].shape[1]:], skip_special_tokens=True)
def run(self, user_message, history=None, verbose=False):
messages = [{"role": "system", "content": hermes_system_prompt(self.tools)}] + list(history or [])
messages.append({"role": "user", "content": user_message})
for _ in range(self.max_steps):
reply = self._generate(messages)
calls = parse_tool_calls(reply) if "<tool_call>" in reply else []
messages.append({"role": "assistant", "content": reply})
if not calls:
return reply
results = []
for c in calls:
fn = self.impl.get(c["name"])
try:
res = fn(**c["arguments"]) if fn else {"error": f"unknown tool {c['name']}"}
except Exception as exc: # report tool failures back to the model
res = {"error": f"{type(exc).__name__}: {exc}"}
results.append(f"<tool_response>\n{json.dumps(res, ensure_ascii=False)}\n</tool_response>")
if verbose:
print("TOOL", c["name"], c["arguments"], "->", res)
messages.append({"role": "user", "content": "\n".join(results)})
return messages[-2]["content"]
|