Debian Codegraph @

examples/tools_runner.py

raw
1 import json
2 from typing_extensions import Literal
3
4 import rich
5
6 from anthropic import Anthropic, beta_tool
7
8 client = Anthropic()
9
10
11 @beta_tool
12 def get_weather(location: str, units: Literal["c", "f"]) -> str:
13 """Lookup the weather for a given city in either celsius or fahrenheit
14
15 Args:
16 location: The city and state, e.g. San Francisco, CA
17 units: Unit for the output, either 'c' for celsius or 'f' for fahrenheit
18 Returns:
19 A dictionary containing the location, temperature, and weather condition.
20 """
21 # Simulate a weather API call
22 print(f"Fetching weather for {location} in {units}")
23
24 # Here you would typically make an API call to a weather service
25 # For demonstration, we return a mock response
26 if units == "c":
27 return json.dumps(
28 {
29 "location": location,
30 "temperature": "20°C",
31 "condition": "Sunny",
32 }
33 )
34 else:
35 return json.dumps(
36 {
37 "location": location,
38 "temperature": "68°F",
39 "condition": "Sunny",
40 }
41 )
42
43
44 def main() -> None:
45 runner = client.beta.messages.tool_runner(
46 max_tokens=1024,
47 model="claude-sonnet-5-5",
48 # alternatively, you can use `tools=[anthropic.beta_tool(get_weather)]`
49 tools=[get_weather],
50 messages=[{"role": "user", "content": "What is the weather in SF?"}],
51 )
52 for message in runner:
53 rich.print(message)
54
55
56 main()