Skip to content
Source
Sign inSign up
TanStack/ai
Open History to see the last commit

example_usage.py

218 lines6.0 KB

1"""
2Example usage of TanStack AI Python SDK with agentic flow and tools.
3​
4This example demonstrates:
51. Setting up an Anthropic adapter
62. Defining tools with execute functions
73. Streaming chat with automatic tool execution
84. Using agent loop strategies
9"""
10​
11import asyncio
12import os
13​
14from tanstack_ai import (
15 AnthropicAdapter,
16 AIAdapterConfig,
17 chat,
18 tool,
19 max_iterations,
21​
22​
23# Define a simple weather tool
24def get_weather(args):
25 """Get weather for a location (simulated)."""
26 location = args.get("location", "unknown")
27 unit = args.get("unit", "fahrenheit")
29 # Simulate weather data
30 return {
31 "location": location,
32 "temperature": 72 if unit == "fahrenheit" else 22,
33 "conditions": "sunny",
34 "unit": unit,
35 }
36​
37​
38# Define a calculator tool
39def calculate(args):
40 """Perform a calculation."""
41 operation = args.get("operation")
42 a = args.get("a", 0)
43 b = args.get("b", 0)
45 if operation == "add":
46 return {"result": a + b}
47 elif operation == "subtract":
48 return {"result": a - b}
49 elif operation == "multiply":
50 return {"result": a * b}
51 elif operation == "divide":
52 if b == 0:
53 return {"error": "Division by zero"}
54 return {"result": a / b}
55 else:
56 return {"error": f"Unknown operation: {operation}"}
57​
58​
59# Define tools using the tool helper
60weather_tool = tool(
61 name="get_weather",
62 description="Get the current weather for a location. Returns temperature, conditions, and forecast.",
63 input_schema={
64 "type": "object",
65 "properties": {
66 "location": {
67 "type": "string",
68 "description": "The city and state, e.g. San Francisco, CA",
69 },
70 "unit": {
71 "type": "string",
72 "enum": ["celsius", "fahrenheit"],
73 "description": "Temperature unit",
74 },
75 },
76 "required": ["location"],
77 },
78 execute=get_weather,
80​
81calculator_tool = tool(
82 name="calculate",
83 description="Perform a mathematical calculation (add, subtract, multiply, divide)",
84 input_schema={
85 "type": "object",
86 "properties": {
87 "operation": {
88 "type": "string",
89 "enum": ["add", "subtract", "multiply", "divide"],
90 "description": "The operation to perform",
91 },
92 "a": {
93 "type": "number",
94 "description": "First operand",
95 },
96 "b": {
97 "type": "number",
98 "description": "Second operand",
99 },
100 },
101 "required": ["operation", "a", "b"],
102 },
103 execute=calculate,
105​
106​
107async def main():
108 """Main example function."""
109 # Set up the Anthropic adapter
110 adapter = AnthropicAdapter(
111 AIAdapterConfig(
112 api_key=os.environ.get("ANTHROPIC_API_KEY"),
113 )
114 )
115​
116 # Example 1: Simple chat without tools
117 print("=" * 80)
118 print("Example 1: Simple chat without tools")
119 print("=" * 80)
121 async for chunk in chat(
122 adapter=adapter,
123 model="claude-3-5-sonnet-20241022",
124 messages=[
125 {"role": "user", "content": "Write a haiku about programming."}
126 ],
127 ):
128 if chunk["type"] == "content":
129 print(chunk["delta"], end="", flush=True)
130 elif chunk["type"] == "done":
131 print("\n\nFinish reason:", chunk.get("finishReason"))
132 if chunk.get("usage"):
133 print("Tokens used:", chunk["usage"])
135 print("\n")
136​
137 # Example 2: Chat with automatic tool execution
138 print("=" * 80)
139 print("Example 2: Chat with automatic tool execution")
140 print("=" * 80)
142 async for chunk in chat(
143 adapter=adapter,
144 model="claude-3-5-sonnet-20241022",
145 messages=[
146 {
147 "role": "user",
148 "content": "What's the weather in San Francisco and what's 15 + 27?",
149 }
150 ],
151 tools=[weather_tool, calculator_tool],
152 agent_loop_strategy=max_iterations(5),
153 ):
154 chunk_type = chunk["type"]
156 if chunk_type == "content":
157 print(chunk["delta"], end="", flush=True)
158 elif chunk_type == "tool_call":
159 print(f"\n[Tool Call: {chunk['toolCall']['function']['name']}]")
160 elif chunk_type == "tool_result":
161 print(f"[Tool Result: {chunk['content'][:100]}...]")
162 elif chunk_type == "done":
163 print("\n\nFinish reason:", chunk.get("finishReason"))
164 if chunk.get("usage"):
165 print("Tokens used:", chunk["usage"])
166 elif chunk_type == "error":
167 print(f"\n[Error: {chunk['error']['message']}]")
169 print("\n")
170​
171 # Example 3: Multi-turn conversation with tools
172 print("=" * 80)
173 print("Example 3: Multi-turn conversation with tools")
174 print("=" * 80)
176 messages = [
177 {"role": "user", "content": "What's the weather in New York?"},
178 ]
180 # First turn
181 async for chunk in chat(
182 adapter=adapter,
183 model="claude-3-5-sonnet-20241022",
184 messages=messages,
185 tools=[weather_tool],
186 ):
187 if chunk["type"] == "content":
188 print(chunk["delta"], end="", flush=True)
189 elif chunk["type"] == "done":
190 print("\n")
192 # Add assistant's response to messages (simplified - in production, collect full response)
193 messages.append({
194 "role": "assistant",
195 "content": "The weather in New York is sunny with a temperature of 72°F.",
196 })
198 # Second turn
199 messages.append({
200 "role": "user",
201 "content": "How about Los Angeles?",
202 })
204 async for chunk in chat(
205 adapter=adapter,
206 model="claude-3-5-sonnet-20241022",
207 messages=messages,
208 tools=[weather_tool],
209 ):
210 if chunk["type"] == "content":
211 print(chunk["delta"], end="", flush=True)
212 elif chunk["type"] == "done":
213 print("\n")
214​
215​
216if __name__ == "__main__":
217 # Run the example
218 asyncio.run(main())