o
    پi1#                     @   sB  d Z ddlZddlZddlmZmZmZmZ ddlm	Z	m
Z
mZmZmZmZ ddlZddlmZ ddlmZ g dZedd	G d
d dZG dd dZejedddedeedf dedeejeef fddZde	de	fddZejdd Ze e	d!dedee fddZ!		d"dedee dee fdd Z"dS )#zIntegration with OpenAI's API.    N)asdict	dataclassfieldreplace)CallableDictListOptionalTupleUnion)	vectorize)cache)OpenAIopenaiazure_openaiT)frozenc                   @   s   e Zd ZU dZdZeed< dZeed< e	e
dZeeef ed< dZee ed	< d
Zeed< dZeed< dZeeeef  ed< dZee ed< dZeeeee f  ed< dZeed< d
Zeed< e	edZeed< dS )OpenAIConfigas  Represents the parameters of the OpenAI API.

    The information was last fetched on 2023/11/20. We document below the
    properties that are specific to the OpenAI API. Not all these properties are
    supported by Outlines.

    Properties
    ----------
    model
        The name of the model. Available models can be found on OpenAI's website.
    frequence_penalty
        Number between 2.0 and -2.0. Positive values penalize new tokens based on
        their existing frequency in the text,
    logit_bias
        Modifies the likelihood of specified tokens to appear in the completion.
        Number between -100 (forbid) and +100 (only allows).
    n
        The number of completions to return for each prompt.
    presence_penalty
        Similar to frequency penalty.
    response_format
        Specifies the format the model must output. `{"type": "json_object"}`
        enables JSON mode.
    seed
        Two completions with the same `seed` value should return the same
        completion. This is however not guaranteed.
    stop
        Up to 4 words where the API will stop the completion.
    temperature
        Number between 0 and 2. Higher values make the output more random, while
        lower values make it more deterministic.
    top_p
        Number between 0 and 1. Parameter for nucleus sampling.
    user
        A unique identifier for the end-user.

     modelr   frequency_penalty)default_factory
logit_biasN
max_tokens   npresence_penaltyresponse_formatseedstopg      ?temperaturetop_puser)__name__
__module____qualname____doc__r   str__annotations__r   floatr   dictr   r   intr   r	   r   r   r   r   r   r   r   r   r    r!    r+   r+   J/home/ubuntu/.local/lib/python3.10/site-packages/outlines/models/openai.pyr      s   
 &r   c                   @   s   e Zd ZdZ	ddee fddZ		ddddddeeee f dee	 d	eeee ef  dee d
ee
 dee	 dejfddZdd Zdd Zdd Zdd ZdS )r   z)An object that represents the OpenAI API.Nsystem_promptc                 C   s&   || _ || _d| _d| _dd | _dS )a  Create an `OpenAI` instance.

        This class supports the standard OpenAI API, the Azure OpeanAI API as
        well as compatible APIs that rely on the OpenAI client.

        Parameters
        ----------
        client
            An instance of the API's async client.
        config
            An instance of `OpenAIConfig`. Can be useful to specify some
            parameters that cannot be set by calling this class' methods.
        r   c                 S   s   | S Nr+   )seqr+   r+   r,   <lambda>e   s    z!OpenAI.__init__.<locals>.<lambda>N)clientconfigprompt_tokenscompletion_tokensformat_sequence)selfr1   r2   r-   r+   r+   r,   __init__H   s
   zOpenAI.__init__)r-   r   samplespromptr   stop_atr   r8   returnc                C   s   |du r| j j}|du r| j j}|du r| j j}|du r | j j}t| j ||||d}t||| j|\}}	}
|  j|	7  _|  j	|
7  _	| 
|S )a  Call the OpenAI API to generate text.

        Parameters
        ----------
        prompt
            A string or list of strings that will be used to prompt the model
        max_tokens
            The maximum number of tokens to generate
        stop_at
            A string or array of strings which, such that the generation stops
            when they are generated.
        system_prompt
            The content of the system message that precedes the user's prompt.
        temperature
            The value of the temperature used to sample tokens
        samples
            The number of completions to generate for each prompt
        stop_at
            Up to 4 words where the API will stop the completion.

        N)r   r   r   r   )r2   r   r   r   r   r   generate_chatr1   r3   r4   r5   )r6   r9   r   r:   r-   r   r8   r2   responser3   r4   r+   r+   r,   __call__g   s   


