1111 FiSpanKindValues ,
1212 SpanAttributes ,
1313)
14+ from openai import Omit
1415from openai ._legacy_response import LegacyAPIResponse
1516from openai .types .create_embedding_response import CreateEmbeddingResponse
1617from opentelemetry import context as context_api
@@ -222,14 +223,23 @@ def _finalize_response(
222223 cast_to : type ,
223224 request_parameters : Mapping [str , Any ],
224225 instance : Any = None ,
226+ request_options : Any = None ,
225227 ) -> Any :
226228 """
227229 Monkey-patch the response object to trace the stream, or finish tracing if the response is
228230 not a stream.
229231 """
230232 response_accumulator_factory = self ._response_accumulator_factories .get (cast_to )
233+ accumulator_parameters = request_parameters
234+ if cast_to is self ._openai .types .chat .ChatCompletion and request_options is not None :
235+ # Validate the on-wire choice count without expanding request metadata
236+ # or passing arbitrary extra_body fields into response extraction.
237+ _ , effective_parameters = _parse_request_args (
238+ (cast_to , request_options ), include_extra_body = True ,
239+ )
240+ accumulator_parameters = {** request_parameters , "n" : effective_parameters .get ("n" , 1 )}
231241 response_accumulator = (
232- response_accumulator_factory (request_parameters )
242+ response_accumulator_factory (accumulator_parameters )
233243 if response_accumulator_factory
234244 else None
235245 )
@@ -241,7 +251,7 @@ def _finalize_response(
241251 extractor = _ResponseAttributesExtractor (self ._openai , self ._config , provider = provider )
242252 if cast_to is self ._openai .types .chat .ChatCompletion :
243253 response_accumulator = _DeepSeekChatAccumulator (
244- request_parameters = request_parameters ,
254+ request_parameters = accumulator_parameters ,
245255 chat_completion_type = cast_to ,
246256 response_attributes_extractor = extractor ,
247257 )
@@ -416,6 +426,7 @@ def __call__(
416426 cast_to = cast_to ,
417427 request_parameters = request_parameters ,
418428 instance = instance ,
429+ request_options = args [1 ],
419430 )
420431 except BaseException as e :
421432 with_span .add_secrets (request_credentials (instance , getattr (e , "request" , None ), {}))
@@ -500,6 +511,7 @@ async def __call__(
500511 cast_to = cast_to ,
501512 request_parameters = request_parameters ,
502513 instance = instance ,
514+ request_options = args [1 ],
503515 )
504516 except Exception :
505517 logger .exception (
@@ -509,19 +521,26 @@ async def __call__(
509521 return response
510522
511523
512- def _parse_request_args (args : Tuple [type , Any ]) -> Tuple [type , Mapping [str , Any ]]:
524+ def _parse_request_args (
525+ args : Tuple [type , Any ], * , include_extra_body : bool = False ,
526+ ) -> Tuple [type , Mapping [str , Any ]]:
513527 # We don't use `signature(request).bind()` because `request` could have been monkey-patched
514528 # (incorrectly) by others and the signature at runtime may not match the original.
515529 # The targeted signature of `request` is here:
516530 # https://github.com/openai/openai-python/blob/f1c7d714914e3321ca2e72839fe2d132a8646e7f/src/openai/_base_client.py#L846-L847 # noqa: E501
517531 cast_to : type = args [0 ]
518- request_parameters : Mapping [str , Any ] = (
519- json_data
520- # See https://github.com/openai/openai-python/blob/f1c7d714914e3321ca2e72839fe2d132a8646e7f/src/openai/_models.py#L427 # noqa: E501
521- if hasattr (args [1 ], "json_data" )
522- and isinstance (json_data := args [1 ].json_data , Mapping )
523- else {}
524- )
532+ json_data = getattr (args [1 ], "json_data" , None )
533+ if include_extra_body and (extra_json := getattr (args [1 ], "extra_json" , None )) is not None :
534+ # Mirror the SDK's shallow extra_body merge without mutating its options.
535+ # Opt in only for completion validation; exported metadata stays unchanged.
536+ if json_data is None :
537+ json_data = extra_json
538+ elif isinstance (json_data , Mapping ) and isinstance (extra_json , Mapping ):
539+ json_data = {
540+ key : value for key , value in {** json_data , ** extra_json }.items ()
541+ if not isinstance (value , Omit )
542+ }
543+ request_parameters : Mapping [str , Any ] = json_data if isinstance (json_data , Mapping ) else {}
525544 # FIXME: Because request parameters is just a Mapping, it can contain any value as long as it
526545 # serializes correctly in an HTTP request body. For example, Enum values may be present if a
527546 # third-party library puts them there. Enums can turn into their intended string values via
0 commit comments