MCPcopy Create free account
hub / github.com/Paper2Poster/Paper2Poster / get_openai_tool_schema

Function get_openai_tool_schema

camel/toolkits/function_tool.py:90–186  ·  view source on GitHub ↗

r"""Generates an OpenAI JSON schema from a given Python function. This function creates a schema compatible with OpenAI's API specifications, based on the provided Python function. It processes the function's parameters, types, and docstrings, and constructs a schema accordingly. N

(func: Callable)

Source from the content-addressed store, hash-verified

88
89
90def get_openai_tool_schema(func: Callable) -> Dict[str, Any]:
91 r"""Generates an OpenAI JSON schema from a given Python function.
92
93 This function creates a schema compatible with OpenAI's API specifications,
94 based on the provided Python function. It processes the function's
95 parameters, types, and docstrings, and constructs a schema accordingly.
96
97 Note:
98 - Each parameter in `func` must have a type annotation; otherwise, it's
99 treated as 'Any'.
100 - Variable arguments (*args) and keyword arguments (**kwargs) are not
101 supported and will be ignored.
102 - A functional description including a brief and detailed explanation
103 should be provided in the docstring of `func`.
104 - All parameters of `func` must be described in its docstring.
105 - Supported docstring styles: ReST, Google, Numpydoc, and Epydoc.
106
107 Args:
108 func (Callable): The Python function to be converted into an OpenAI
109 JSON schema.
110
111 Returns:
112 Dict[str, Any]: A dictionary representing the OpenAI JSON schema of
113 the provided function.
114
115 See Also:
116 `OpenAI API Reference
117 <https://platform.openai.com/docs/api-reference/assistants/object>`_
118 """
119 params: Mapping[str, Parameter] = signature(func).parameters
120 fields: Dict[str, Tuple[type, FieldInfo]] = {}
121 for param_name, p in params.items():
122 param_type = p.annotation
123 param_default = p.default
124 param_kind = p.kind
125 param_annotation = p.annotation
126 # Variable parameters are not supported
127 if (
128 param_kind == Parameter.VAR_POSITIONAL
129 or param_kind == Parameter.VAR_KEYWORD
130 ):
131 continue
132 # If the parameter type is not specified, it defaults to typing.Any
133 if param_annotation is Parameter.empty:
134 param_type = Any
135 # Check if the parameter has a default value
136 if param_default is Parameter.empty:
137 fields[param_name] = (param_type, FieldInfo())
138 else:
139 fields[param_name] = (param_type, FieldInfo(default=param_default))
140
141 # Applying `create_model()` directly will result in a mypy error,
142 # create an alias to avoid this.
143 def _create_mol(name, field):
144 return create_model(name, **field)
145
146 model = _create_mol(to_pascal(func.__name__), fields)
147 parameters_dict = get_pydantic_object_schema(model)

Callers 3

__init__Method · 0.70

Calls 5

to_pascalFunction · 0.90
_create_molFunction · 0.70

Tested by

no test coverage detected