| 1 | import inspect |
| 2 | from datetime import datetime |
| 3 | |
| 4 | |
| 5 | def debug_print(debug: bool, *args: str) -> None: |
| 6 | if not debug: |
| 7 | return |
| 8 | timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S") |
| 9 | message = " ".join(map(str, args)) |
| 10 | print(f"\033[97m[\033[90m{timestamp}\033[97m]\033[90m {message}\033[0m") |
| 11 | |
| 12 | |
| 13 | def merge_fields(target, source): |
| 14 | for key, value in source.items(): |
| 15 | if isinstance(value, str): |
| 16 | target[key] += value |
| 17 | elif value is not None and isinstance(value, dict): |
| 18 | merge_fields(target[key], value) |
| 19 | |
| 20 | |
| 21 | def merge_chunk(final_response: dict, delta: dict) -> None: |
| 22 | delta.pop("role", None) |
| 23 | merge_fields(final_response, delta) |
| 24 | |
| 25 | tool_calls = delta.get("tool_calls") |
| 26 | if tool_calls and len(tool_calls) > 0: |
| 27 | index = tool_calls[0].pop("index") |
| 28 | merge_fields(final_response["tool_calls"][index], tool_calls[0]) |
| 29 | |
| 30 | |
| 31 | def function_to_json(func) -> dict: |
| 32 | """ |
| 33 | Converts a Python function into a JSON-serializable dictionary |
| 34 | that describes the function's signature, including its name, |
| 35 | description, and parameters. |
| 36 | |
| 37 | Args: |
| 38 | func: The function to be converted. |
| 39 | |
| 40 | Returns: |
| 41 | A dictionary representing the function's signature in JSON format. |
| 42 | """ |
| 43 | type_map = { |
| 44 | str: "string", |
| 45 | int: "integer", |
| 46 | float: "number", |
| 47 | bool: "boolean", |
| 48 | list: "array", |
| 49 | dict: "object", |
| 50 | type(None): "null", |
| 51 | } |
| 52 | |
| 53 | try: |
| 54 | signature = inspect.signature(func) |
| 55 | except ValueError as e: |
| 56 | raise ValueError( |
| 57 | f"Failed to get signature for function {func.__name__}: {str(e)}" |
| 58 | ) |
| 59 | |
| 60 | parameters = {} |
| 61 | for param in signature.parameters.values(): |
| 62 | try: |
| 63 | param_type = type_map.get(param.annotation, "string") |
| 64 | except KeyError as e: |
| 65 | raise KeyError( |
| 66 | f"Unknown type annotation {param.annotation} for parameter {param.name}: {str(e)}" |
| 67 | ) |
| 68 | parameters[param.name] = {"type": param_type} |
| 69 | |
| 70 | required = [ |
| 71 | param.name |
| 72 | for param in signature.parameters.values() |
| 73 | if param.default == inspect._empty |
| 74 | ] |
| 75 | |
| 76 | return { |
| 77 | "type": "function", |
| 78 | "function": { |
| 79 | "name": func.__name__, |
| 80 | "description": func.__doc__ or "", |
| 81 | "parameters": { |
| 82 | "type": "object", |
| 83 | "properties": parameters, |
| 84 | "required": required, |
| 85 | }, |
| 86 | }, |
| 87 | } |