-
Notifications
You must be signed in to change notification settings - Fork 10
Expand file tree
/
Copy pathtool_calling_example.py
More file actions
192 lines (156 loc) · 5.96 KB
/
tool_calling_example.py
File metadata and controls
192 lines (156 loc) · 5.96 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
#!/usr/bin/env python3
"""
tool_calling_example.py: CLI for tool/function calling with ai-sdk.
Usage: tool_calling_example.py --a INT --b INT [--provider openai|anthropic] [--model MODEL_ID] [--use-pydantic]
"""
import os
import argparse
from pydantic import BaseModel, Field
from typing import Optional, List
from ai_sdk import openai, anthropic, generate_text, tool
try:
from dotenv import load_dotenv # type: ignore
except Exception: # pragma: no cover
def load_dotenv() -> None: # type: ignore
return None
# ---------------------------------------------------------------------------
# Tool definitions with both JSON schema and Pydantic models
# ---------------------------------------------------------------------------
# JSON Schema approach (legacy)
def add_exec(a: int, b: int) -> int:
return a + b
add_tool_json = tool(
name="add",
description="Add two integers.",
parameters={
"type": "object",
"properties": {"a": {"type": "integer"}, "b": {"type": "integer"}},
"required": ["a", "b"],
},
execute=add_exec,
)
# Pydantic model approach (recommended)
class AddParams(BaseModel):
a: int = Field(description="First integer to add")
b: int = Field(description="Second integer to add")
def add_exec_pydantic(a: int, b: int) -> int:
return a + b
add_tool_pydantic = tool(
name="add_pydantic",
description="Add two integers using Pydantic validation.",
parameters=AddParams,
execute=add_exec_pydantic,
)
# Complex Pydantic model example
class CalculatorParams(BaseModel):
a: float = Field(description="First number")
b: float = Field(description="Second number")
operation: str = Field(description="Mathematical operation", pattern="^[+\\-*/]$")
def calculator_exec(a: float, b: float, operation: str) -> float:
"""Perform basic mathematical operations."""
if operation == "+":
return a + b
elif operation == "-":
return a - b
elif operation == "*":
return a * b
elif operation == "/":
if b == 0:
raise ValueError("Division by zero")
return a / b
else:
raise ValueError(f"Unknown operation: {operation}")
calculator_tool = tool(
name="calculator",
description="Perform basic mathematical operations",
parameters=CalculatorParams,
execute=calculator_exec,
)
# User profile example with validation
class UserProfileParams(BaseModel):
name: str = Field(description="User's full name", min_length=1, max_length=100)
age: int = Field(description="User's age", ge=0, le=120)
email: Optional[str] = Field(default=None, description="User's email address")
interests: List[str] = Field(default_factory=list, description="User's interests")
is_active: bool = Field(default=True, description="Whether the user is active")
def create_user_profile_exec(
name: str,
age: int,
email: Optional[str] = None,
interests: Optional[List[str]] = None,
is_active: bool = True,
) -> dict:
"""Create a new user profile."""
return {
"id": f"user_{hash(name) % 10000}",
"name": name,
"age": age,
"email": email,
"interests": interests or [],
"is_active": is_active,
"created_at": "2024-01-01T00:00:00Z",
}
user_profile_tool = tool(
name="create_user_profile",
description="Create a new user profile with validation",
parameters=UserProfileParams,
execute=create_user_profile_exec,
)
def main():
load_dotenv()
parser = argparse.ArgumentParser(description="Tool calling CLI using ai-sdk.")
parser.add_argument("--a", type=int, required=True, help="First integer.")
parser.add_argument("--b", type=int, required=True, help="Second integer.")
parser.add_argument("--provider", choices=["openai", "anthropic"], default="openai")
parser.add_argument("--model", default=os.getenv("AI_SDK_MODEL", "gpt-4o-mini"))
parser.add_argument(
"--use-pydantic",
action="store_true",
help="Use Pydantic model instead of JSON schema",
)
parser.add_argument(
"--demo",
choices=["add", "calculator", "user-profile"],
default="add",
help="Demo to run",
)
args = parser.parse_args()
client = openai if args.provider == "openai" else anthropic
api_key_env = "OPENAI_API_KEY" if args.provider == "openai" else "ANTHROPIC_API_KEY"
model = client(args.model, api_key=os.getenv(api_key_env))
# Choose tool based on demo type and Pydantic preference
if args.demo == "add":
if args.use_pydantic:
tool_to_use = add_tool_pydantic
prompt = f"Use the 'add_pydantic' tool to compute the sum of {args.a} and {args.b}."
else:
tool_to_use = add_tool_json
prompt = f"Use the 'add' tool to compute the sum of {args.a} and {args.b}."
elif args.demo == "calculator":
tool_to_use = calculator_tool
prompt = f"Use the calculator tool to multiply {args.a} and {args.b}."
elif args.demo == "user-profile":
tool_to_use = user_profile_tool
prompt = (
"Create a user profile for Alice, age 30, with interests in Python and AI."
)
else:
raise ValueError(f"Unknown demo: {args.demo}")
print(
f"Running {args.demo} demo with {'Pydantic' if args.use_pydantic else 'JSON schema'} approach..."
)
print(f"Provider: {args.provider}, Model: {args.model}")
print(f"Prompt: {prompt}")
print("-" * 50)
res = generate_text(model=model, prompt=prompt, tools=[tool_to_use])
print("Response:", res.text)
# Show tool information
print("\nTool Information:")
print(f" Name: {tool_to_use.name}")
print(f" Description: {tool_to_use.description}")
print(f" Uses Pydantic: {tool_to_use._pydantic_model is not None}")
if tool_to_use._pydantic_model:
print(f" Pydantic Model: {tool_to_use._pydantic_model.__name__}")
print(f" JSON Schema: {tool_to_use.parameters}")
if __name__ == "__main__":
main()