"""A scripted model: an OpenAI-compatible chat completion that makes the tool calls of a fixed script, one per turn, then says it's done. It finds each tool by its MCP method name at the end of the tool's name, whatever prefix Hermes gives MCP tools. >>> tools = [{'type': 'function', 'function': {'name': 'mcp_host_listMessages'}}] >>> req = {'messages': [{'role': 'user', 'content': 'go'}], 'tools': tools} >>> step = next_step([('listMessages', {})], req) >>> step['tool_calls'][0]['function'] {'name': 'mcp_host_listMessages', 'arguments': '{}'} >>> req['messages'] += [{'role': 'assistant', 'tool_calls': step['tool_calls']}, ... {'role': 'tool', 'content': '[]'}] >>> next_step([('listMessages', {})], req)['content'] 'Done: I made 1 calls.' """ import json def tool_named(tools, method): """The full name of the tool for MCP `method`. >>> tool_named([{'function': {'name': 'mcp_host_reply'}}], 'reply') 'mcp_host_reply' """ names = [t["function"]["name"] for t in tools] for name in names: if name == method or name.endswith("_" + method): return name raise KeyError(f"no tool for {method} among {len(names)} tools") def next_step(script, req): """The assistant message for the next turn: the next call, or the end.""" done = sum(1 for m in req["messages"] if m["role"] == "tool") if done >= len(script): return {"role": "assistant", "content": f"Done: I made {done} calls."} method, args = script[done] return {"role": "assistant", "content": None, "tool_calls": [{ "id": f"call_{done}", "type": "function", "function": {"name": tool_named(req.get("tools", []), method), "arguments": json.dumps(args)}, }]} def completion(model, message): """A non-streamed chat.completion with `message`.""" return { "id": "fake", "object": "chat.completion", "created": 0, "model": model, "choices": [{"index": 0, "message": message, "finish_reason": "tool_calls" if message.get("tool_calls") else "stop"}], "usage": {"prompt_tokens": 1, "completion_tokens": 1, "total_tokens": 2}, } def chunks(model, message): """The same message, as server-sent event lines of a streamed completion. >>> lines = list(chunks('m', {'role': 'assistant', 'content': 'hi'})) >>> lines[-1] 'data: [DONE]' """ delta = {"role": "assistant"} if message.get("tool_calls"): delta["tool_calls"] = [dict(c, index=i) for i, c in enumerate(message["tool_calls"])] else: delta["content"] = message["content"] base = {"id": "fake", "object": "chat.completion.chunk", "created": 0, "model": model} yield "data: " + json.dumps(dict(base, choices=[ {"index": 0, "delta": delta, "finish_reason": None}])) yield "data: " + json.dumps(dict(base, choices=[{ "index": 0, "delta": {}, "finish_reason": "tool_calls" if message.get("tool_calls") else "stop"}], usage={"prompt_tokens": 1, "completion_tokens": 1, "total_tokens": 2})) yield "data: [DONE]"