Download code/opusdb/agent.py from KeremTT/OPUS-5.5-DATABASE: direct link, hf CLI and curl.
- Browser
- Download file 3.39 kB
-
https://huggingface.co/datasets/KeremTT/OPUS-5.5-DATABASE/resolve/main/code/opusdb/agent.py
- Command line
-
hf download hf://datasets/KeremTT/OPUS-5.5-DATABASE/code/opusdb/agent.py
-
curl -L -o agent.py https://huggingface.co/datasets/KeremTT/OPUS-5.5-DATABASE/resolve/main/code/opusdb/agent.py
3.39 kB
| """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 | |
| 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"] | |