Debian Codegraph @

examples/tools_runner_search_tool.py

raw
1 import json
2 from typing import Any, List
3 from typing_extensions import Literal
4
5 import rich
6
7 from anthropic import Anthropic, beta_tool
8 from anthropic.lib.tools import BetaFunctionTool, BetaFunctionToolResultType
9 from anthropic.types.beta import BetaToolReferenceBlockParam
10
11 client = Anthropic()
12
13
14 @beta_tool(defer_loading=True)
15 def get_weather(location: str, units: Literal["c", "f"]) -> str:
16 """Lookup the weather for a given city in either celsius or fahrenheit
17
18 Args:
19 location: The city and state, e.g. San Francisco, CA
20 units: Unit for the output, either 'c' for celsius or 'f' for fahrenheit
21 Returns:
22 A dictionary containing the location, temperature, and weather condition.
23 """
24 # Simulate a weather API call
25 print(f"Fetching weather for {location} in {units}")
26
27 # Here you would typically make an API call to a weather service
28 # For demonstration, we return a mock response
29 if units == "c":
30 return json.dumps(
31 {
32 "location": location,
33 "temperature": "20°C",
34 "condition": "Sunny",
35 }
36 )
37 else:
38 return json.dumps(
39 {
40 "location": location,
41 "temperature": "68°F",
42 "condition": "Sunny",
43 }
44 )
45
46
47 def make_tool_searcher(tools: List[BetaFunctionTool[Any]]) -> BetaFunctionTool[Any]:
48 """Returns a tool that Claude can use to search through all available tools"""
49
50 @beta_tool
51 def search_available_tools(*, keyword: str) -> BetaFunctionToolResultType:
52 """Search for useful tools using a query string"""
53
54 results: list[BetaToolReferenceBlockParam] = []
55 for tool in tools:
56 if keyword in json.dumps(tool.to_dict()):
57 results.append({"type": "tool_reference", "tool_name": tool.name})
58
59 return results
60
61 return search_available_tools
62
63
64 def main() -> None:
65 tools: list[BetaFunctionTool[Any]] = [
66 get_weather,
67 # ... many more tools
68 ]
69 runner = client.beta.messages.tool_runner(
70 max_tokens=1024,
71 model="claude-sonnet-5",
72 tools=[*tools, make_tool_searcher(tools)],
73 messages=[{"role": "user", "content": "What is the weather in SF?"}],
74 betas=["tool-search-tool-2025-10-19"],
75 )
76 for message in runner:
77 rich.print(message)
78
79
80 main()