Validate the format of the `tools` parameter for chat requests. Valid inputs are accepted and standardized, while invalid inputs raise ValueError. Empty dict/list will be returned as None. Args: raw_tools: Raw `tools` parameter obtained from kwargs (can
(self, raw_tools: Any)
| 756 | return incremental_result |
| 757 | |
| 758 | def _validate_tools(self, raw_tools: Any) -> Optional[list[dict]]: |
| 759 | """ |
| 760 | Validate the format of the `tools` parameter for chat requests. |
| 761 | Valid inputs are accepted and standardized, while invalid inputs raise ValueError. |
| 762 | Empty dict/list will be returned as None. |
| 763 | |
| 764 | Args: |
| 765 | raw_tools: Raw `tools` parameter obtained from kwargs (can be any type) |
| 766 | |
| 767 | Returns: |
| 768 | Optional[List[Dict[str, Any]]]: Standardized list of valid tool dictionaries if validation passes; |
| 769 | None if `raw_tools` is None or empty (empty dict/list). |
| 770 | |
| 771 | Raises: |
| 772 | ValueError: Raised when input type is invalid or format does not meet standards. |
| 773 | """ |
| 774 | if raw_tools is None: |
| 775 | return None |
| 776 | if isinstance(raw_tools, ChatCompletionToolsParam): |
| 777 | return [raw_tools] |
| 778 | if isinstance(raw_tools, list) and all(isinstance(t, ChatCompletionToolsParam) for t in raw_tools): |
| 779 | if not raw_tools: |
| 780 | return None |
| 781 | else: |
| 782 | return raw_tools |
| 783 | |
| 784 | if not isinstance(raw_tools, dict) and not isinstance(raw_tools, list): |
| 785 | raise ValueError( |
| 786 | f"Invalid tools top-level type! Expected None, dict (single tool) or list (multiple tools), " |
| 787 | f"but got type '{type(raw_tools).__name__}' (value: {raw_tools})." |
| 788 | ) |
| 789 | tools_list: list[dict[str, Any]] = [raw_tools] if isinstance(raw_tools, dict) else raw_tools |
| 790 | |
| 791 | if not tools_list: |
| 792 | return None |
| 793 | |
| 794 | validated_tools = [] |
| 795 | for idx, tool in enumerate(tools_list): |
| 796 | if not isinstance(tool, dict): |
| 797 | raise ValueError( |
| 798 | f"Invalid element type in tools list! At index {idx}, " |
| 799 | f"expected dict (tool definition), but got type '{type(tool).__name__}' (value: {tool})." |
| 800 | ) |
| 801 | |
| 802 | try: |
| 803 | validated_tool_obj = ChatCompletionToolsParam.model_validate(tool) |
| 804 | validated_tools.append(validated_tool_obj.model_dump()) |
| 805 | except ValidationError as e: |
| 806 | raise ValueError( |
| 807 | f"Invalid tool format at index {idx} in tools list! " f"Tool content: {tool}\nError details: {e}" |
| 808 | ) from e |
| 809 | |
| 810 | return validated_tools |
| 811 | |
| 812 | |
| 813 | if __name__ == "__main__": |