""" agent_anthropic.py — Anthropic (Claude) drop-in variant of agent.py for Project 3. Same tools.py, same bounded loop and guardrails; only the function-calling mechanics change to Claude's tool-use format. Cost note: pay-per-token. Install: pip install anthropic python-dotenv .env: ANTHROPIC_API_KEY=your_anthropic_api_key_here ANTHROPIC_MODEL=claude-haiku-4-5-20251001 """ import os import anthropic from dotenv import find_dotenv, load_dotenv from tools import TOOLS load_dotenv(find_dotenv()) client = anthropic.Anthropic(api_key=os.environ["ANTHROPIC_API_KEY"]) MODEL_NAME = os.environ.get("ANTHROPIC_MODEL", "claude-haiku-4-5-20251001") MAX_STEPS = 6 # guardrail: never loop forever SYSTEM = ( "You are a helpful agent that can use tools. " "Use tools when they help; otherwise answer directly. " "For get_weather you must supply numeric latitude and longitude. " "Never claim to have done something a tool did not return." ) # Claude tool schema: note `input_schema` (vs Gemini's `parameters`). TOOLS_SCHEMA = [ {"name": "calculator", "description": "Evaluate a maths expression, e.g. '2*(3+4)' or 'sqrt(144)'.", "input_schema": {"type": "object", "properties": {"expression": {"type": "string"}}, "required": ["expression"]}}, {"name": "get_weather", "description": "Current weather for a latitude/longitude.", "input_schema": {"type": "object", "properties": {"latitude": {"type": "number"}, "longitude": {"type": "number"}}, "required": ["latitude", "longitude"]}}, {"name": "save_note", "description": "Save a short note to persistent storage.", "input_schema": {"type": "object", "properties": {"text": {"type": "string"}}, "required": ["text"]}}, {"name": "list_notes", "description": "List all saved notes.", "input_schema": {"type": "object", "properties": {}}}, ] def run(goal, trace=None): """Execute the agent loop; return (final_answer, trace).""" trace = trace if trace is not None else [] messages = [{"role": "user", "content": goal}] for step in range(MAX_STEPS): resp = client.messages.create( model=MODEL_NAME, max_tokens=1024, system=SYSTEM, tools=TOOLS_SCHEMA, messages=messages, ) # Collect any tool-use blocks from the assistant turn. tool_uses = [b for b in resp.content if b.type == "tool_use"] messages.append({"role": "assistant", "content": resp.content}) if resp.stop_reason != "tool_use" or not tool_uses: # Final answer: gather text blocks. text = "".join(b.text for b in resp.content if b.type == "text") return text, trace # Execute each requested tool, return results in one user turn. results = [] for tu in tool_uses: name, args = tu.name, dict(tu.input or {}) fn = TOOLS.get(name) if fn is None: result = f"Error: unknown tool '{name}'." else: try: result = fn(**args) except TypeError as e: result = f"Error: bad arguments for {name}: {e}" trace.append(f"step {step+1}: {name}({args}) -> {result}") results.append({"type": "tool_result", "tool_use_id": tu.id, "content": str(result)}) messages.append({"role": "user", "content": results}) return "Stopped: reached the maximum number of steps.", trace if __name__ == "__main__": ans, tr = run("What is sqrt(2025), and save the result as a note.") print("TRACE:\n" + "\n".join(tr)) print("\nANSWER:", ans)