o
    h:                     @  s<  d dl mZ d dlZd dlZd dlZd dlZ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mZ d dlmZmZmZ d dlmZ dd	lmZ dd
lmZ ddlmZ ddlm Z  eG dd dZ!eG dd dZ"ed Z#d3ddZ$ej%dd Z&	d4d5ddZ'd6d#d$Z(d7d(d)Z)				*	*d8d9d1d2Z*dS ):    )annotationsN)	dataclass)	AnnotatedAnyCallableLiteralget_args
get_originget_type_hints)	DocstringDocstringSectionKind)	BaseModelFieldcreate_model)	FieldInfo   )	UserError)RunContextWrapper)ensure_strict_json_schema)ToolContextc                   @  sj   e Zd ZU dZded< 	 ded< 	 ded< 	 ded	< 	 d
ed< 	 dZded< 	 dZded< 	 dddZdS )
FuncSchemazg
    Captures the schema for a python function, in preparation for sending it to an LLM as a tool.
    strname
str | Nonedescriptionztype[BaseModel]params_pydantic_modelzdict[str, Any]params_json_schemazinspect.Signature	signatureFbooltakes_contextTstrict_json_schemadatar   return tuple[list[Any], dict[str, Any]]c           	      C  s   g }i }d}t | jj D ]L\}\}}| jr|dkrqt||d}|j|jkr2||p-g  d}q|j|j	kr@|
|p=i  q|j|j|jfv rV|sQ|| q|||< q|||< q||fS )z
        Converts validated data from the Pydantic model into (args, kwargs), suitable for calling
        the original function.
        Fr   NT)	enumerater   
parametersitemsr   getattrkindVAR_POSITIONALextendVAR_KEYWORDupdatePOSITIONAL_ONLYPOSITIONAL_OR_KEYWORDappend)	selfr!   positional_argskeyword_argsseen_var_positionalidxr   paramvalue r7   W/var/www/html/openai_agents/venv/lib/python3.10/site-packages/agents/function_schema.pyto_call_args*   s$   

zFuncSchema.to_call_argsN)r!   r   r"   r#   )__name__
__module____qualname____doc____annotations__r   r    r9   r7   r7   r7   r8   r      s"   
 r   c                   @  s.   e Zd ZU dZded< 	 ded< 	 ded< dS )	FuncDocumentationzHContains metadata about a Python function, extracted from its docstring.r   r   r   r   zdict[str, str] | Noneparam_descriptionsN)r:   r;   r<   r=   r>   r7   r7   r7   r8   r?   M   s   
 r?   )googlenumpysphinxdocr   r"   DocstringStylec           	      C  s   dddd}g d}|D ]}t || t jr|d  d7  < qg d}|D ]}t || t jr7|d  d7  < q%g d}|D ]}t || t jrP|d	  d7  < q>t| }|dkr]d	S g d}|D ]}|| |kro|  S qcd	S )
Nr   )rC   rB   rA   )z	^:param\sz^:type\sz	^:return:z^:rtype:rC   r   )z^Parameters\s*\n\s*-{3,}z^Returns\s*\n\s*-{3,}z^Yields\s*\n\s*-{3,}rB   )z^(Args|Arguments):z^(Returns):z
^(Raises):rA   )research	MULTILINEmaxvalues)	rD   scoressphinx_patternspatternnumpy_patternsgoogle_patterns	max_scorestylesstyler7   r7   r8   _detect_docstring_style^   s2   rS   c               	   c  sD    t d} |  }| t j zd V  W | | d S | | w )Ngriffe)logging	getLoggergetEffectiveLevelsetLevelERROR)loggerprevious_levelr7   r7   r8   _suppress_griffe_logging   s   
r\   funcCallable[..., Any]rR   DocstringStyle | Nonec                 C  s   | j }t| }|st|dddS t  t|d|pt|d}| }W d   n1 s.w   Y  tdd |D d}dd |D }t| j ||pKddS )	a  
    Extracts metadata from a function docstring, in preparation for sending it to an LLM as a tool.

    Args:
        func: The function to extract documentation from.
        style: The style of the docstring to use for parsing. If not provided, we will attempt to
            auto-detect the style.

    Returns:
        A FuncDocumentation object containing the function's name, description, and parameter
        descriptions.
    N)r   r   r@   r   )linenoparserc                 s  s"    | ]}|j tjkr|jV  qd S N)r(   r   textr6   ).0sectionr7   r7   r8   	<genexpr>   s     z.generate_func_documentation.<locals>.<genexpr>c                 S  s.   i | ]}|j tjkr|jD ]}|j|jqqS r7   )r(   r   r%   r6   r   r   )rd   re   r5   r7   r7   r8   
