1from typing import Any
2import json
3
4
5TOOLS = [
6 {
7 "name": "get_weather",
8 "description": "Get the current weather for a location",
9 "parameters": {
10 "type": "object",
11 "properties": {
12 "city": {
13 "type": "string",
14 "description": "The city name"
15 },
16 "unit": {
17 "type": "string",
18 "enum": ["celsius", "fahrenheit"],
19 "default": "celsius"
20 }
21 },
22 "required": ["city"]
23 }
24 },
25 {
26 "name": "search_web",
27 "description": "Search the web for information",
28 "parameters": {
29 "type": "object",
30 "properties": {
31 "query": {
32 "type": "string",
33 "description": "The search query"
34 }
35 },
36 "required": ["query"]
37 }
38 }
39]
40
41
42def get_weather(city: str, unit: str = "celsius") -> dict:
43 """Simulated weather API."""
44 return {
45 "city": city,
46 "temperature": 22 if unit == "celsius" else 72,
47 "unit": unit,
48 "condition": "sunny"
49 }
50
51def search_web(query: str) -> dict:
52 """Simulated search."""
53 return {
54 "query": query,
55 "results": [
56 {"title": "Result 1", "url": "https://example.com/1"},
57 {"title": "Result 2", "url": "https://example.com/2"}
58 ]
59 }
60
61
62TOOL_FUNCTIONS = {
63 "get_weather": get_weather,
64 "search_web": search_web
65}
66
67def execute_tool(tool_name: str, arguments: dict) -> Any:
68 """Execute a tool by name with given arguments."""
69 if tool_name not in TOOL_FUNCTIONS:
70 raise ValueError(f"Unknown tool: {tool_name}")
71
72 func = TOOL_FUNCTIONS[tool_name]
73 return func(**arguments)
74
75
76print("Available tools:")
77for tool in TOOLS:
78 print(f" • {tool['name']}: {tool['description']}")
79
80
81tool_call = {
82 "name": "get_weather",
83 "arguments": {"city": "San Francisco", "unit": "celsius"}
84}
85
86print(f"\nTool call: {tool_call['name']}")
87print(f"Arguments: {tool_call['arguments']}")
88
89result = execute_tool(tool_call["name"], tool_call["arguments"])
90print(f"Result: {json.dumps(result, indent=2)}")