|
| 1 | +from __future__ import annotations |
| 2 | + |
| 3 | +import json |
| 4 | +from typing import TYPE_CHECKING, Any, Dict, Iterable, cast |
| 5 | +from typing_extensions import TypeVar, TypeGuard |
| 6 | + |
| 7 | +import pydantic |
| 8 | + |
| 9 | +from .._tools import PydanticFunctionTool |
| 10 | +from ..._types import Omit, omit |
| 11 | +from ..._utils import is_dict, is_given |
| 12 | +from ..._compat import PYDANTIC_V1, model_parse_json |
| 13 | +from ..._models import construct_type_unchecked |
| 14 | +from .._pydantic import is_basemodel_type, to_strict_json_schema, is_dataclass_like_type |
| 15 | + |
| 16 | +if TYPE_CHECKING: |
| 17 | + from ...types.chat.completion_create_params import ResponseFormat as ResponseFormatParam |
| 18 | + from ...types.chat.completion import ChoiceMessageToolCallChatCompletionMessageToolCallFunction as Function |
| 19 | + |
| 20 | +ResponseFormatT = TypeVar("ResponseFormatT") |
| 21 | + |
| 22 | + |
| 23 | +def type_to_response_format_param( |
| 24 | + response_format: type | ResponseFormatParam | Omit, |
| 25 | +) -> ResponseFormatParam | Omit: |
| 26 | + """Convert Pydantic model to API response_format parameter.""" |
| 27 | + if not is_given(response_format): |
| 28 | + return omit |
| 29 | + |
| 30 | + if is_dict(response_format): |
| 31 | + return response_format |
| 32 | + |
| 33 | + response_format = cast(type, response_format) |
| 34 | + |
| 35 | + if is_basemodel_type(response_format): |
| 36 | + name = response_format.__name__ |
| 37 | + json_schema_type = response_format |
| 38 | + elif is_dataclass_like_type(response_format): |
| 39 | + name = response_format.__name__ |
| 40 | + json_schema_type = pydantic.TypeAdapter(response_format) |
| 41 | + else: |
| 42 | + raise TypeError(f"Unsupported response_format type - {response_format}") |
| 43 | + |
| 44 | + return { |
| 45 | + "type": "json_schema", |
| 46 | + "json_schema": { |
| 47 | + "schema": to_strict_json_schema(json_schema_type), |
| 48 | + "name": name, |
| 49 | + "strict": True, |
| 50 | + }, |
| 51 | + } |
| 52 | + |
| 53 | + |
| 54 | +def validate_input_tools(tools: Iterable[Dict[str, Any]] | Omit = omit) -> Iterable[Dict[str, Any]] | Omit: |
| 55 | + """Validate tools for strict parsing support.""" |
| 56 | + if not is_given(tools): |
| 57 | + return omit |
| 58 | + |
| 59 | + for tool in tools: |
| 60 | + if tool.get("type") != "function": |
| 61 | + raise ValueError(f"Only function tools support auto-parsing; got {tool.get('type')}") |
| 62 | + |
| 63 | + strict = tool.get("function", {}).get("strict") |
| 64 | + if strict is not True: |
| 65 | + name = tool.get("function", {}).get("name", "unknown") |
| 66 | + raise ValueError(f"Tool '{name}' is not strict. Only strict function tools can be auto-parsed") |
| 67 | + |
| 68 | + return cast(Iterable[Dict[str, Any]], tools) |
| 69 | + |
| 70 | + |
| 71 | +def parse_chat_completion( |
| 72 | + *, |
| 73 | + response_format: type[ResponseFormatT] | ResponseFormatParam | Omit, |
| 74 | + chat_completion: Any, |
| 75 | + input_tools: Iterable[Dict[str, Any]] | Omit = omit, |
| 76 | +) -> Any: |
| 77 | + """Parse completion: response content and tool call arguments into Pydantic models.""" |
| 78 | + from ...types.chat.parsed_chat_completion import ( |
| 79 | + ParsedChatCompletion, |
| 80 | + ParsedChoice, |
| 81 | + ParsedChatCompletionMessage, |
| 82 | + ) |
| 83 | + from ...types.chat.parsed_function_tool_call import ParsedFunctionToolCall, ParsedFunction |
| 84 | + |
| 85 | + tool_list = list(input_tools) if is_given(input_tools) else [] |
| 86 | + |
| 87 | + choices = [] |
| 88 | + for choice in chat_completion.choices: |
| 89 | + message = choice.message |
| 90 | + |
| 91 | + # Parse tool calls if present |
| 92 | + tool_calls = [] |
| 93 | + if hasattr(message, "tool_calls") and message.tool_calls: |
| 94 | + for tool_call in message.tool_calls: |
| 95 | + if tool_call.type == "function": |
| 96 | + parsed_args = _parse_function_tool_arguments( |
| 97 | + input_tools=tool_list, function=tool_call.function |
| 98 | + ) |
| 99 | + tool_calls.append( |
| 100 | + construct_type_unchecked( |
| 101 | + value={ |
| 102 | + **tool_call.to_dict(), |
| 103 | + "function": { |
| 104 | + **tool_call.function.to_dict(), |
| 105 | + "parsed_arguments": parsed_args, |
| 106 | + }, |
| 107 | + }, |
| 108 | + type_=ParsedFunctionToolCall, |
| 109 | + ) |
| 110 | + ) |
| 111 | + else: |
| 112 | + tool_calls.append(tool_call) |
| 113 | + |
| 114 | + # Parse response content |
| 115 | + parsed_content = None |
| 116 | + if is_given(response_format) and not is_dict(response_format): |
| 117 | + if message.content and not getattr(message, "refusal", None): |
| 118 | + parsed_content = _parse_content(response_format, message.content) |
| 119 | + |
| 120 | + choices.append( |
| 121 | + construct_type_unchecked( |
| 122 | + type_=cast(Any, ParsedChoice), |
| 123 | + value={ |
| 124 | + **choice.to_dict(), |
| 125 | + "message": { |
| 126 | + **message.to_dict(), |
| 127 | + "parsed": parsed_content, |
| 128 | + "tool_calls": tool_calls if tool_calls else None, |
| 129 | + }, |
| 130 | + }, |
| 131 | + ) |
| 132 | + ) |
| 133 | + |
| 134 | + return construct_type_unchecked( |
| 135 | + type_=cast(Any, ParsedChatCompletion), |
| 136 | + value={ |
| 137 | + **chat_completion.to_dict(), |
| 138 | + "choices": choices, |
| 139 | + }, |
| 140 | + ) |
| 141 | + |
| 142 | + |
| 143 | +def _parse_function_tool_arguments(*, input_tools: list[Dict[str, Any]], function: Function) -> object | None: |
| 144 | + """Parse tool call arguments using Pydantic if tool schema is available.""" |
| 145 | + input_tool = next( |
| 146 | + (t for t in input_tools if t.get("type") == "function" and t.get("function", {}).get("name") == function.name), |
| 147 | + None, |
| 148 | + ) |
| 149 | + if not input_tool: |
| 150 | + return None |
| 151 | + |
| 152 | + input_fn = input_tool.get("function") |
| 153 | + if isinstance(input_fn, PydanticFunctionTool): |
| 154 | + return model_parse_json(input_fn.model, function.arguments) |
| 155 | + |
| 156 | + if input_fn and input_fn.get("strict"): |
| 157 | + return json.loads(function.arguments) |
| 158 | + |
| 159 | + return None |
| 160 | + |
| 161 | + |
| 162 | +def _parse_content(response_format: type[ResponseFormatT], content: str) -> ResponseFormatT: |
| 163 | + """Deserialize JSON string into typed Pydantic model.""" |
| 164 | + if is_basemodel_type(response_format): |
| 165 | + return cast(ResponseFormatT, model_parse_json(response_format, content)) |
| 166 | + |
| 167 | + if is_dataclass_like_type(response_format): |
| 168 | + if PYDANTIC_V1: |
| 169 | + raise TypeError(f"Non BaseModel types are only supported with Pydantic v2 - {response_format}") |
| 170 | + return pydantic.TypeAdapter(response_format).validate_json(content) |
| 171 | + |
| 172 | + raise TypeError(f"Unable to automatically parse response format type {response_format}") |
0 commit comments