Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Function schema

FuncSchemadataclass

Captures the schema for a python function, in preparation for sending it to an LLM as a tool.

Source code insrc/agents/function_schema.py
@dataclassclassFuncSchema:"""    Captures the schema for a python function, in preparation for sending it to an LLM as a tool.    """name:str"""The name of the function."""description:str|None"""The description of the function."""params_pydantic_model:type[BaseModel]"""A Pydantic model that represents the function's parameters."""params_json_schema:dict[str,Any]"""The JSON schema for the function's parameters, derived from the Pydantic model."""signature:inspect.Signature"""The signature of the function."""takes_context:bool=False"""Whether the function takes a RunContextWrapper argument (must be the first argument)."""strict_json_schema:bool=True"""Whether the JSON schema is in strict mode. We **strongly** recommend setting this to True,    as it increases the likelihood of correct JSON input."""defto_call_args(self,data:BaseModel)->tuple[list[Any],dict[str,Any]]:"""        Converts validated data from the Pydantic model into (args, kwargs), suitable for calling        the original function.        """positional_args:list[Any]=[]keyword_args:dict[str,Any]={}seen_var_positional=False# Use enumerate() so we can skip the first parameter if it's context.foridx,(name,param)inenumerate(self.signature.parameters.items()):# If the function takes a RunContextWrapper and this is the first parameter, skip it.ifself.takes_contextandidx==0:continuevalue=getattr(data,name,None)ifparam.kind==param.VAR_POSITIONAL:# e.g. *args: extend positional args and mark that *args is now seenpositional_args.extend(valueor[])seen_var_positional=Trueelifparam.kind==param.VAR_KEYWORD:# e.g. **kwargs handlingkeyword_args.update(valueor{})elifparam.kindin(param.POSITIONAL_ONLY,param.POSITIONAL_OR_KEYWORD):# Before *args, add to positional args. After *args, add to keyword args.ifnotseen_var_positional:positional_args.append(value)else:keyword_args[name]=valueelse:# For KEYWORD_ONLY parameters, always use keyword args.keyword_args[name]=valuereturnpositional_args,keyword_args

nameinstance-attribute

name:str

The name of the function.

descriptioninstance-attribute

description:str|None

The description of the function.

params_pydantic_modelinstance-attribute

params_pydantic_model:type[BaseModel]

A Pydantic model that represents the function's parameters.

params_json_schemainstance-attribute

params_json_schema:dict[str,Any]

The JSON schema for the function's parameters, derived from the Pydantic model.

signatureinstance-attribute

signature:Signature

The signature of the function.

takes_contextclass-attributeinstance-attribute

takes_context:bool=False

Whether the function takes a RunContextWrapper argument (must be the first argument).

strict_json_schemaclass-attributeinstance-attribute

strict_json_schema:bool=True

Whether the JSON schema is in strict mode. Westrongly recommend setting this to True,as it increases the likelihood of correct JSON input.

to_call_args

to_call_args(data:BaseModel,)->tuple[list[Any],dict[str,Any]]

Converts validated data from the Pydantic model into (args, kwargs), suitable for callingthe original function.

Source code insrc/agents/function_schema.py
defto_call_args(self,data:BaseModel)->tuple[list[Any],dict[str,Any]]:"""    Converts validated data from the Pydantic model into (args, kwargs), suitable for calling    the original function.    """positional_args:list[Any]=[]keyword_args:dict[str,Any]={}seen_var_positional=False# Use enumerate() so we can skip the first parameter if it's context.foridx,(name,param)inenumerate(self.signature.parameters.items()):# If the function takes a RunContextWrapper and this is the first parameter, skip it.ifself.takes_contextandidx==0:continuevalue=getattr(data,name,None)ifparam.kind==param.VAR_POSITIONAL:# e.g. *args: extend positional args and mark that *args is now seenpositional_args.extend(valueor[])seen_var_positional=Trueelifparam.kind==param.VAR_KEYWORD:# e.g. **kwargs handlingkeyword_args.update(valueor{})elifparam.kindin(param.POSITIONAL_ONLY,param.POSITIONAL_OR_KEYWORD):# Before *args, add to positional args. After *args, add to keyword args.ifnotseen_var_positional:positional_args.append(value)else:keyword_args[name]=valueelse:# For KEYWORD_ONLY parameters, always use keyword args.keyword_args[name]=valuereturnpositional_args,keyword_args

