| 1 |
from __future__ import annotations |
| 2 |
|
| 3 |
from typing import TYPE_CHECKING, Any, List, Union, Iterable, cast |
| 4 |
from datetime import datetime |
| 5 |
from itertools import chain |
| 6 |
from typing_extensions import Literal |
| 7 |
|
| 8 |
import httpx2 |
| 9 |
|
| 10 |
if TYPE_CHECKING: |
| 11 |
from collections.abc import Sequence |
| 12 |
|
| 13 |
from ...._client import AsyncAnthropic |
| 14 |
from ....lib.tools._beta_session_runner import SessionToolRunner, BetaAnyRunnableTool |
| 15 |
|
| 16 |
from ...._types import Body, Omit, Query, Headers, NotGiven, SequenceNotStr, omit, not_given |
| 17 |
from ...._utils import is_given, path_template, strip_not_given |
| 18 |
from ...._compat import cached_property |
| 19 |
from ...._resource import SyncAPIResource, AsyncAPIResource |
| 20 |
from ...._response import ( |
| 21 |
to_raw_response_wrapper, |
| 22 |
to_streamed_response_wrapper, |
| 23 |
async_to_raw_response_wrapper, |
| 24 |
async_to_streamed_response_wrapper, |
| 25 |
) |
| 26 |
from ...._streaming import Stream, AsyncStream |
| 27 |
from ....pagination import SyncPageCursor, AsyncPageCursor |
| 28 |
from ...._base_client import AsyncPaginator, make_request_options |
| 29 |
from ....types.anthropic_beta_param import AnthropicBetaParam |
| 30 |
from ....types.beta.beta_managed_agents_delta_type import BetaManagedAgentsDeltaType |
| 31 |
from ....types.beta.sessions.beta_managed_agents_event_params import BetaManagedAgentsEventParams |
| 32 |
from ....types.beta.sessions.beta_managed_agents_session_event import BetaManagedAgentsSessionEvent |
| 33 |
from ....types.beta.sessions.beta_managed_agents_send_session_events import BetaManagedAgentsSendSessionEvents |
| 34 |
from ....types.beta.sessions.beta_managed_agents_stream_session_events import BetaManagedAgentsStreamSessionEvents |
| 35 |
|
| 36 |
__all__ = ["Events", "AsyncEvents"] |
| 37 |
|
| 38 |
|
| 39 |
class Events(SyncAPIResource): |
| 40 |
@cached_property |
| 41 |
def with_raw_response(self) -> EventsWithRawResponse: |
| 42 |
""" |
| 43 |
This property can be used as a prefix for any HTTP method call to return |
| 44 |
the raw response object instead of the parsed content. |
| 45 |
|
| 46 |
For more information, see https://www.github.com/anthropics/anthropic-sdk-python#accessing-raw-response-data-eg-headers |
| 47 |
""" |
| 48 |
return EventsWithRawResponse(self) |
| 49 |
|
| 50 |
@cached_property |
| 51 |
def with_streaming_response(self) -> EventsWithStreamingResponse: |
| 52 |
""" |
| 53 |
An alternative to `.with_raw_response` that doesn't eagerly read the response body. |
| 54 |
|
| 55 |
For more information, see https://www.github.com/anthropics/anthropic-sdk-python#with_streaming_response |
| 56 |
""" |
| 57 |
return EventsWithStreamingResponse(self) |
| 58 |
|
| 59 |
def list( |
| 60 |
self, |
| 61 |
session_id: str, |
| 62 |
*, |
| 63 |
created_at_gt: Union[str, datetime] | Omit = omit, |
| 64 |
created_at_gte: Union[str, datetime] | Omit = omit, |
| 65 |
created_at_lt: Union[str, datetime] | Omit = omit, |
| 66 |
created_at_lte: Union[str, datetime] | Omit = omit, |
| 67 |
limit: int | Omit = omit, |
| 68 |
order: Literal["asc", "desc"] | Omit = omit, |
| 69 |
page: str | Omit = omit, |
| 70 |
types: SequenceNotStr[str] | Omit = omit, |
| 71 |
betas: List[AnthropicBetaParam] | Omit = omit, |
| 72 |
workspace_id: str | Omit = omit, |
| 73 |
# Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. |
| 74 |
# The extra values given here take precedence over values defined on the client or passed to this method. |
| 75 |
extra_headers: Headers | None = None, |
| 76 |
extra_query: Query | None = None, |
| 77 |
extra_body: Body | None = None, |
| 78 |
timeout: float | httpx2.Timeout | None | NotGiven = not_given, |
| 79 |
) -> SyncPageCursor[BetaManagedAgentsSessionEvent]: |
| 80 |
""" |
| 81 |
List Events |
| 82 |
|
| 83 |
Args: |
| 84 |
created_at_gt: Return events created after this time (exclusive). Compared against the event's |
| 85 |
`processed_at` value. |
| 86 |
|
| 87 |
created_at_gte: Return events created at or after this time (inclusive). Compared against the |
| 88 |
event's `processed_at` value. |
| 89 |
|
| 90 |
created_at_lt: Return events created before this time (exclusive). Compared against the event's |
| 91 |
`processed_at` value. |
| 92 |
|
| 93 |
created_at_lte: Return events created at or before this time (inclusive). Compared against the |
| 94 |
event's `processed_at` value. |
| 95 |
|
| 96 |
order: Sort direction for results, ordered by the event's `processed_at`. Defaults to |
| 97 |
`asc` (chronological). |
| 98 |
|
| 99 |
page: Opaque pagination cursor from a previous response's `next_page`. |
| 100 |
|
| 101 |
types: Filter by event type. Values match the `type` field on returned events (for |
| 102 |
example, `user.message` or `agent.tool_use`). Omit to return all event types. |
| 103 |
|
| 104 |
betas: Optional header to specify the beta version(s) you want to use. |
| 105 |
|
| 106 |
workspace_id: Optional header to select the Workspace for this request. The value is a |
| 107 |
Workspace ID (for example, `wrkspc_011CZkZaBF1tNoB5wlCeusgy`). |
| 108 |
|
| 109 |
Only needed for credentials that can act on more than one Workspace. A |
| 110 |
credential that belongs to a specific Workspace may omit it; if sent, it must |
| 111 |
match that Workspace. |
| 112 |
|
| 113 |
extra_headers: Send extra headers |
| 114 |
|
| 115 |
extra_query: Add additional query parameters to the request |
| 116 |
|
| 117 |
extra_body: Add additional JSON properties to the request |
| 118 |
|
| 119 |
timeout: Override the client-level default timeout for this request, in seconds |
| 120 |
""" |
| 121 |
if not session_id: |
| 122 |
raise ValueError(f"Expected a non-empty value for `session_id` but received {session_id!r}") |
| 123 |
extra_headers = { |
| 124 |
**strip_not_given( |
| 125 |
{ |
| 126 |
"anthropic-beta": ",".join(chain((str(e) for e in betas), ["managed-agents-2026-04-01"])) |
| 127 |
if is_given(betas) |
| 128 |
else not_given, |
| 129 |
"anthropic-workspace-id": workspace_id, |
| 130 |
} |
| 131 |
), |
| 132 |
**(extra_headers or {}), |
| 133 |
} |
| 134 |
extra_headers = {"anthropic-beta": "managed-agents-2026-04-01", **(extra_headers or {})} |
| 135 |
return self._get_api_list( |
| 136 |
path_template("/v1/sessions/{session_id}/events?beta=true", session_id=session_id), |
| 137 |
page=SyncPageCursor[BetaManagedAgentsSessionEvent], |
| 138 |
options=make_request_options( |
| 139 |
extra_headers=extra_headers, |
| 140 |
extra_query=extra_query, |
| 141 |
extra_body=extra_body, |
| 142 |
timeout=timeout, |
| 143 |
query={ |
| 144 |
"created_at[gt]": created_at_gt, |
| 145 |
"created_at[gte]": created_at_gte, |
| 146 |
"created_at[lt]": created_at_lt, |
| 147 |
"created_at[lte]": created_at_lte, |
| 148 |
"limit": limit, |
| 149 |
"order": order, |
| 150 |
"page": page, |
| 151 |
"types": types, |
| 152 |
}, |
| 153 |
), |
| 154 |
model=cast( |
| 155 |
Any, BetaManagedAgentsSessionEvent |
| 156 |
), # Union types cannot be passed in as arguments in the type system |
| 157 |
) |
| 158 |
|
| 159 |
def send( |
| 160 |
self, |
| 161 |
session_id: str, |
| 162 |
*, |
| 163 |
events: Iterable[BetaManagedAgentsEventParams], |
| 164 |
betas: List[AnthropicBetaParam] | Omit = omit, |
| 165 |
workspace_id: str | Omit = omit, |
| 166 |
# Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. |
| 167 |
# The extra values given here take precedence over values defined on the client or passed to this method. |
| 168 |
extra_headers: Headers | None = None, |
| 169 |
extra_query: Query | None = None, |
| 170 |
extra_body: Body | None = None, |
| 171 |
timeout: float | httpx2.Timeout | None | NotGiven = not_given, |
| 172 |
) -> BetaManagedAgentsSendSessionEvents: |
| 173 |
""" |
| 174 |
Send Events |
| 175 |
|
| 176 |
Args: |
| 177 |
events: Events to send to the `session`. |
| 178 |
|
| 179 |
betas: Optional header to specify the beta version(s) you want to use. |
| 180 |
|
| 181 |
workspace_id: Optional header to select the Workspace for this request. The value is a |
| 182 |
Workspace ID (for example, `wrkspc_011CZkZaBF1tNoB5wlCeusgy`). |
| 183 |
|
| 184 |
Only needed for credentials that can act on more than one Workspace. A |
| 185 |
credential that belongs to a specific Workspace may omit it; if sent, it must |
| 186 |
match that Workspace. |
| 187 |
|
| 188 |
extra_headers: Send extra headers |
| 189 |
|
| 190 |
extra_query: Add additional query parameters to the request |
| 191 |
|
| 192 |
extra_body: Add additional JSON properties to the request |
| 193 |
|
| 194 |
timeout: Override the client-level default timeout for this request, in seconds |
| 195 |
""" |
| 196 |
if not session_id: |
| 197 |
raise ValueError(f"Expected a non-empty value for `session_id` but received {session_id!r}") |
| 198 |
extra_headers = { |
| 199 |
**strip_not_given( |
| 200 |
{ |
| 201 |
"anthropic-beta": ",".join(chain((str(e) for e in betas), ["managed-agents-2026-04-01"])) |
| 202 |
if is_given(betas) |
| 203 |
else not_given, |
| 204 |
"anthropic-workspace-id": workspace_id, |
| 205 |
} |
| 206 |
), |
| 207 |
**(extra_headers or {}), |
| 208 |
} |
| 209 |
extra_headers = {"anthropic-beta": "managed-agents-2026-04-01", **(extra_headers or {})} |
| 210 |
return self._post( |
| 211 |
path_template("/v1/sessions/{session_id}/events?beta=true", session_id=session_id), |
| 212 |
body={"events": events}, |
| 213 |
options=make_request_options( |
| 214 |
extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout |
| 215 |
), |
| 216 |
cast_to=BetaManagedAgentsSendSessionEvents, |
| 217 |
) |
| 218 |
|
| 219 |
def stream( |
| 220 |
self, |
| 221 |
session_id: str, |
| 222 |
*, |
| 223 |
event_deltas: List[BetaManagedAgentsDeltaType] | Omit = omit, |
| 224 |
betas: List[AnthropicBetaParam] | Omit = omit, |
| 225 |
workspace_id: str | Omit = omit, |
| 226 |
# Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. |
| 227 |
# The extra values given here take precedence over values defined on the client or passed to this method. |
| 228 |
extra_headers: Headers | None = None, |
| 229 |
extra_query: Query | None = None, |
| 230 |
extra_body: Body | None = None, |
| 231 |
timeout: float | httpx2.Timeout | None | NotGiven = not_given, |
| 232 |
) -> Stream[BetaManagedAgentsStreamSessionEvents]: |
| 233 |
""" |
| 234 |
Stream Events |
| 235 |
|
| 236 |
Args: |
| 237 |
event_deltas: When set, this connection also receives streaming deltas (`event_start`, |
| 238 |
`event_delta`) while an event is being produced, before the event itself |
| 239 |
arrives. Deltas are best-effort; when the final event is produced it carries the |
| 240 |
complete content. A model request that ends early (an error or interrupt) |
| 241 |
produces no final event — its terminal `span.model_request_end` closes the |
| 242 |
preview. Accepts one or more event types to preview and may be repeated: |
| 243 |
`agent.message` streams `content_delta` fragments; `agent.thinking` is |
| 244 |
start-only — a signal that the agent has begun extended thinking, concluded by |
| 245 |
the `agent.thinking` event itself. Only previews of the requested event types |
| 246 |
are sent. |
| 247 |
|
| 248 |
betas: Optional header to specify the beta version(s) you want to use. |
| 249 |
|
| 250 |
workspace_id: Optional header to select the Workspace for this request. The value is a |
| 251 |
Workspace ID (for example, `wrkspc_011CZkZaBF1tNoB5wlCeusgy`). |
| 252 |
|
| 253 |
Only needed for credentials that can act on more than one Workspace. A |
| 254 |
credential that belongs to a specific Workspace may omit it; if sent, it must |
| 255 |
match that Workspace. |
| 256 |
|
| 257 |
extra_headers: Send extra headers |
| 258 |
|
| 259 |
extra_query: Add additional query parameters to the request |
| 260 |
|
| 261 |
extra_body: Add additional JSON properties to the request |
| 262 |
|
| 263 |
timeout: Override the client-level default timeout for this request, in seconds |
| 264 |
""" |
| 265 |
if not session_id: |
| 266 |
raise ValueError(f"Expected a non-empty value for `session_id` but received {session_id!r}") |
| 267 |
extra_headers = { |
| 268 |
**strip_not_given( |
| 269 |
{ |
| 270 |
"anthropic-beta": ",".join(chain((str(e) for e in betas), ["managed-agents-2026-04-01"])) |
| 271 |
if is_given(betas) |
| 272 |
else not_given, |
| 273 |
"anthropic-workspace-id": workspace_id, |
| 274 |
} |
| 275 |
), |
| 276 |
**(extra_headers or {}), |
| 277 |
} |
| 278 |
extra_headers = {"anthropic-beta": "managed-agents-2026-04-01", **(extra_headers or {})} |
| 279 |
return self._get( |
| 280 |
path_template("/v1/sessions/{session_id}/events/stream?beta=true", session_id=session_id), |
| 281 |
options=make_request_options( |
| 282 |
extra_headers=extra_headers, |
| 283 |
extra_query=extra_query, |
| 284 |
extra_body=extra_body, |
| 285 |
timeout=timeout, |
| 286 |
query={"event_deltas": event_deltas}, |
| 287 |
), |
| 288 |
cast_to=cast( |
| 289 |
Any, BetaManagedAgentsStreamSessionEvents |
| 290 |
), # Union types cannot be passed in as arguments in the type system |
| 291 |
stream=True, |
| 292 |
stream_cls=Stream[BetaManagedAgentsStreamSessionEvents], |
| 293 |
) |
| 294 |
|
| 295 |
|
| 296 |
class AsyncEvents(AsyncAPIResource): |
| 297 |
@cached_property |
| 298 |
def with_raw_response(self) -> AsyncEventsWithRawResponse: |
| 299 |
""" |
| 300 |
This property can be used as a prefix for any HTTP method call to return |
| 301 |
the raw response object instead of the parsed content. |
| 302 |
|
| 303 |
For more information, see https://www.github.com/anthropics/anthropic-sdk-python#accessing-raw-response-data-eg-headers |
| 304 |
""" |
| 305 |
return AsyncEventsWithRawResponse(self) |
| 306 |
|
| 307 |
@cached_property |
| 308 |
def with_streaming_response(self) -> AsyncEventsWithStreamingResponse: |
| 309 |
""" |
| 310 |
An alternative to `.with_raw_response` that doesn't eagerly read the response body. |
| 311 |
|
| 312 |
For more information, see https://www.github.com/anthropics/anthropic-sdk-python#with_streaming_response |
| 313 |
""" |
| 314 |
return AsyncEventsWithStreamingResponse(self) |
| 315 |
|
| 316 |
def list( |
| 317 |
self, |
| 318 |
session_id: str, |
| 319 |
*, |
| 320 |
created_at_gt: Union[str, datetime] | Omit = omit, |
| 321 |
created_at_gte: Union[str, datetime] | Omit = omit, |
| 322 |
created_at_lt: Union[str, datetime] | Omit = omit, |
| 323 |
created_at_lte: Union[str, datetime] | Omit = omit, |
| 324 |
limit: int | Omit = omit, |
| 325 |
order: Literal["asc", "desc"] | Omit = omit, |
| 326 |
page: str | Omit = omit, |
| 327 |
types: SequenceNotStr[str] | Omit = omit, |
| 328 |
betas: List[AnthropicBetaParam] | Omit = omit, |
| 329 |
workspace_id: str | Omit = omit, |
| 330 |
# Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. |
| 331 |
# The extra values given here take precedence over values defined on the client or passed to this method. |
| 332 |
extra_headers: Headers | None = None, |
| 333 |
extra_query: Query | None = None, |
| 334 |
extra_body: Body | None = None, |
| 335 |
timeout: float | httpx2.Timeout | None | NotGiven = not_given, |
| 336 |
) -> AsyncPaginator[BetaManagedAgentsSessionEvent, AsyncPageCursor[BetaManagedAgentsSessionEvent]]: |
| 337 |
""" |
| 338 |
List Events |
| 339 |
|
| 340 |
Args: |
| 341 |
created_at_gt: Return events created after this time (exclusive). Compared against the event's |
| 342 |
`processed_at` value. |
| 343 |
|
| 344 |
created_at_gte: Return events created at or after this time (inclusive). Compared against the |
| 345 |
event's `processed_at` value. |
| 346 |
|
| 347 |
created_at_lt: Return events created before this time (exclusive). Compared against the event's |
| 348 |
`processed_at` value. |
| 349 |
|
| 350 |
created_at_lte: Return events created at or before this time (inclusive). Compared against the |
| 351 |
event's `processed_at` value. |
| 352 |
|
| 353 |
order: Sort direction for results, ordered by the event's `processed_at`. Defaults to |
| 354 |
`asc` (chronological). |
| 355 |
|
| 356 |
page: Opaque pagination cursor from a previous response's `next_page`. |
| 357 |
|
| 358 |
types: Filter by event type. Values match the `type` field on returned events (for |
| 359 |
example, `user.message` or `agent.tool_use`). Omit to return all event types. |
| 360 |
|
| 361 |
betas: Optional header to specify the beta version(s) you want to use. |
| 362 |
|
| 363 |
workspace_id: Optional header to select the Workspace for this request. The value is a |
| 364 |
Workspace ID (for example, `wrkspc_011CZkZaBF1tNoB5wlCeusgy`). |
| 365 |
|
| 366 |
Only needed for credentials that can act on more than one Workspace. A |
| 367 |
credential that belongs to a specific Workspace may omit it; if sent, it must |
| 368 |
match that Workspace. |
| 369 |
|
| 370 |
extra_headers: Send extra headers |
| 371 |
|
| 372 |
extra_query: Add additional query parameters to the request |
| 373 |
|
| 374 |
extra_body: Add additional JSON properties to the request |
| 375 |
|
| 376 |
timeout: Override the client-level default timeout for this request, in seconds |
| 377 |
""" |
| 378 |
if not session_id: |
| 379 |
raise ValueError(f"Expected a non-empty value for `session_id` but received {session_id!r}") |
| 380 |
extra_headers = { |
| 381 |
**strip_not_given( |
| 382 |
{ |
| 383 |
"anthropic-beta": ",".join(chain((str(e) for e in betas), ["managed-agents-2026-04-01"])) |
| 384 |
if is_given(betas) |
| 385 |
else not_given, |
| 386 |
"anthropic-workspace-id": workspace_id, |
| 387 |
} |
| 388 |
), |
| 389 |
**(extra_headers or {}), |
| 390 |
} |
| 391 |
extra_headers = {"anthropic-beta": "managed-agents-2026-04-01", **(extra_headers or {})} |
| 392 |
return self._get_api_list( |
| 393 |
path_template("/v1/sessions/{session_id}/events?beta=true", session_id=session_id), |
| 394 |
page=AsyncPageCursor[BetaManagedAgentsSessionEvent], |
| 395 |
options=make_request_options( |
| 396 |
extra_headers=extra_headers, |
| 397 |
extra_query=extra_query, |
| 398 |
extra_body=extra_body, |
| 399 |
timeout=timeout, |
| 400 |
query={ |
| 401 |
"created_at[gt]": created_at_gt, |
| 402 |
"created_at[gte]": created_at_gte, |
| 403 |
"created_at[lt]": created_at_lt, |
| 404 |
"created_at[lte]": created_at_lte, |
| 405 |
"limit": limit, |
| 406 |
"order": order, |
| 407 |
"page": page, |
| 408 |
"types": types, |
| 409 |
}, |
| 410 |
), |
| 411 |
model=cast( |
| 412 |
Any, BetaManagedAgentsSessionEvent |
| 413 |
), # Union types cannot be passed in as arguments in the type system |
| 414 |
) |
| 415 |
|
| 416 |
async def send( |
| 417 |
self, |
| 418 |
session_id: str, |
| 419 |
*, |
| 420 |
events: Iterable[BetaManagedAgentsEventParams], |
| 421 |
betas: List[AnthropicBetaParam] | Omit = omit, |
| 422 |
workspace_id: str | Omit = omit, |
| 423 |
# Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. |
| 424 |
# The extra values given here take precedence over values defined on the client or passed to this method. |
| 425 |
extra_headers: Headers | None = None, |
| 426 |
extra_query: Query | None = None, |
| 427 |
extra_body: Body | None = None, |
| 428 |
timeout: float | httpx2.Timeout | None | NotGiven = not_given, |
| 429 |
) -> BetaManagedAgentsSendSessionEvents: |
| 430 |
""" |
| 431 |
Send Events |
| 432 |
|
| 433 |
Args: |
| 434 |
events: Events to send to the `session`. |
| 435 |
|
| 436 |
betas: Optional header to specify the beta version(s) you want to use. |
| 437 |
|
| 438 |
workspace_id: Optional header to select the Workspace for this request. The value is a |
| 439 |
Workspace ID (for example, `wrkspc_011CZkZaBF1tNoB5wlCeusgy`). |
| 440 |
|
| 441 |
Only needed for credentials that can act on more than one Workspace. A |
| 442 |
credential that belongs to a specific Workspace may omit it; if sent, it must |
| 443 |
match that Workspace. |
| 444 |
|
| 445 |
extra_headers: Send extra headers |
| 446 |
|
| 447 |
extra_query: Add additional query parameters to the request |
| 448 |
|
| 449 |
extra_body: Add additional JSON properties to the request |
| 450 |
|
| 451 |
timeout: Override the client-level default timeout for this request, in seconds |
| 452 |
""" |
| 453 |
if not session_id: |
| 454 |
raise ValueError(f"Expected a non-empty value for `session_id` but received {session_id!r}") |
| 455 |
extra_headers = { |
| 456 |
**strip_not_given( |
| 457 |
{ |
| 458 |
"anthropic-beta": ",".join(chain((str(e) for e in betas), ["managed-agents-2026-04-01"])) |
| 459 |
if is_given(betas) |
| 460 |
else not_given, |
| 461 |
"anthropic-workspace-id": workspace_id, |
| 462 |
} |
| 463 |
), |
| 464 |
**(extra_headers or {}), |
| 465 |
} |
| 466 |
extra_headers = {"anthropic-beta": "managed-agents-2026-04-01", **(extra_headers or {})} |
| 467 |
return await self._post( |
| 468 |
path_template("/v1/sessions/{session_id}/events?beta=true", session_id=session_id), |
| 469 |
body={"events": events}, |
| 470 |
options=make_request_options( |
| 471 |
extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout |
| 472 |
), |
| 473 |
cast_to=BetaManagedAgentsSendSessionEvents, |
| 474 |
) |
| 475 |
|
| 476 |
async def stream( |
| 477 |
self, |
| 478 |
session_id: str, |
| 479 |
*, |
| 480 |
event_deltas: List[BetaManagedAgentsDeltaType] | Omit = omit, |
| 481 |
betas: List[AnthropicBetaParam] | Omit = omit, |
| 482 |
workspace_id: str | Omit = omit, |
| 483 |
# Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. |
| 484 |
# The extra values given here take precedence over values defined on the client or passed to this method. |
| 485 |
extra_headers: Headers | None = None, |
| 486 |
extra_query: Query | None = None, |
| 487 |
extra_body: Body | None = None, |
| 488 |
timeout: float | httpx2.Timeout | None | NotGiven = not_given, |
| 489 |
) -> AsyncStream[BetaManagedAgentsStreamSessionEvents]: |
| 490 |
""" |
| 491 |
Stream Events |
| 492 |
|
| 493 |
Args: |
| 494 |
event_deltas: When set, this connection also receives streaming deltas (`event_start`, |
| 495 |
`event_delta`) while an event is being produced, before the event itself |
| 496 |
arrives. Deltas are best-effort; when the final event is produced it carries the |
| 497 |
complete content. A model request that ends early (an error or interrupt) |
| 498 |
produces no final event — its terminal `span.model_request_end` closes the |
| 499 |
preview. Accepts one or more event types to preview and may be repeated: |
| 500 |
`agent.message` streams `content_delta` fragments; `agent.thinking` is |
| 501 |
start-only — a signal that the agent has begun extended thinking, concluded by |
| 502 |
the `agent.thinking` event itself. Only previews of the requested event types |
| 503 |
are sent. |
| 504 |
|
| 505 |
betas: Optional header to specify the beta version(s) you want to use. |
| 506 |
|
| 507 |
workspace_id: Optional header to select the Workspace for this request. The value is a |
| 508 |
Workspace ID (for example, `wrkspc_011CZkZaBF1tNoB5wlCeusgy`). |
| 509 |
|
| 510 |
Only needed for credentials that can act on more than one Workspace. A |
| 511 |
credential that belongs to a specific Workspace may omit it; if sent, it must |
| 512 |
match that Workspace. |
| 513 |
|
| 514 |
extra_headers: Send extra headers |
| 515 |
|
| 516 |
extra_query: Add additional query parameters to the request |
| 517 |
|
| 518 |
extra_body: Add additional JSON properties to the request |
| 519 |
|
| 520 |
timeout: Override the client-level default timeout for this request, in seconds |
| 521 |
""" |
| 522 |
if not session_id: |
| 523 |
raise ValueError(f"Expected a non-empty value for `session_id` but received {session_id!r}") |
| 524 |
extra_headers = { |
| 525 |
**strip_not_given( |
| 526 |
{ |
| 527 |
"anthropic-beta": ",".join(chain((str(e) for e in betas), ["managed-agents-2026-04-01"])) |
| 528 |
if is_given(betas) |
| 529 |
else not_given, |
| 530 |
"anthropic-workspace-id": workspace_id, |
| 531 |
} |
| 532 |
), |
| 533 |
**(extra_headers or {}), |
| 534 |
} |
| 535 |
extra_headers = {"anthropic-beta": "managed-agents-2026-04-01", **(extra_headers or {})} |
| 536 |
return await self._get( |
| 537 |
path_template("/v1/sessions/{session_id}/events/stream?beta=true", session_id=session_id), |
| 538 |
options=make_request_options( |
| 539 |
extra_headers=extra_headers, |
| 540 |
extra_query=extra_query, |
| 541 |
extra_body=extra_body, |
| 542 |
timeout=timeout, |
| 543 |
query={"event_deltas": event_deltas}, |
| 544 |
), |
| 545 |
cast_to=cast( |
| 546 |
Any, BetaManagedAgentsStreamSessionEvents |
| 547 |
), # Union types cannot be passed in as arguments in the type system |
| 548 |
stream=True, |
| 549 |
stream_cls=AsyncStream[BetaManagedAgentsStreamSessionEvents], |
| 550 |
) |
| 551 |
|
| 552 |
def tool_runner( |
| 553 |
self, |
| 554 |
session_id: str, |
| 555 |
*, |
| 556 |
tools: Sequence[BetaAnyRunnableTool], |
| 557 |
max_idle: float | None | NotGiven = not_given, |
| 558 |
environment_key: str | None = None, |
| 559 |
extra_headers: Headers | None = None, |
| 560 |
) -> SessionToolRunner: |
| 561 |
"""Dispatch a self-hosted session's tool-call events. |
| 562 |
|
| 563 |
The sessions-side counterpart to `client.beta.messages.tool_runner`: |
| 564 |
returns a `anthropic.lib.environments.SessionToolRunner` — an |
| 565 |
async iterable that attaches to the session's event stream, reconciles |
| 566 |
against the events-list endpoint, runs the matching tool from `tools` |
| 567 |
for each tool-call event, posts the matching result event back, and |
| 568 |
yields one `anthropic.lib.environments.DispatchedToolCall` per |
| 569 |
completed call. It handles both tool-call kinds: `agent.tool_use` |
| 570 |
(built-in agent-toolset tools) answered with `user.tool_result`, and |
| 571 |
`agent.custom_tool_use` (custom, user-defined tools) answered with |
| 572 |
`user.custom_tool_result`. A call the server gated behind user |
| 573 |
confirmation (`evaluated_permission` `ask`, e.g. a tool configured |
| 574 |
with the `always_ask` permission policy) is held until the matching |
| 575 |
`user.tool_confirmation` event arrives — executed on `allow`, |
| 576 |
never executed on `deny` (the denied call is still yielded with |
| 577 |
`confirmation="deny"` so it can be observed). Internally drives |
| 578 |
event-stream reconnect (with capped backoff) via an anyio task group |
| 579 |
so it works under both `asyncio` and `trio`. |
| 580 |
|
| 581 |
Iteration ends when the session terminates (`session.status_terminated` |
| 582 |
/ `session.deleted`), when the consumer breaks out of the loop, or — |
| 583 |
once the session has gone idle with `stop_reason` `end_turn` — |
| 584 |
`max_idle` seconds elapse with no new event (any new event resets that |
| 585 |
countdown; it re-arms on the next `end_turn` idle). `max_idle=None` |
| 586 |
disables that last condition. It does **not** touch the work-item lease — |
| 587 |
wrap it in an `anthropic.lib.environments.EnvironmentWorker` if |
| 588 |
you need heartbeating / force-stop. |
| 589 |
|
| 590 |
Usage: |
| 591 |
|
| 592 |
```py |
| 593 |
from anthropic.lib.tools.agent_toolset import AgentToolContext, beta_agent_toolset_20260401 |
| 594 |
|
| 595 |
async with AgentToolContext(workdir=...) as env: |
| 596 |
async for call in client.beta.sessions.events.tool_runner( |
| 597 |
work.data.id, |
| 598 |
tools=[*beta_agent_toolset_20260401(env), my_tool], |
| 599 |
): |
| 600 |
... |
| 601 |
``` |
| 602 |
|
| 603 |
Args: |
| 604 |
session_id: The session whose events stream we attach to. Passed |
| 605 |
positionally, matching `list` / `send` / `stream` on this |
| 606 |
resource. |
| 607 |
tools: Registry of tool callables the runner will execute when the |
| 608 |
agent emits matching `agent.tool_use` / `agent.custom_tool_use` |
| 609 |
events — the same `anthropic.lib.tools.BetaAsyncFunctionTool` |
| 610 |
shape `client.beta.messages.tool_runner` accepts. |
| 611 |
max_idle: Seconds to keep running after the session goes idle with |
| 612 |
`stop_reason` `end_turn` before stopping; any new event resets |
| 613 |
the countdown. Defaults to `DEFAULT_MAX_IDLE` (60s) when not |
| 614 |
given. `None` disables it. |
| 615 |
environment_key: The self-hosted environment key. When set, the |
| 616 |
runner builds a Bearer-only scoped sub-client keyed to that |
| 617 |
environment for the event stream / list / send calls; leave it |
| 618 |
unset to authenticate those calls with the parent client's own |
| 619 |
credentials. |
| 620 |
extra_headers: Optional headers passed through per request on every |
| 621 |
call the runner makes (event stream / list / send). They are |
| 622 |
threaded into each call's `extra_headers=` and never assigned |
| 623 |
onto the client, so client state is not mutated. Auth and |
| 624 |
`x-stainless-helper` are supplied by the runner's scoped |
| 625 |
sub-client (and the parent client's `default_headers` propagate |
| 626 |
via its `client.copy()`); a header given here overrides the |
| 627 |
scoped client's same-named default for that request, so use it for |
| 628 |
caller passthrough (e.g. trace ids), not to set auth. |
| 629 |
""" |
| 630 |
# DEFAULT_MAX_IDLE resolved here rather than as a literal signature |
| 631 |
# default so the value can't drift from the constant; the lazy import |
| 632 |
# also keeps the host-only environment lib out of `import anthropic`. |
| 633 |
from ....lib.tools._beta_session_runner import DEFAULT_MAX_IDLE, SessionToolRunner |
| 634 |
|
| 635 |
if not is_given(max_idle): |
| 636 |
max_idle = DEFAULT_MAX_IDLE |
| 637 |
|
| 638 |
return SessionToolRunner( |
| 639 |
cast("AsyncAnthropic", self._client), |
| 640 |
session_id, |
| 641 |
tools=tools, |
| 642 |
max_idle=max_idle, |
| 643 |
environment_key=environment_key, |
| 644 |
extra_headers=extra_headers, |
| 645 |
) |
| 646 |
|
| 647 |
|
| 648 |
class EventsWithRawResponse: |
| 649 |
def __init__(self, events: Events) -> None: |
| 650 |
self._events = events |
| 651 |
|
| 652 |
self.list = to_raw_response_wrapper( |
| 653 |
events.list, |
| 654 |
) |
| 655 |
self.send = to_raw_response_wrapper( |
| 656 |
events.send, |
| 657 |
) |
| 658 |
self.stream = to_raw_response_wrapper( |
| 659 |
events.stream, |
| 660 |
) |
| 661 |
|
| 662 |
|
| 663 |
class AsyncEventsWithRawResponse: |
| 664 |
def __init__(self, events: AsyncEvents) -> None: |
| 665 |
self._events = events |
| 666 |
|
| 667 |
self.list = async_to_raw_response_wrapper( |
| 668 |
events.list, |
| 669 |
) |
| 670 |
self.send = async_to_raw_response_wrapper( |
| 671 |
events.send, |
| 672 |
) |
| 673 |
self.stream = async_to_raw_response_wrapper( |
| 674 |
events.stream, |
| 675 |
) |
| 676 |
|
| 677 |
|
| 678 |
class EventsWithStreamingResponse: |
| 679 |
def __init__(self, events: Events) -> None: |
| 680 |
self._events = events |
| 681 |
|
| 682 |
self.list = to_streamed_response_wrapper( |
| 683 |
events.list, |
| 684 |
) |
| 685 |
self.send = to_streamed_response_wrapper( |
| 686 |
events.send, |
| 687 |
) |
| 688 |
self.stream = to_streamed_response_wrapper( |
| 689 |
events.stream, |
| 690 |
) |
| 691 |
|
| 692 |
|
| 693 |
class AsyncEventsWithStreamingResponse: |
| 694 |
def __init__(self, events: AsyncEvents) -> None: |
| 695 |
self._events = events |
| 696 |
|
| 697 |
self.list = async_to_streamed_response_wrapper( |
| 698 |
events.list, |
| 699 |
) |
| 700 |
self.send = async_to_streamed_response_wrapper( |
| 701 |
events.send, |
| 702 |
) |
| 703 |
self.stream = async_to_streamed_response_wrapper( |
| 704 |
events.stream, |
| 705 |
) |