Debian Codegraph @

examples/managed-agents-observe-tool-calls.py

raw
1 #!/usr/bin/env python3
2 """Observe every tool call with the low-level session tool runner.
3
4 `client.beta.sessions.events.tool_runner(...)` is the "observe every call"
5 path: an async iterable that attaches to a session's event stream, runs the
6 matching local tool for each tool-call event, posts the result back, and yields
7 one `DispatchedToolCall` per completed call. It does NOT manage a work-item
8 lease — `EnvironmentWorker` is what does that.
9
10 This file has two scenarios:
11
12 main() — the primary entry point. A session you created and drive yourself:
13 no work queue, no lease, not necessarily self-hosted. Create an
14 agent + session, send a prompt, then iterate tool_runner and print
15 each dispatched tool call. Reach for this when you just want to see
16 (or audit, or react to) each tool call on a session you own.
17
18 observe_as_self_hosted_worker() — a second scenario, NOT called by default.
19 The shape to use when you *are* a self-hosted worker: it composes
20 the work poller + the agent tool context + your OWN heartbeat task
21 running in parallel with the tool_runner loop. Reach for this only
22 when you need per-call visibility AND lease management together —
23 otherwise `EnvironmentWorker` already does both for you.
24
25 Security model: the tools execute bash and file operations directly on the host.
26 Run inside a container or other isolation boundary you control.
27 """
28
29 from __future__ import annotations
30
31 import os
32 import sys
33 import asyncio
34 import logging
35
36 import anyio
37
38 from anthropic import AsyncAnthropic
39 from anthropic.lib.environments import MANAGED_AGENTS_BETA
40 from anthropic.lib.tools.agent_toolset import AgentToolContext, beta_agent_toolset_20260401
41
42 MODEL_ID = "claude-haiku-4-5"
43
44
45 def _require_env(name: str) -> str:
46 val = os.environ.get(name)
47 if not val:
48 sys.exit(f"error: environment variable {name} is required")
49 return val
50
51
52 async def main() -> None:
53 """Primary scenario: drive a session yourself and watch each tool call.
54
55 No work queue and no lease are involved — we create the session, send a
56 prompt, and consume `tool_runner` directly. tool_runner is passed no
57 `environment_key`, so it authenticates with the client's own credentials;
58 that makes this scenario work against a non-self-hosted environment too.
59 """
60 logging.basicConfig(level=logging.INFO)
61 client = AsyncAnthropic()
62
63 environment_id = _require_env("ANTHROPIC_ENVIRONMENT_ID")
64 workdir = os.environ.get("ANTHROPIC_WORKDIR", ".")
65
66 # 1. Create an agent with the built-in agent toolset.
67 agent = await client.beta.agents.create(
68 name="observe-tool-calls-example",
69 model={"id": MODEL_ID},
70 system="You are a test agent. Use the available tools to answer.",
71 tools=[{"type": "agent_toolset_20260401"}],
72 )
73 print(f"created agent {agent.id}")
74
75 # 2. Create a session. A session always lives in an environment, but here we
76 # just create it and drive its tool calls ourselves — there is no work
77 # item and no lease to manage.
78 session = await client.beta.sessions.create(
79 agent=agent.id,
80 environment_id=environment_id,
81 title="observe-tool-calls-example",
82 betas=[MANAGED_AGENTS_BETA],
83 )
84 print(f"created session {session.id}")
85
86 try:
87 # 3. Send a prompt that will make the agent call a tool or two.
88 await client.beta.sessions.events.send(
89 session.id,
90 events=[
91 {
92 "type": "user.message",
93 "content": [{"type": "text", "text": "Run pwd and then ls to show me the working directory."}],
94 }
95 ],
96 betas=[MANAGED_AGENTS_BETA],
97 )
98
99 # 4. Observe every dispatched tool call. tool_runner attaches to the
100 # session's event stream, runs the matching local tool for each
101 # tool-call event, posts the result back, and yields one
102 # DispatchedToolCall per completed call. AgentToolContext gives the
103 # tools their workdir; passing client + session also downloads the
104 # session agent's skills into the workdir before the first tool runs.
105 print("\n--- dispatched tool calls ---")
106 async with AgentToolContext(workdir=workdir, client=client, session=session) as env:
107 async for call in client.beta.sessions.events.tool_runner(
108 session.id,
109 tools=beta_agent_toolset_20260401(env),
110 ):
111 print(f" {call.name} {call.event.input} is_error={call.is_error} posted={call.posted}")
112
113 finally:
114 # 5. Clean up the session.
115 await client.beta.sessions.delete(session.id, betas=[MANAGED_AGENTS_BETA])
116 print(f"\ndeleted session {session.id}")
117
118
119 async def observe_as_self_hosted_worker() -> None:
120 """Secondary scenario — NOT called by main(); shown for reference.
121
122 Use this shape when you *are* a self-hosted worker (you poll a work queue and
123 hold a work-item lease) but you also want per-call visibility into every
124 dispatched tool call.
125
126 tool_runner does NOT manage the work-item lease — EnvironmentWorker does.
127 EnvironmentWorker.run() / .handle_item() already run a tool_runner internally
128 while heartbeating the lease and force-stopping the work on exit, so reach
129 for them unless you specifically need to see each call. Rolling your own
130 heartbeat, as below, is the cost of getting per-call visibility AND lease
131 management together.
132
133 NOTE: the heartbeat loop here is a deliberately simplified shape — just
134 enough to keep the lease warm while the session runs. EnvironmentWorker's
135 internal heartbeat is the careful reference: it bounds each request,
136 distinguishes transient from fatal failures, and assumes the lease lost after
137 a TTL of failed beats so two workers never end up serving the same item.
138 """
139 logging.basicConfig(level=logging.INFO)
140 client = AsyncAnthropic()
141
142 environment_id = _require_env("ANTHROPIC_ENVIRONMENT_ID")
143 environment_key = _require_env("ANTHROPIC_ENVIRONMENT_KEY")
144
145 async def heartbeat(work_id: str, env_id: str, stop: anyio.Event) -> None:
146 # Scope the environment key onto a sub-client so each request carries
147 # `Authorization: Bearer <env_key>` and no `X-Api-Key`, inheriting the
148 # parent's timeout / retries / http_client / default_headers. This is
149 # what `EnvironmentWorker` does internally for its heartbeat.
150 scoped = client.copy(auth_token=environment_key, credentials=None)
151 scoped.api_key = None
152 # The first beat claims the lease with NO_HEARTBEAT; later beats echo
153 # the server's last value back.
154 last = "NO_HEARTBEAT"
155 while not stop.is_set():
156 resp = await scoped.beta.environments.work.heartbeat(
157 work_id,
158 environment_id=env_id,
159 expected_last_heartbeat=last,
160 )
161 last = resp.last_heartbeat
162 if resp.state in ("stopping", "stopped") or not resp.lease_extended:
163 stop.set()
164 return
165 # Beat at roughly half the lease TTL; wake immediately if we stop.
166 interval = resp.ttl_seconds / 2 if resp.ttl_seconds > 0 else 30.0
167 with anyio.move_on_after(interval):
168 await stop.wait()
169
170 # The poller claims + acks each work item; with auto_stop=True (the default)
171 # it also calls work.stop when our loop body returns. The lease heartbeat is
172 # the part tool_runner does not do, so we run it ourselves alongside the loop.
173 async for work in client.beta.environments.work.poller(
174 environment_id=environment_id,
175 environment_key=environment_key,
176 ):
177 session_id = work.data.id
178
179 # Fetch the session once and hand it to AgentToolContext: on enter it
180 # downloads each of the session agent's skills into the workdir.
181 session = await client.beta.sessions.retrieve(session_id)
182 async with AgentToolContext(workdir="/workspace", client=client, session=session) as env:
183 async with anyio.create_task_group() as tg:
184 stop = anyio.Event()
185 tg.start_soon(heartbeat, work.id, work.environment_id, stop)
186 try:
187 # Pass environment_key so the event stream / list / send
188 # calls authenticate as the environment, like the worker does.
189 async for call in client.beta.sessions.events.tool_runner(
190 session_id,
191 tools=beta_agent_toolset_20260401(env),
192 environment_key=environment_key,
193 ):
194 print(f" {call.name} {call.event.input} is_error={call.is_error} posted={call.posted}")
195 finally:
196 # Stop the heartbeat and tear the task group down once the
197 # session's tool calls are done (or the loop raised).
198 stop.set()
199 tg.cancel_scope.cancel()
200
201
202 if __name__ == "__main__":
203 asyncio.run(main())