<dictcomp>   s    z/generate_func_documentation.<locals>.<dictcomp>)	r:   inspectgetdocr?   r\   r   rS   parsenext)r]   rR   r   rD   	docstringparsedr   r@   r7   r7   r8   generate_func_documentation   s&   

rn   
annotationr   tuple[Any, tuple[Any, ...]]c                 C  s\   d}| }t |tu r*t|}|s	 ||fS |d }g ||dd R }t |tu s
||fS )zIReturns the underlying annotation and any metadata from typing.Annotated.r7   r   r   N)r	   r   r   )ro   metadataannargsr7   r7   r8   _strip_annotated   s   rt   rq   tuple[Any, ...]r   c                 C  s    | D ]}t |tr|  S qdS )zIExtracts a human readable description from Annotated metadata if present.N)
isinstancer   )rq   itemr7   r7   r8   "_extract_description_from_metadata   s
   
rx   Tdocstring_stylename_overridedescription_overrideuse_docstring_infor   r    c           !   	   C  s  |rt | |}t|jpi }nd}i }t| dd}i }	i }
| D ]\}}|dkr*q!t|\}}||	|< t|}|dur@||
|< q!|
 D ]
\}}||| qE|pY|rW|jn| j	}t
| }t|j }d}g }|r|d \}}|	||j}|t
jkrt|p|}|tu s|tu rd}n|||f n|||f |dd D ]-\}}|	||j}|t
jkrt|p|}|tu s|tu rtd| j	 |||f qi }|D ]\}}|	||j}|j}|t
jkrt}||d}|j|jkr,t|tu rt|}t|d	kr|d tu rt|d  }n	tt }nt| }|tt|d
f||< q|j|jkrht|tu rWt|}t|d	krPt|d |d f }ntt tf }ntt |f }|tt|d
f||< q|t
jkry|td|df||< qt!|t"r|t"j#||p|j$df||< q|t||df||< qt%| dfdt&i|}|' } |rt(| } t)||p|r|j$nd|| |||dS )a  
    Given a Python function, extracts a `FuncSchema` from it, capturing the name, description,
    parameter descriptions, and other metadata.

    Args:
        func: The function to extract the schema from.
        docstring_style: The style of the docstring to use for parsing. If not provided, we will
            attempt to auto-detect the style.
        name_override: If provided, use this name instead of the function's `__name__`.
        description_override: If provided, use this description instead of the one derived from the
            docstring.
        use_docstring_info: If True, uses the docstring to generate the description and parameter
            descriptions.
        strict_json_schema: Whether the JSON schema is in strict mode. If True, we'll ensure that
            the schema adheres to the "strict" standard the OpenAI API expects. We **strongly**
            recommend setting this to True, as it increases the likelihood of the LLM producing
            correct JSON input.

    Returns:
        A `FuncSchema` object containing the function's name, description, parameter descriptions,
        and other metadata.
    NT)include_extrasr"   Fr   r   zLRunContextWrapper/ToolContext param found at non-first position in function    )default_factoryr   .)r   )defaultr   _args__base__)r   r   r   r   r   r   r    )*rn   dictr@   r
   r&   rt   rx   
setdefaultr   r:   rh   r   listr%   getro   _emptyr	   r   r   r/   r   r   r   r(   r)   tupler   lenEllipsisr   r+   r   rv   r   merge_field_infosr   r   r   model_json_schemar   r   )!r]   ry   rz   r{   r|   r    doc_infoparam_descstype_hints_with_extras
type_hintsannotated_param_descsr   ro   stripped_annrq   r   	func_namesigparamsr   filtered_params
first_namefirst_paramrr   originr5   fieldsr   field_descriptionargs_of_tuple	dict_argsdynamic_modeljson_schemar7   r7   r8   function_schema   s    












	

r   )rD   r   r"   rE   rb   )r]   r^   rR   r_   r"   r?   )ro   r   r"   rp   )rq   ru   r"   r   )NNNTT)r]   r^   ry   r_   rz   r   r{   r   r|   r   r    r   r"   r   )+
__future__r   
contextlibrh   rU   rF   dataclassesr   typingr   r   r   r   r   r	   r
   rT   r   r   pydanticr   r   r   pydantic.fieldsr   
exceptionsr   run_contextr   strict_schemar   tool_contextr   r   r?   rE   rS   contextmanagerr\   rn   rt   rx   r   r7   r7   r7   r8   <module>   s@    $8
(

*
