Keep it small: a message list, a tool registry, a step cap, error handling that returns errors to the model as tool results, and correlation IDs.
Provider-agnostic sketch:
import json
def run_agent(client, messages, tool_specs, registry, max_steps=8):
for _ in range(max_steps): # hard stop condition
msg = client.chat(messages=messages, tools=tool_specs)
messages.append(msg)
if not msg.tool_calls: # model produced a final answer
return msg.content
for call in msg.tool_calls:
try:
args = json.loads(call.arguments)
result = registry[call.name](**args) # validate args and permissions here
except Exception as e:
result = f"ERROR: {e}" # let the model see and recover
messages.append({"role": "tool", "tool_call_id": call.id, "content": str(result)})
return "Stopped: step limit reached"