FuncDocumentationdataclass

Contains metadata about a python function, extracted from its docstring.

Source code insrc/agents/function_schema.py
@dataclassclassFuncDocumentation:"""Contains metadata about a python function, extracted from its docstring."""name:str"""The name of the function, via `__name__`."""description:str|None"""The description of the function, derived from the docstring."""param_descriptions:dict[str,str]|None"""The parameter descriptions of the function, derived from the docstring."""

nameinstance-attribute

name:str

The name of the function, via__name__.

descriptioninstance-attribute

description:str|None

The description of the function, derived from the docstring.

param_descriptionsinstance-attribute

param_descriptions:dict[str,str]|None

The parameter descriptions of the function, derived from the docstring.

generate_func_documentation

generate_func_documentation(func:Callable[...,Any],style:DocstringStyle|None=None,)->FuncDocumentation

Extracts metadata from a function docstring, in preparation for sending it to an LLM as a tool.

Parameters:

NameTypeDescriptionDefault
funcCallable[...,Any]

The function to extract documentation from.

required
styleDocstringStyle | None

The style of the docstring to use for parsing. If not provided, we will attempt toauto-detect the style.

None

Returns:

TypeDescription
FuncDocumentation

A FuncDocumentation object containing the function's name, description, and parameter

FuncDocumentation

descriptions.

Source code insrc/agents/function_schema.py
defgenerate_func_documentation(func:Callable[...,Any],style:DocstringStyle|None=None)->FuncDocumentation:"""    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.    """name=func.__name__doc=inspect.getdoc(func)ifnotdoc:returnFuncDocumentation(name=name,description=None,param_descriptions=None)with_suppress_griffe_logging():docstring=Docstring(doc,lineno=1,parser=styleor_detect_docstring_style(doc))parsed=docstring.parse()description:str|None=next((section.valueforsectioninparsedifsection.kind==DocstringSectionKind.text),None)param_descriptions:dict[str,str]={param.name:param.descriptionforsectioninparsedifsection.kind==DocstringSectionKind.parametersforparaminsection.value}returnFuncDocumentation(name=func.__name__,description=description,param_descriptions=param_descriptionsorNone,)

function_schema

function_schema(func:Callable[...,Any],docstring_style:DocstringStyle|None=None,name_override:str|None=None,description_override:str|None=None,use_docstring_info:bool=True,strict_json_schema:bool=True,)->FuncSchema

Given a python function, extracts aFuncSchema from it, capturing the name, description,parameter descriptions, and other metadata.

Parameters:

NameTypeDescriptionDefault
funcCallable[...,Any]

The function to extract the schema from.

required
docstring_styleDocstringStyle | None

The style of the docstring to use for parsing. If not provided, we willattempt to auto-detect the style.

None
name_overridestr | None

If provided, use this name instead of the function's__name__.

None
description_overridestr | None

If provided, use this description instead of the one derived from thedocstring.

None
use_docstring_infobool

If True, uses the docstring to generate the description and parameterdescriptions.

True
strict_json_schemabool

Whether the JSON schema is in strict mode. If True, we'll ensure thatthe schema adheres to the "strict" standard the OpenAI API expects. Westronglyrecommend setting this to True, as it increases the likelihood of the LLM providingcorrect JSON input.

True

Returns:

TypeDescription
FuncSchema

AFuncSchema object containing the function's name, description, parameter descriptions,

FuncSchema

and other metadata.

