1# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
  2
  3from __future__ import annotations
  4
  5from typing import Any, List, Iterable, cast
  6from typing_extensions import Literal
  7
  8import httpx
  9
 10from ... import _legacy_response
 11from ..._types import Body, Omit, Query, Headers, NotGiven, omit, not_given
 12from ..._utils import maybe_transform, async_maybe_transform
 13from ..._compat import cached_property
 14from ..._resource import SyncAPIResource, AsyncAPIResource
 15from ..._response import to_streamed_response_wrapper, async_to_streamed_response_wrapper
 16from ...pagination import SyncConversationCursorPage, AsyncConversationCursorPage
 17from ..._base_client import AsyncPaginator, make_request_options
 18from ...types.conversations import item_list_params, item_create_params, item_retrieve_params
 19from ...types.conversations.conversation import Conversation
 20from ...types.responses.response_includable import ResponseIncludable
 21from ...types.conversations.conversation_item import ConversationItem
 22from ...types.responses.response_input_item_param import ResponseInputItemParam
 23from ...types.conversations.conversation_item_list import ConversationItemList
 24
 25__all__ = ["Items", "AsyncItems"]
 26
 27
 28class Items(SyncAPIResource):
 29    @cached_property
 30    def with_raw_response(self) -> ItemsWithRawResponse:
 31        """
 32        This property can be used as a prefix for any HTTP method call to return
 33        the raw response object instead of the parsed content.
 34
 35        For more information, see https://www.github.com/openai/openai-python#accessing-raw-response-data-eg-headers
 36        """
 37        return ItemsWithRawResponse(self)
 38
 39    @cached_property
 40    def with_streaming_response(self) -> ItemsWithStreamingResponse:
 41        """
 42        An alternative to `.with_raw_response` that doesn't eagerly read the response body.
 43
 44        For more information, see https://www.github.com/openai/openai-python#with_streaming_response
 45        """
 46        return ItemsWithStreamingResponse(self)
 47
 48    def create(
 49        self,
 50        conversation_id: str,
 51        *,
 52        items: Iterable[ResponseInputItemParam],
 53        include: List[ResponseIncludable] | Omit = omit,
 54        # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs.
 55        # The extra values given here take precedence over values defined on the client or passed to this method.
 56        extra_headers: Headers | None = None,
 57        extra_query: Query | None = None,
 58        extra_body: Body | None = None,
 59        timeout: float | httpx.Timeout | None | NotGiven = not_given,
 60    ) -> ConversationItemList:
 61        """
 62        Create items in a conversation with the given ID.
 63
 64        Args:
 65          items: The items to add to the conversation. You may add up to 20 items at a time.
 66
 67          include: Additional fields to include in the response. See the `include` parameter for
 68              [listing Conversation items above](https://platform.openai.com/docs/api-reference/conversations/list-items#conversations_list_items-include)
 69              for more information.
 70
 71          extra_headers: Send extra headers
 72
 73          extra_query: Add additional query parameters to the request
 74
 75          extra_body: Add additional JSON properties to the request
 76
 77          timeout: Override the client-level default timeout for this request, in seconds
 78        """
 79        if not conversation_id:
 80            raise ValueError(f"Expected a non-empty value for `conversation_id` but received {conversation_id!r}")
 81        return self._post(
 82            f"/conversations/{conversation_id}/items",
 83            body=maybe_transform({"items": items}, item_create_params.ItemCreateParams),
 84            options=make_request_options(
 85                extra_headers=extra_headers,
 86                extra_query=extra_query,
 87                extra_body=extra_body,
 88                timeout=timeout,
 89                query=maybe_transform({"include": include}, item_create_params.ItemCreateParams),
 90            ),
 91            cast_to=ConversationItemList,
 92        )
 93
 94    def retrieve(
 95        self,
 96        item_id: str,
 97        *,
 98        conversation_id: str,
 99        include: List[ResponseIncludable] | Omit = omit,
100        # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs.
101        # The extra values given here take precedence over values defined on the client or passed to this method.
102        extra_headers: Headers | None = None,
103        extra_query: Query | None = None,
104        extra_body: Body | None = None,
105        timeout: float | httpx.Timeout | None | NotGiven = not_given,
106    ) -> ConversationItem:
107        """
108        Get a single item from a conversation with the given IDs.
109
110        Args:
111          include: Additional fields to include in the response. See the `include` parameter for
112              [listing Conversation items above](https://platform.openai.com/docs/api-reference/conversations/list-items#conversations_list_items-include)
113              for more information.
114
115          extra_headers: Send extra headers
116
117          extra_query: Add additional query parameters to the request
118
119          extra_body: Add additional JSON properties to the request
120
121          timeout: Override the client-level default timeout for this request, in seconds
122        """
123        if not conversation_id:
124            raise ValueError(f"Expected a non-empty value for `conversation_id` but received {conversation_id!r}")
125        if not item_id:
126            raise ValueError(f"Expected a non-empty value for `item_id` but received {item_id!r}")
127        return cast(
128            ConversationItem,
129            self._get(
130                f"/conversations/{conversation_id}/items/{item_id}",
131                options=make_request_options(
132                    extra_headers=extra_headers,
133                    extra_query=extra_query,
134                    extra_body=extra_body,
135                    timeout=timeout,
136                    query=maybe_transform({"include": include}, item_retrieve_params.ItemRetrieveParams),
137                ),
138                cast_to=cast(Any, ConversationItem),  # Union types cannot be passed in as arguments in the type system
139            ),
140        )
141
142    def list(
143        self,
144        conversation_id: str,
145        *,
146        after: str | Omit = omit,
147        include: List[ResponseIncludable] | Omit = omit,
148        limit: int | Omit = omit,
149        order: Literal["asc", "desc"] | Omit = omit,
150        # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs.
151        # The extra values given here take precedence over values defined on the client or passed to this method.
152        extra_headers: Headers | None = None,
153        extra_query: Query | None = None,
154        extra_body: Body | None = None,
155        timeout: float | httpx.Timeout | None | NotGiven = not_given,
156    ) -> SyncConversationCursorPage[ConversationItem]:
157        """
158        List all items for a conversation with the given ID.
159
160        Args:
161          after: An item ID to list items after, used in pagination.
162
163          include: Specify additional output data to include in the model response. Currently
164              supported values are:
165
166              - `web_search_call.action.sources`: Include the sources of the web search tool
167                call.
168              - `code_interpreter_call.outputs`: Includes the outputs of python code execution
169                in code interpreter tool call items.
170              - `computer_call_output.output.image_url`: Include image urls from the computer
171                call output.
172              - `file_search_call.results`: Include the search results of the file search tool
173                call.
174              - `message.input_image.image_url`: Include image urls from the input message.
175              - `message.output_text.logprobs`: Include logprobs with assistant messages.
176              - `reasoning.encrypted_content`: Includes an encrypted version of reasoning
177                tokens in reasoning item outputs. This enables reasoning items to be used in
178                multi-turn conversations when using the Responses API statelessly (like when
179                the `store` parameter is set to `false`, or when an organization is enrolled
180                in the zero data retention program).
181
182          limit: A limit on the number of objects to be returned. Limit can range between 1 and
183              100, and the default is 20.
184
185          order: The order to return the input items in. Default is `desc`.
186
187              - `asc`: Return the input items in ascending order.
188              - `desc`: Return the input items in descending order.
189
190          extra_headers: Send extra headers
191
192          extra_query: Add additional query parameters to the request
193
194          extra_body: Add additional JSON properties to the request
195
196          timeout: Override the client-level default timeout for this request, in seconds
197        """
198        if not conversation_id:
199            raise ValueError(f"Expected a non-empty value for `conversation_id` but received {conversation_id!r}")
200        return self._get_api_list(
201            f"/conversations/{conversation_id}/items",
202            page=SyncConversationCursorPage[ConversationItem],
203            options=make_request_options(
204                extra_headers=extra_headers,
205                extra_query=extra_query,
206                extra_body=extra_body,
207                timeout=timeout,
208                query=maybe_transform(
209                    {
210                        "after": after,
211                        "include": include,
212                        "limit": limit,
213                        "order": order,
214                    },
215                    item_list_params.ItemListParams,
216                ),
217            ),
218            model=cast(Any, ConversationItem),  # Union types cannot be passed in as arguments in the type system
219        )
220
221    def delete(
222        self,
223        item_id: str,
224        *,
225        conversation_id: str,
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 | httpx.Timeout | None | NotGiven = not_given,
232    ) -> Conversation:
233        """
234        Delete an item from a conversation with the given IDs.
235
236        Args:
237          extra_headers: Send extra headers
238
239          extra_query: Add additional query parameters to the request
240
241          extra_body: Add additional JSON properties to the request
242
243          timeout: Override the client-level default timeout for this request, in seconds
244        """
245        if not conversation_id:
246            raise ValueError(f"Expected a non-empty value for `conversation_id` but received {conversation_id!r}")
247        if not item_id:
248            raise ValueError(f"Expected a non-empty value for `item_id` but received {item_id!r}")
249        return self._delete(
250            f"/conversations/{conversation_id}/items/{item_id}",
251            options=make_request_options(
252                extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout
253            ),
254            cast_to=Conversation,
255        )
256
257
258class AsyncItems(AsyncAPIResource):
259    @cached_property
260    def with_raw_response(self) -> AsyncItemsWithRawResponse:
261        """
262        This property can be used as a prefix for any HTTP method call to return
263        the raw response object instead of the parsed content.
264
265        For more information, see https://www.github.com/openai/openai-python#accessing-raw-response-data-eg-headers
266        """
267        return AsyncItemsWithRawResponse(self)
268
269    @cached_property
270    def with_streaming_response(self) -> AsyncItemsWithStreamingResponse:
271        """
272        An alternative to `.with_raw_response` that doesn't eagerly read the response body.
273
274        For more information, see https://www.github.com/openai/openai-python#with_streaming_response
275        """
276        return AsyncItemsWithStreamingResponse(self)
277
278    async def create(
279        self,
280        conversation_id: str,
281        *,
282        items: Iterable[ResponseInputItemParam],
283        include: List[ResponseIncludable] | Omit = omit,
284        # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs.
285        # The extra values given here take precedence over values defined on the client or passed to this method.
286        extra_headers: Headers | None = None,
287        extra_query: Query | None = None,
288        extra_body: Body | None = None,
289        timeout: float | httpx.Timeout | None | NotGiven = not_given,
290    ) -> ConversationItemList:
291        """
292        Create items in a conversation with the given ID.
293
294        Args:
295          items: The items to add to the conversation. You may add up to 20 items at a time.
296
297          include: Additional fields to include in the response. See the `include` parameter for
298              [listing Conversation items above](https://platform.openai.com/docs/api-reference/conversations/list-items#conversations_list_items-include)
299              for more information.
300
301          extra_headers: Send extra headers
302
303          extra_query: Add additional query parameters to the request
304
305          extra_body: Add additional JSON properties to the request
306
307          timeout: Override the client-level default timeout for this request, in seconds
308        """
309        if not conversation_id:
310            raise ValueError(f"Expected a non-empty value for `conversation_id` but received {conversation_id!r}")
311        return await self._post(
312            f"/conversations/{conversation_id}/items",
313            body=await async_maybe_transform({"items": items}, item_create_params.ItemCreateParams),
314            options=make_request_options(
315                extra_headers=extra_headers,
316                extra_query=extra_query,
317                extra_body=extra_body,
318                timeout=timeout,
319                query=await async_maybe_transform({"include": include}, item_create_params.ItemCreateParams),
320            ),
321            cast_to=ConversationItemList,
322        )
323
324    async def retrieve(
325        self,
326        item_id: str,
327        *,
328        conversation_id: str,
329        include: List[ResponseIncludable] | 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 | httpx.Timeout | None | NotGiven = not_given,
336    ) -> ConversationItem:
337        """
338        Get a single item from a conversation with the given IDs.
339
340        Args:
341          include: Additional fields to include in the response. See the `include` parameter for
342              [listing Conversation items above](https://platform.openai.com/docs/api-reference/conversations/list-items#conversations_list_items-include)
343              for more information.
344
345          extra_headers: Send extra headers
346
347          extra_query: Add additional query parameters to the request
348
349          extra_body: Add additional JSON properties to the request
350
351          timeout: Override the client-level default timeout for this request, in seconds
352        """
353        if not conversation_id:
354            raise ValueError(f"Expected a non-empty value for `conversation_id` but received {conversation_id!r}")
355        if not item_id:
356            raise ValueError(f"Expected a non-empty value for `item_id` but received {item_id!r}")
357        return cast(
358            ConversationItem,
359            await self._get(
360                f"/conversations/{conversation_id}/items/{item_id}",
361                options=make_request_options(
362                    extra_headers=extra_headers,
363                    extra_query=extra_query,
364                    extra_body=extra_body,
365                    timeout=timeout,
366                    query=await async_maybe_transform({"include": include}, item_retrieve_params.ItemRetrieveParams),
367                ),
368                cast_to=cast(Any, ConversationItem),  # Union types cannot be passed in as arguments in the type system
369            ),
370        )
371
372    def list(
373        self,
374        conversation_id: str,
375        *,
376        after: str | Omit = omit,
377        include: List[ResponseIncludable] | Omit = omit,
378        limit: int | Omit = omit,
379        order: Literal["asc", "desc"] | Omit = omit,
380        # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs.
381        # The extra values given here take precedence over values defined on the client or passed to this method.
382        extra_headers: Headers | None = None,
383        extra_query: Query | None = None,
384        extra_body: Body | None = None,
385        timeout: float | httpx.Timeout | None | NotGiven = not_given,
386    ) -> AsyncPaginator[ConversationItem, AsyncConversationCursorPage[ConversationItem]]:
387        """
388        List all items for a conversation with the given ID.
389
390        Args:
391          after: An item ID to list items after, used in pagination.
392
393          include: Specify additional output data to include in the model response. Currently
394              supported values are:
395
396              - `web_search_call.action.sources`: Include the sources of the web search tool
397                call.
398              - `code_interpreter_call.outputs`: Includes the outputs of python code execution
399                in code interpreter tool call items.
400              - `computer_call_output.output.image_url`: Include image urls from the computer
401                call output.
402              - `file_search_call.results`: Include the search results of the file search tool
403                call.
404              - `message.input_image.image_url`: Include image urls from the input message.
405              - `message.output_text.logprobs`: Include logprobs with assistant messages.
406              - `reasoning.encrypted_content`: Includes an encrypted version of reasoning
407                tokens in reasoning item outputs. This enables reasoning items to be used in
408                multi-turn conversations when using the Responses API statelessly (like when
409                the `store` parameter is set to `false`, or when an organization is enrolled
410                in the zero data retention program).
411
412          limit: A limit on the number of objects to be returned. Limit can range between 1 and
413              100, and the default is 20.
414
415          order: The order to return the input items in. Default is `desc`.
416
417              - `asc`: Return the input items in ascending order.
418              - `desc`: Return the input items in descending order.
419
420          extra_headers: Send extra headers
421
422          extra_query: Add additional query parameters to the request
423
424          extra_body: Add additional JSON properties to the request
425
426          timeout: Override the client-level default timeout for this request, in seconds
427        """
428        if not conversation_id:
429            raise ValueError(f"Expected a non-empty value for `conversation_id` but received {conversation_id!r}")
430        return self._get_api_list(
431            f"/conversations/{conversation_id}/items",
432            page=AsyncConversationCursorPage[ConversationItem],
433            options=make_request_options(
434                extra_headers=extra_headers,
435                extra_query=extra_query,
436                extra_body=extra_body,
437                timeout=timeout,
438                query=maybe_transform(
439                    {
440                        "after": after,
441                        "include": include,
442                        "limit": limit,
443                        "order": order,
444                    },
445                    item_list_params.ItemListParams,
446                ),
447            ),
448            model=cast(Any, ConversationItem),  # Union types cannot be passed in as arguments in the type system
449        )
450
451    async def delete(
452        self,
453        item_id: str,
454        *,
455        conversation_id: str,
456        # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs.
457        # The extra values given here take precedence over values defined on the client or passed to this method.
458        extra_headers: Headers | None = None,
459        extra_query: Query | None = None,
460        extra_body: Body | None = None,
461        timeout: float | httpx.Timeout | None | NotGiven = not_given,
462    ) -> Conversation:
463        """
464        Delete an item from a conversation with the given IDs.
465
466        Args:
467          extra_headers: Send extra headers
468
469          extra_query: Add additional query parameters to the request
470
471          extra_body: Add additional JSON properties to the request
472
473          timeout: Override the client-level default timeout for this request, in seconds
474        """
475        if not conversation_id:
476            raise ValueError(f"Expected a non-empty value for `conversation_id` but received {conversation_id!r}")
477        if not item_id:
478            raise ValueError(f"Expected a non-empty value for `item_id` but received {item_id!r}")
479        return await self._delete(
480            f"/conversations/{conversation_id}/items/{item_id}",
481            options=make_request_options(
482                extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout
483            ),
484            cast_to=Conversation,
485        )
486
487
488class ItemsWithRawResponse:
489    def __init__(self, items: Items) -> None:
490        self._items = items
491
492        self.create = _legacy_response.to_raw_response_wrapper(
493            items.create,
494        )
495        self.retrieve = _legacy_response.to_raw_response_wrapper(
496            items.retrieve,
497        )
498        self.list = _legacy_response.to_raw_response_wrapper(
499            items.list,
500        )
501        self.delete = _legacy_response.to_raw_response_wrapper(
502            items.delete,
503        )
504
505
506class AsyncItemsWithRawResponse:
507    def __init__(self, items: AsyncItems) -> None:
508        self._items = items
509
510        self.create = _legacy_response.async_to_raw_response_wrapper(
511            items.create,
512        )
513        self.retrieve = _legacy_response.async_to_raw_response_wrapper(
514            items.retrieve,
515        )
516        self.list = _legacy_response.async_to_raw_response_wrapper(
517            items.list,
518        )
519        self.delete = _legacy_response.async_to_raw_response_wrapper(
520            items.delete,
521        )
522
523
524class ItemsWithStreamingResponse:
525    def __init__(self, items: Items) -> None:
526        self._items = items
527
528        self.create = to_streamed_response_wrapper(
529            items.create,
530        )
531        self.retrieve = to_streamed_response_wrapper(
532            items.retrieve,
533        )
534        self.list = to_streamed_response_wrapper(
535            items.list,
536        )
537        self.delete = to_streamed_response_wrapper(
538            items.delete,
539        )
540
541
542class AsyncItemsWithStreamingResponse:
543    def __init__(self, items: AsyncItems) -> None:
544        self._items = items
545
546        self.create = async_to_streamed_response_wrapper(
547            items.create,
548        )
549        self.retrieve = async_to_streamed_response_wrapper(
550            items.retrieve,
551        )
552        self.list = async_to_streamed_response_wrapper(
553            items.list,
554        )
555        self.delete = async_to_streamed_response_wrapper(
556            items.delete,
557        )