U
    Zhq                     @  s  d dl mZ d dlmZmZmZmZmZmZm	Z	 d dl
mZ d dlmZ d dlZddlmZ ddlmZmZmZmZmZ dd	lmZmZ dd
lmZ ddlmZmZ ddlm Z m!Z! ddl"m#Z# ddl$m%Z% ddl&m'Z' ddl(m)Z)m*Z+m,Z-m.Z/ ddl0m1Z1 ddl2m3Z3m4Z4 ddl5m6Z6m7Z7 ddl8m9Z9 ddl:m;Z; ddl<m=Z= ddl>m?Z? ddl@mAZA ddlBmCZC ddlDmEZE ddlFmGZG ddlHmIZI ddgZJG dd deZKG d d deZLG d!d" d"ZMG d#d$ d$ZNG d%d& d&ZOG d'd( d(ZPdS ))    )annotations)DictListTypeUnionIterableOptionalcast)partial)LiteralN   )_legacy_response)	NOT_GIVENBodyQueryHeadersNotGiven)maybe_transformasync_maybe_transform)cached_property)SyncAPIResourceAsyncAPIResource)to_streamed_response_wrapper"async_to_streamed_response_wrapper)Stream)completion_create_params)make_request_options)ResponseFormatTvalidate_input_toolsparse_chat_completiontype_to_response_format_param)	ChatModel)ChatCompletionStreamManager AsyncChatCompletionStreamManager)MetadataReasoningEffort)ChatCompletion)ChatCompletionChunk)ParsedChatCompletion)ChatCompletionToolParam)ChatCompletionAudioParam)ChatCompletionMessageParam) ChatCompletionStreamOptionsParam)$ChatCompletionPredictionContentParam)#ChatCompletionToolChoiceOptionParamCompletionsAsyncCompletionsc                %   @  s\  e Zd ZeddddZeddddZeeeeeeeeeeeeeeeeeeeeeeeeeeeeddded	 d
dddddddddddddddddddddddddddddd d!d"d#d$d%#d&d'Zeeeeeeeeeeeeeeeeeeeeeeeeeeeeddded	 d
ddd(ddddddddddddddddddddddddddd d!d"d#d)d%#d*d+ZdS ),r/   CompletionsWithRawResponsereturnc                 C  s   t | S a  
        This property can be used as a prefix for any HTTP method call to return the
        the raw response object instead of the parsed content.

        For more information, see https://www.github.com/openai/openai-python#accessing-raw-response-data-eg-headers
        )r1   self r7   J/tmp/pip-unpacked-wheel-693nel7n/openai/resources/beta/chat/completions.pywith_raw_response+   s    zCompletions.with_raw_response CompletionsWithStreamingResponsec                 C  s   t | S z
        An alternative to `.with_raw_response` that doesn't eagerly read the response body.

        For more information, see https://www.github.com/openai/openai-python#with_streaming_response
        )r:   r5   r7   r7   r8   with_streaming_response5   s    z#Completions.with_streaming_responseN audioresponse_formatfrequency_penaltyfunction_call	functions
