(
*,
response_format: type[ResponseFormatT] | completion_create_params.ResponseFormat | Omit,
input_tools: Iterable[ChatCompletionToolUnionParam] | Omit,
chat_completion: ChatCompletion | ParsedChatCompletion[object],
)
| 84 | |
| 85 | |
| 86 | def parse_chat_completion( |
| 87 | *, |
| 88 | response_format: type[ResponseFormatT] | completion_create_params.ResponseFormat | Omit, |
| 89 | input_tools: Iterable[ChatCompletionToolUnionParam] | Omit, |
| 90 | chat_completion: ChatCompletion | ParsedChatCompletion[object], |
| 91 | ) -> ParsedChatCompletion[ResponseFormatT]: |
| 92 | if is_given(input_tools): |
| 93 | input_tools = [t for t in input_tools] |
| 94 | else: |
| 95 | input_tools = [] |
| 96 | |
| 97 | choices: list[ParsedChoice[ResponseFormatT]] = [] |
| 98 | for choice in chat_completion.choices: |
| 99 | if choice.finish_reason == "length": |
| 100 | raise LengthFinishReasonError(completion=chat_completion) |
| 101 | |
| 102 | if choice.finish_reason == "content_filter": |
| 103 | raise ContentFilterFinishReasonError() |
| 104 | |
| 105 | message = choice.message |
| 106 | |
| 107 | tool_calls: list[ParsedFunctionToolCall] = [] |
| 108 | if message.tool_calls: |
| 109 | for tool_call in message.tool_calls: |
| 110 | if tool_call.type == "function": |
| 111 | tool_call_dict = tool_call.to_dict() |
| 112 | tool_calls.append( |
| 113 | construct_type_unchecked( |
| 114 | value={ |
| 115 | **tool_call_dict, |
| 116 | "function": { |
| 117 | **cast(Any, tool_call_dict["function"]), |
| 118 | "parsed_arguments": parse_function_tool_arguments( |
| 119 | input_tools=input_tools, function=tool_call.function |
| 120 | ), |
| 121 | }, |
| 122 | }, |
| 123 | type_=ParsedFunctionToolCall, |
| 124 | ) |
| 125 | ) |
| 126 | elif tool_call.type == "custom": |
| 127 | # warn user that custom tool calls are not callable here |
| 128 | log.warning( |
| 129 | "Custom tool calls are not callable. Ignoring tool call: %s - %s", |
| 130 | tool_call.id, |
| 131 | tool_call.custom.name, |
| 132 | stacklevel=2, |
| 133 | ) |
| 134 | elif TYPE_CHECKING: # type: ignore[unreachable] |
| 135 | assert_never(tool_call) |
| 136 | else: |
| 137 | tool_calls.append(tool_call) |
| 138 | |
| 139 | choices.append( |
| 140 | construct_type_unchecked( |
| 141 | type_=ParsedChoice[ResponseFormatT], |
| 142 | value={ |
| 143 | **choice.to_dict(), |
no test coverage detected