Source code insrc/agents/function_schema.py
deffunction_schema(func:Callable[...,Any],docstring_style:DocstringStyle|None=None,name_override:str|None=None,description_override:str|None=None,use_docstring_info:bool=True,strict_json_schema:bool=True,)->FuncSchema:"""    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 providing            correct JSON input.    Returns:        A `FuncSchema` object containing the function's name, description, parameter descriptions,        and other metadata.    """# 1. Grab docstring infoifuse_docstring_info:doc_info=generate_func_documentation(func,docstring_style)param_descs=doc_info.param_descriptionsor{}else:doc_info=Noneparam_descs={}# Ensure name_override takes precedence even if docstring info is disabled.func_name=name_overrideor(doc_info.nameifdoc_infoelsefunc.__name__)# 2. Inspect function signature and get type hintssig=inspect.signature(func)type_hints=get_type_hints(func)params=list(sig.parameters.items())takes_context=Falsefiltered_params=[]ifparams:first_name,first_param=params[0]# Prefer the evaluated type hint if availableann=type_hints.get(first_name,first_param.annotation)ifann!=inspect._empty:origin=get_origin(ann)oranniforiginisRunContextWrapperororiginisToolContext:takes_context=True# Mark that the function takes contextelse:filtered_params.append((first_name,first_param))else:filtered_params.append((first_name,first_param))# For parameters other than the first, raise error if any use RunContextWrapper or ToolContext.forname,paraminparams[1:]:ann=type_hints.get(name,param.annotation)ifann!=inspect._empty:origin=get_origin(ann)oranniforiginisRunContextWrapperororiginisToolContext:raiseUserError(f"RunContextWrapper/ToolContext param found at non-first position in function"f"{func.__name__}")filtered_params.append((name,param))# We will collect field definitions for create_model as a dict:#   field_name -> (type_annotation, default_value_or_Field(...))fields:dict[str,Any]={}forname,paraminfiltered_params:ann=type_hints.get(name,param.annotation)default=param.default# If there's no type hint, assume `Any`ifann==inspect._empty:ann=Any# If a docstring param description exists, use itfield_description=param_descs.get(name,None)# Handle different parameter kindsifparam.kind==param.VAR_POSITIONAL:# e.g. *args: extend positional argsifget_origin(ann)istuple:# e.g. def foo(*args: tuple[int, ...]) -> treat as List[int]args_of_tuple=get_args(ann)iflen(args_of_tuple)==2andargs_of_tuple[1]isEllipsis:ann=list[args_of_tuple[0]]# type: ignoreelse:ann=list[Any]else:# If user wrote *args: int, treat as List[int]ann=list[ann]# type: ignore# Default factory to empty listfields[name]=(ann,Field(default_factory=list,description=field_description),# type: ignore)elifparam.kind==param.VAR_KEYWORD:# **kwargs handlingifget_origin(ann)isdict:# e.g. def foo(**kwargs: dict[str, int])dict_args=get_args(ann)iflen(dict_args)==2:ann=dict[dict_args[0],dict_args[1]]# type: ignoreelse:ann=dict[str,Any]else:# e.g. def foo(**kwargs: int) -> Dict[str, int]ann=dict[str,ann]# type: ignorefields[name]=(ann,Field(default_factory=dict,description=field_description),# type: ignore)else:# Normal parameterifdefault==inspect._empty:# Required fieldfields[name]=(ann,Field(...,description=field_description),)elifisinstance(default,FieldInfo):# Parameter with a default value that is a Field(...)fields[name]=(ann,FieldInfo.merge_field_infos(default,description=field_descriptionordefault.description),)else:# Parameter with a default valuefields[name]=(ann,Field(default=default,description=field_description),)# 3. Dynamically build a Pydantic modeldynamic_model=create_model(f"{func_name}_args",__base__=BaseModel,**fields)# 4. Build JSON schema from that modeljson_schema=dynamic_model.model_json_schema()ifstrict_json_schema:json_schema=ensure_strict_json_schema(json_schema)# 5. Return as a FuncSchema dataclassreturnFuncSchema(name=func_name,# Ensure description_override takes precedence even if docstring info is disabled.description=description_overrideor(doc_info.descriptionifdoc_infoelseNone),params_pydantic_model=dynamic_model,params_json_schema=json_schema,signature=sig,takes_context=takes_context,strict_json_schema=strict_json_schema,)

[8]ページ先頭

©2009-2025 Movatter.jp