
    6i%                        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        \/root/.openclaw/workspace/visionaryfx/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_fnr8   (   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,   r0   )r1   getsourcelinesjoinstripr3   	getsourcereplacer   )r9   source_lines
definitionr6   r7   bodys         r#   format_functionrD   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)r1   r2   return_annotation	Signatureemptyisclass
issubclassr   )r9   return_types     r#   %is_return_type_base_model_or_instancerL   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)rP   r    uuiduuid4rQ   	unique_idrS   rT   rU   r   clientlogging	getLoggerlogger
addHandler)	selfrP   rQ   rR   rS   rT   rU   rV   handlers	            r#   __init__zInstructions.__init__d   s    ( 	)DJJL)TZZ\*.!2#/vx''		2#)r 	,GKK""7+	,r"   distilzgpt-3.5-turbo)rP   modemodelfine_tune_formatargsrd   )rc   dispatchre   rf   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".
        rc   rh   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'rg   kwargsr*   c                      j                  rnj                  | |      } j                  j                  j                  j
                  di |dS )N)rP   r)   rg   rk   
base_model)re   response_modelr!   )openai_kwargsr   r[   chatcompletionscreate)rg   rk   ro   r)   re   rP   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)rP   rS   )track)rg   rk   resprf   r)   rP   r`   s      r#   _distilz:Instructions.distil.<locals>._wrap_distil.<locals>._distil   s<    4*6*

$4   r"   rh   )rL   r1   r2   rF   	functoolswrapsr   rg   rk   r   r   )
r)   msgrt   rx   rs   rf   rd   re   rP   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   r   )rS   r   r   r   r	   r   lencallable)r`   rP   rd   re   rf   rg   allowed_modesr|   s   `````   r#   rc   zInstructions.distil   s    < ":.}$CM?&CC$##33#	@H%#	@ax7889#	@ #	@J t9>htAw/Q((r"   r)   .rk   rw   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)rT   )rP   	arguments)rolefunction_callr   )fn_namefn_reprrg   rk   rw   schemaN)r   typer%   r'   r   ro   appendmodel_dump_jsonrT   r^   infojsondumpsr(   r   rD   
model_dumpmodel_json_schema)r`   r)   rg   rk   rw   rP   rS   rm   openai_function_callro   function_bodys              r#   rv   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"   rm   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)`)rU   rD   r8   r=   mapr    itemsfilter)r`   rP   r)   rg   rk   rm   func_defstr_args
str_kwargs	call_argsr   s              r#   ro   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   rb   r   r   r	   r   r   r   r   rc   r   tupler   r   rv   r   r   ro   r!   r"   r#   rN   rN   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"   rN   )(enumr   rX   r\   r1   ry   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   processing.function_callsr   r   r   r   Enumr%   r    r8   	lru_cacherD   r   rL   rN   r!   r"   r#   <module>r      s            5 < V -  4 cN:Y/1y 1
TYY 
-hsCx0 -S -2 :(38, : : :&Oc0B Ot O r"   