Debian Codegraph @

examples/tools_runner_deferred_streaming.py

raw
1 from anthropic import Anthropic, beta_tool
2
3 client = Anthropic()
4
5
6 @beta_tool
7 def list_files(directory: str) -> str:
8 """List the files in a directory.
9
10 Args:
11 directory: The directory to list.
12 """
13 return f"{directory}/app.log\n{directory}/notes.txt"
14
15
16 @beta_tool
17 def delete_file(path: str) -> str:
18 """Delete a file.
19
20 Args:
21 path: The file to delete.
22 """
23 return f"Deleted {path}."
24
25
26 def main() -> None:
27 runner = client.beta.messages.tool_runner(
28 model="claude-sonnet-5",
29 max_tokens=1024,
30 max_iterations=10,
31 tools=[list_files, delete_file],
32 messages=[{"role": "user", "content": "List the files in /tmp/demo, then delete the ones that end in .log."}],
33 stream=True,
34 run_tools_eagerly=True,
35 )
36
37 for stream in runner:
38 # `list_files` runs while the reply is still streaming. A `delete_file` call waits for the answer below.
39 for event in stream:
40 if event.type == "content_block_start" and event.content_block.type == "tool_use":
41 if event.content_block.name == "delete_file":
42 runner.defer_tool_call(event.content_block)
43 elif event.type == "text":
44 print(event.text, end="", flush=True)
45
46 held = runner.deferred_tool_calls
47 if not held:
48 continue
49
50 print("\nThe model wants to run:")
51 for tool_use in held:
52 print(f" {tool_use.name}({tool_use.input})")
53 if input("Allow? [y/N] ").strip().lower() != "y":
54 print("Stopped before running them.")
55 break
56 # The held calls run when this loop body ends.
57
58
59 main()