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