zOpenAI.__call__c                 O   s   t d)Nz7Streaming is currently not supported for the OpenAI API)NotImplementedError)r6   argskwargsr+   r+   r,   stream   s   zOpenAI.streamc                 K   s"   t  | }t|jfi ||_|S r.   )copyr   r2   )r6   rA   new_instancer+   r+   r,   new_with_replacements   s   
zOpenAI.new_with_replacementsc                 C   s   | j jd S )Nz API)	__class__r"   r6   r+   r+   r,   __str__   s   zOpenAI.__str__c                 C   s
   t | jS r.   )r&   r2   rG   r+   r+   r,   __repr__   s   
zOpenAI.__repr__r.   NN)r"   r#   r$   r%   r	   r&   r7   r   r   r*   r(   npndarrayr>   rB   rE   rH   rI   r+   r+   r+   r,   r   E   s>    
"	
2r   z(),(),(),()->(s),(),())	signaturer9   r-   r2   r;   c                    s   t t  fdd}|rd|dgng d| dg|| ||I dH tfddt|jD }d	 }||d
 |d fS )a  Call OpenAI's Chat Completion API.

    Parameters
    ----------
    prompt
        The prompt we use to start the generation. Passed to the model
        with the "user" role.
    system_prompt
        The system prompt, passed to the model with the "system" role
        before the prompt.
    client
        The API client
    config
        An `OpenAIConfig` instance.

    Returns
    -------
    A tuple that contains the model's response(s) and usage statistics.

    c                    s0    j jjdd it|I d H }| S )Nmessagesr+   )chatcompletionscreater   
model_dump)r9   r-   r2   	responses)r1   system_messageuser_messager+   r,   call_api   s   zgenerate_chat.<locals>.call_apisystem)rolecontentr!   Nc                    s    g | ]} d  | d d qS )choicesmessagerY   r+   ).0i)rS   r+   r,   
<listcomp>   s     z!generate_chat.<locals>.<listcomp>usager3   r4   )error_handlerr   rK   arrayranger   )r9   r-   r1   r2   rV   resultsr_   r+   )r1   rS   rT   rU   r,   r<      s   r<   api_call_fnc                    s    fdd}|S )z-Handle OpenAI API errors and missing API key.c                     s~   dd l }z | i |W S  |j|j|jfy% } ztd| d }~w |j|j|j|j|j	|j
fy> } z|d }~ww )Nr   z%Could not connect to the OpenAI API: )r   APITimeoutErrorInternalServerErrorRateLimitErrorOSErrorAuthenticationErrorBadRequestErrorConflictErrorPermissionDeniedErrorNotFoundErrorUnprocessableEntityError)r@   rA   r   erd   r+   r,   call   s*   zerror_handler.<locals>.callr+   )rd   rq   r+   rp   r,   r`      s   r`   c                 O   s   t | g|R i |S r.   )r   )model_or_clientr@   rA   r+   r+   r,   r      s   r   
model_namec                 K   s`   zddl m} W n ty   tdw |d urt|| d}nt| d}|di |}t||S )Nr   )AsyncOpenAIzXThe `openai` library needs to be installed in order to use Outlines' OpenAI integration.r   r+   )r   rt   ImportErrorr   r   r   )rs   r2   openai_client_paramsrt   r1   r+   r+   r,   openai_model   s   

rx   deployment_namec                 K   sf   zddl m} W n ty   tdw |d urt|| d}|d u r't| d}|di |}t||S )Nr   )AsyncAzureOpenAIz^The `openai` library needs to be installed in order to use Outlines' Azure OpenAI integration.ru   r+   )r   rz   rv   r   r   r   )ry   rs   r2   azure_openai_client_paramsrz   r1   r+   r+   r,   r     s   

r   r.   rJ   )#r%   rC   	functoolsdataclassesr   r   r   r   typingr   r   r   r	   r
   r   numpyrK   outlines.baser   outlines.cachingr   __all__r   r   partialr&   rL   r*   r<   r`   singledispatchr   registerrx   r   r+   r+   r+   r,   <module>   sR     5e
3
