"""Ask the model a question; its tool calls are answered by Simple English Wikipedia. pip install torch transformers python agent.py "What is a volcano?" # uses a GPU when available python agent.py --offline articles.jsonl "What is a volcano?" # use a local dump instead The model writes `<|call|>search: volcano<|/call|>` or `<|call|>read: Moon<|/call|>`. This script stops generation there, runs the call, appends `<|result|>...<|/result|>` and lets the model continue until `<|end|>`. Set SEW_TOOLS_USER_AGENT to identify your client to Wikimedia (https://meta.wikimedia.org/wiki/User-Agent_policy). """ import argparse import os import sys import torch from transformers import AutoModelForCausalLM, AutoTokenizer sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) from sew_tools import LocalWiki, WikipediaAPI # noqa: E402 CALL, END_CALL, RESULT, END_RESULT, END = "<|call|>", "<|/call|>", "<|result|>", "<|/result|>", "<|end|>" def run_tool(backend, call): """Execute 'search: q' / 'read: title' and format the result as in training.""" tool, _, arg = call.partition(":") tool, arg = tool.strip().lower(), arg.strip() try: if tool == "search" and arg: res = backend.search(arg, 3) return "\n".join(f"[{i + 1}] {r['title']}: {r['snippet']}" for i, r in enumerate(res)) or "No results." if tool == "read" and arg: art = backend.read(arg) return f"{art['title']}: {art['text']}" if art else "No article with that title." except Exception as e: return f"Error: {type(e).__name__}" return "Unknown tool." def ask(model, tok, backend, question, max_calls=3, max_new_tokens=200, verbose=False): text = tok.apply_chat_template([{"role": "user", "content": question}], tokenize=False, add_generation_prompt=True) ids = tok(text, return_tensors="pt", add_special_tokens=False).input_ids.to(model.device) for _ in range(max_calls + 1): with torch.no_grad(): out = model.generate(ids, max_new_tokens=max_new_tokens, do_sample=False) new = out[0, ids.shape[1]:] piece = tok.decode(new, skip_special_tokens=False) ids = out if piece.endswith(END_CALL) and CALL in piece: call = piece.split(CALL, 1)[1][:-len(END_CALL)] result = run_tool(backend, call) if verbose: print(f"[tool] {call.strip()}\n{result}\n", file=sys.stderr) extra = tok(RESULT + result + END_RESULT, return_tensors="pt", add_special_tokens=False).input_ids.to(model.device) ids = torch.cat([ids, extra], dim=1) continue return tok.decode(new, skip_special_tokens=True).strip() return "(stopped: too many tool calls)" def main(): p = argparse.ArgumentParser() p.add_argument("question", nargs="*") p.add_argument("--model", default=os.path.dirname(os.path.abspath(__file__))) p.add_argument("--offline", default=None, help="articles.jsonl to use instead of the live API") p.add_argument("-v", "--verbose", action="store_true", help="print tool calls and results") p.add_argument("--device", default="auto", help="auto (cuda > mps > cpu), cuda, mps, cpu") a = p.parse_args() tok = AutoTokenizer.from_pretrained(a.model) device = a.device if device == "auto": device = ("cuda" if torch.cuda.is_available() else "mps" if torch.backends.mps.is_available() else "cpu") dtype = torch.bfloat16 if device.startswith("cuda") and torch.cuda.is_bf16_supported() else torch.float32 model = AutoModelForCausalLM.from_pretrained(a.model, dtype=dtype).to(device).eval() backend = LocalWiki(a.offline) if a.offline else WikipediaAPI() if a.question: print(ask(model, tok, backend, " ".join(a.question), verbose=a.verbose)) return for line in sys.stdin: if line.strip(): print(ask(model, tok, backend, line.strip(), verbose=a.verbose)) if __name__ == "__main__": main()