Loading source
Pulling the file list, source metadata, and syntax-aware rendering for this listing.
Source from repo
A comprehensive collection of Agent Skills for context engineering, multi-agent architectures, and production agent systems.
Files
Skill
Size
Entrypoint
Format
Open file
Syntax-highlighted preview of this file as included in the skill package.
examples/interleaved-thinking/examples/02_tool_usage.py
1"""2Example 2: Tool Usage with Trace Capture34Demonstrates how M2.1's interleaved thinking reasons between tool calls.5This is where interleaved thinking really shines - you can see the model6adapting to tool outputs in real-time.7"""89import json10import os11from pathlib import Path12from dotenv import load_dotenv1314from reasoning_trace_optimizer import TraceCapture15from reasoning_trace_optimizer.capture import format_trace_for_display1617# Load environment variables from the project root18env_path = Path(__file__).parent.parent / ".env"19load_dotenv(env_path)202122# Define mock tools23TOOLS = [24{25"name": "get_weather",26"description": "Get current weather for a location. Returns temperature and conditions.",27"input_schema": {28"type": "object",29"properties": {30"location": {31"type": "string",32"description": "City name, e.g., 'San Francisco, CA'",33}34},35"required": ["location"],36},37},38{39"name": "get_forecast",40"description": "Get 3-day weather forecast for a location.",41"input_schema": {42"type": "object",43"properties": {44"location": {45"type": "string",46"description": "City name",47},48"days": {49"type": "integer",50"description": "Number of days (1-3)",51"default": 3,52},53},54"required": ["location"],55},56},57]585960# Mock tool executor61def execute_tool(name: str, input_data: dict) -> str:62"""Execute a mock tool and return results."""63if name == "get_weather":64location = input_data.get("location", "Unknown")65# Simulate different weather for different cities66if "san francisco" in location.lower():67return json.dumps({68"location": location,69"temperature": "18°C",70"conditions": "Foggy",71"humidity": "85%",72})73elif "new york" in location.lower():74return json.dumps({75"location": location,76"temperature": "22°C",77"conditions": "Partly cloudy",78"humidity": "60%",79})80else:81return json.dumps({82"location": location,83"temperature": "20°C",84"conditions": "Clear",85"humidity": "50%",86})8788elif name == "get_forecast":89location = input_data.get("location", "Unknown")90days = input_data.get("days", 3)91forecast = []92for i in range(days):93forecast.append({94"day": i + 1,95"high": f"{20 + i * 2}°C",96"low": f"{12 + i}°C",97"conditions": ["Sunny", "Cloudy", "Rainy"][i % 3],98})99return json.dumps({100"location": location,101"forecast": forecast,102})103104return json.dumps({"error": f"Unknown tool: {name}"})105106107def main():108"""Run a task with tools and observe interleaved thinking."""109110capture = TraceCapture(111api_key=os.getenv("ANTHROPIC_API_KEY"),112base_url="https://api.minimax.io/anthropic",113model="MiniMax-M2.1",114)115116task = """Compare the current weather in San Francisco and New York City.117Then tell me which city would be better for outdoor activities this weekend."""118119system_prompt = """You are a helpful weather assistant.120Use the available tools to get accurate weather information.121Always provide specific data to support your recommendations."""122123print("=" * 60)124print("TOOL USAGE WITH INTERLEAVED THINKING")125print("=" * 60)126print(f"\nTask: {task}")127print(f"\nTools available: {', '.join(t['name'] for t in TOOLS)}")128print("\nCapturing trace with tool usage...\n")129130# Capture the trace (using non-streaming for reliability)131trace = capture.run(132task=task,133system_prompt=system_prompt,134tools=TOOLS,135tool_executor=execute_tool,136max_turns=10,137)138139print("\n\n" + "=" * 60)140print("TRACE ANALYSIS")141print("=" * 60)142143print(f"\nSuccess: {trace.success}")144print(f"Total Turns: {trace.total_turns}")145print(f"Thinking Blocks: {len(trace.thinking_blocks)}")146print(f"Tool Calls: {len(trace.tool_calls)}")147148# Show how thinking evolved between tool calls149print("\n" + "=" * 60)150print("THINKING EVOLUTION ACROSS TOOL CALLS")151print("=" * 60)152153for i, thinking in enumerate(trace.thinking_blocks):154print(f"\n[Turn {thinking.turn_index}] Thinking Block {i + 1}")155print("-" * 40)156157# Show what tool was called after this thinking158turn_tools = trace.get_tool_calls_at_turn(thinking.turn_index)159if turn_tools:160print(f"Following action: Called {', '.join(t.name for t in turn_tools)}")161else:162print("Following action: Generated response")163164# Show key reasoning points (first 300 chars)165print(f"\nReasoning preview:\n{thinking.content[:300]}...")166167# Show tool call results168print("\n" + "=" * 60)169print("TOOL CALL SUMMARY")170print("=" * 60)171172for tc in trace.tool_calls:173status = "✅" if tc.success else "❌"174print(f"\n{status} {tc.name}")175print(f" Input: {json.dumps(tc.input)}")176print(f" Result: {tc.result[:100]}..." if tc.result and len(tc.result) > 100 else f" Result: {tc.result}")177178# Final response179if trace.final_response:180print("\n" + "=" * 60)181print("FINAL RESPONSE")182print("=" * 60)183print(trace.final_response)184185186if __name__ == "__main__":187main()188