
    {h{%                        d dl Z d dlZd dlZd dlZd dlZd dlZd dlmZmZ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 d dlmZmZ d dlmZ d dlmZ  ed	      Z e
d
e      Z G d de      Z G d de j>                        Z dedef   de!fdZ"ejF                  dedef   de!fd       Z$dedef   de%fdZ& G d d      Z'y)    N)AnyCallableOptionalTypeVar	TypedDictLiteralUnion)	ParamSpecNotRequired)ChatCompletion)ChatCompletionMessageParam)	BaseModelvalidate_call)OpenAI)openai_schemaPT_Retval)boundc                   >    e Zd ZU ee   ed<   eeeee	f         ed<   y)OpenAIChatKwargsmessages	functionsN)
__name__
__module____qualname__listr   __annotations__r   dictstrr        R/var/www/html/hubwallet-dev/venv/lib/python3.12/site-packages/instructor/distil.pyr   r      s&    -..4S#X/00r!   r   c                       e Zd ZdZdZy)FinetuneFormatr   rawN)r   r   r   MESSAGESRAWr    r!   r"   r$   r$   #   s    H
Cr!   r$   fn.returnc                     t        j                  |       }d| j                   | }t        j                  |       }|rd| d}nd}| d| S )aJ  
    Get the function signature as a string.

    :Example:

    >>> def my_function(a: int, b: int) -> int:
    >>>     return a + b
    >>>
    >>> get_signature_from_fn(my_function)
    "def my_function(a: int, b: int) -> int"

    :param fn: Function to get the signature for.
    :return: Function signature as a string.
    def """

""" 
)inspect	signaturer   getdoc)r(   siglines	docstringformatted_docstrings        r"   get_signature_from_fnr7   (   sa     

B
C2;;-u%Er"I %i[6 WB*+,,r!   funcc                 ,   t        j                  |       }dj                  |d         j                         }t        j                  |       }|rd| d}nd}t        j
                  |       }|j                  d| j                   d      }| d| d| S )z@
    Format a function as a string with docstring and body.
     r   r,   r-   r.   r+   r/   )r0   getsourcelinesjoinstripr2   	getsourcereplacer   )r8   source_lines
