Debian Codegraph @

src/anthropic/resources/beta/sessions/threads/events.py

raw
1 from __future__ import annotations
2
3 from typing import Any, List, cast
4 from itertools import chain
5
6 import httpx2
7
8 from ....._types import Body, Omit, Query, Headers, NotGiven, omit, not_given
9 from ....._utils import is_given, path_template, strip_not_given
10 from ....._compat import cached_property
11 from ....._resource import SyncAPIResource, AsyncAPIResource
12 from ....._response import (
13 to_raw_response_wrapper,
14 to_streamed_response_wrapper,
15 async_to_raw_response_wrapper,
16 async_to_streamed_response_wrapper,
17 )
18 from ....._streaming import Stream, AsyncStream
19 from .....pagination import SyncPageCursor, AsyncPageCursor
20 from ....._base_client import AsyncPaginator, make_request_options
21 from .....types.anthropic_beta_param import AnthropicBetaParam
22 from .....types.beta.beta_managed_agents_delta_type import BetaManagedAgentsDeltaType
23 from .....types.beta.sessions.beta_managed_agents_session_event import BetaManagedAgentsSessionEvent
24 from .....types.beta.sessions.beta_managed_agents_stream_session_thread_events import (
25 BetaManagedAgentsStreamSessionThreadEvents,
26 )
27
28 __all__ = ["Events", "AsyncEvents"]
29
30
31 class Events(SyncAPIResource):
32 @cached_property
33 def with_raw_response(self) -> EventsWithRawResponse:
34 """
35 This property can be used as a prefix for any HTTP method call to return
36 the raw response object instead of the parsed content.
37
38 For more information, see https://www.github.com/anthropics/anthropic-sdk-python#accessing-raw-response-data-eg-headers
39 """
40 return EventsWithRawResponse(self)
41
42 @cached_property
43 def with_streaming_response(self) -> EventsWithStreamingResponse:
44 """
45 An alternative to `.with_raw_response` that doesn't eagerly read the response body.
46
47 For more information, see https://www.github.com/anthropics/anthropic-sdk-python#with_streaming_response
48 """
49 return EventsWithStreamingResponse(self)
50
51 def list(
52 self,
53 thread_id: str,
54 *,
55 session_id: str,
56 limit: int | Omit = omit,
57 page: str | Omit = omit,
58 betas: List[AnthropicBetaParam] | Omit = omit,
59 workspace_id: str | Omit = omit,
60 # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs.
61 # The extra values given here take precedence over values defined on the client or passed to this method.
62 extra_headers: Headers | None = None,
63 extra_query: Query | None = None,
64 extra_body: Body | None = None,
65 timeout: float | httpx2.Timeout | None | NotGiven = not_given,
66 ) -> SyncPageCursor[BetaManagedAgentsSessionEvent]:
67 """
68 List Session Thread Events
69
70 Args:
71 betas: Optional header to specify the beta version(s) you want to use.
72
73 workspace_id: Optional header to select the Workspace for this request. The value is a
74 Workspace ID (for example, `wrkspc_011CZkZaBF1tNoB5wlCeusgy`).
75
76 Only needed for credentials that can act on more than one Workspace. A
77 credential that belongs to a specific Workspace may omit it; if sent, it must
78 match that Workspace.
79
80 extra_headers: Send extra headers
81
82 extra_query: Add additional query parameters to the request
83
84 extra_body: Add additional JSON properties to the request
85
86 timeout: Override the client-level default timeout for this request, in seconds
87 """
88 if not session_id:
89 raise ValueError(f"Expected a non-empty value for `session_id` but received {session_id!r}")
90 if not thread_id:
91 raise ValueError(f"Expected a non-empty value for `thread_id` but received {thread_id!r}")
92 extra_headers = {
93 **strip_not_given(
94 {
95 "anthropic-beta": ",".join(chain((str(e) for e in betas), ["managed-agents-2026-04-01"]))
96 if is_given(betas)
97 else not_given,
98 "anthropic-workspace-id": workspace_id,
99 }
100 ),
101 **(extra_headers or {}),
102 }
103 extra_headers = {"anthropic-beta": "managed-agents-2026-04-01", **(extra_headers or {})}
104 return self._get_api_list(
105 path_template(
106 "/v1/sessions/{session_id}/threads/{thread_id}/events?beta=true",
107 session_id=session_id,
108 thread_id=thread_id,
109 ),
110 page=SyncPageCursor[BetaManagedAgentsSessionEvent],
111 options=make_request_options(
112 extra_headers=extra_headers,
113 extra_query=extra_query,
114 extra_body=extra_body,
115 timeout=timeout,
116 query={
117 "limit": limit,
118 "page": page,
119 },
120 ),
121 model=cast(
122 Any, BetaManagedAgentsSessionEvent
123 ), # Union types cannot be passed in as arguments in the type system
124 )
125
126 def stream(
127 self,
128 thread_id: str,
129 *,
130 session_id: str,
131 event_deltas: List[BetaManagedAgentsDeltaType] | Omit = omit,
132 betas: List[AnthropicBetaParam] | Omit = omit,
133 workspace_id: str | Omit = omit,
134 # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs.
135 # The extra values given here take precedence over values defined on the client or passed to this method.
136 extra_headers: Headers | None = None,
137 extra_query: Query | None = None,
138 extra_body: Body | None = None,
139 timeout: float | httpx2.Timeout | None | NotGiven = not_given,
140 ) -> Stream[BetaManagedAgentsStreamSessionThreadEvents]:
141 """
142 Stream Session Thread Events
143
144 Args:
145 event_deltas: When set, this connection also receives streaming deltas (`event_start`,
146 `event_delta`) while an event is being produced, before the event itself
147 arrives. Deltas are best-effort; when the final event is produced it carries the
148 complete content. A model request that ends early (an error or interrupt)
149 produces no final event — its terminal `span.model_request_end` closes the
150 preview. Accepts one or more event types to preview and may be repeated:
151 `agent.message` streams `content_delta` fragments; `agent.thinking` is
152 start-only — a signal that the agent has begun extended thinking, concluded by
153 the `agent.thinking` event itself. Only previews of the requested event types
154 are sent.
155
156 betas: Optional header to specify the beta version(s) you want to use.
157
158 workspace_id: Optional header to select the Workspace for this request. The value is a
159 Workspace ID (for example, `wrkspc_011CZkZaBF1tNoB5wlCeusgy`).
160
161 Only needed for credentials that can act on more than one Workspace. A
162 credential that belongs to a specific Workspace may omit it; if sent, it must
163 match that Workspace.
164
165 extra_headers: Send extra headers
166
167 extra_query: Add additional query parameters to the request
168
169 extra_body: Add additional JSON properties to the request
170
171 timeout: Override the client-level default timeout for this request, in seconds
172 """
173 if not session_id:
174 raise ValueError(f"Expected a non-empty value for `session_id` but received {session_id!r}")
175 if not thread_id:
176 raise ValueError(f"Expected a non-empty value for `thread_id` but received {thread_id!r}")
177 extra_headers = {
178 **strip_not_given(
179 {
180 "anthropic-beta": ",".join(chain((str(e) for e in betas), ["managed-agents-2026-04-01"]))
181 if is_given(betas)
182 else not_given,
183 "anthropic-workspace-id": workspace_id,
184 }
185 ),
186 **(extra_headers or {}),
187 }
188 extra_headers = {"anthropic-beta": "managed-agents-2026-04-01", **(extra_headers or {})}
189 return self._get(
190 path_template(
191 "/v1/sessions/{session_id}/threads/{thread_id}/stream?beta=true",
192 session_id=session_id,
193 thread_id=thread_id,
194 ),
195 options=make_request_options(
196 extra_headers=extra_headers,
197 extra_query=extra_query,
198 extra_body=extra_body,
199 timeout=timeout,
200 query={"event_deltas": event_deltas},
201 ),
202 cast_to=cast(
203 Any, BetaManagedAgentsStreamSessionThreadEvents
204 ), # Union types cannot be passed in as arguments in the type system
205 stream=True,
206 stream_cls=Stream[BetaManagedAgentsStreamSessionThreadEvents],
207 )
208
209
210 class AsyncEvents(AsyncAPIResource):
211 @cached_property
212 def with_raw_response(self) -> AsyncEventsWithRawResponse:
213 """
214 This property can be used as a prefix for any HTTP method call to return
215 the raw response object instead of the parsed content.
216
217 For more information, see https://www.github.com/anthropics/anthropic-sdk-python#accessing-raw-response-data-eg-headers
218 """
219 return AsyncEventsWithRawResponse(self)
220
221 @cached_property
222 def with_streaming_response(self) -> AsyncEventsWithStreamingResponse:
223 """
224 An alternative to `.with_raw_response` that doesn't eagerly read the response body.
225
226 For more information, see https://www.github.com/anthropics/anthropic-sdk-python#with_streaming_response
227 """
228 return AsyncEventsWithStreamingResponse(self)
229
230 def list(
231 self,
232 thread_id: str,
233 *,
234 session_id: str,
235 limit: int | Omit = omit,
236 page: str | Omit = omit,
237 betas: List[AnthropicBetaParam] | Omit = omit,
238 workspace_id: str | Omit = omit,
239 # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs.
240 # The extra values given here take precedence over values defined on the client or passed to this method.
241 extra_headers: Headers | None = None,
242 extra_query: Query | None = None,
243 extra_body: Body | None = None,
244 timeout: float | httpx2.Timeout | None | NotGiven = not_given,
245 ) -> AsyncPaginator[BetaManagedAgentsSessionEvent, AsyncPageCursor[BetaManagedAgentsSessionEvent]]:
246 """
247 List Session Thread Events
248
249 Args:
250 betas: Optional header to specify the beta version(s) you want to use.
251
252 workspace_id: Optional header to select the Workspace for this request. The value is a
253 Workspace ID (for example, `wrkspc_011CZkZaBF1tNoB5wlCeusgy`).
254
255 Only needed for credentials that can act on more than one Workspace. A
256 credential that belongs to a specific Workspace may omit it; if sent, it must
257 match that Workspace.
258
259 extra_headers: Send extra headers
260
261 extra_query: Add additional query parameters to the request
262
263 extra_body: Add additional JSON properties to the request
264
265 timeout: Override the client-level default timeout for this request, in seconds
266 """
267 if not session_id:
268 raise ValueError(f"Expected a non-empty value for `session_id` but received {session_id!r}")
269 if not thread_id:
270 raise ValueError(f"Expected a non-empty value for `thread_id` but received {thread_id!r}")
271 extra_headers = {
272 **strip_not_given(
273 {
274 "anthropic-beta": ",".join(chain((str(e) for e in betas), ["managed-agents-2026-04-01"]))
275 if is_given(betas)
276 else not_given,
277 "anthropic-workspace-id": workspace_id,
278 }
279 ),
280 **(extra_headers or {}),
281 }
282 extra_headers = {"anthropic-beta": "managed-agents-2026-04-01", **(extra_headers or {})}
283 return self._get_api_list(
284 path_template(
285 "/v1/sessions/{session_id}/threads/{thread_id}/events?beta=true",
286 session_id=session_id,
287 thread_id=thread_id,
288 ),
289 page=AsyncPageCursor[BetaManagedAgentsSessionEvent],
290 options=make_request_options(
291 extra_headers=extra_headers,
292 extra_query=extra_query,
293 extra_body=extra_body,
294 timeout=timeout,
295 query={
296 "limit": limit,
297 "page": page,
298 },
299 ),
300 model=cast(
301 Any, BetaManagedAgentsSessionEvent
302 ), # Union types cannot be passed in as arguments in the type system
303 )
304
305 async def stream(
306 self,
307 thread_id: str,
308 *,
309 session_id: str,
310 event_deltas: List[BetaManagedAgentsDeltaType] | Omit = omit,
311 betas: List[AnthropicBetaParam] | Omit = omit,
312 workspace_id: str | Omit = omit,
313 # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs.
314 # The extra values given here take precedence over values defined on the client or passed to this method.
315 extra_headers: Headers | None = None,
316 extra_query: Query | None = None,
317 extra_body: Body | None = None,
318 timeout: float | httpx2.Timeout | None | NotGiven = not_given,
319 ) -> AsyncStream[BetaManagedAgentsStreamSessionThreadEvents]:
320 """
321 Stream Session Thread Events
322
323 Args:
324 event_deltas: When set, this connection also receives streaming deltas (`event_start`,
325 `event_delta`) while an event is being produced, before the event itself
326 arrives. Deltas are best-effort; when the final event is produced it carries the
327 complete content. A model request that ends early (an error or interrupt)
328 produces no final event — its terminal `span.model_request_end` closes the
329 preview. Accepts one or more event types to preview and may be repeated:
330 `agent.message` streams `content_delta` fragments; `agent.thinking` is
331 start-only — a signal that the agent has begun extended thinking, concluded by
332 the `agent.thinking` event itself. Only previews of the requested event types
333 are sent.
334
335 betas: Optional header to specify the beta version(s) you want to use.
336
337 workspace_id: Optional header to select the Workspace for this request. The value is a
338 Workspace ID (for example, `wrkspc_011CZkZaBF1tNoB5wlCeusgy`).
339
340 Only needed for credentials that can act on more than one Workspace. A
341 credential that belongs to a specific Workspace may omit it; if sent, it must
342 match that Workspace.
343
344 extra_headers: Send extra headers
345
346 extra_query: Add additional query parameters to the request
347
348 extra_body: Add additional JSON properties to the request
349
350 timeout: Override the client-level default timeout for this request, in seconds
351 """
352 if not session_id:
353 raise ValueError(f"Expected a non-empty value for `session_id` but received {session_id!r}")
354 if not thread_id:
355 raise ValueError(f"Expected a non-empty value for `thread_id` but received {thread_id!r}")
356 extra_headers = {
357 **strip_not_given(
358 {
359 "anthropic-beta": ",".join(chain((str(e) for e in betas), ["managed-agents-2026-04-01"]))
360 if is_given(betas)
361 else not_given,
362 "anthropic-workspace-id": workspace_id,
363 }
364 ),
365 **(extra_headers or {}),
366 }
367 extra_headers = {"anthropic-beta": "managed-agents-2026-04-01", **(extra_headers or {})}
368 return await self._get(
369 path_template(
370 "/v1/sessions/{session_id}/threads/{thread_id}/stream?beta=true",
371 session_id=session_id,
372 thread_id=thread_id,
373 ),
374 options=make_request_options(
375 extra_headers=extra_headers,
376 extra_query=extra_query,
377 extra_body=extra_body,
378 timeout=timeout,
379 query={"event_deltas": event_deltas},
380 ),
381 cast_to=cast(
382 Any, BetaManagedAgentsStreamSessionThreadEvents
383 ), # Union types cannot be passed in as arguments in the type system
384 stream=True,
385 stream_cls=AsyncStream[BetaManagedAgentsStreamSessionThreadEvents],
386 )
387
388
389 class EventsWithRawResponse:
390 def __init__(self, events: Events) -> None:
391 self._events = events
392
393 self.list = to_raw_response_wrapper(
394 events.list,
395 )
396 self.stream = to_raw_response_wrapper(
397 events.stream,
398 )
399
400
401 class AsyncEventsWithRawResponse:
402 def __init__(self, events: AsyncEvents) -> None:
403 self._events = events
404
405 self.list = async_to_raw_response_wrapper(
406 events.list,
407 )
408 self.stream = async_to_raw_response_wrapper(
409 events.stream,
410 )
411
412
413 class EventsWithStreamingResponse:
414 def __init__(self, events: Events) -> None:
415 self._events = events
416
417 self.list = to_streamed_response_wrapper(
418 events.list,
419 )
420 self.stream = to_streamed_response_wrapper(
421 events.stream,
422 )
423
424
425 class AsyncEventsWithStreamingResponse:
426 def __init__(self, events: AsyncEvents) -> None:
427 self._events = events
428
429 self.list = async_to_streamed_response_wrapper(
430 events.list,
431 )
432 self.stream = async_to_streamed_response_wrapper(
433 events.stream,
434 )