logit_biaslogprobsmax_completion_tokens
max_tokensmetadata
modalitiesnparallel_tool_calls
predictionpresence_penaltyreasoning_effortseedservice_tierstopstorestream_optionstemperaturetool_choicetoolstop_logprobstop_puserweb_search_optionsextra_headersextra_query
extra_bodytimeout$Iterable[ChatCompletionMessageParam]Union[str, ChatModel]-Optional[ChatCompletionAudioParam] | NotGiven type[ResponseFormatT] | NotGivenOptional[float] | NotGiven0completion_create_params.FunctionCall | NotGiven6Iterable[completion_create_params.Function] | NotGiven#Optional[Dict[str, int]] | NotGivenOptional[bool] | NotGivenOptional[int] | NotGivenOptional[Metadata] | NotGiven5Optional[List[Literal[('text', 'audio')]]] | NotGivenbool | NotGiven9Optional[ChatCompletionPredictionContentParam] | NotGiven$Optional[ReasoningEffort] | NotGivenBOptional[Literal[('auto', 'default', 'flex', 'scale')]] | NotGiven0Union[Optional[str], List[str], None] | NotGiven5Optional[ChatCompletionStreamOptionsParam] | NotGiven.ChatCompletionToolChoiceOptionParam | NotGiven,Iterable[ChatCompletionToolParam] | NotGivenstr | NotGiven4completion_create_params.WebSearchOptions | NotGivenHeaders | NoneQuery | NoneBody | None'float | httpx.Timeout | None | NotGiven%ParsedChatCompletion[ResponseFormatT]#messagesmodelr>   r?   r@   rA   rB   rC   rD   rE   rF   rG   rH   rI   rJ   rK   rL   rM   rN   rO   rP   rQ   rR   rS   rT   rU   rV   rW   rX   rY   rZ   r[   r\   r]   r3   c       "   $   #     s   t  ddi|pi }ddd fdd}#| jdt||||||||	|
||||||||t ||||d	|||||||d
tjt|| |!|"|#dttt	t
  td	dS )a  Wrapper over the `client.chat.completions.create()` method that provides richer integrations with Python specific types
        & returns a `ParsedChatCompletion` object, which is a subclass of the standard `ChatCompletion` class.

        You can pass a pydantic model to this method and it will automatically convert the model
        into a JSON schema, send it to the API and parse the response content back into the given model.

        This method will also automatically parse `function` tool calls if:
        - You use the `openai.pydantic_function_tool()` helper method
        - You mark your tool schema with `"strict": True`

        Example usage:
        ```py
        from pydantic import BaseModel
        from openai import OpenAI


        class Step(BaseModel):
            explanation: str
            output: str


        class MathResponse(BaseModel):
            steps: List[Step]
            final_answer: str


        client = OpenAI()
        completion = client.beta.chat.completions.parse(
            model="gpt-4o-2024-08-06",
            messages=[
                {"role": "system", "content": "You are a helpful math tutor."},
                {"role": "user", "content": "solve 8x + 31 = 2"},
            ],
            response_format=MathResponse,
        )

        message = completion.choices[0].message
        if message.parsed:
            print(message.parsed.steps)
            print("answer: ", message.parsed.final_answer)
        ```
        X-Stainless-Helper-Methodbeta.chat.completions.parser&   rx   raw_completionr3   c                   s   t  | dS N)r?   Zchat_completioninput_tools_parse_chat_completionr   r?   rU   r7   r8   parser   s
    z!Completions.parse.<locals>.parser/chat/completionsF)rz   r{   r>   r@   rA   rB   rC   rD   rE   rF   rG   rH   rI   rJ   rK   rL   rM   r?   rN   rO   rP   rQ   streamrR   rS   rT   rU   rV   rW   rX   rY   rZ   r[   r\   r]   Zpost_parserbodyoptionsZcast_tor   )_validate_input_tools_postr   _type_to_response_formatr   CompletionCreateParamsr   r	   r   r(   r   r&   $r6   rz   r{   r>   r?   r@   rA   rB   rC   rD   rE   rF   rG   rH   rI   rJ   rK   rL   rM   rN   rO   rP   rQ   rR   rS   rT   rU   rV   rW   rX   rY   rZ   r[   r\   r]   r   r7   r   r8   parse>   sl    R !$	zCompletions.parseJcompletion_create_params.ResponseFormat | type[ResponseFormatT] | NotGivenz,ChatCompletionStreamManager[ResponseFormatT]c       "   $   &   C  sz   ddi|pi }t | jjjj|||dt||||||	|
|||||||||||||||||||||| |!|"d$}#t|#||dS )a  Wrapper over the `client.chat.completions.create(stream=True)` method that provides a more granular event API
        and automatic accumulation of each delta.

        This also supports all of the parsing utilities that `.parse()` does.

        Unlike `.create(stream=True)`, the `.stream()` method requires usage within a context manager to prevent accidental leakage of the response:

        ```py
        with client.beta.chat.completions.stream(
            model="gpt-4o-2024-08-06",
            messages=[...],
        ) as stream:
            for event in stream:
                if event.type == "content.delta":
                    print(event.delta, flush=True, end="")
        ```

        When the context manager is entered, a `ChatCompletionStream` instance is returned which, like `.create(stream=True)` is an iterator. The full list of events that are yielded by the iterator are outlined in [these docs](https://github.com/openai/openai-python/blob/main/helpers.md#chat-completions-events).

        When the context manager exits, the response will be closed, however the `stream` instance is still available outside
        the context manager.
        r|   beta.chat.completions.streamT)#rz   r{   r>   r   r?   r@   rA   rB   rC   rD   rE   rF   rG   rH   rI   rJ   rK   rL   rM   rN   rO   rQ   rP   rR   rS   rT   rU   rV   rW   rX   rY   rZ   r[   r\   r]   r?   r   )r
   _clientchatcompletionscreater   r"   $r6   rz   r{   r>   r?   r@   rA   rB   rC   rD   rE   rF   rG   rH   rI   rJ   rK   rL   rM   rN   rO   rP   rQ   rR   rS   rT   rU   rV   rW   rX   rY   rZ   r[   r\   r]   Zapi_requestr7   r7   r8   r      s`    ? 
&zCompletions.stream	__name__
__module____qualname__r   r9   r<   r   r   r   r7   r7   r7   r8   r/   *   s   	V c                %   @  s\  e Zd ZeddddZeddddZeeeeeeeeeeeeeeeeeeeeeeeeeeeeddded	 d
dddddddddddddddddddddddddddddd d!d"d#d$d%#d&d'Zeeeeeeeeeeeeeeeeeeeeeeeeeeeeddded	 d
ddd(ddddddddddddddddddddddddddd d!d"d#d)d%#d*d+ZdS ),r0   AsyncCompletionsWithRawResponser2   c                 C  s   t | S r4   )r   r5   r7   r7   r8   r9   B  s    z"AsyncCompletions.with_raw_response%AsyncCompletionsWithStreamingResponsec                 C  s   t | S r;   )r   r5   r7   r7   r8   r<   L  s    z(AsyncCompletions.with_streaming_responseNr=   r^   r_   r`   ra   rb   rc   rd   re   rf   rg   rh   ri   rj   rk   rl   rm   rn   ro   rp   rq   rr   rs   rt   ru   rv   rw   rx   ry   c       "   $   #     s   t  ddi|pi }ddd fdd}#| jdt||||||||	|
||||||||t ||||d	|||||||d
tjI dH t|| |!|"|#dttt	t
  td	dI dH S )a  Wrapper over the `client.chat.completions.create()` method that provides richer integrations with Python specific types
        & returns a `ParsedChatCompletion` object, which is a subclass of the standard `ChatCompletion` class.

        You can pass a pydantic model to this method and it will automatically convert the model
        into a JSON schema, send it to the API and parse the response content back into the given model.

        This method will also automatically parse `function` tool calls if:
        - You use the `openai.pydantic_function_tool()` helper method
        - You mark your tool schema with `"strict": True`

        Example usage:
        ```py
        from pydantic import BaseModel
        from openai import AsyncOpenAI


        class Step(BaseModel):
            explanation: str
            output: str


        class MathResponse(BaseModel):
            steps: List[Step]
            final_answer: str


        client = AsyncOpenAI()
        completion = await client.beta.chat.completions.parse(
            model="gpt-4o-2024-08-06",
            messages=[
                {"role": "system", "content": "You are a helpful math tutor."},
                {"role": "user", "content": "solve 8x + 31 = 2"},
            ],
            response_format=MathResponse,
        )

        message = completion.choices[0].message
        if message.parsed:
            print(message.parsed.steps)
            print("answer: ", message.parsed.final_answer)
        ```
        r|   r}   r&   rx   r~   c                   s   t  | dS r   r   r   r   r7   r8   r     s
    z&AsyncCompletions.parse.<locals>.parserr   F)rz   r{   r>   r@   rA   rB   rC   rD   rE   rF   rG   rH   rI   rJ   rK   rL   rM   r?   rN   rO   rQ   rP   r   rR   rS   rT   rU   rV   rW   rX   rY   Nr   r   )r   r   r   r   r   r   r   r	   r   r(   r   r&   r   r7   r   r8   r   U  sl    R !$	zAsyncCompletions.parser   z1AsyncChatCompletionStreamManager[ResponseFormatT]c       "   $   %   C  s   t | ddi|pi }| jjjj|||dt||||||	|
||||||||||||||||||||| |!|"|d#}#t|#||dS )a  Wrapper over the `client.chat.completions.create(stream=True)` method that provides a more granular event API
        and automatic accumulation of each delta.

        This also supports all of the parsing utilities that `.parse()` does.

        Unlike `.create(stream=True)`, the `.stream()` method requires usage within a context manager to prevent accidental leakage of the response:

        ```py
        async with client.beta.chat.completions.stream(
            model="gpt-4o-2024-08-06",
            messages=[...],
        ) as stream:
            async for event in stream:
                if event.type == "content.delta":
                    print(event.delta, flush=True, end="")
        ```

        When the context manager is entered, an `AsyncChatCompletionStream` instance is returned which, like `.create(stream=True)` is an async iterator. The full list of events that are yielded by the iterator are outlined in [these docs](https://github.com/openai/openai-python/blob/main/helpers.md#chat-completions-events).

        When the context manager exits, the response will be closed, however the `stream` instance is still available outside
        the context manager.
        r|   r   T)#rz   r{   r>   r   r?   r@   rA   rB   rC   rD   rE   rF   rG   rH   rI   rJ   rK   rL   rM   rN   rO   rP   rQ   rR   rS   rT   rU   rV   rW   rX   rZ   r[   r\   r]   rY   r   )r   r   r   r   r   r   r#   r   r7   r7   r8   r     s`    > 
%zAsyncCompletions.streamr   r7   r7   r7   r8   r0   A  s   	V c                   @  s   e Zd ZdddddZdS )r1   r/   Noner   r3   c                 C  s   || _ t|j| _d S N)_completionsr   Zto_raw_response_wrapperr   r6   r   r7   r7   r8   __init__Z  s    z#CompletionsWithRawResponse.__init__Nr   r   r   r   r7   r7   r7   r8   r1   Y  s   r1   c                   @  s   e Zd ZdddddZdS )r   r0   r   r   c                 C  s   || _ t|j| _d S r   )r   r   Zasync_to_raw_response_wrapperr   r   r7   r7   r8   r   c  s    z(AsyncCompletionsWithRawResponse.__init__Nr   r7   r7   r7   r8   r   b  s   r   c                   @  s   e Zd ZdddddZdS )r:   r/   r   r   c                 C  s   || _ t|j| _d S r   )r   r   r   r   r7   r7   r8   r   l  s    z)CompletionsWithStreamingResponse.__init__Nr   r7   r7   r7   r8   r:   k  s   r:   c                   @  s   e Zd ZdddddZdS )r   r0   r   r   c                 C  s   || _ t|j| _d S r   )r   r   r   r   r7   r7   r8   r   u  s    z.AsyncCompletionsWithStreamingResponse.__init__Nr   r7   r7   r7   r8   r   t  s   r   )Q
__future__r   typingr   r   r   r   r   r   r	   	functoolsr
   Ztyping_extensionsr   Zhttpx r   _typesr   r   r   r   r   _utilsr   r   _compatr   Z	_resourcer   r   	_responser   r   Z
_streamingr   Z
types.chatr   Z_base_clientr   Zlib._parsingr   r   r   r   r   r    r   Ztypes.chat_modelr!   Zlib.streaming.chatr"   r#   Ztypes.shared_paramsr$   r%   Ztypes.chat.chat_completionr&   Z types.chat.chat_completion_chunkr'   Z!types.chat.parsed_chat_completionr(   Z%types.chat.chat_completion_tool_paramr)   Z&types.chat.chat_completion_audio_paramr*   Z(types.chat.chat_completion_message_paramr+   Z/types.chat.chat_completion_stream_options_paramr,   Z3types.chat.chat_completion_prediction_content_paramr-   Z3types.chat.chat_completion_tool_choice_option_paramr.   __all__r/   r0   r1   r   r:   r   r7   r7   r7   r8   <module>   sJ   $    			