definitionr5   r6   bodys         r"   format_functionrC   A   s    
 ))$/L,q/*002Jt$I %i[6 T"D<<$t}}o.3D\/04&99r!   c                     t        j                  |       j                  }|t         j                  j                  k7  sJ d       t        j
                  |      xr t        |t              S )z
    Check if the return type of a function is a pydantic BaseModel or an instance of it.

    :param func: Function to check.
    :return: True if the return type is a pydantic BaseModel or an instance of it.
    z9Must have a return type hint that is a pydantic BaseModel)r0   r1   return_annotation	Signatureemptyisclass
issubclassr   )r8   return_types     r"   %is_return_type_base_model_or_instancerK   U   s[     ##D);;K'++111 C1 ??;'NJ{I,NNr!   c                      e Zd Zdddej                  dddfdee   dee   deeej                        dede
d	ed
ee   ddfdZddddddedee   ded   dedee   deeeeeef   f   eeeef   geeeeef   f   f   f   fdZedej                  fdedef   deedf   deeef   dedee   deddfd       Zdededef   deedf   deeef   dee   defdZy)InstructionsN   Fnameidlog_handlersfinetune_formatindentinclude_code_bodyopenai_clientr)   c                    || _         |xs t        t        j                               | _        t        t        j                               | _        || _        || _        || _        |xs
 t               | _
        t        j                  | j                         | _        |xs g D ]  }| j                  j                  |        y)a  
        Instructions for distillation and dispatch.

        :param name: Name of the instructions.
        :param id: ID of the instructions.
        :param log_handlers: List of log handlers to use.
        :param finetune_format: Format to use for finetuning.
        :param indent: Indentation to use for finetuning.
        :param include_code_body: Whether to include the code body in the finetuning.
        N)rO   r   uuiduuid4rP   	unique_idrR   rS   rT   r   clientlogging	getLoggerlogger
addHandler)	selfrO   rP   rQ   rR   rS   rT   rU   handlers	            r"   __init__zInstructions.__init__d   s    ( 	)DJJL)TZZ\*.!2#/vx''		2#)r 	,GKK""7+	,r!   distilzgpt-3.5-turbo)rO   modemodelfine_tune_formatargsrc   )rb   dispatchrd   re   c                    ddh}|v s
J d|         j                   dt        t        t        f   dt        t        t        t        t
        f   f   f fd}t        |      dk(  rt        |d         r ||d         S |S )	ag  
        Decorator to track the function call and response, supports distillation and dispatch modes.

        If used without arguments, it must be used as a decorator.

        :Example:

        >>> @distil
        >>> def my_function() -> MyModel:
        >>>     return MyModel()
        >>>
        >>> @distil(name="my_function")
        >>> def my_function() -> MyModel:
        >>>     return MyModel()

        :param fn: Function to track.
        :param name: Name of the function to track. Defaults to the function name.
        :param mode: Mode to use for distillation. Defaults to "distil".
        rb   rg   zMust be in r(   r)   c                     d  d}t               sJ |       t        j                         j                  t	        j
                         dt        j                  dt        j                  dt        f 	fd       }t	        j
                         dt        j                  dt        j                  dt        f 	fd       }dk(  r|S |S )	NzReturn type hint for z# must subclass `pydantic.BaseModel'rf   kwargsr)   c                      j                  rnj                  | |      } j                  j                  j                  j
                  di |dS )N)rO   r(   rf   rj   
base_model)rd   response_modelr    )openai_kwargsr   rZ   chatcompletionscreate)rf   rj   rn   r(   rd   rO   return_base_modelr_   s      r"   	_dispatchz<Instructions.distil.<locals>._wrap_distil.<locals>._dispatch   si     $ 2 2!%2;;!0 !3 ! ;t{{''33:: ##4 r!   c                  F     | i |}j                  | ||       |S )N)rO   rR   )track)rf   rj   respre   r(   rO   r_   s      r"   _distilz:Instructions.distil.<locals>._wrap_distil.<locals>._distil   s<    4*6*

$4   r!   rg   )rK   r0   r1   rE   	functoolswrapsr   rf   rj   r   r   )
r(   msgrs   rw   rr   re   rc   rd   rO   r_   s
   `   @r"   _wrap_distilz)Instructions.distil.<locals>._wrap_distil   s     *"-PQC8<AcA< ' 1 1" 5 G G__R  188    ! __R 
qvv 
 
h 
 !
 !%
 29??r!      r   )rR   r   r   r   r	   r   lencallable)r_   rO   rc   rd   re   rf   allowed_modesr{   s   `````   r"   rb   zInstructions.distil   s    < ":.}$CM?&CC$##33#	@H%#	@ax7889#	@ #	@J t9>htAw/Q((r!   r(   .rj   rv   c           	         |r|n|j                   }t        |      }|t        j                  k(  rt	        |      j                  }| j                  |||||      }	|	d   j                  d|j                   |j                  | j                        dd       |g|	d<   | j                  j                  t        j                  |	             |t        j                  k(  ret        |t        |      |||j!                         |j#                               }
| j                  j                  t        j                  |
             yy)	a  
        Track the function call and response in a log file, later used for finetuning.

        :param fn: Function to track.
        :param args: Arguments passed to the function.
        :param kwargs: Keyword arguments passed to the function.
        :param resp: Response returned by the function.
        :param name: Name of the function to track. Defaults to the function name.
        :param finetune_format: Format to use for finetuning. Defaults to "raw".
        r   	assistant)rS   )rO   	arguments)rolefunction_callr   )fn_namefn_reprrf   rj   rv   schemaN)r   typer$   r&   r   rn   appendmodel_dump_jsonrS   r]   infojsondumpsr'   r   rC   
model_dumpmodel_json_schema)r_   r(   rf   rj   rv   rO   rR   rl   openai_function_callrn   function_bodys              r"   ru   zInstructions.track   s   ( t$Z
n555#0#<#J#J  ..tRvzRM*%,,' * 3 3%)%9%9%9%M& +?)?M+&KKTZZ67n000 '+__&!335M KKTZZ67 1r!   rl   c                 D   | j                   rt        |      }nt        |      }dj                  t	        t
        |            }dj                  d |j                         D              xs d }dj                  t        d ||g            }	ddd| ddd| d	|	 d
dgi}
|
S )Nz, c              3   V   K   | ]!  \  }}| d t        j                  |        # yw)=N)r   r   ).0kvs      r"   	<genexpr>z-Instructions.openai_kwargs.<locals>.<genexpr>  s'     HA1TZZ]O,Hs   ')r   systemz'Predict the results of this function:

)r   contentuserzReturn `(z)`)rT   rC   r7   r<   mapr   itemsfilter)r_   rO   r(   rf   rj   rl   func_defstr_args
str_kwargs	call_argsr   s              r"   rn   zInstructions.openai_kwargs  s     !!&r*H,R0H99Sd^,IIHHHPD 	 IIfTHj+ABC	 $!J8*U
 #!)$q2>	+
 r!   )r   r   r   r$   r&   r   r   r   r[   Handlerintboolr   ra   r   r   r	   r   r   r   r   rb   r   tupler   r   ru   r   r   rn   r    r!   r"   rM   rM   c   s!    # 8<*8*A*A"'*.,sm, SM, tGOO45	,
 (, ,  ,  ', 
,F #.6$59LL smL *+	L
 L #>2L 
E(N2334(1h;'((1eHn<T6U3U*VVW	Y
L\  #*8*A*A.8S#X.8 CHo.8 S#X	.8
 .8 sm.8 (.8 
.8 .8` S#X CHo	
 S#X O 
r!   rM   )(enumr   rW   r[   r0   rx   typingr   r   r   r   r   r   r	   typing_extensionsr
   r   !openai.types.chat.chat_completionr   /openai.types.chat.chat_completion_message_paramr   pydanticr   r   openair   instructor.function_callsr   r   r   r   Enumr$   r   r7   	lru_cacherC   r   rK   rM   r    r!   r"   <module>r      s            5 < V -  3 cN:Y/1y 1
TYY 
-hsCx0 -S -2 :(38, : : :&Oc0B Ot O r!   