MCPcopy
hub / github.com/HKUDS/AI-Researcher / function_to_json

Function function_to_json

research_agent/inno/util.py:211–286  ·  view source on GitHub ↗

Converts a Python function into a JSON-serializable dictionary that describes the function's signature, including its name, description, and parameters. Args: func: The function to be converted. Returns: A dictionary representing the function's signature in JSO

(func)

Source from the content-addressed store, hash-verified

209
210
211def function_to_json(func) -> dict:
212 """
213 Converts a Python function into a JSON-serializable dictionary
214 that describes the function's signature, including its name,
215 description, and parameters.
216
217 Args:
218 func: The function to be converted.
219
220 Returns:
221 A dictionary representing the function's signature in JSON format.
222 """
223 type_map = {
224 str: "string",
225 int: "integer",
226 float: "number",
227 bool: "boolean",
228 # list: "array",
229 # dict: "object",
230 type(None): "null",
231 }
232 # def get_type_info(annotation):
233 # if hasattr(annotation, "__origin__"): # 处理typing类型
234 # origin = annotation.__origin__
235 # if origin is list: # 处理List类型
236 # item_type = annotation.__args__[0]
237 # return {
238 # "type": "array",
239 # "items": {
240 # "type": type_map.get(item_type, "string")
241 # }
242 # }
243 # elif origin is dict: # 处理Dict类型
244 # return {"type": "object"}
245 # return {"type": type_map.get(annotation, "string")}
246
247 try:
248 signature = inspect.signature(func)
249 except ValueError as e:
250 raise ValueError(
251 f"Failed to get signature for function {func.__name__}: {str(e)}"
252 )
253
254 parameters = {}
255 # for param in signature.parameters.values():
256 # try:
257 # param_type = type_map.get(param.annotation, "string")
258 # except KeyError as e:
259 # raise KeyError(
260 # f"Unknown type annotation {param.annotation} for parameter {param.name}: {str(e)}"
261 # )
262 # parameters[param.name] = {"type": param_type}
263 for param in signature.parameters.values():
264 try:
265 parameters[param.name] = get_type_info(param.annotation, type_map)
266 except KeyError as e:
267 raise KeyError(f"Unknown type annotation {param.annotation} for parameter {param.name}: {str(e)}")
268

Callers 3

planning_tools.pyFile · 0.90
get_chat_completionMethod · 0.85

Calls 1

get_type_infoFunction · 0.85

Tested by

no test coverage detected