Ë
    òÏjsn ã                  óÎ  — U d Z ddlmZ ddlZddlZddlZddlZddlZddlZddl	Z	ddl
Z
ddlmZmZmZmZmZmZ ddlmZ ddlmZ ddlmZ ddlmZ dd	lmZ dd
lmZmZmZmZm Z m!Z! ddl"m#Z# ddl$Z$ddl%Z%ddl&Z&ddl'm(Z(m)Z) ddl*m+Z+m,Z,m-Z-m.Z.m/Z/m0Z0m1Z1m2Z2m3Z3 ddl4m5Z5m6Z6 ddl7m8Z8m9Z9 ddl:m;Z;m<Z<m=Z=m>Z>m?Z?m@Z@mAZAmBZBmCZCmDZDmEZEmFZFmGZGmHZHmIZImJZJmKZK ddl:mLZM ddlNmOZOmPZPmQZQ ddlRmSZSmTZT ddlUmVZV ddlWmXZXmYZY ddlZm[Z[m\Z\m]Z]m^Z^ ddl_m`Z`maZambZb ddlcmdZdmeZemfZfmgZg ddlhmiZi ddljmkZk ddllmmZm ddlnmoZo ddlpmqZqmrZrmsZs ddltmuZumvZv ddlwmxZxmyZymzZz dd l{m|Z|m}Z}m~Z~ dd!lm€Z€m�Z�m‚Z‚mƒZƒm„Z„m…Z…m†Z† dd"l‡m€Zˆ dd#l‰mŠZŠ dd$l‹mŒZŒ dd%l�mŽZŽm�Z�m�Z�m‘Z‘m’Z’m“Z“m”Z”m•Z•m–Z–m—Z—m˜Z˜ dd&l™mšZšm›Z›mœZœm�Z� dd'lžmŸZŸ erddl Z dd(l4m¡Z¡ dd)l¢m£Z£  e�jH                  e¥«      Z¦ e�jN                   e$�jP                  «       ¬*«      Z©daªd+e«d,<   d~d-„Z¬ e!e6eŸ«      Z­dd.„Z®d/Z¯d0Z°d€d1„Z±	 	 	 	 	 	 d�d2„Z²d‚d3„Z³d4Z´	 dƒd5„Zµdƒd6„Z¶d„d7„Z·	 	 d…	 	 	 	 	 	 	 d†d8„Z¸	 d‡	 	 	 	 	 dˆd9„Z¹	 	 	 	 	 	 d‰d:„Zº	 	 	 	 	 	 dŠd;„Z» G d<„ d=e%�jx                  e+«      Z½ G d>„ d?e%�j|                  e+«      Z¿ G d@„ dAe%�j€                  e-«      ZÁ G dB„ dCe%�j„                  e1«      ZÃ G dD„ dEe%�jx                  e/«      ZÄ G dF„ dGe%�jŠ                  e0«      ZÆ G dH„ dIe%�jŽ                  e2«      ZÈ G dJ„ dKe%�j’                  e,«      ZÊ G dL„ dMe%�j–                  e.«      ZÌ G dN„ dOe%�jš                  e3«      ZÎd‹dP„ZÏdŒdQ„ZÐd�dR„ZÑdSZÒdŽdT„ZÓ e dUe€¬V«      ZÔeÕeÖef   e×eÔ   z  e×z  ZØdWe«dX<   eÕeÔz  ZÙdWe«dY<    G dZ„ d[e8«      ZÚ G d\„ d]eÚ«      ZÛd�d^„ZÜd�d_„ZÝ	 	 	 	 d‘d`„ZÞd’da„Zßd“db„Zàd”dc„Zád”dd„Zâd•de„Zãddfœ	 	 	 	 	 d–dg„Zä	 	 	 	 	 	 d—dh„Zå G di„ djeæ«      Zç	 d˜	 	 	 	 	 d™dk„Zè	 d˜	 	 	 	 	 d™dl„Zédšdm„Zêd›dn„Zë	 	 	 	 dœdo„Zì	 	 	 	 	 	 d�dp„Zídždq„Zîdždr„Zï	 	 	 	 dŸds„Zðd dt„Zñ	 	 	 	 d¡du„Zòd¢dv„Zód£dw„Zôddxœ	 	 	 	 	 d¤dy„Zõd¥dz„Zö	 	 	 d¦	 	 	 	 	 	 	 	 	 d§d{„Z÷d¨d|„Zø	 	 	 	 d©	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 dªd}„Zùy)«a"  OpenAI chat wrapper.

!!! warning "API scope"

        `ChatOpenAI` targets
        [official OpenAI API specifications](https://github.com/openai/openai-openapi)
        only. Non-standard response fields added by third-party providers (e.g.,
        `reasoning_content`, `reasoning_details`) are **not** extracted or
        preserved. If you are pointing `base_url` at a provider such as
        OpenRouter, vLLM, or DeepSeek, use the corresponding provider-specific
        LangChain package instead (e.g., `ChatDeepSeek`, `ChatOpenRouter`).
é    )ÚannotationsN)ÚAsyncIteratorÚ	AwaitableÚCallableÚIteratorÚMappingÚSequence)Úpartial)ÚBytesIO)ÚJSONDecodeError)Úceil)Ú
itemgetter)ÚTYPE_CHECKINGÚAnyÚLiteralÚ	TypeAliasÚTypeVarÚcast)Úurlparse)ÚAsyncCallbackManagerForLLMRunÚCallbackManagerForLLMRun)	ÚContextOverflowErrorÚModelAPIErrorÚModelAuthenticationErrorÚModelConnectionErrorÚModelInvalidRequestErrorÚModelNotFoundErrorÚModelPermissionDeniedErrorÚModelRateLimitErrorÚModelTimeoutError)ÚLanguageModelInputÚModelProfileRegistry)ÚBaseChatModelÚLangSmithParams)Ú	AIMessageÚAIMessageChunkÚBaseMessageÚBaseMessageChunkÚChatMessageÚChatMessageChunkÚFunctionMessageÚFunctionMessageChunkÚHumanMessageÚHumanMessageChunkÚInvalidToolCallÚSystemMessageÚSystemMessageChunkÚToolCallÚToolMessageÚToolMessageChunkÚis_data_content_block)Úcontent)ÚInputTokenDetailsÚOutputTokenDetailsÚUsageMetadata)Ú_convert_from_v03_ai_messageÚconvert_to_openai_data_block)Útool_call_chunk)ÚJsonOutputParserÚPydanticOutputParser)ÚJsonOutputKeyToolsParserÚPydanticToolsParserÚmake_invalid_tool_callÚparse_tool_call)ÚChatGenerationÚChatGenerationChunkÚ
ChatResult)ÚRunnableÚRunnableLambdaÚRunnableMapÚRunnablePassthrough)Úrun_in_executor)ÚBaseTool)Ú
_stringify)Úget_pydantic_field_names)ÚGATEWAY_METADATA_RESPONSE_KEYÚ_parse_gateway_metadataÚ_resolve_gateway_config)Úconvert_to_openai_functionÚconvert_to_openai_tool)ÚPydanticBaseModelÚTypeBaseModelÚis_basemodel_subclass)ÚLC_AUTO_PREFIXÚ_build_model_kwargsÚfrom_env)Ú	BaseModelÚ
ConfigDictÚFieldÚ	SecretStrÚValidationErrorÚfield_validatorÚmodel_validator)rY   )ÚSelf)Ú__version__)Ú_astream_with_chunk_timeoutÚ!_build_proxied_async_httpx_clientÚ _build_proxied_sync_httpx_clientÚ
_float_envÚ_get_default_async_httpx_clientÚ_get_default_httpx_clientÚ_log_proxy_env_bypass_onceÚ_resolve_socket_optionsÚ _resolve_sync_and_async_api_keysÚ+_should_bypass_socket_options_for_proxy_envÚ_warn_if_proxy_env_shadowed)Ú$_convert_from_v1_to_chat_completionsÚ_convert_from_v1_to_responsesÚ_convert_to_v03_ai_messageÚ_unwrap_non_standard)Ú	_PROFILES)ÚModelProfile©ÚResponse)Úcafilezhttpx.Client | NoneÚ_ssrf_clientc                 óB   — t         €ddlm}   | t        d¬«      a t         S )Nr   ©Ússrf_safe_clientF)ÚverifyÚfollow_redirects)rv   Ú#langchain_core._security._transportry   Úglobal_ssl_contextrx   s    ú^/var/www/html/gaurav-v2/venv/lib/python3.12/site-packages/langchain_openai/chat_models/base.pyÚ_get_ssrf_safe_clientr   ¸   s"   € äÐÝHá'Ü%¸ô
ˆô Ðó    c                óT   — t         j                  | «      xs i }|j                  «       S ©N)Ú_MODEL_PROFILESÚgetÚcopy)Ú
model_nameÚdefaults     r~   Ú_get_default_model_profilerˆ   Æ   s#   € Ü×!Ñ! *Ó-Ò3°€GØ�<‰<‹>Ðr€   )	Úfile_searchÚweb_search_previewÚ
web_searchÚcomputer_use_previewÚcode_interpreterÚmcpÚimage_generationÚtool_searchÚapply_patch)Údefer_loadingÚasyncc           
     ó   — | j                  d«      }| j                  d«      }| j                  d«      }|dk(  rt        | j                  dd«      ||¬«      S |dk(  r�| j                  dd«      xs d}i }| j                  d	«      x}rt        |«      |d	<   g }g }| j                  d
«      x}	r$|	D ]  }
	 |j                  t	        |
d¬«      «       Œ! | j                  d«      x}r||d<   t        ||||||¬«      S |dv r*|dk(  rd|ini }t        | j                  dd«      |||¬«      S |dk(  r;t        | j                  dd«      t        t        | j                  d«      «      |¬«      S |dk(  rKi }d| v r| d   |d<   t        | j                  dd«      t        t        | j                  d«      «      |||¬«      S t        | j                  dd«      ||¬«      S # t
        $ r/}|j                  t        |
t        |«      «      «       Y d}~�ŒZd}~ww xY w)zˆConvert a dictionary to a LangChain message.

    Args:
        _dict: The dictionary.

    Returns:
        The LangChain message.
    ÚroleÚnameÚidÚuserr6   Ú )r6   r—   r–   Ú	assistantÚfunction_callÚ
tool_callsT)Ú	return_idNÚaudio)r6   Úadditional_kwargsr–   r—   rœ   Úinvalid_tool_calls©ÚsystemÚ	developerr£   Ú__openai_role__)r6   r–   r—   rŸ   Úfunction©r6   r–   r—   ÚtoolÚtool_call_id)r6   r¨   rŸ   r–   r—   ©r6   r•   r—   )r„   r-   ÚdictÚappendrB   Ú	ExceptionrA   Ústrr%   r0   r+   r   r3   r)   )Ú_dictr•   r–   Úid_r6   rŸ   r›   rœ   r    Úraw_tool_callsÚraw_tool_callÚerž   s                r~   Ú_convert_dict_to_messager³   Ú   sE  € ð �9‰9�VÓ€DØ�9‰9�VÓ€DØ
�)‰)�D‹/€CØˆv‚~Ü E§I¡I¨i¸Ó$<ÀÈ4ÔPÐPØˆ{Òð —)‘)˜I rÓ*Ò0¨bˆØ"$ÐØ!ŸI™I oÓ6Ð6ˆ=Ð6Ü15°mÓ1DÐ˜oÑ.Øˆ
ØÐØ"ŸY™Y |Ó4Ð4ˆ>Ð4Û!/�ðØ×%Ñ%¤o°mÈtÔ&TÕUð "0ð —I‘I˜gÓ&Ð&ˆ5Ð&Ø).Ð˜gÑ&ÜØØ/ØØØ!Ø1ô
ð 	
ð Ð&Ñ&Ø9=ÀÒ9LÐ.°Ñ5ÐRTÐÜØ—I‘I˜i¨Ó,ØØØ/ô	
ð 	
ð ˆzÒÜØ—I‘I˜i¨Ó,´4¼¸U¿Y¹YÀvÓ=NÓ3OÐTWô
ð 	
ð ˆv‚~ØÐØ�U‰?Ø(-¨f©Ð˜fÑ%ÜØ—I‘I˜i¨Ó,Üœc 5§9¡9¨^Ó#<Ó=Ø/ØØô
ð 	
ô ˜uŸy™y¨°BÓ7¸dÀsÔKÐKøôK !ò Ø&×-Ñ-Ü.¨}¼cÀ!»fÓE÷ò ûðús   Â2GÇ	HÇ$HÈHc                ó|   — d| v r
| d   |d<   |S t        | j                  d«      x}t        «      rd|v r|d   |d<   |S )a#  Apply an OpenAI prompt cache breakpoint to a formatted content block.

    A breakpoint set directly on the block takes precedence over one nested in
    `extras`. Membership (not truthiness) decides whether to copy it, so a
    present-but-falsy value (e.g. `None`) is still preserved.
    Úprompt_cache_breakpointÚextras)Ú
isinstancer„   rª   )Úsource_blockÚformatted_blockr¶   s      r~   Ú_apply_prompt_cache_breakpointrº     sb   € ð ! LÑ0Ø5AØ%ñ6
ˆÐ1Ñ2ð Ðô	 
˜l×.Ñ.¨xÓ8Ð8�F¼$Ô	?Ø! VÑ+à5;Ð<UÑ5VˆÐ1Ñ2ØÐr€   c                óú   — t        | t        «      rjg }| D ]a  }t        |t        «      r>|j                  d«      dk(  r*d|v r&d|d   dœ}d|v r|d   |d<   |j	                  |«       ŒQ|j	                  |«       Œc |S | S )zwSanitize content for chat/completions API.

    For list content, filters text blocks to only keep supported keys.
    ÚtypeÚtext©r¼   r½   rµ   )r·   Úlistrª   r„   r«   )r6   Ú	sanitizedÚblockÚsanitized_blocks       r~   Ú"_sanitize_chat_completions_contentrÃ   1  s”   € ô
 �'œ4Ô Øˆ	ÛˆEä˜5¤$Ô'Ø—I‘I˜fÓ%¨Ò/Ø˜e‘Oà+1¸5À¹=Ñ"I�Ø,°Ñ5ØAFØ1ñB�OÐ$=Ñ>ð × Ñ  Õ1à× Ñ  Õ'ð ð ÐØ€Nr€   Úadditional_toolsc                óR   — t        | «      j                  «       j                  d«      S )zÖReturn whether a message's role is the assistant's.

    Assistant content is replayed model output, not a caller's instruction, so it is
    exempt from the placement checks a caller's own blocks are held to.
    Úai)r­   ÚlowerÚ
startswith©r•   s    r~   Ú_is_ai_rolerÊ   N  s    € ô ˆt‹9�?‰?Ó×'Ñ'¨Ó-Ð-r€   c                ó
   — | dv S )zÖReturn whether a message's role carries provider instructions.

    `SystemMessage` reports `"system"` whether or not it is later emitted with
    OpenAI's `developer` role, so one check covers both spellings.
    r¡   © rÉ   s    r~   Ú_is_system_rolerÍ   W  s   € ð Ð*Ð*Ð*r€   c                ó¸   — t        | t        «      sy| D ]D  }t        |t        «      sŒt        |«      j	                  d«      t
        k(  sŒ6d|› �}t        |«      ‚ y)aé  Reject an `additional_tools` block that cannot work where it was placed.

    The block only reaches the wire as a Responses top-level input item carried on
    a system message. Anywhere else it is this provider's own block type in a
    position this provider forbids, which the error taxonomy makes loud rather than
    silent: nothing routes a request to the Responses API based on message content,
    so a silent drop would make the broken case the default outcome.

    Args:
        content: The message's content.
        reason: Sentence explaining why this placement cannot work, and how to fix
            it. Appended to the error.

    Raises:
        ValueError: If an `additional_tools` block is present, in either spelling.
    Nr¼   z`additional_tools` )r·   r¿   rª   rp   r„   Ú_ADDITIONAL_TOOLS_BLOCK_TYPEÚ
ValueError)r6   ÚreasonÚ	raw_blockÚmsgs       r~   Ú_raise_if_additional_toolsrÔ   `  sX   € ô" �gœtÔ$ØÛˆ	ä�y¤$Õ'Ü$ YÓ/×3Ñ3°FÓ;Ü+ó,ð (¨ xÐ0ˆCÜ˜S“/Ð!ñ r€   c           	     ó®  — t        |«      rn)t        |«      st        | d«       n|dk(  rt        | d«       | �rt        | t        «      �r	g }| D �]ÿ  }t        |t
        «      rd|v r|d   dv s|d   dv r|dk(  rŒ,t        |t
        «      rat        |«      rV|dk(  r(t        |«      j                  «       j                  d«      s)t        ||¬	«      }|j                  t        ||«      «       Œ�t        |t
        «      rb|j                  d«      d
k(  rNd
|v rJt        |j                  d«      x}t
        «      r)d|v r%d
|d
   dœ}|j                  t        ||«      «       �Œt        |t
        «      rÐ|j                  d«      dk(  r¼|j                  d«      x}r©t        |t
        «      r™|j                  d«      dk(  rD|j                  d«      x}r1|j                  d«      x}	r|j                  ddd|› d|	› �idœ«       �Œ®|j                  d«      dk(  r+|j                  d«      x}
r|j                  dd|
idœ«       �Œí�Œï|j                  |«       �Œ |S | }|S )zFormat message content.zˆmust be carried on a `SystemMessage`. OpenAI restricts the input item to `role: "developer"`, so it cannot be sent on any other message.úchat/completionszarequires the Responses API and cannot be sent via Chat Completions. Set `use_responses_api=True`.r¼   )Útool_useÚthinkingÚreasoning_content)r›   Úcode_interpreter_callÚ	responsesrÆ   ©Úapir½   r¶   rµ   r¾   ÚimageÚsourceÚbase64Ú
media_typeÚdataÚ	image_urlÚurlzdata:z;base64,©r¼   rã   )rÊ   rÍ   rÔ   r·   r¿   rª   r5   r­   rÇ   rÈ   r;   r«   rº   r„   )r6   rÝ   r•   Úformatted_contentrÁ   r¹   r¶   rß   rá   râ   rä   s              r~   Ú_format_message_contentrç   }  sj  € ô �4Ôð 	Ü˜TÔ"Ü"ØðQõ	
ð
 
Ð"Ò	"Ü"Øð,ô	
ò
 ”:˜g¤tÕ,ØÐÜˆEô ˜5¤$Ô'Ø˜e‘Oà˜&‘MÐ%RÑRà˜f™Ð)SÑSØÐ#5Ò5ð ä˜5¤$Ô'Ü)¨%Ô0ð  Ò+´°D³	·±Ó0A×0LÑ0LÈTÔ0Rä">¸uÈ#Ô"N�Ø!×(Ñ(Ü2°5¸/ÓJõô ˜5¤$Ô'Ø—I‘I˜fÓ%¨Ò/Ø˜e‘OÜ¨¯©°8Ó)<Ð<˜v¼dÔCØ-°Ñ7à+1¸5À¹=Ñ"I�Ø!×(Ñ(Ü2°5¸/ÓJöô
 ˜5¤$Ô'Ø—I‘I˜fÓ%¨Ò0Ø$Ÿy™y¨Ó2Ð2�VÐ2Ü˜v¤tÔ,à—:‘:˜fÓ%¨Ò1Ø#)§:¡:¨lÓ#;Ð;�ZÐ;Ø!'§¡¨FÓ!3Ð3˜Ð3à%×,Ñ,à$/Ø*/°5¸¸ÀHÈTÈFÐ1SÐ)Tñöð —Z‘Z Ó'¨5Ò0¸V¿Z¹ZÈÓ=NÐ6N°cÐ6NØ%×,Ñ,Ø!,¸EÀ3¸<ÑHöñ à!×(Ñ(¨Ö/ðy ð@ Ðð $ÐàÐr€   c                ó&  — dt        | j                  || j                  ¬«      i}| j                  xs | j                  j                  d«      x}�||d<   t        | t        «      r| j                  |d<   |S t        | t        «      rd|d<   |S t        | t        «      �r�d|d<   | j                  s| j                  rK| j                  D �cg c]  }t        |«      ‘Œ c}| j                  D �cg c]  }t        |«      ‘Œ c}z   |d<   nˆd| j                  v rX| j                  d   |d<   h d	£}|d   D ���cg c]+  }|j                  «       D ��ci c]  \  }}||v sŒ||“Œ c}}‘Œ- c}}}|d<   n"d
| j                  v r| j                  d
   |d
<   n	 d
|v sd|v r|d   xs d|d<   d}	| j                  D ]F  }
t        |
t         «      sŒ|
j                  d«      dk(  sŒ)|
j                  d«      x}sŒ=|dk7  sŒCd|i}	ŒH |	s7d| j                  v r)| j                  d   }d|v rd| j                  d   d   in|}	|	r|	|d<   |S t        | t"        «      r!| j                  j                  dd«      |d<   |S t        | t$        «      rd|d<   |S t        | t&        «      rSd|d<   | j(                  |d<   t+        |d   «      |d<   h d£}|j                  «       D ��ci c]  \  }}||v sŒ||“Œ }}}|S d| › �}t-        |«      ‚c c}w c c}w c c}}w c c}}}w c c}}w )zDConvert a LangChain message to dictionary format expected by OpenAI.r6   )rÝ   r•   r–   Nr•   r˜   rš   rœ   >   r—   r¼   r¥   r›   r¼   rž   r—   rÛ   r¤   r¢   r¥   r§   r¨   >   r•   r6   r¨   zGot unknown type )rç   r6   r¼   r–   rŸ   r„   r·   r)   r•   r-   r%   rœ   r    Ú!_lc_tool_call_to_openai_tool_callÚ)_lc_invalid_tool_call_to_openai_tool_callÚitemsrª   r0   r+   r3   r¨   rÃ   Ú	TypeError)ÚmessagerÝ   Úmessage_dictr–   ÚtcÚtool_call_supported_propsÚ	tool_callÚkÚvrž   rÁ   r¯   Ú	raw_audioÚsupported_propsrÓ   s                  r~   Ú_convert_message_to_dictrö   Ø  s™  € ð 	Ô*¨7¯?©?ÀÈ'Ï,É,ÔWð$€Lð —‘ÒE × 9Ñ 9× =Ñ =¸fÓ EÐEˆÐRØ#ˆ�VÑô �'œ;Ô'Ø&Ÿ|™|ˆ�VÑðD ÐôC 
�Gœ\Ô	*Ø%ˆ�VÑð@ Ðô 
�GœYÕ	'Ø*ˆ�VÑØ×Ò ×!;Ò!;à@G×@RÒ@Ró*Ù@R¸"Ô1°"Õ5Ð@Rñ*ð "×4Ò4óá4�Bô :¸"Õ=Ø4ññ*ˆL˜Ò&ð ˜W×6Ñ6Ñ6Ø)0×)BÑ)BÀ<Ñ)PˆL˜Ñ&Ú(BÐ%ð ".¨lÒ!;õ*á!;�Ið #,§/¡/Ô"3ÔVÑ"3™$˜!˜Q°qÐ<UÒ7U��A‘Ð"3ÔVØ!;ó*ˆL˜Ò&ð  × 9Ñ 9Ñ9ð -4×,EÑ,EÀoÑ,VˆL˜Ò)àà˜lÑ*¨l¸lÑ.JØ&2°9Ñ&=Ò&EÀˆL˜Ñ#à'+ˆØ—_”_ˆEä˜5¤$Õ'Ø—I‘I˜fÓ%¨Ó0Ø!ŸI™I d›OÐ+�SÑ+Ø˜;Ó&ð ˜s˜‘ð %ñ ˜ G×$=Ñ$=Ñ=Ø×1Ñ1°'Ñ:ˆIð ˜9Ñ$ð �w×0Ñ0°Ñ9¸$Ñ?Ñ@àð ñ
 Ø$)ˆL˜Ñ!ð$ Ðô# 
�Gœ]Ô	+Ø&×8Ñ8×<Ñ<Ø˜xó 
ˆ�VÑð  Ðô 
�Gœ_Ô	-Ø)ˆ�VÑð Ðô 
�Gœ[Ô	)Ø%ˆ�VÑØ'.×';Ñ';ˆ�^Ñ$Ü"DØ˜Ñ#ó#
ˆ�YÑò >ˆØ)5×);Ñ);Ô)=ÔVÑ)=¡  AÀÀoÒAU˜˜1™Ð)=ˆÑVð Ðð " ' Ð+ˆÜ˜‹nÐùòw*ùòùó Wùô*ùó^ Ws6   Ã	K6Ã+K;Ä3LÅL ÅL ÅLËLËLÌ Lc           
     óˆ  — | j                  d«      }t        t        | j                  d«      «      }t        t        | j                  d«      xs d«      }i }| j                  d«      r!t        | d   «      }d|v r
|d   €d|d<   ||d<   g }| j                  d«      x}rS	 |D �	cg c]G  }	t	        |	d   j                  d«      |	d   j                  d	«      |	j                  d«      |	d
   ¬«      ‘ŒI }}	|dk(  s	|t        k(  rt        ||¬«      S |dk(  s	|t        k(  rt        ||||¬«      S |dv s	|t        k(  r|dk(  rddi}ni }t        |||¬«      S |dk(  s	|t        k(  rt        || d   |¬«      S |dk(  s	|t        k(  rt        || d   |¬«      S |s	|t        k(  rt        |||¬«      S  |||¬«      S c c}	w # t
        $ r Y ŒÐw xY w)z%Convert to a LangChain message chunk.r—   r•   r6   r™   r›   r–   rœ   r¥   Ú	argumentsÚindex)r–   Úargsr—   rù   r˜   )r6   r—   rš   )r6   rŸ   r—   Útool_call_chunksr¡   r£   r¤   )r6   r—   rŸ   r¦   r§   r¨   )r6   r¨   r—   r©   )r„   r   r­   rª   r<   ÚKeyErrorr.   r&   r1   r,   r4   r*   )
r®   Údefault_classr¯   r•   r6   rŸ   r›   rû   r°   Úrtcs
             r~   Ú_convert_delta_to_message_chunkrÿ   *  s  € ð �)‰)�D‹/€CÜ”�U—Y‘Y˜vÓ&Ó'€DÜ”3˜Ÿ	™	 )Ó,Ò2°Ó3€GØ ÐØ‡y�y�Ô!Ü˜U ?Ñ3Ó4ˆØ�]Ñ" }°VÑ'<Ð'DØ$&ˆM˜&Ñ!Ø-:Ð˜/Ñ*ØÐØŸ™ <Ó0Ð0€~Ð0ð	ñ *ó ñ *�Cô  Ø˜Z™×,Ñ,¨VÓ4Ø˜Z™×,Ñ,¨[Ó9Ø—w‘w˜t“}Ø˜g™,ö	ð *ð ð  ð ˆv‚~˜Ô*;Ò;Ü ¨°SÔ9Ð9Øˆ{Ò˜m¬~Ò=ÜØØ/ØØ-ô	
ð 	
ð Ð&Ñ&¨-Ô;MÒ*MØ�;ÒØ!2°KÐ @Ñà "ÐÜ!Ø Ð7Hô
ð 	
ð ˆzÒ˜]Ô.BÒBÜ#¨G¸%À¹-ÈCÔPÐPØˆv‚~˜Ô*:Ò:ÜØ¨%°Ñ*?ÀCô
ð 	
ñ ˆ}Ô 0Ò0Ü¨°d¸sÔCÐCÙ ¨SÔ1Ð1ùòK øô ò 	Ùð	ús%   ÂF5 Â"AF0Ã.F5 Æ0F5 Æ5	GÇ Gc                óî  — t        |t        «      r:t        | t        «      s%dt        |«      › dt        | «      › �}t        |«      ‚|| z   S t        |t        «      rst        | t        «      s%dt        |«      › dt        | «      › �}t        |«      ‚|j                  «       D ��ci c]"  \  }}|t        | j                  |d«      |«      “Œ$ c}}S t        j                  dt        |«      › �«       |S c c}}w )Nz%Got different types for token usage: z and r   z!Unexpected type for token usage: )
r·   Úintr¼   rÐ   rª   rë   Ú_update_token_usager„   ÚwarningsÚwarn)Úoverall_token_usageÚ	new_usagerÓ   rò   ró   s        r~   r  r  b  s
  € ô
 �)œSÔ!ÜÐ-¬sÔ3à7Ü˜	“?Ð# 5¬Ð.AÓ)BÐ(CðEð ô ˜S“/Ð!ØÐ.Ñ.Ð.Ü�)œTÔ"ÜÐ-¬tÔ4à7Ü˜	“?Ð# 5¬Ð.AÓ)BÐ(CðEð ô ˜S“/Ð!ð "Ÿ™Ô)ô
á)‘��1ð Ô"Ð#6×#:Ñ#:¸1¸aÓ#@À!ÓDÑDØ)ò
ð 	
ô ‡M�MÐ5´d¸9³oÐ5FÐGÔHØÐùó
s   Â#'C1c                  ó   — e Zd ZdZy)ÚOpenAIContextOverflowErrorzABadRequestError raised when input exceeds OpenAI's context limit.N©Ú__name__Ú
__module__Ú__qualname__Ú__doc__rÌ   r€   r~   r  r  ~  s   „ ÚKr€   r  c                  ó   — e Zd ZdZy)ÚOpenAIAPIContextOverflowErrorz:APIError raised when input exceeds OpenAI's context limit.Nr	  rÌ   r€   r~   r  r  ‚  ó   „ ÚDr€   r  c                  ó   — e Zd ZdZy)ÚOpenAIAuthenticationErrorzBOpenAI authentication error classified as a LangChain model error.Nr	  rÌ   r€   r~   r  r  †  s   „ ÚLr€   r  c                  ó   — e Zd ZdZy)ÚOpenAIPermissionDeniedErrorz>OpenAI permission error classified as a LangChain model error.Nr	  rÌ   r€   r~   r  r  Š  s   „ ò Ir€   r  c                  ó   — e Zd ZdZy)ÚOpenAIInvalidRequestErrorz?OpenAI bad-request error classified as a LangChain model error.Nr	  rÌ   r€   r~   r  r  �  s   „ ÚIr€   r  c                  ó   — e Zd ZdZy)ÚOpenAIModelNotFoundErrorz=OpenAI not-found error classified as a LangChain model error.Nr	  rÌ   r€   r~   r  r  ”  s   „ ÚGr€   r  c                  ó   — e Zd ZdZy)ÚOpenAIRateLimitErrorz>OpenAI rate-limit error classified as a LangChain model error.Nr	  rÌ   r€   r~   r  r  ˜  ó   „ ÚHr€   r  c                  ó   — e Zd ZdZy)ÚOpenAIAPIErrorz:OpenAI server error classified as a LangChain model error.Nr	  rÌ   r€   r~   r  r  œ  r  r€   r  c                  ó   — e Zd ZdZy)ÚOpenAIConnectionErrorz>OpenAI connection error classified as a LangChain model error.Nr	  rÌ   r€   r~   r  r     r  r€   r  c                  ó   — e Zd ZdZy)ÚOpenAITimeoutErrorz;OpenAI timeout error classified as a LangChain model error.Nr	  rÌ   r€   r~   r!  r!  ¤  s   „ ÚEr€   r!  c                ó  — dt        | «      v s*d| j                  v sd| j                  v sd| j                  v r-t        | j                  | j                  | j                  ¬«      | ‚d| j                  v rDd}t        j                  |«       t        | j                  | j                  | j                  ¬«      | ‚d| j                  v rd	}t        j                  |«       t        | j                  | j                  | j                  ¬«      | ‚)
NÚcontext_length_exceededz(Input tokens exceed the configured limitzprompt is too longÚContextWindowExceededError©rí   ÚresponseÚbodyzH'response_format' of type 'json_schema' is not supported with this modelzëThis model does not support OpenAI's structured output feature, which is the default method for `with_structured_output` as of langchain-openai==0.3. To use `with_structured_output` with this model, specify `method="function_calling"`.z"Invalid schema for response_formata3  Invalid schema for OpenAI's structured output feature, which is the default method for `with_structured_output` as of langchain-openai==0.3. Specify `method="function_calling"` instead or update your schema. See supported schemas: https://platform.openai.com/docs/guides/structured-outputs#supported-schemas)r­   rí   r  r&  r'  r  r  r  )r²   rí   s     r~   Ú_handle_openai_bad_requestr(  ¨  sì   € à!¤S¨£VÑ+Ø5¸¿¹ÑBØ 1§9¡9Ñ,Ø'¨1¯9©9Ñ4ä(Ø—I‘I¨¯
©
¸¿¹ô
àð	ð 	SØ	
�‰ñð3ð 	ô 	�‰�gÔÜ'Ø—I‘I¨¯
©
¸¿¹ô
àð	ð ,¨q¯y©yÑ8ð[ð 	ô 	�‰�gÔÜ
#Ø—	‘	 A§J¡J°Q·V±Vôàðr€   c                ó  — t        | «      }d|v r-t        | j                  | j                  | j                  ¬«      | ‚t        | t        j                  «      r-t        | j                  | j                  | j                  ¬«      | ‚t        | t        j                  «      r-t        | j                  | j                  | j                  ¬«      | ‚t        | t        j                  «      r-t        | j                  | j                  | j                  ¬«      | ‚t        | t        j                  «      r-t        | j                  | j                  | j                  ¬«      | ‚t        | t        j                   «      r-t#        | j                  | j                  | j                  ¬«      | ‚t        | t        j$                  «      rt'        | j                  «      | ‚t        | t        j(                  «      r"t+        | j                  | j                  ¬«      | ‚‚ )Nzexceeds the context window)rí   Úrequestr'  r%  )rí   r*  )r­   r  rí   r*  r'  r·   ÚopenaiÚAuthenticationErrorr  r&  ÚPermissionDeniedErrorr  ÚNotFoundErrorr  ÚRateLimitErrorr  ÚInternalServerErrorr  ÚAPITimeoutErrorr!  ÚAPIConnectionErrorr  )r²   Úerror_messages     r~   Ú_handle_openai_api_errorr4  Í  s…  € Ü˜“F€MØ# }Ñ4Ü+Ø—I‘I q§y¡y°q·v±vô
àð	ô �!”V×/Ñ/Ô0Ü'Ø—I‘I¨¯
©
¸¿¹ô
àð	ô �!”V×1Ñ1Ô2Ü)Ø—I‘I¨¯
©
¸¿¹ô
àð	ô �!”V×)Ñ)Ô*Ü&Ø—I‘I¨¯
©
¸¿¹ô
àð	ô �!”V×*Ñ*Ô+Ü"Ø—I‘I¨¯
©
¸¿¹ô
àð	ô �!”V×/Ñ/Ô0Ü Q§Y¡Y¸¿¹È!Ï&É&ÔQÐWXÐXÜ�!”V×+Ñ+Ô,Ü  §¡Ó+°Ð2Ü�!”V×.Ñ.Ô/Ü#¨A¯I©I¸q¿y¹yÔIÈqÐPØ	r€   c                óR   — t        |dd«      }|€yt        |«      }|�
|| t        <   yy)zÎAdd parsed LangSmith gateway metadata to `generation_info`, if present.

    Args:
        generation_info: Generation info to mutate in place.
        raw_response: The raw provider response, or None.
    ÚheadersN)ÚgetattrrO   rN   )Úgeneration_infoÚraw_responser6  Úgateway_metadatas       r~   Ú_add_gateway_metadatar;  ì  s;   € ô �l I¨tÓ4€GØ€ØÜ.¨wÓ7ÐØÐ#Ø9IˆÔ5Ò6ð $r€   )z	gpt-5-prozgpt-5.2-prozgpt-5.4-prozgpt-5.5-prozgpt-5.6-solc                ó>   — | sy| j                  t        «      xs d| v S )NFÚcodex)rÈ   Ú_RESPONSES_API_ONLY_PREFIXES©r†   s    r~   Ú_model_prefers_responses_apir@    s$   € ÙØØ× Ñ Ô!=Ó>ÒWÀ'ÈZÐBWÐWr€   Ú_BM)Úboundr   Ú_DictOrPydanticClassÚ_DictOrPydanticc                  óÈ  ‡ — e Zd ZU dZ edd¬«      Zded<    edd¬«      Zded<    edd¬«      Zded<    edd¬«      Z	ded	<    ed
d¬«      Z
ded<   	 dZded<   	  ee¬«      Zded<   	  edd¬«      Zded<   	  edd¬«      Zded<   	  edd¬«      Zded<   	  e edd¬«      ¬«      Zded<    edd ¬«      Zd!ed"<   	 dZd#ed$<   	 dZd%ed&<   	 dZded'<   	 dZded(<   	 dZd%ed)<   	 dZd#ed*<   	 dZd%ed+<   	 dZd,ed-<   	 d.Zd/ed0<   	 dZd%ed1<   	 dZded2<   	  ed¬«      Zd%ed3<   	 dZ ded4<   	 dZ!d5ed6<   	 dZ"ded7<   	 dZ#ded8<   	 dZ$d9ed:<   dZ%d;ed<<    edd¬«      Z&d=ed><   	  edd¬«      Z'd=ed?<   	  edd¬«      Z(d@edA<   	  edB„ d¬C«      Z)dedD<   	  eddE¬«      Z*dFedG<   	 dZ+dHedI<   	 d.Z,d/edJ<   	  ed¬«      Z-d5edK<   	 dZ.dLedM<   	 dZ/dNedO<   	 dZ0d5edP<   	 dZ1dedQ<   	 dZ2d#edR<   	 dZ3dedS<   	 d.Z4d/edT<   	 dZ5d#edU<   	  e edVd¬«      ¬«      Z6dedW<   	  e7d¬X«      Z8e9d„dY„«       Z:e9d…dZ„«       Z; e<d[¬\«      e=d†d]„«       «       Z> e?dDd^¬\«      e=d‡d_„«       «       Z@ e<d[¬\«      e=d†d`„«       «       ZA e<d^¬\«      dˆda„«       ZB e<d^¬\«      dˆdb„«       ZC e<d^¬\«      dˆdc„«       ZDd‰dd„ZEe9dŠde„«       ZFd‹df„ZG	 	 	 	 	 	 	 	 dŒdg„ZHd�dh„ZI	 	 dŽ	 	 	 	 	 	 	 	 	 d�di„ZJ	 	 dŽ	 	 	 	 	 	 	 	 	 d�dj„ZK	 d‘	 	 	 	 	 d’dk„ZL	 	 dŽddlœ	 	 	 	 	 	 	 	 	 	 	 d“dm„ZM	 	 dŽ	 	 	 	 	 	 	 	 	 d”dn„ZNd•do„ZOddpœ	 	 	 	 	 	 	 d–dq„ZP	 d‘	 	 	 	 	 d—dr„ZQ	 	 dŽddlœ	 	 	 	 	 	 	 	 	 	 	 d˜ds„ZR	 	 dŽ	 	 	 	 	 	 	 	 	 d™dt„ZSe9dŠdu„«       ZT	 d‘	 	 	 	 	 dšˆ fdv„ZU	 d‘	 	 	 	 	 d›dw„ZVe9d…dx„«       ZWdœdy„ZXd�ˆ fdz„ZY	 d‘dd{œ	 	 	 	 	 	 	 džˆ fd|„ZZddddd}œ	 	 	 	 	 	 	 	 	 	 	 	 	 dŸˆ fd~„Z[	 d‘dd.ddd€œ	 	 	 	 	 	 	 	 	 	 	 	 	 d d�„Z\d¡d‚„Z]	 	 	 	 d¢dƒ„Z^ˆ xZ_S )£ÚBaseChatOpenAIah  Base wrapper around OpenAI large language models for chat.

    This base class targets
    [official OpenAI API specifications](https://github.com/openai/openai-openapi)
    only. Non-standard response fields added by third-party providers (e.g.,
    `reasoning_content`) are not extracted. Use a provider-specific subclass for
    full provider support.
    NT)r‡   Úexcluder   ÚclientÚasync_clientÚroot_clientÚroot_async_clientúgpt-3.5-turboÚmodel©r‡   Úaliasr­   r†   úfloat | NoneÚtemperature)Údefault_factoryúdict[str, Any]Úmodel_kwargsÚapi_key)rO  r‡   zCSecretStr | None | Callable[[], str] | Callable[[], Awaitable[str]]Úopenai_api_keyÚbase_urlú
str | NoneÚopenai_api_baseÚorganizationÚopenai_organizationÚOPENAI_PROXY)r‡   Úopenai_proxyÚtimeoutz(float | tuple[float, float] | Any | NoneÚrequest_timeoutúbool | NoneÚstream_usageú
int | NoneÚmax_retriesÚpresence_penaltyÚfrequency_penaltyÚseedÚlogprobsÚtop_logprobszdict[int, int] | NoneÚ
logit_biasFÚboolÚ	streamingÚnÚtop_pÚ
max_tokensÚreasoning_effortúdict[str, Any] | NoneÚ	reasoningÚ	verbosityÚtiktoken_model_namezMapping[str, str] | NoneÚdefault_headerszMapping[str, object] | NoneÚdefault_queryz
Any | NoneÚhttp_clientÚhttp_async_clientz%Sequence[tuple[int, int, int]] | NoneÚhttp_socket_optionsc                 ó   — t        dd«      S )NÚ'LANGCHAIN_OPENAI_STREAM_CHUNK_TIMEOUT_Sç      ^@)re   rÌ   r€   r~   Ú<lambda>zBaseChatOpenAI.<lambda>N  s   € ¤
Ø5°uô!
r€   )rR  rG  Ústream_chunk_timeoutÚstop_sequenceszlist[str] | str | NoneÚstopzMapping[str, Any] | NoneÚ
extra_bodyÚinclude_response_headersÚdisabled_paramszlist[dict[str, Any]] | NoneÚcontext_managementúlist[str] | NoneÚincludeÚprompt_cache_optionsÚservice_tierÚstoreÚ
truncationÚuse_previous_response_idÚuse_responses_apiÚLC_OUTPUT_VERSIONÚoutput_version)Úpopulate_by_namec                óz   — | j                   }t        |t        «      r|j                  «       j	                  d«      S y)a,  Whether requests are routed through the LangSmith gateway.

        Detected from the resolved API key: LangSmith keys (used to authenticate
        to the gateway) carry the `lsv2_` prefix. Callable keys cannot be
        inspected without invoking them, so they are treated as non-gateway.
        Úlsv2_F)rV  r·   r\   Úget_secret_valuerÈ   )ÚselfrU  s     r~   Ú_uses_gatewayzBaseChatOpenAI._uses_gateway  s6   € ð ×%Ñ%ˆÜ�gœyÔ)Ø×+Ñ+Ó-×8Ñ8¸ÓAÐAØr€   c                ó   — | j                   S )zSame as model_name.r?  ©r’  s    r~   rM  zBaseChatOpenAI.model%  s   € ð �‰Ðr€   Úbefore)Úmodec                ó0   — t        | «      }t        ||«      S )z>Build extra kwargs from additional params that were passed in.)rM   rW   )ÚclsÚvaluesÚall_required_field_namess      r~   Úbuild_extrazBaseChatOpenAI.build_extra*  s   € ô $<¸CÓ#@Ð Ü" 6Ð+CÓDÐDr€   Úafterc                ó^   — |�*|dk  r%t        dd«      }t        j                  d||«       |S |S )aƒ  Reject negative constructor values; fall back to the env-driven default.

        Matches the env-var path in `_float_env`: a negative value is a typo,
        not an opt-out (`None`/`0` are the documented off switches). Configs
        hydrated from YAML/JSON would otherwise silently disable the wrapper
        and reintroduce the indefinite-stream hang the feature prevents.
        r   rz  r{  z`Invalid `stream_chunk_timeout=%r` (negative); falling back to %s. Pass `None` or `0` to disable.)re   ÚloggerÚwarning)r™  ÚvalueÚfallbacks      r~   Ú_validate_stream_chunk_timeoutz-BaseChatOpenAI._validate_stream_chunk_timeout1  sA   € ð Ð ¨¢Ü!Ð"KÈUÓSˆHÜ�N‰NðEàØô	ð ˆOØˆr€   c                óž  — |j                  d«      xs |j                  d«      xs d}|j                  «       }|j                  d«      r	d|vrd|d<   |j                  d«      rid|vre|j                  d	«      d
k7  rQ|j                  d«      xs i j                  d«      d
k7  r*|j                  d«      }|�|dk7  r|j                  dd«       |S )z¬Validate temperature parameter for different models.

        - gpt-5 models (excluding gpt-5-chat) only allow `temperature=1` or unset
            (Defaults to 1)
        r†   rM  r™   Úo1rQ  é   úgpt-5Úchatro  Únonerq  ÚeffortN)r„   rÇ   rÈ   Úpop)r™  rš  rM  Úmodel_lowerrQ  s        r~   Úvalidate_temperaturez#BaseChatOpenAI.validate_temperatureF  sÌ   € ð —
‘
˜<Ó(ÒE¨F¯J©J°wÓ,?ÒEÀ2ˆØ—k‘k“mˆð ×!Ñ! $Ô'¨MÀÑ,GØ$%ˆF�=Ñ!ð ×"Ñ" 7Ô+Ø˜{Ñ*Ø—
‘
Ð-Ó.°&Ò8Ø—‘˜KÓ(Ò.¨B×3Ñ3°HÓ=ÀÒGà Ÿ*™* ]Ó3ˆKØÐ&¨;¸!Ò+;ð —
‘
˜=¨$Ô/àˆr€   c                ó2   — | j                  dt        «       | S )aÎ  Set package version in metadata.

        Note: Subclasses that inherit from `BaseChatOpenAI` (e.g.
        `ChatDeepSeek`, `ChatXAI`) must use a **unique** validator name
        (e.g. `_set_deepseek_version`) instead of overriding this one. Pydantic
        replaces same-named `model_validator` methods rather than chaining them,
        so reusing `_set_openai_chat_version` would silently drop the parent's
        `langchain-openai` version entry.
        zlangchain-openai)Ú_add_versionra   r•  s    r~   Ú_set_openai_chat_versionz'BaseChatOpenAI._set_openai_chat_versionf  s   € ð 	×ÑÐ,¬kÔ:Øˆr€   c                óN   — | j                   €| j                  i «      rd| _         | S )z:Expose unconditional instance-level Responses API routing.T)r‹  Ú_use_responses_apir•  s    r~   Ú_infer_use_responses_apiz'BaseChatOpenAI._infer_use_responses_apit  s*   € ð ×!Ñ!Ð)¨d×.EÑ.EÀbÔ.IØ%)ˆDÔ"Øˆr€   c                óð  ‡ — ‰ j                   �‰ j                   dk  rd}t        |«      ‚‰ j                   �(‰ j                   dkD  r‰ j                  rd}t        |«      ‚‰ j                  xs, t	        j
                  d«      xs t	        j
                  d«      ‰ _        t        ‰ j                  ‰ j                  ddd	¬
«      }|j                  ‰ _        |j                  ‰ _        |j                  }t        ˆ fd„dD «       «      r'|s‰ j                  €dt        j                  vrd‰ _        d}d}‰ j                  �t        ‰ j                  «      \  }}‰ j                  ‰ j                  ‰ j                   ‰ j"                  ‰ j$                  dœ}‰ j&                  �‰ j&                  |d<   ‰ j(                  rR‰ j*                  s‰ j,                  r:‰ j(                  }‰ j*                  }‰ j,                  }	d|›d|›d|	›�}t        |«      ‚t/        ‰ j0                  ‰ j*                  ‰ j,                  ‰ j(                  ¬«      rd}
t3        «        n,t5        ‰ j0                  «      }
t7        |
‰ j(                  ¬«       ‰ j8                  s½|€d‰ _        d‰ _        n¬‰ j(                  r-‰ j*                  s!t=        ‰ j(                  t>        |
¬«      ‰ _        ‰ j*                  xs! tA        ‰ j                  ‰ j                   |
«      |dœ}tC        jD                  di |¤|¤Ž‰ _        ‰ j:                  jF                  jH                  ‰ _        ‰ jJ                  s¬‰ j(                  r-‰ j,                  s!tM        ‰ j(                  t>        |
¬«      ‰ _        ‰ j,                  xs! tO        ‰ j                  ‰ j                   |
«      |dœ}tC        jP                  di |¤|¤Ž‰ _)        ‰ jR                  jF                  jH                  ‰ _%        ‰ S )z?Validate that api key and python package exists in environment.Nr¦  zn must be at least 1.zn must be 1 when streaming.ÚOPENAI_ORG_IDÚOPENAI_ORGANIZATIONz	openai/v1ÚOPENAI_API_BASEÚOPENAI_API_KEY)rW  rU  Úprovider_pathÚbase_url_envÚapi_key_envc              3  ó<   •K  — | ]  }t        ‰|d «      d u –— Œ y ­wr‚   )r7  )Ú.0Úkeyr’  s     €r~   Ú	<genexpr>z6BaseChatOpenAI.validate_environment.<locals>.<genexpr>š  s+   øè ø€ ð 
ñ	�ô �D˜#˜tÓ$¨Ô,ñ	ùs   ƒ)ra  r]  rH  rJ  rI  rK  rv  rw  ÚOPENAI_BASE_URLT)rZ  rW  r^  rt  ru  rc  zwCannot specify 'openai_proxy' if one of 'http_client'/'http_async_client' is already specified. Received:
openai_proxy=z
http_client=z
http_async_client=)rx  rv  rw  r]  rÌ   )r]  )Úproxyrz   Úsocket_options)rv  rU  )*rl  rÐ   rk  r[  ÚosÚgetenvrP   rY  rV  rW  rU  Úbase_url_from_gatewayÚallÚenvironra  rj   r_  rt  ru  rc  r]  rv  rw  rk   rx  rh   ri   rl   rH  rJ  rd   r}   rg   r+  ÚOpenAIr¨  ÚcompletionsrI  rc   rf   ÚAsyncOpenAIrK  )r’  rÓ   Ú_gateway_configÚ_base_url_from_gatewayÚsync_api_key_valueÚasync_api_key_valueÚclient_paramsr]  rv  rw  Úresolved_socket_optionsÚsync_specificÚasync_specifics   `            r~   Úvalidate_environmentz#BaseChatOpenAI.validate_environment{  sÜ  ø€ ð �6‰6Ð $§&¡&¨1¢*Ø)ˆCÜ˜S“/Ð!Ø�6‰6Ð $§&¡&¨1¢*°·²Ø/ˆCÜ˜S“/Ð!ð ×$Ñ$ò 0Ü�y‰y˜Ó)ò0ä�y‰yÐ.Ó/ð 	Ô ô 2Ø×)Ñ)Ø×'Ñ'Ø%Ø*Ø(ô
ˆð  /×7Ñ7ˆÔØ-×5Ñ5ˆÔØ!0×!FÑ!FÐô
 ó 
ñ	ó
ô 
ñ #Ø×$Ñ$Ð,Ð1BÌ"Ï*É*Ñ1Tà $ˆDÔð >BÐØIMÐà×ÑÐ*ô 7WØ×#Ñ#ó7Ñ3ÐÐ 3ð
 !×4Ñ4Ø×,Ñ,Ø×+Ñ+Ø#×3Ñ3Ø!×/Ñ/ñ
ˆð ×ÑÐ'Ø+/×+;Ñ+;ˆM˜-Ñ(à×Ò $×"2Ò"2°d×6LÒ6LØ×,Ñ,ˆLØ×*Ñ*ˆKØ $× 6Ñ 6Ðð!à�/  K >Ð1FÐ4EÐ3GðIð ô
 ˜S“/Ð!Ü6Ø $× 8Ñ 8Ø×(Ñ(Ø"×4Ñ4Ø×*Ñ*õ	
ð IKÐ#Ü&Õ(ä&=¸d×>VÑ>VÓ&WÐ#Ü'Ø'°d×6GÑ6Gõð �{Š{Ø!Ð)ð #�”Ø#'�Õ à×$Ò$¨T×-=Ò-=Ü'GØ"×/Ñ/Ü1Ø'>ô(�DÔ$ð $(×#3Ñ#3ò $Ü0Ø×,Ñ,Ø×,Ñ,Ø/óð
  2ñ!�ô $*§=¡=Ñ#R°=Ð#RÀMÑ#R�Ô Ø"×.Ñ.×3Ñ3×?Ñ?�”Ø× Ò Ø× Ò ¨×)?Ò)?Ü)JØ×+Ñ+Ü-Ø#:ô*�Ô&ð  $×5Ñ5ò  Ü2Ø×(Ñ(Ø×(Ñ(Ø+óð
 /ñˆNô &,×%7Ñ%7ñ &Øð&à ñ&ˆDÔ"ð !%× 6Ñ 6× ;Ñ ;× GÑ GˆDÔØˆr€   c                óŠ   — t        | j                  «      xs d }|�'|j                  d«      r| j                  i «      sd|d<   |S )NÚmid_conversation_toolsF)rˆ   r†   r„   r²  )r’  Úprofiles     r~   Ú_resolve_model_profilez%BaseChatOpenAI._resolve_model_profile  sH   € Ü,¨T¯_©_Ó=ÒEÀˆàÐØ—‘Ð4Ô5Ø×+Ñ+¨BÔ/ð 16ˆGÐ,Ñ-Øˆr€   c                óÊ  — i d| j                   “d| j                  “d| j                  “d| j                  “d| j                  “d| j
                  “d| j                  “d| j                  xs d	“d
| j                  “d| j                  “d| j                  “d| j                  “d| j                  “d| j                  “d| j                  “d| j                  “d| j                   “| j"                  | j$                  | j&                  | j(                  dœ¥}| j*                  | j,                  dœ|j/                  «       D ��ci c]  \  }}|€Œ	||“Œ c}}¥| j0                  ¥S c c}}w )ú2Get the default parameters for calling OpenAI API.rd  re  rf  rm  rg  rh  ri  r  Nrn  r€  rl  rQ  ro  rq  rr  rƒ  r…  )r†  r‡  r‰  rˆ  )rM  Ústream)rd  re  rf  rm  rg  rh  ri  r  rn  r€  rl  rQ  ro  rq  rr  rƒ  r…  r†  r‡  r‰  rˆ  r†   rk  rë   rT  )r’  Úexclude_if_nonerò   ró   s       r~   Ú_default_paramszBaseChatOpenAI._default_params  s­  € ð
Ø × 5Ñ 5ð
à ×!7Ñ!7ð
ð �D—I‘Ið
ð �T—Z‘Zð	
ð
 ˜Ÿ™ð
ð ˜D×-Ñ-ð
ð ˜$Ÿ/™/ð
ð �D—I‘IÒ% ð
ð ˜$Ÿ/™/ð
ð ˜$Ÿ/™/ð
ð �—‘ð
ð ˜4×+Ñ+ð
ð  × 5Ñ 5ð
ð ˜Ÿ™ð
ð ˜Ÿ™ð
ð  ! $×"9Ñ"9ð!
ð" �t—|‘|ð#
ð$ %)×$=Ñ$=Ø ×-Ñ-ØŸ/™/Ø—Z‘Zò+
ˆð2 —_‘_Ø—n‘nñ
ð !0× 5Ñ 5Ô 7ÔIÑ 7™˜˜1¸1¹=ˆq�!‰tÐ 7ÒIð
ð ×Ñð	
ð 	
ùó Js   Ä>
EÅ	Ec                ó
  — i }d }|D ]c  }|€Œ|j                  d«      }|�7|j                  «       D ]$  \  }}|€Œ	||v rt        ||   |«      ||<   Œ |||<   Œ& |�ŒS|j                  d«      }Œe || j                  dœ}|r||d<   |S )NÚtoken_usageÚsystem_fingerprint)rÞ  r†   )r„   rë   r  r†   )	r’  Úllm_outputsr  rß  ÚoutputrÞ  rò   ró   Úcombineds	            r~   Ú_combine_llm_outputsz#BaseChatOpenAI._combine_llm_outputs9  s¾   € Ø$&ÐØ!ÐÛ!ˆFØˆ~àØ Ÿ*™* ]Ó3ˆKØÐ&Ø'×-Ñ-Ö/‘D�A�qØ�yØ ØÐ/Ñ/Ü1DØ/°Ñ2°Aó2Ð+¨AÒ.ð 23Ð+¨AÒ.ð 0ð "Ñ)Ø%+§Z¡ZÐ0DÓ%EÑ"ð! "ð" $7ÀdÇoÁoÑVˆÙØ-?ˆHÐ)Ñ*Øˆr€   c                ót  — |j                  d«      dk(  ry |j                  d«      }|j                  dg «      xs" |j                  di «      j                  dg «      }|rt        ||j                  d«      «      nd }t        |«      dk(  r?t         |d|¬	«      |¬
«      }| j                  dk(  rd|j
                  j                  d<   |S |d   }|d   €y t        |d   |«      }	|ri |¥ni }
|j                  d«      x}rM||
d<   |j                  d«      x}r||
d<   |j                  d«      x}r||
d<   |j                  d«      x}r||
d<   |j                  d«      }|r||
d<   |rt        |	t        «      r||	_
        d|	j                  d<   | j                  dk(  rd|	j                  d<   t        |	|
xs d ¬
«      S )Nr¼   zcontent.deltaÚusageÚchoicesÚchunkr‡  r   r™   )r6   Úusage_metadata©rí   r8  Úv1r�  ÚdeltaÚfinish_reasonrM  r†   rß  rg  r+  Úmodel_provider)r„   Ú_create_usage_metadataÚlenrD   r�  rí   Úresponse_metadatarÿ   r·   r&   rè  )r’  rç  Údefault_chunk_classÚbase_generation_inforÞ  ræ  rè  Úgeneration_chunkÚchoiceÚmessage_chunkr8  rì  r†   rß  r‡  rg  s                   r~   Ú"_convert_chunk_to_generation_chunkz1BaseChatOpenAI._convert_chunk_to_generation_chunkR  sþ  € ð �9‰9�VÓ Ò/ØØ—i‘i Ó(ˆà�I‰I�i Ó$ò 9à�y‰y˜ "Ó%×)Ñ)¨)°RÓ8ð 	ñ ô # ;°·	±	¸.Ó0IÔJàð 	ô
 ˆw‹<˜1Òä2Ù+°BÀ~ÔVØ 4ô Ðð ×"Ñ" dÒ*ØOSÐ ×(Ñ(×:Ñ:Ð;KÑLà#Ð#à˜‘ˆØ�'‰?Ð"Øä7Ø�7‰OÐ0ó
ˆñ 7KÐ2Ð1Ñ2ÐPRˆà"ŸJ™J Ó7Ð7ˆ=Ð7Ø/<ˆO˜OÑ,Ø"ŸY™Y wÓ/Ð/ˆzÐ/Ø0:� Ñ-Ø%*§Y¡YÐ/CÓ%DÐDÐ!ÐDØ8J�Ð 4Ñ5Ø$Ÿy™y¨Ó8Ð8ˆ|Ð8Ø2>� Ñ/à—:‘:˜jÓ)ˆÙØ*2ˆO˜JÑ'áœj¨¼ÔGØ+9ˆMÔ(à<Dˆ×'Ñ'Ð(8Ñ9à×Ñ $Ò&Ø@DˆM×+Ñ+Ð,<Ñ=Ü"Ø!°?Ò3JÀdô
ð 	
r€   c                ó6   — | j                   €d}t        |«      ‚y)z8Check that sync client is available, raise error if not.NzÃSync client is not available. This happens when an async callable was provided for the API key. Use async methods (ainvoke, astream) instead, or provide a string or sync callable for the API key.)rH  rÐ   )r’  rÓ   s     r~   Ú_ensure_sync_client_availablez,BaseChatOpenAI._ensure_sync_client_available™  s(   € à�;‰;ÐðQð ô
 ˜S“/Ð!ð r€   c              +  óê  K  — | j                  «        d|d<    | j                  |fd|i|¤Ž}i }i }	 | j                  s| j                  rp | j                  j
                  j                  j                  di |¤Ž}|j                  «       }	| j                  rdt        |j                  «      i}t        ||«       n& | j                  j                  j                  di |¤Ž}	|j                  d«      }
|	5 }d}d}d}d}d}|D ]‰  }|r|ni }t        |||||
||| j                  ¬«      \  }}}}|sŒ.|r|ri |¥|j                  xs i ¥|_        |r|j!                  |j"                  |¬	«       d}d
|j$                  j&                  v rd}|–— Œ‹ 	 d d d «       y # 1 sw Y   y xY w# t(        j*                  $ r}t-        |«       Y d }~y d }~wt(        j.                  $ r}t1        |«       Y d }~y d }~ww xY w­w)NTrÚ  r  r6  Úresponse_formatéÿÿÿÿF©ÚschemaÚmetadataÚhas_reasoningr�  ©rç  rq  rÌ   )rø  Ú_get_request_payloadr�  r“  rJ  Úwith_raw_responserÛ   ÚcreateÚparserª   r6  r;  r„   Ú,_convert_responses_chunk_to_generation_chunkr�  r8  Úon_llm_new_tokenr½   rí   rŸ   r+  ÚBadRequestErrorr(  ÚAPIErrorr4  ©r’  Úmessagesr  Úrun_managerÚkwargsÚpayloadr6  rò  Úraw_context_managerÚcontext_managerÚoriginal_schema_objr&  Úis_first_chunkÚcurrent_indexÚcurrent_output_indexÚcurrent_sub_indexrÿ  rç  rþ  ró  r²   s                        r~   Ú_stream_responsesz BaseChatOpenAI._stream_responses£  s!  è ø€ ð 	×*Ñ*Ô,ØˆˆxÑØ+�$×+Ñ+¨HÑJ¸4ÐJÀ6ÑJˆØˆØ%'Ðð5	(Ø×,Ò,°×0BÒ0BàG�D×$Ñ$×6Ñ6×@Ñ@×GÑGÑRÈ'ÑRð $ð #6×";Ñ";Ó"=�Ø×0Ò0Ø(¬$Ð/B×/JÑ/JÓ*KÐL�GÜ%Ð&:Ð<OÕPà"C $×"2Ñ"2×"<Ñ"<×"CÑ"CÑ"NÀgÑ"N�Ø"(§*¡*Ð->Ó"?Ðá  HØ!%�Ø "�Ø')Ð$Ø$&Ð!Ø %�Û%�EÙ*8™w¸b�Hô EØØ%Ø,Ø)Ø2Ø!)Ø&3Ø'+×':Ñ':ô	ñØ%Ø,Ø)Ø(ò (Ù)Ñ.Bð@Ø"6ð@à#3×#CÑ#CÒ#IÀrð@Ð,Ô<ñ 'Ø'×8Ñ8Ø 0× 5Ñ 5Ð=Mð 9ô ð */˜Ø&Ð*:×*BÑ*B×*TÑ*TÑTØ,0˜MØ.Ó.ñ= &÷ !—‘ûôJ ×%Ñ%ò 	*Ü& q×)Ñ)ûÜ�‰ò 	(Ü$ Q×'Ñ'ûð	(üsl   ‚/G3²CF" Ã3:FÄ.AFÆF" ÆG3ÆFÆF" ÆG3ÆF" Æ"G0Æ5GÇ G3ÇG0ÇG+Ç&G3Ç+G0Ç0G3c               ó�  K  — d|d<    | j                   |fd|i|¤Ž}i }i }	 | j                  s| j                  rx | j                  j                  j
                  j                  di |¤Žƒ d {  –—† }|j                  «       }	| j                  rdt        |j                  «      i}t        ||«       n. | j                  j
                  j                  di |¤Žƒ d {  –—† }	|j                  d«      }
|	4 ƒd {  –—† }d}d}d}d}d}t        || j                  | j                  ¬«      2 3 d {  –—† }|r|ni }t        |||||
||| j                   ¬	«      \  }}}}|sŒ4|r|ri |¥|j"                  xs i ¥|_        |r%|j%                  |j&                  |¬
«      ƒ d {  –—†  d}d|j(                  j*                  v rd}|­–— Œš7 �ŒU7 Œé7 ŒÏ7 Œœ7 Œ/6 d d d «      ƒd {  –—†7   y # 1 ƒd {  –—†7  sw Y   y xY w# t,        j.                  $ r}t1        |«       Y d }~y d }~wt,        j2                  $ r}t5        |«       Y d }~y d }~ww xY w­w)NTrÚ  r  r6  rú  rû  Fr?  rü  r   rq  rÌ   )r  r�  r“  rK  r  rÛ   r  r  rª   r6  r;  r„   rb   r}  r†   r  r�  r8  r  r½   rí   rŸ   r+  r  r(  r  r4  r	  s                        r~   Ú_astream_responsesz!BaseChatOpenAI._astream_responsesæ  sy  è ø€ ð  ˆˆxÑØ+�$×+Ñ+¨HÑJ¸4ÐJÀ6ÑJˆØˆØ%'Ðð=	(Ø×,Ò,°×0BÒ0BàS˜$×0Ñ0×BÑB×LÑL×SÑSñ Ø!ñ÷ ð $ð
 #6×";Ñ";Ó"=�Ø×0Ò0Ø(¬$Ð/B×/JÑ/JÓ*KÐL�GÜ%Ð&:Ð<OÕPà(O¨×(>Ñ(>×(HÑ(H×(OÑ(Oñ )Øñ)÷ #�ð #)§*¡*Ð->Ó"?Ðç&‘¨(Ø!%�Ø "�Ø')Ð$Ø$&Ð!Ø %�Ü#>ØØ×-Ñ-Ø#Ÿ™õ$÷ "/˜%ñ
 +9™w¸b�Hô EØØ%Ø,Ø)Ø2Ø!)Ø&3Ø'+×':Ñ':ô	ñØ%Ø,Ø)Ø(ò (Ù)Ñ.Bð@Ø"6ð@à#3×#CÑ#CÒ#IÀrð@Ð,Ô<ñ 'Ø"-×">Ñ">Ø 0× 5Ñ 5Ð=Mð #?ó #÷ ð ð */˜Ø&Ð*:×*BÑ*B×*TÑ*TÑTØ,0˜MØ.Ô.ðmùð#øð
 'øð"/øð8øð9$÷ '———“ûôR ×%Ñ%ò 	*Ü& q×)Ñ)ûÜ�‰ò 	(Ü$ Q×'Ñ'ûð	(üsð   ‚I¢AG5 Á-GÁ.A-G5 ÃGÃG5 Ã7GÃ8G5 Ã;-G Ä(GÄ,G	Ä-GÄ0+G Å?G ÆGÆ&G ÇG5 ÇG5 ÇG5 Ç	GÇG ÇG ÇG5 ÇGÇG5 ÇIÇ G2Ç&G)Ç'G2Ç.G5 Ç1IÇ2G5 Ç5IÈHÈIÈIÈ.H>È9IÈ>IÉIc                ó  — ||j                  di «      j                  d«      | j                  j                  di «      j                  d«      | j                  g}|D ]  }t        |t        «      sŒ|c S  | j                  xs dS )zìDetermine whether to include usage metadata in streaming output.

        For backwards compatibility, we check for `stream_options` passed
        explicitly to kwargs or in the `model_kwargs` and override `self.stream_usage`.
        Ústream_optionsÚinclude_usageF)r„   rT  ra  r·   rj  )r’  ra  r  Ústream_usage_sourcesrß   s        r~   Ú_should_stream_usagez#BaseChatOpenAI._should_stream_usage0  s‚   € ð Ø�J‰JÐ'¨Ó,×0Ñ0°ÓAØ×Ñ×!Ñ!Ð"2°BÓ7×;Ñ;¸OÓLØ×Ñð	 
Ðó +ˆFÜ˜&¤$Õ'Ø’ð +ð × Ñ Ò) EÐ)r€   )ra  c             +  ó‚  K  — | j                  «        d|d<    | j                  |fi |¤Ž}|rd|i|d<    | j                  |fd|i|¤Ž}t        }i }	 d|v ro| j                  rt        j                  d«       |j                  d«        | j                  j                  j                  j                  j                  di |¤Ž}	|	}
nœ| j                  s| j                  rf | j                  j                  j                   di |¤Ž}|j#                  «       }| j                  rdt%        |j&                  «      i}t)        ||«       n | j                  j                   di |¤Ž}|}
|
5 }d}|D ]—  }t+        |t$        «      s|j-                  «       }| j/                  |||r|ni «      }|€Œ=|j0                  j2                  }|j4                  xs i j7                  d	«      }|r|j9                  |j:                  ||¬
«       d}|–— Œ™ 	 d d d «       tG        d«      rJd|v rE|jI                  «       }| jK                  |«      }|r|j9                  |j:                  |¬«       |–— y y y # 1 sw Y   Œ`xY w# t<        j>                  $ r}tA        |«       Y d }~Œ†d }~wt<        jB                  $ r}tE        |«       Y d }~Œ¬d }~ww xY w­w)NTrÚ  r  r  r  rú  úLCannot currently include response headers when response_format is specified.r6  rg  ©rç  rg  FÚget_final_completionr   rÌ   )&rø  r  r  r&   r�  r  r  r«  rJ  Úbetar¨  rÉ  rÚ  r“  rH  r  r  r  rª   r6  r;  r·   Ú
model_dumprö  rí   Ú	__class__r8  r„   r  r½   r+  r  r(  r  r4  Úhasattrr   Ú%_get_generation_chunk_from_completion©r’  r
  r  r  ra  r  r  rñ  rò  Úresponse_streamr  r9  r&  r  rç  ró  rg  r²   Úfinal_completions                      r~   Ú_streamzBaseChatOpenAI._streamC  sÌ  è ø€ ð 	×*Ñ*Ô,ØˆˆxÑØ0�t×0Ñ0°ÑHÀÑHˆÙØ(7¸Ð'FˆFÐ#Ñ$Ø+�$×+Ñ+¨HÑJ¸4ÐJÀ6ÑJˆÜ6DÐØ!Ðð/	(Ø  GÑ+Ø×0Ò0Ü—M‘Mð8ôð —‘˜HÔ%Ø"O $×"2Ñ"2×"7Ñ"7×"<Ñ"<×"HÑ"H×"OÑ"Oñ #Øñ#�ð #2‘à×0Ò0°D×4FÒ4FØ#G 4§;¡;×#@Ñ#@×#GÑ#GÑ#RÈ'Ñ#R�LØ+×1Ñ1Ó3�HØ×4Ò4Ø09¼4À×@TÑ@TÓ;UÐ/VÐ,Ü)Ð*>ÀÕMà1˜tŸ{™{×1Ñ1Ñ<°GÑ<�HØ"*�Ù  HØ!%�Û%�EÜ% e¬TÔ2Ø %× 0Ñ 0Ó 2˜Ø'+×'NÑ'NØØ+Ù0>Ñ,ÀBó(Ð$ð
 (Ð/Ø Ø*:×*BÑ*B×*LÑ*LÐ'Ø 0× @Ñ @Ò FÀB×KÑKÈJÓW�HÙ"Ø#×4Ñ4Ø,×1Ñ1Ø"2Ø%-ð 5ô ð
 &+�NØ*Ó*ñ' &÷ !ô4 �8Ð3Ô4Ð9JÈgÑ9UØ'×<Ñ<Ó>ÐØ#×IÑIØ ó Ðñ Ø×,Ñ,Ø$×)Ñ)Ð1Að -ô ð #Ó"ð :VÐ4÷5 !�ûô, ×%Ñ%ò 	*Ü& q×)Ñ)ûÜ�‰ò 	(Ü$ Q×'Ñ'ûð	(üs]   ‚AJ?ÁDI. Å#BI"ÈI. ÈAJ?É"I+É'I. É.J<ÊJÊJ?ÊJ<Ê'J7Ê2J?Ê7J<Ê<J?c                ó®  — | j                  «         | j                  |fd|i|¤Ž}d }d }	 d|v r]|j                  d«        | j                  j                  j
                  j                  j                  di |¤Ž}|j                  «       }�nx| j                  |«      �r0|j                  d«      }	|	r<t        |	«      r1 | j                  j                  j                  j                  di |¤Ž}n0 | j                  j                  j                  j                  di |¤Ž}|j                  «       }| j                  rdt        |j                  «      i}|xs i }t!        ||«       |j                  t"        d «      }
t%        ||	|| j&                  ¬«      }|
�9|j(                  D ]*  }|j*                  xs i |_        |
|j*                  t"        <   Œ, |S  | j,                  j                  j                  di |¤Ž}|j                  «       }| j                  r%|�#t;        |d«      rdt        |j                  «      i}|xs i }t!        ||«       | jA                  |«      S # t.        j0                  $ r}t3        |«       Y d }~Œxd }~wt.        j4                  $ r}t7        |«       Y d }~Œžd }~wt8        $ r&}|�t;        |d«      r|j<                  |_        |‚d }~ww xY w©Nr  rú  rÚ  r6  )rý  rþ  r�  Úhttp_responserÌ   )!rø  r  r«  rJ  r¨  rÉ  r  r  r²  r„   Ú_is_pydantic_classrÛ   r  r�  rª   r6  r;  rN   Ú'_construct_lc_result_from_responses_apir�  Úgenerationsr8  rH  r+  r  r(  r  r4  r¬   r$  r,  r&  Ú_create_chat_result©r’  r
  r  r  r  r  r8  r9  r&  r  r:  ÚresultÚ
generationr²   s                 r~   Ú	_generatezBaseChatOpenAI._generate�  s¾  € ð 	×*Ñ*Ô,Ø+�$×+Ñ+¨HÑJ¸4ÐJÀ6ÑJˆØˆØˆð2	Ø  GÑ+Ø—‘˜HÔ%àM�D×$Ñ$×)Ñ)×5Ñ5×GÑG×MÑMÑXÐPWÑXð ð (×-Ñ-Ó/’Ø×(Ñ(¨Õ1Ø&,§j¡jÐ1BÓ&CÐ#Ù&Ô+=Ð>QÔ+RØ#U 4×#3Ñ#3×#=Ñ#=×#OÑ#O×#UÑ#Uñ $Ø!ñ$‘Lð $W 4×#3Ñ#3×#=Ñ#=×#OÑ#O×#VÑ#Vñ $Ø!ñ$�Lð (×-Ñ-Ó/�Ø×0Ò0Ø'0´$°|×7KÑ7KÓ2LÐ&M�OØ"1Ò"7°R�Ü% o°|ÔDð $3×#6Ñ#6Ü1°4ó$Ð ô AØØ.Ø,Ø#'×#6Ñ#6ô	�ð $Ð/Ø&,×&8Ô&8˜
Ø5?×5OÑ5OÒ5UÐSU˜
Ô2à,ð #×2Ñ2Ô3PÒQð '9ð
 �àC˜tŸ{™{×<Ñ<×CÑCÑNÀgÑN�Ø'×-Ñ-Ó/�ð ×)Ò)ØÐ(Ü˜ iÔ0à(¬$¨|×/CÑ/CÓ*DÐEˆOØ)Ò/¨RˆÜ˜o¨|Ô<Ø×'Ñ'¨°/ÓBÐBøô! ×%Ñ%ò 	*Ü& q×)Ñ)ûÜ�‰ò 	(Ü$ Q×'Ñ'ûÜò 	ØÐ'¬G°LÀ/Ô,RØ)×7Ñ7�”
ØˆGûð	ús6   «F"I Ç6I ÉKÉ,I<É<KÊJ"Ê"KÊ.!KËKc                ó¢  — t        | j                  t        «      r| j                  S | j                  dk(  s�| j                  €ƒ| j
                  €w| j                  €k| j                  €_| j                  sSt        | j                  «      s>| j                  xs dj                  «       j                  d«      r|j                  d«      ryt        |«      S )Núresponses/v1r™   úgpt-6ÚtoolsT)r·   r‹  rj  r�  rƒ  r…  rq  r‰  rŠ  r@  r†   rÇ   rÈ   r„   r²  )r’  r  s     r~   r²  z!BaseChatOpenAI._use_responses_apiØ  s§   € Ü�d×,Ñ,¬dÔ3Ø×)Ñ)Ð)à×Ñ >Ò1Ø×&Ñ&Ð2Ø�|‰|Ð'Ø�~‰~Ð)Ø�‰Ð*Ø×,Ò,Ü+¨D¯O©OÔ<à—‘Ò& B×-Ñ-Ó/×:Ñ:¸7ÔCØ—K‘K Ô(ð Ü! 'Ó*Ð*r€   ©r  c               ó¤  — | j                  |«      j                  «       }|�||d<   i | j                  ¥|¥}| j                  |«      rC| j                  r)t        |«      \  }}|r|n|}|r||d<   t        ||«      }|S t        ||«      }|S |D �	cg c]1  }	t        |	t        «      rt        t        |	«      «      n
t        |	«      ‘Œ3 c}	|d<   |S c c}	w )Nr  Úprevious_response_idr
  )Ú_convert_inputÚto_messagesrÜ  r²  rŠ  Ú_get_last_messagesÚ _construct_responses_api_payloadr·   r%   rö   rm   )
r’  Úinput_r  r  r
  r  Úlast_messagesr;  Úpayload_to_useÚms
             r~   r  z#BaseChatOpenAI._get_request_payloadë  sÿ   € ð ×&Ñ& vÓ.×:Ñ:Ó<ˆØÐØ!ˆF�6‰Nà4�T×)Ñ)Ð4¨VÐ4ˆà×"Ñ" 7Ô+Ø×,Ò,Ü6HÈÓ6RÑ3�Ð3Ù2F¡ÈH�Ù'Ø6J�GÐ2Ñ3Ü:¸>È7ÓS�ð ˆô ;¸8ÀWÓM�ð ˆñ "ó	#ñ "�Aô ˜a¤Ô+ô )Ô)MÈaÓ)PÔQä-¨aÓ0ñ1ð "ñ	#ˆG�JÑð ˆùò#s   Â6Cc                ó¬  — g }t        |t        t        j                  z  «      sGt	        |«      }t        |«      dkD  r|d d › d�}dt        |«      j                  › d|› �}t        |«      ‚t        |t        «      r|n|j                  ddddhiiid	¬
«      }|j                  d«      rt        |j                  d«      «      ‚	 |d   }|€'dt        |j                  «       «      › �}t        |«      ‚|j                  d«      }	|j                  d«      }
|D ]™  }t        |d   «      }|	r!t        |t         «      rt#        |	|
«      |_        |xs i }|j                  d«      �|j                  d«      n|j                  d«      |d<   d|v r|d   |d<   t'        ||¬«      }|j)                  |«       Œ› |	d|j                  d| j*                  «      |j                  dd«      dœ}d|v r|d   |d<   |
r|
|d<   t        |t        j                  «      rŠt-        |dd «      r}|j.                  d   j0                  }t3        |d«      r&|j4                  |d   j0                  j6                  d<   t3        |d«      r&|j8                  |d   j0                  j6                  d<   t;        ||¬«      S # t        $ r$}d|j                  «       › �}t        |«      |‚d }~ww xY w)NéÈ   z...zcUnexpected response type from OpenAI-compatible endpoint. Expected a dict or openai.BaseModel, got ú: ræ  Ú__all__rí   ÚparsedF)rG  r  Úerrorz Response missing 'choices' key: z´Received response with null value for 'choices'. This can happen when using OpenAI-compatible APIs (e.g., vLLM) that return a response in an unexpected format. Full response keys: rå  r‡  rì  rg  ré  r+  rM  rß  r™   )rÞ  rí  r†   rß  r—   r   Úrefusal)r/  Ú
llm_output)r·   rª   r+  rY   Úreprrï  r¼   r
  rÐ   r"  r„   rü   Úkeysr¿   rì   r³   r%   rî  rè  rC   r«   r†   r7  ræ  rí   r$  rH  rŸ   rJ  rE   )r’  r&  r8  r/  ÚpreviewrÓ   Úresponse_dictræ  r²   rÞ  r‡  Úresrí   ÚgenrK  s                  r~   r0  z"BaseChatOpenAI._create_chat_result
  s  € ð
 ˆä˜(¤D¬6×+;Ñ+;Ñ$;Ô<ô ˜8“nˆGÜ�7‹|˜cÒ!Ø$ T c˜]˜O¨3Ð/�ð<ä˜“>×*Ñ*Ð+¨2¨g¨Yð8ð ô
 ˜S“/Ð!ô ˜(¤DÔ)ñ ð ×$Ñ$Ø" Y°¸X¸JÐ0GÐ$HÐIØð %ó ð 	ð ×Ñ˜WÔ%Ü˜]×.Ñ.¨wÓ7Ó8Ð8ð	'Ø# IÑ.ˆGð
 ˆ?ð
'ô (,¨M×,>Ñ,>Ó,@Ó'AÐ&BðDð ô ˜C“.Ð à#×'Ñ'¨Ó0ˆØ$×(Ñ(¨Ó8ˆãˆCÜ.¨s°9©~Ó>ˆGÙœz¨'´9Ô=Ü)?Ø ó*�Ô&ð .Ò3°ˆOð —7‘7˜?Ó+Ð7ð —‘˜Ô(à$×(Ñ(¨Ó9ð ˜OÑ,ð
 ˜SÑ Ø.1°*©o� 
Ñ+Ü ¨À/ÔRˆCØ×Ñ˜sÕ#ð ð" 'Ø&Ø'×+Ñ+¨G°T·_±_ÓEØ"/×"3Ñ"3Ð4HÈ"Ó"Mñ	
ˆ
ð �=Ñ Ø,¨TÑ2ˆJ�tÑÙØ)5ˆJ�~Ñ&ä�h¤× 0Ñ 0Ô1´gØ�i ô7
ð ×&Ñ& qÑ)×1Ñ1ˆGÜ�w Ô)ØELÇ^Á^�˜A‘×&Ñ&×8Ñ8¸ÑBÜ�w 	Ô*ØFMÇoÁo�˜A‘×&Ñ&×8Ñ8¸ÑCä k¸jÔIÐIøôo ò 	'Ø4°]×5GÑ5GÓ5IÐ4JÐKˆCÜ˜3“- QÐ&ûð	'ús   ÃJ& Ê&	KÊ/KËKc              óR  K  — d|d<    | j                   |fi |¤Ž}|rd|i|d<    | j                  |fd|i|¤Ž}t        }i }	 d|v ro| j                  rt	        j
                  d«       |j                  d«        | j                  j                  j                  j                  j                  di |¤Ž}	|	}
n¬| j                  s| j                  rn | j                  j                  j                  di |¤Žƒ d {  –—† }|j!                  «       }| j                  rdt#        |j$                  «      i}t'        ||«       n$ | j                  j                  di |¤Žƒ d {  –—† }|}
|
4 ƒd {  –—† }d}t)        || j*                  | j,                  ¬	«      2 3 d {  –—† }t/        |t"        «      s|j1                  «       }| j3                  |||r|ni «      }|€ŒC|j4                  j6                  }|j8                  xs i j;                  d
«      }|r&|j=                  |j>                  ||¬«      ƒ d {  –—†  d}|­–— Œ¨7 �ŒB7 Œà7 ŒÕ7 Œª7 Œ6 d d d «      ƒd {  –—†7   n# 1 ƒd {  –—†7  sw Y   nxY wnQ# t@        jB                  $ r}tE        |«       Y d }~n.d }~wt@        jF                  $ r}tI        |«       Y d }~nd }~ww xY wtK        d«      r]d|v rX|jM                  «       ƒ d {  –—†7  }| jO                  |«      }|r&|j=                  |j>                  |¬«      ƒ d {  –—†7   |­–— y y y ­w)NTrÚ  r  r  r  rú  r  r6  r?  rg  r  Fr   r   rÌ   )(r  r  r&   r�  r  r  r«  rK  r!  r¨  rÉ  rÚ  r“  rI  r  r  r  rª   r6  r;  rb   r}  r†   r·   r"  rö  rí   r#  r8  r„   r  r½   r+  r  r(  r  r4  r$  r   r%  r&  s                      r~   Ú_astreamzBaseChatOpenAI._astreamk  s,  è ø€ ð  ˆˆxÑØ0�t×0Ñ0°ÑHÀÑHˆÙØ(7¸Ð'FˆFÐ#Ñ$Ø+�$×+Ñ+¨HÑJ¸4ÐJÀ6ÑJˆÜ6DÐØ!Ðð5	(Ø  GÑ+Ø×0Ò0Ü—M‘Mð8ôð —‘˜HÔ%Ø"U $×"8Ñ"8×"=Ñ"=×"BÑ"B×"NÑ"N×"UÑ"Uñ #Øñ#�ð #2‘à×0Ò0°D×4FÒ4FØ)S¨×):Ñ):×)LÑ)L×)SÑ)Sñ *Ø!ñ*÷ $�Lð  ,×1Ñ1Ó3�HØ×4Ò4Ø09¼4À×@TÑ@TÓ;UÐ/VÐ,Ü)Ð*>ÀÕMà%= T×%6Ñ%6×%=Ñ%=Ñ%HÀÑ%H×H�HØ"*�ß&‘¨(Ø!%�Ü#>ØØ×-Ñ-Ø#Ÿ™õ$÷ +˜%ô
 & e¬TÔ2Ø %× 0Ñ 0Ó 2˜Ø'+×'NÑ'NØØ+Ù0>Ñ,ÀBó(Ð$ð
 (Ð/Ø Ø*:×*BÑ*B×*LÑ*LÐ'Ø 0× @Ñ @Ò FÀB×KÑKÈJÓW�HÙ"Ø)×:Ñ:Ø,×1Ñ1Ø"2Ø%-ð ;ó ÷ ð ð
 &+�NØ*Ô*ðG$ùð  Iøà&øð+øð"øð#$÷ '———“üô4 ×%Ñ%ò 	*Ü& q×)Ñ)ûÜ�‰ò 	(Ü$ Q×'Ñ'ûð	(úä�8Ð3Ô4Ð9JÈgÑ9UØ%-×%BÑ%BÓ%D×DÐDÐØ#×IÑIØ ó Ðñ Ø!×2Ñ2Ø$×)Ñ)Ð1Að 3ó ÷ ñ ð #Ô"ð :VÐ4ùsø   ‚?L'ÁB4I, Ã6H8Ã7A#I, ÅH;ÅI, Å'H=Å(I, Å+%IÆIÆH?ÆIÆBIÈ+IÈ,IÈ8I, È;I, È=I, È?IÉIÉIÉI, ÉIÉI, ÉI(ÉIÉI(É$I, É+L'É,J:É?JÊ
L'ÊJ:Ê%J5Ê0L'Ê5J:Ê:&L'Ë K#Ë!8L'ÌLÌL'c              ‹  óô  K  —  | j                   |fd|i|¤Ž}i }d }	 d|v re|j                  d«        | j                  j                  j                  j
                  j                  di |¤Žƒ d {  –—† }|j                  «       }�nŠ| j                  |«      �r:|j                  d«      }	|	rDt        |	«      r9 | j                  j                  j
                  j                  di |¤Žƒ d {  –—† }n8 | j                  j                  j
                  j                  di |¤Žƒ d {  –—† }|j                  «       }| j                  rdt        |j                  «      i}t        ||«       |j                  t         d «      }
t#        ||	|| j$                  ¬«      }|
�9|j&                  D ]*  }|j(                  xs i |_        |
|j(                  t         <   Œ, |S  | j*                  j
                  j                  di |¤Žƒ d {  –—† }|j                  «       }| j                  r%|�#t9        |d«      rdt        |j                  «      i}t        ||«       t?        d | j@                  |«      ƒ d {  –—† S 7 �Œþ7 �Œ‡7 �ŒQ7 Œz# t,        j.                  $ r}t1        |«       Y d }~Œ‹d }~wt,        j2                  $ r}t5        |«       Y d }~Œ±d }~wt6        $ r&}|�t9        |d«      r|j:                  |_        |‚d }~ww xY w7 Œ�­wr+  )!r  r«  rK  r¨  rÉ  r  r  r²  r„   r-  rÛ   r  r�  rª   r6  r;  rN   r.  r�  r/  r8  rI  r+  r  r(  r  r4  r¬   r$  r,  r&  rJ   r0  r1  s                 r~   Ú
_ageneratezBaseChatOpenAI._agenerate½  sñ  è ø€ ð ,�$×+Ñ+¨HÑJ¸4ÐJÀ6ÑJˆØˆØˆð7	Ø  GÑ+Ø—‘˜HÔ%Ø%d T×%;Ñ%;×%@Ñ%@×%LÑ%L×%^Ñ%^×%dÑ%dñ &Øñ&÷  �ð (×-Ñ-Ó/’Ø×(Ñ(¨Õ1Ø&,§j¡jÐ1BÓ&CÐ#Ù&Ô+=Ð>QÔ+RàV˜d×4Ñ4×>Ñ>×PÑP×VÑVñ Ø%ñ÷ ñ !ð X˜d×4Ñ4×>Ñ>×PÑP×WÑWñ Ø%ñ÷ ð !ð
 (×-Ñ-Ó/�Ø×0Ò0Ø'0´$°|×7KÑ7KÓ2LÐ&M�OÜ% o°|ÔDð $3×#6Ñ#6Ü1°4ó$Ð ô AØØ.Ø,Ø#'×#6Ñ#6ô	�ð $Ð/Ø&,×&8Ô&8˜
Ø5?×5OÑ5OÒ5UÐSU˜
Ô2à,ð #×2Ñ2Ô3PÒQð '9ð
 �à%O T×%6Ñ%6×%HÑ%H×%OÑ%Oñ &Øñ&÷  �ð (×-Ñ-Ó/�ð ×)Ò)ØÐ(Ü˜ iÔ0à(¬$¨|×/CÑ/CÓ*DÐEˆOÜ˜o¨|Ô<Ü$Ø�$×*Ñ*¨H°oó
÷ 
ð 	
ðy ùðùðùð6 ùô ×%Ñ%ò 	*Ü& q×)Ñ)ûÜ�‰ò 	(Ü$ Q×'Ñ'ûÜò 	ØÐ'¬G°LÀ/Ô,RØ)×7Ñ7�”
ØˆGûð	úð
ús°   ‚K8�AI8 Á/I-Á0A9I8 Ã)I0Ã*8I8 Ä"I3Ä#B.I8 ÇK8Ç)I8 Ç;I6Ç<I8 ÈAK8É(K6É)K8É-I8 É0I8 É3I8 É6I8 É8K3ÊJÊK8ÊK3Ê1KÊ<K8ËK3Ë!K.Ë.K3Ë3K8c                ó6   — d| j                   i| j                  ¥S )zGet the identifying parameters.r†   )r†   rÜ  r•  s    r~   Ú_identifying_paramsz"BaseChatOpenAI._identifying_params
	  s   € ð ˜dŸo™oÐF°×1EÑ1EÐFÐFr€   c           
     ód  •— d| j                   it        ‰| �	  |¬«      ¥| j                  ¥|¥}|j	                  d«      x}rdt        |t        «      rTd}|D ��cg c]A  }t        |t        «      r-|j	                  d«      dk(  ri |¥|D �ci c]	  }||v r|d“Œ c}¥n|‘ŒC c}}|d<   |S c c}w c c}}w )z,Get the parameters used to invoke the model.rM  r9  r8  )r6  Úauthorizationr¼   rŽ   z**REDACTED**)r†   ÚsuperÚ_get_invocation_paramsrÜ  r„   r·   r¿   rª   )	r’  r  r  Úparamsr8  Úsensitive_fieldsr§   Úfieldr#  s	           €r~   r[  z%BaseChatOpenAI._get_invocation_params	  sý   ø€ ð
 �T—_‘_ð
ä‰gÑ,°$Ð,Ó7ð
ð ×"Ñ"ð
ð ð	
ˆð —Z‘Z Ó(Ð(ˆEÐ(¬j¸ÄÔ.EØ;Ðñ "ôñ "�Dô ˜d¤DÔ)¨d¯h©h°vÓ.>À%Ò.GðØðñ &6óá%5˜EØ  D™=ð ˜~Ñ-Ø%5ññð ñ	ð "òˆF�7‰Oð ˆùòùós   Á0B,ÂB'ÂB,Â'B,c           	     óp  —  | j                   dd|i|¤Ž}t        d|j                  d| j                  «      d|j                  d| j                  «      ¬«      }|j                  d| j
                  «      xs |j                  d| j
                  «      x}r||d	<   |xs |j                  dd
«      x}r||d<   |S )z Get standard params for tracing.r  r+  rM  r¨  rQ  )Úls_providerÚls_model_nameÚls_model_typeÚls_temperaturern  Úmax_completion_tokensÚls_max_tokensNÚls_stoprÌ   )r[  r$   r„   r†   rQ  rn  )r’  r  r  r\  Ú	ls_paramsre  rf  s          r~   Ú_get_ls_paramszBaseChatOpenAI._get_ls_params,	  sÅ   € ð -�×,Ñ,ÑA°$ÐA¸&ÑAˆÜ#Ø Ø Ÿ*™* W¨d¯o©oÓ>Ø Ø!Ÿ:™: m°T×5EÑ5EÓFô	
ˆ	ð #ŸJ™J |°T·_±_ÓEò 
ÈÏÉØ# T§_¡_óJ
ð 
ˆ=ð 
ð *7ˆI�oÑ&ØÒ6˜fŸj™j¨°Ó6Ð6ˆ7Ð6Ø#*ˆI�iÑ ØÐr€   c                 ó   — y)zvReturn type of chat model.

        Will always return `'openai-chat'` regardless of the specific model name.
        zopenai-chatrÌ   r•  s    r~   Ú	_llm_typezBaseChatOpenAI._llm_type?	  s   € ð r€   c                ó  — | j                   �| j                   }n| j                  }	 t        j                  |«      }||fS # t        $ r@ |j                  «       }d}|j                  d«      rd}t        j                  |«      }Y ||fS w xY w)NÚcl100k_base)zgpt-4ozgpt-4.1r§  r7  Ú
o200k_base)rs  r†   ÚtiktokenÚencoding_for_modelrü   rÇ   rÈ   Úget_encoding)r’  rM  Úencodingr¬  Úencoders        r~   Ú_get_encoding_modelz"BaseChatOpenAI._get_encoding_modelG	  s’   € Ø×#Ñ#Ð/Ø×,Ñ,‰Eà—O‘OˆEð	6Ü×2Ñ2°5Ó9ˆHð �hˆÐøô ò 	6ØŸ+™+›-ˆKØ#ˆGØ×%Ñ%Ð&MÔNØ&�Ü×,Ñ,¨WÓ5‰HØ�hˆÐð	6ús   §A  Á AB	ÂB	c                óÐ   •— | j                   �| j                  |«      S t        j                  d   dk  rt        ‰| �  |«      S | j                  «       \  }}|j                  |«      S )z9Get the tokens present in the text with tiktoken package.r¦  é   )Úcustom_get_token_idsÚsysÚversion_inforZ  Úget_token_idsrs  Úencode)r’  r½   Ú_Úencoding_modelr#  s       €r~   ry  zBaseChatOpenAI.get_token_idsW	  sg   ø€ à×$Ñ$Ð0Ø×,Ñ,¨TÓ2Ð2ä×Ñ˜AÑ !Ò#Ü‘7Ñ(¨Ó.Ð.Ø ×4Ñ4Ó6Ñˆˆ>Ø×$Ñ$ TÓ*Ð*r€   )Úallow_fetching_imagesc          
     ó’  •— |�t        j                  d«       t        j                  d   dk  rt        ‰| �  |«      S | j                  «       \  }}|j                  d«      rd}d}n'|j                  d«      rd}d}nd	|› d
�}t        |«      ‚d}	|D �
cg c]  }
t        |
«      ‘Œ }}
|D �]�  }|	|z  }	|j                  «       D �]s  \  }}|dk(  r|	dz  }	Œt        |t        «      �r|D �]  }t        |t        «      s|d   dk(  r5t        |t        «      r|d   n|}|	t        |j!                  |«      «      z  }	ŒQ|d   dk(  r@|d   j#                  d«      dk(  r|	dz  }	Œv|r t%        |d   d   «      }|sŒŒ|	t'        |Ž z  }	Œ˜Œ™|d   dk(  rG|	t        |j!                  |d   d   «      «      z  }	|	t        |j!                  |d   d   «      «      z  }	Œè|d   dk(  rt        j                  d«       �Œd|› �}t)        |«      ‚ n*|s�ŒB|	t        |j!                  t        |«      «      «      z  }	|dk(  s�Œo|	|z  }	�Œv �Œ’ |	dz  }	|	S c c}
w )aX  Calculate num tokens for supported OpenAI chat models.

        !!! warning
            You must have the `pillow` installed if you want to count image tokens if
            you are specifying the image as a base64 string, and you must have both
            `pillow` and `httpx` installed if you are specifying the image as a URL. If
            these aren't installed image inputs will be ignored in token counting.

        [OpenAI reference](https://github.com/openai/openai-cookbook/blob/main/examples/How_to_format_inputs_to_ChatGPT_models.ipynb).

        Args:
            messages: The message inputs to tokenize.
            tools: If provided, sequence of `dict`, `BaseModel`, function, or `BaseTool`
                to be converted to tool schemas.
            allow_fetching_images: Whether to allow fetching images for token counting.
        zECounting tokens in tool schemas is not yet supported. Ignoring tools.r¦  ru  zgpt-3.5-turbo-0301é   rû  )rL  úgpt-4r§  r7  r¥  Úo3Úo4é   zFget_num_tokens_from_messages() is not presently implemented for model z†. See https://platform.openai.com/docs/guides/text-generation/managing-tokens for information on how messages are converted to tokens.r   r¨   r¼   r½   rã   ÚdetailÚlowéU   rä   r¥   rø   r–   ÚfilezEToken counts for file inputs are not supported. Ignoring file inputs.z!Unrecognized content block type

)r  r  rw  rx  rZ  Úget_num_tokens_from_messagesrs  rÈ   ÚNotImplementedErrorrö   rë   r·   r¿   r­   rª   rï  rz  r„   Ú_url_to_sizeÚ_count_image_tokensrÐ   )r’  r
  r8  r}  rM  rq  Útokens_per_messageÚtokens_per_namerÓ   Ú
num_tokensrC  Úmessages_dictrí   r¾  r¡  Úvalr½   Ú
image_sizer#  s                     €r~   rˆ  z+BaseChatOpenAI.get_num_tokens_from_messagesa	  s   ø€ ð0 ÐÜ�M‰MØWôô ×Ñ˜AÑ !Ò#Ü‘7Ñ7¸ÓAÐAØ×2Ñ2Ó4‰ˆˆxØ×ÑÐ0Ô1à!"Ðà ‰OØ×ÑØJô
ð "#ÐØ‰OðØ"˜Gð $LðLð ô & cÓ*Ð*Øˆ
Ù>FÓG¹h¸Ô1°!Õ4¸hˆÐGÜ$ˆGØÐ,Ñ,ˆJØ%Ÿm™mŸo‘
��Uð ˜.Ò(Ø !‘O�JØÜ˜e¤TÕ*ä$˜Ü% c¬3Ô/°3°v±;À&Ò3HÜ2<¸SÄ$Ô2G 3 v¢;ÈS˜DØ&¬#¨h¯o©o¸dÓ.CÓ*DÑD™JØ  ™[¨KÒ7Ø" ;Ñ/×3Ñ3°HÓ=ÀÒFØ *¨bÑ 0¡
Ù!6Ü-9¸#¸kÑ:JÈ5Ñ:QÓ-R 
Ù'1Ø$,Ø *Ô.AÀ:Ð.NÑ N¡
à $ð ! ™[¨JÒ6Ø&¬#Ø (§¡°°J±ÀÑ0LÓ Mó+ñ ˜Jð '¬#¨h¯o©o¸cÀ*¹oÈfÑ>UÓ.VÓ*WÑW™JØ  ™[¨FÒ2Ü$ŸM™Mð!8öð
 %HÈÀuÐ"M˜CÜ",¨S£/Ð1ñ9  %ñ: Ùð ¤# h§o¡o´c¸%³jÓ&AÓ"BÑB�JØ˜&”=Ø /Ñ1’JòY .ð %ð` 	�a‰ˆ
ØÐùòe Hs   ÂI)Útool_choiceÚstrictÚparallel_tool_callsrú  c               óÐ  •— |�||d<   |r|dur| j                   sd}|D �cg c]  }t        ||¬«      ‘Œ }}t        ||d¬«      D ]j  \  }	}
t        |	t        «      sŒt        |	d«      sŒ$t        |	j                  t        «      sŒ?t        D ]#  }||	j                  v sŒ|	j                  |   |
|<   Œ% Œl g }|D ]7  }d|v r|j                  |d   d   «       Œd|v r|j                  |d   «       Œ8Œ9 |rkt        |t        «      r"||v rdd|id	œ}nJ|t        v rd
|i}n=|dk(  rd}n5n4t        |t        «      rd}n!t        |t        «      rnd|› �}t        |«      ‚||d<   |rst        |t        «      rS|j                  d
«      dk(  r?d|j                  di «      v r+|d   j                  dd«      }t        t        |d   d   «      }t!        ||¬«      |d<   t#        ‰| �H  dd|i|¤ŽS c c}w )a¯  Bind tool-like objects to this chat model.

        Assumes model is compatible with OpenAI tool-calling API.

        Args:
            tools: A list of tool definitions to bind to this chat model.

                Supports any tool definition handled by [`convert_to_openai_tool`][langchain_core.utils.function_calling.convert_to_openai_tool].
            tool_choice: Which tool to require the model to call. Options are:

                - `str` of the form `'<<tool_name>>'`: calls `<<tool_name>>` tool.
                - `'auto'`: automatically selects a tool (including no tool).
                - `'none'`: does not call a tool.
                - `'any'` or `'required'` or `True`: force at least one tool to be called.
                - `dict` of the form `{"type": "function", "function": {"name": <<tool_name>>}}`: calls `<<tool_name>>` tool.
                - `False` or `None`: no effect, default OpenAI behavior.
            strict: If `True`, model output is guaranteed to exactly match the JSON Schema
                provided in the tool definition. The input schema will also be validated according to the
                [supported schemas](https://platform.openai.com/docs/guides/structured-outputs/supported-schemas?api-mode=responses#supported-schemas).
                If `False`, input schema will not be validated and model output will not
                be validated. If `None`, `strict` argument will not be passed to the model.
            parallel_tool_calls: Set to `False` to disable parallel tool use.
                Defaults to `None` (no specification, which allows parallel tool use).
            response_format: Optional schema to format model response. If provided
                and the model does not call a tool, the model will generate a
                [structured response](https://platform.openai.com/docs/guides/structured-outputs).
            kwargs: Any additional parameters are passed directly to `bind`.
        Nr”  FT©r“  r¶   r¥   r–   ©r¼   r¥   r¼   ÚanyÚrequiredzEUnrecognized tool_choice type. Expected str, bool or dict. Received: r’  Újson_schemarý  r“  rú  r8  rÌ   )r‹  rR   Úzipr·   rK   r$  r¶   rª   Ú_TOOL_EXTRAS_PASSTHROUGHr«   r­   ÚWellKnownToolsrj  rÐ   r„   r   Ú"_convert_to_openai_response_formatrZ  Úbind)r’  r8  r’  r“  r”  rú  r  r§   Úformatted_toolsÚoriginalÚ	formattedr¾  Ú
tool_namesrÓ   r#  s                 €r~   Ú
bind_toolszBaseChatOpenAI.bind_toolsÇ	  s3  ø€ ðL Ð*Ø,?ˆFÐ(Ñ)ñ
 ˜v¨UÑ2¸4×;QÒ;QØˆFáDIó
ÙDI¸DÔ" 4°Ö7ÀEð 	ð 
ô $' u¨oÀe×#LÑˆH�iä˜8¤XÕ.Ü˜H hÕ/Ü˜xŸ™´Õ5ç3�CØ˜hŸo™oÒ-Ø)1¯©¸Ñ)=˜	 #šñ 4ð $Mð ˆ
Û#ˆDØ˜TÑ!Ø×!Ñ! $ zÑ"2°6Ñ":Õ;Ø˜4‘Ø×!Ñ! $ v¡,Õ/àð $ñ Ü˜+¤sÔ+à *Ñ,à *Ø%+¨[Ð$9ñ#‘Kð !¤NÑ2Ø#)¨;Ð"7‘Kð ! EÒ)Ø",‘KàÜ˜K¬Ô.Ø(‘Ü˜K¬Ô.Øð!Ø!, ð/ð ô ! “oÐ%Ø$/ˆF�=Ñ!áä˜?¬DÔ1Ø#×'Ñ'¨Ó/°=Ò@Ø × 3Ñ 3°MÀ2Ó FÑFð )¨Ñ7×;Ñ;¸HÀdÓK�Ü"&¤t¨_¸]Ñ-KÈHÑ-UÓ"V�Ü(JØ¨ô)ˆFÐ$Ñ%ô ‰w‰|Ñ< /Ð<°VÑ<Ð<ùò{
s   ¡G#Úfunction_calling©ÚmethodÚinclude_rawr“  r8  c          
     ót  — |�|dk(  rd}t        |«      ‚t        |«      }|dk(  rŸ|r't        |t        «      rt	        j
                  d«       d}| j                  rj| j                  j                  d«      s*| j                  j                  d«      s| j                  dk(  r%t	        j
                  d	| j                  › d
�«       d}|dk(  rt|€d}t        |«      ‚t        |«      d   d   }	 | j                  d(i |	d|||dœ|dœdœ|¥¤Ž}
 | j                  |gfi |
¤Ž}|rt        |gd¬«      }�n"t        |	d¬«      }�n|dk(  r7 | j                  d(i ddid|i|dœdœ|¥¤Ž}|rt        |¬«      n	t        «       }n×|dk(  rÁ|€d}t        |«      ‚t!        ||¬«      }i t#        d(|||dœt        |«      dœdœ|¤Ž¥}
|r|D �cg c]  }t        ||¬«      ‘Œ c}|
d<    | j                  d(i |
¤Ž}|rGt%        t'        t(        t+        t,        |«      ¬«      «      j/                  t+        t,        |«      ¬«      }nt        «       }nd|› d�}t        |«      ‚|r^t1        j2                  t5        d «      |z  d!„ ¬"«      }t1        j2                  d#„ ¬$«      }|j7                  |gd%¬&«      }t9        |¬'«      |z  S ||z  S c c}w ))a¤  Model wrapper that returns outputs formatted to match the given schema.

        Args:
            schema: The output schema. Can be passed in as:

                - An OpenAI function/tool schema,
                - A JSON Schema,
                - A `TypedDict` class,
                - Or a Pydantic class.

                If `schema` is a Pydantic class then the model output will be a
                Pydantic instance of that class, and the model-generated fields will be
                validated by the Pydantic class. Otherwise the model output will be a
                dict and will not be validated.

                See `langchain_core.utils.function_calling.convert_to_openai_tool` for
                more on how to properly specify types and descriptions of schema fields
                when specifying a Pydantic or `TypedDict` class.

            method: The method for steering model generation, one of:

                - `'function_calling'`:
                    Uses OpenAI's [tool-calling API](https://platform.openai.com/docs/guides/function-calling)
                    (formerly called function calling)
                - `'json_schema'`:
                    Uses OpenAI's [Structured Output API](https://platform.openai.com/docs/guides/structured-outputs)
                - `'json_mode'`:
                    Uses OpenAI's [JSON mode](https://platform.openai.com/docs/guides/structured-outputs/json-mode).
                    Note that if using JSON mode then you must include instructions for
                    formatting the output into the desired schema into the model call

            include_raw:
                If `False` then only the parsed structured output is returned.

                If an error occurs during model output parsing it will be raised.

                If `True` then both the raw model response (a `BaseMessage`) and the
                parsed model response will be returned.

                If an error occurs during output parsing it will be caught and returned
                as well.

                The final output is always a `dict` with keys `'raw'`, `'parsed'`, and
                `'parsing_error'`.
            strict:

                - `True`:
                    Model output is guaranteed to exactly match the schema.
                    The input schema will also be validated according to the
                    [supported schemas](https://platform.openai.com/docs/guides/structured-outputs/supported-schemas?api-mode=responses#supported-schemas).
                - `False`:
                    Input schema will not be validated and model output will not be
                    validated.
                - `None`:
                    `strict` argument will not be passed to the model.

            tools:
                A list of tool-like objects to bind to the chat model. Requires that:

                - `method` is `'json_schema'` (default).
                - `strict=True`
                - `include_raw=True`

                If a model elects to call a tool, the resulting `AIMessage` in `'raw'`
                will include tool calls.

                ??? example

                    ```python
                    from langchain.chat_models import init_chat_model
                    from pydantic import BaseModel


                    class ResponseSchema(BaseModel):
                        response: str


                    def get_weather(location: str) -> str:
                        """Get weather at a location."""
                        pass

                    model = init_chat_model("openai:gpt-5.5")

                    structured_model = model.with_structured_output(
                        ResponseSchema,
                        tools=[get_weather],
                        strict=True,
                        include_raw=True,
                    )

                    structured_model.invoke("What's the weather in Boston?")
                    ```

                    ```python
                    {
                        "raw": AIMessage(content="", tool_calls=[...], ...),
                        "parsing_error": None,
                        "parsed": None,
                    }
                    ```

            kwargs: Additional keyword args are passed through to the model.

        Returns:
            A `Runnable` that takes same inputs as a
                `langchain_core.language_models.chat.BaseChatModel`. If `include_raw` is
                `False` and `schema` is a Pydantic class, `Runnable` outputs an instance
                of `schema` (i.e., a Pydantic object). Otherwise, if `include_raw` is
                `False` then `Runnable` outputs a `dict`.

                If `include_raw` is `True`, then `Runnable` outputs a `dict` with keys:

                - `'raw'`: `BaseMessage`
                - `'parsed'`: `None` if there was a parsing error, otherwise the type
                    depends on the `schema` as described above.
                - `'parsing_error'`: `BaseException | None`

        !!! warning "Behavior changed in `langchain-openai` 0.3.12"

            Support for `tools` added.

        !!! warning "Behavior changed in `langchain-openai` 0.3.21"

            Pass `kwargs` through to the model.
        Ú	json_modez<Argument `strict` is not supported with `method`='json_mode'rš  záReceived a Pydantic BaseModel V1 schema. This is not supported by method="json_schema". Please use method="function_calling" or specify schema via JSON Schema or Pydantic V2 BaseModel. Overriding to method="function_calling".r¥  zgpt-3zgpt-4-r€  z+Cannot use method='json_schema' with model a   since it doesn't support OpenAI's Structured Output API. You can see supported models here: https://platform.openai.com/docs/guides/structured-outputs#supported-models. To fix this warning, set `method='function_calling'. Overriding to method='function_calling'.zGschema must be specified when method is not 'json_mode'. Received None.r¥   r–   F)r§  r“  )r  rý  )r’  r”  r“  Úls_structured_output_formatT)r8  Úfirst_tool_only)Úkey_namer¬  r¼   Újson_objectr§  )rú  r«  )Úpydantic_objectr–  r8  )rý  )Úoutput_typez\Unrecognized method argument. Expected one of 'function_calling' or 'json_mode'. Received: 'Ú'Úrawc                 ó   — y r‚   rÌ   ©r{  s    r~   r|  z7BaseChatOpenAI.with_structured_output.<locals>.<lambda>3  s   € ÐRVr€   )rH  Úparsing_errorc                 ó   — y r‚   rÌ   r´  s    r~   r|  z7BaseChatOpenAI.with_structured_output.<locals>.<lambda>5  s   € Àdr€   )rH  rµ  )Úexception_key)r²  rÌ   )rÐ   r-  Ú
issubclassÚBaseModelV1r  r  r†   rÈ   rR   Ú_filter_disabled_paramsr¤  r@   r?   rŸ  r>   r=   rž  rª   rG   r
   Ú_oai_structured_outputs_parserr   r¼   Ú
with_typesrI   Úassignr   Úwith_fallbacksrH   )r’  rý  r§  r¨  r“  r8  r  rÓ   Úis_pydantic_schemaÚ	tool_nameÚbind_kwargsÚllmÚoutput_parserrú  ÚtÚparser_assignÚparser_noneÚparser_with_fallbacks                     r~   Úwith_structured_outputz%BaseChatOpenAI.with_structured_output4
  sT  € ðR Ð &¨KÒ"7ØPˆCÜ˜S“/Ð!Ü/°Ó7Ðà�]Ò"ñ #¤z°&¼+Ô'Fä—‘ð?ôð ,�à�ŠØ—‘×*Ñ*¨7Ô3Ø—?‘?×-Ñ-¨hÔ7Ø—?‘? gÒ-ä—‘ØAÀ$Ç/Á/ÐARð S?ð ?ôð ,�àÐ'Ò'Øˆ~ð%ð ô ! “oÐ%Ü.¨vÓ6°zÑBÀ6ÑJˆIØ6˜$×6Ñ6ñ à#,Ø+0Ø$à-3¸vÑ"FØ"(ñ4ñ		ð ð	ñˆKð "�$—/‘/ 6 (Ñ:¨kÑ:ˆCÙ!Ü*=Ø!˜(Ø$(ô+’ô
 !9Ø&¸ô!’ð �{Ò"Ø�$—)‘)ñ 	à(.°Ð'>à#+¨VÐ"4Ø"(ñ4ñð ðñ	ˆCñ &ô %°VÕ<ä%Ó'ñ ð
 �}Ò$Øˆ~ð%ð ô ! “oÐ%Ü@ÀÐPVÔWˆOð	Üð Ø$3à-3¸vÑ"FÜ"8¸Ó"@ñ1ñð ñð	ˆKñ áFKó(ÙFKÀÔ*¨1°VÖ<Àeñ(�˜GÑ$ð �$—)‘)Ñ*˜kÑ*ˆCÙ!Ü .ÜÔ:Ä4ÌÈfÓCUÔVó!ç‘*¬¬d°FÓ);�*Ó<ñ ô !1Ó 2‘ð+Ø+1¨(°!ð5ð ô ˜S“/Ð!áÜ/×6Ñ6Ü! %Ó(¨=Ñ8ÉôˆMô .×4Ñ4¹NÔKˆKØ#0×#?Ñ#?Ø�¨_ð $@ó $Ð ô  3Ô'Ð*>Ñ>Ð>Ø�]Ñ"Ð"ùò5(s   Æ?J5c                ó¾   — | j                   s|S i }|j                  «       D ]9  \  }}|| j                   v r!| j                   |   �|| j                   |   v rŒ5|||<   Œ; |S r‚   )r‚  rë   )r’  r  Úfilteredrò   ró   s        r~   rº  z&BaseChatOpenAI._filter_disabled_params<  sm   € Ø×#Ò#ØˆMØˆØ—L‘L–N‰DˆAˆqà�D×(Ñ(Ñ(Ø×$Ñ$ QÑ'Ð/°1¸×8LÑ8LÈQÑ8OÑ3OààˆH�QŠKð #ð ˆr€   c                óD  — | j                  |«      }|j                  d   j                  }t        |t        «      r6|j
                  }d|j                  v r|j                  j                  d«       nd}t        d|j                  |¬«      }t        ||j                  ¬«      S )zDGet chunk from completion (e.g., from final completion of a stream).r   rœ   Nr™   )r6   rŸ   rè  ré  )r0  r/  rí   r·   r%   rè  rŸ   r«  r&   rD   rK  )r’  Ú
completionÚchat_resultÚchat_messagerè  rí   s         r~   r%  z4BaseChatOpenAI._get_generation_chunk_from_completionJ  s™   € ð ×.Ñ.¨zÓ:ˆØ"×.Ñ.¨qÑ1×9Ñ9ˆÜ�l¤IÔ.Ø)×8Ñ8ˆNà˜|×=Ñ=Ñ=Ø×.Ñ.×2Ñ2°<Õ@à!ˆNÜ ØØ*×<Ñ<Ø)ô
ˆô
 #Ø¨[×-CÑ-Cô
ð 	
r€   ©Úreturnrj  )rÐ  r­   )rš  rS  rÐ  r   )r¡  rP  rÐ  rP  )rÐ  r`   )rÐ  zModelProfile | None©rÐ  rS  )rà  zlist[dict | None]rÐ  rª   )rç  rª   rñ  r¼   rò  údict | NonerÐ  zChatGenerationChunk | None)rÐ  ÚNone)NN)
r
  úlist[BaseMessage]r  r„  r  úCallbackManagerForLLMRun | Noner  r   rÐ  úIterator[ChatGenerationChunk])
r
  rÔ  r  r„  r  ú$AsyncCallbackManagerForLLMRun | Noner  r   rÐ  ú"AsyncIterator[ChatGenerationChunk]r‚   )ra  r`  r  r   rÐ  rj  )r
  rÔ  r  r„  r  rÕ  ra  r`  r  r   rÐ  rÖ  )
r
  rÔ  r  r„  r  rÕ  r  r   rÐ  rE   ©r  rª   rÐ  rj  ©r@  r!   r  r„  r  r   rÐ  rª   )r&  zdict | openai.BaseModelr8  rÒ  rÐ  rE   )r
  rÔ  r  r„  r  r×  ra  r`  r  r   rÐ  rØ  )
r
  rÔ  r  r„  r  r×  r  r   rÐ  rE   )r  r„  r  r   rÐ  rS  )r  r„  r  r   rÐ  r$   )rÐ  ztuple[str, tiktoken.Encoding])r½   r­   rÐ  z	list[int])r
  úSequence[BaseMessage]r8  z<Sequence[dict[str, Any] | type | Callable | BaseTool] | Noner}  rj  rÐ  r  )r8  z5Sequence[dict[str, Any] | type | Callable | BaseTool]r’  zdict | str | bool | Noner“  r`  r”  r`  rú  ú_DictOrPydanticClass | Noner  r   rÐ  z'Runnable[LanguageModelInput, AIMessage]©rý  rÜ  r§  z7Literal['function_calling', 'json_mode', 'json_schema']r¨  rj  r“  r`  r8  zlist | Noner  r   rÐ  z-Runnable[LanguageModelInput, _DictOrPydantic])r  r   rÐ  rS  )rÌ  zopenai.BaseModelrÐ  rD   )`r
  r  r  r  r[   rH  Ú__annotations__rI  rJ  rK  r†   rQ  rª   rT  rV  rY  r[  rX   r]  r_  ra  rc  rd  re  rf  rg  rh  ri  rk  rl  rm  rn  ro  rq  rr  rs  rt  ru  rv  rw  rx  r}  r  r€  r�  r‚  rƒ  r…  r†  r‡  rˆ  r‰  rŠ  r‹  r�  rZ   Úmodel_configÚpropertyr“  rM  r_   Úclassmethodrœ  r^   r£  r­  r°  r³  rÓ  r×  rÜ  rã  rö  rø  r  r  r  r)  r4  r²  r  r0  rS  rU  rW  r[  rh  rj  rs  ry  rˆ  r¤  rÈ  rº  r%  Ú__classcell__©r#  s   @r~   rF  rF    sÃ  ø… ññ  ¨dÔ3€FˆCÓ3á d°DÔ9€L�#Ó9á T°4Ô8€K�Ó8á"¨4¸Ô>Ð�sÓ>á O¸7ÔC€J�ÓCØà $€K�Ó$Ø+á#(¸Ô#>€L�.Ó>ØVñ 	�I tÔ,ð ØKó-ð/ñb #(°¸JÔ"G€O�ZÓGðñ ',°DÀÔ&OÐ˜ÓOØNñ  %Ù  ¸Ô>ô €L�*ó ñ AFØ˜IôA€OÐ=ó ðð
 !%€L�+Ó$ðð  #€K�Ó"Ø<à%)Ð�lÓ)Ø$à&*Ð�|Ó*Ø;à€Dˆ*ÓØà €HˆkÓ Ø%à#€L�*Ó#ðð )-€JÐ%Ó,ØPà€IˆtÓØ/à€A€zÓØAà€Eˆ<ÓØDá"¨4Ô0€J�
Ó0Ø/à#'Ð�jÓ'ðð< (,€IÐ$Ó+ðð !€IˆzÓ ðð '+Ð˜Ó*ðð 15€OÐ-Ó4à15€MÐ.Ó5ñ $¨D¸$Ô?€K�Ó?ðñ %*°$ÀÔ$EÐ�zÓEðñ BGØ˜dôBÐÐ>ó ð<ñ| */ñ
ð ô	*Ð˜,ó ð"ñH $)°Ð=MÔ#N€DÐ
 ÓNØ!à+/€JÐ(Ó/ðð( &+Ð˜dÓ*ðñ .3¸4Ô-@€OÐ*Ó@ðð  7;ÐÐ3Ó:ðð !%€GÐÓ$ðð 37ÐÐ/Ó6ðð
  $€L�*Ó#ðð €Eˆ;Óðð "€J�
Ó!ðð &+Ð˜dÓ*ðð< &*Ð�{Ó)ðñ "'Ù Ð!4¸dÔCô"€N�Jó ðñ" ¨tÔ4€Làò
ó ð
ð òó ðñ ˜(Ô#ØòEó ó $ðEñ
 Ð+°'Ô:Øòó ó ;ðñ& ˜(Ô#Øòó ó $ðñ< ˜'Ô"òó #ðñ ˜'Ô"òó #ðñ ˜'Ô"òMó #ðMó^
ð ò
ó ð
óBð2E
àðE
ð "ðE
ð *ð	E
ð
 
$óE
óN"ð "&Ø7;ð	A(à#ðA(ð ðA(ð 5ð	A(ð
 ðA(ð 
'óA(ðL "&Ø<@ð	H(à#ðH(ð ðH(ð :ð	H(ð
 ðH(ð 
,óH(ðV +/ð*Ø'ð*Ø:=ð*à	ó*ð, "&Ø7;ð	K#ð %)ñK#à#ðK#ð ðK#ð 5ð	K#ð "ðK#ð ðK#ð 
'óK#ð` "&Ø7;ð	FCà#ðFCð ðFCð 5ð	FCð
 ðFCð 
óFCóP+ð. "&ñ	à"ðð ð	ð
 ðð 
óðD (,ð_Jà)ð_Jð %ð_Jð 
ó	_JðH "&Ø<@ð	P#ð %)ñP#à#ðP#ð ðP#ð :ð	P#ð "ðP#ð ðP#ð 
,óP#ðj "&Ø<@ð	K
à#ðK
ð ðK
ð :ð	K
ð
 ðK
ð 
óK
ðZ òGó ðGð
 (,ðØ$ðØ7:ðà	õð< (,ðØ$ðØ7:ðà	óð& òó ðóõ +ð OSðdð
 '+ñdà'ðdð Lðdð
  $ðdð 
õdðT 15Ø"Ø+/Ø7;ñk=àDðk=ð .ð	k=ð
 ðk=ð )ðk=ð 5ðk=ð ðk=ð 
1õk=ð^ /3ðF#ð Ø!Ø"Ø!ñF#à+ðF#ð
ð	F#ð ðF#ð ðF#ð ðF#ð ðF#ð 
7óF#óPð
Ø*ð
à	÷
r€   rF  c                  ó  ‡ — e Zd ZU dZ edd¬«      Zded<   	 edd„«       Ze	dd„«       Z
edd	„«       Ze	dd
„«       Zedˆ fd„«       Zddœ	 	 	 	 	 	 	 dˆ fd„Zdˆ fd„Z	 	 	 	 	 	 dˆ fd„Z	 ddddddœ	 	 	 	 	 	 	 	 	 	 	 	 	 dˆ fd„Zˆ xZS )Ú
ChatOpenAIu¡z  Interface to OpenAI chat model APIs.

    !!! warning "API scope"

        `ChatOpenAI` targets
        [official OpenAI API specifications](https://github.com/openai/openai-openapi)
        only. Non-standard response fields added by third-party providers (e.g.,
        `reasoning_content`, `reasoning_details`) are **not** extracted or
        preserved. If you are pointing `base_url` at a provider such as
        OpenRouter, vLLM, or DeepSeek, use the corresponding provider-specific
        LangChain package instead (e.g., `ChatDeepSeek`, `ChatOpenRouter`).

    ???+ info "Setup"

        Install `langchain-openai` and set environment variable `OPENAI_API_KEY`.

        ```bash
        pip install -U langchain-openai

        # or using uv
        uv add langchain-openai
        ```

        ```bash
        export OPENAI_API_KEY="your-api-key"
        ```

    ??? info "Key init args â€” completion params"

        | Param               | Type          | Description                                                                                                 |
        | ------------------- | ------------- | ----------------------------------------------------------------------------------------------------------- |
        | `model`             | `str`         | Name of OpenAI model to use.                                                                                |
        | `temperature`       | `float`       | Sampling temperature.                                                                                       |
        | `max_tokens`        | `int | None`  | Max number of tokens to generate.                                                                           |
        | `logprobs`          | `bool | None` | Whether to return logprobs.                                                                                 |
        | `stream_options`    | `dict`        | Configure streaming outputs, like whether to return token usage when streaming (`{"include_usage": True}`). |
        | `use_responses_api` | `bool | None` | Whether to use the responses API.                                                                           |

        See full list of supported init args and their descriptions below.

    ??? info "Key init args â€” client params"

        | Param          | Type                                       | Description                                                                         |
        | -------------- | ------------------------------------------ | ----------------------------------------------------------------------------------- |
        | `timeout`      | `float | Tuple[float, float] | Any | None` | Timeout for requests.                                                               |
        | `max_retries`  | `int | None`                               | Max number of retries.                                                              |
        | `api_key`      | `str | None`                               | OpenAI API key. If not passed in will be read from env var `OPENAI_API_KEY`.        |
        | `base_url`     | `str | None`                               | Base URL for API requests. Only specify if using a proxy or service emulator. Falls back to env var `OPENAI_API_BASE`, then to `OPENAI_BASE_URL` (read by the underlying SDK client). |
        | `organization` | `str | None`                               | OpenAI organization ID. If not passed in will be read from env var `OPENAI_ORG_ID`. |

        See full list of supported init args and their descriptions below.

    ??? info "Instantiate"

        Create a model instance with desired params. For example:

        ```python
        from langchain_openai import ChatOpenAI

        model = ChatOpenAI(
            model="...",
            temperature=0,
            max_tokens=None,
            timeout=None,
            max_retries=2,
            # api_key="...",
            # base_url="...",
            # organization="...",
            # other params...
        )
        ```

        See all available params below.

        !!! tip "Preserved params"
            Any param which is not explicitly supported will be passed directly to
            [`openai.OpenAI.chat.completions.create(...)`](https://platform.openai.com/docs/api-reference/chat/create)
            every time to the model is invoked. For example:

            ```python
            from langchain_openai import ChatOpenAI
            import openai

            ChatOpenAI(..., frequency_penalty=0.2).invoke(...)

            # Results in underlying API call of:

            openai.OpenAI(..).chat.completions.create(..., frequency_penalty=0.2)

            # Which is also equivalent to:

            ChatOpenAI(...).invoke(..., frequency_penalty=0.2)
            ```

    ??? info "Invoke"

        Generate a response from the model:

        ```python
        messages = [
            (
                "system",
                "You are a helpful translator. Translate the user sentence to French.",
            ),
            ("human", "I love programming."),
        ]
        model.invoke(messages)
        ```

        Results in an `AIMessage` response:

        ```python
        AIMessage(
            content="J'adore la programmation.",
            response_metadata={
                "token_usage": {
                    "completion_tokens": 5,
                    "prompt_tokens": 31,
                    "total_tokens": 36,
                },
                "model_name": "gpt-4.1-mini",
                "system_fingerprint": "fp_43dfabdef1",
                "finish_reason": "stop",
                "logprobs": None,
            },
            id="run-012cffe2-5d3d-424d-83b5-51c6d4a593d1-0",
            usage_metadata={"input_tokens": 31, "output_tokens": 5, "total_tokens": 36},
        )
        ```

    ??? info "Stream"

        Stream a response from the model:

        ```python
        for chunk in model.stream(messages):
            print(chunk.text, end="")
        ```

        Results in a sequence of `AIMessageChunk` objects with partial content:

        ```python
        AIMessageChunk(content="", id="run-9e1517e3-12bf-48f2-bb1b-2e824f7cd7b0")
        AIMessageChunk(content="J", id="run-9e1517e3-12bf-48f2-bb1b-2e824f7cd7b0")
        AIMessageChunk(content="'adore", id="run-9e1517e3-12bf-48f2-bb1b-2e824f7cd7b0")
        AIMessageChunk(content=" la", id="run-9e1517e3-12bf-48f2-bb1b-2e824f7cd7b0")
        AIMessageChunk(
            content=" programmation", id="run-9e1517e3-12bf-48f2-bb1b-2e824f7cd7b0"
        )
        AIMessageChunk(content=".", id="run-9e1517e3-12bf-48f2-bb1b-2e824f7cd7b0")
        AIMessageChunk(
            content="",
            response_metadata={"finish_reason": "stop"},
            id="run-9e1517e3-12bf-48f2-bb1b-2e824f7cd7b0",
        )
        ```

        To collect the full message, you can concatenate the chunks:

        ```python
        stream = model.stream(messages)
        full = next(stream)
        for chunk in stream:
            full += chunk
        ```

        ```python
        full = AIMessageChunk(
            content="J'adore la programmation.",
            response_metadata={"finish_reason": "stop"},
            id="run-bf917526-7f58-4683-84f7-36a6b671d140",
        )
        ```

    ??? info "Async"

        Asynchronous equivalents of `invoke`, `stream`, and `batch` are also available:

        ```python
        # Invoke
        await model.ainvoke(messages)

        # Stream
        async for chunk in (await model.astream(messages))

        # Batch
        await model.abatch([messages])
        ```

        Results in an `AIMessage` response:

        ```python
        AIMessage(
            content="J'adore la programmation.",
            response_metadata={
                "token_usage": {
                    "completion_tokens": 5,
                    "prompt_tokens": 31,
                    "total_tokens": 36,
                },
                "model_name": "gpt-4.1-mini",
                "system_fingerprint": "fp_43dfabdef1",
                "finish_reason": "stop",
                "logprobs": None,
            },
            id="run-012cffe2-5d3d-424d-83b5-51c6d4a593d1-0",
            usage_metadata={
                "input_tokens": 31,
                "output_tokens": 5,
                "total_tokens": 36,
            },
        )
        ```

        For batched calls, results in a `list[AIMessage]`.

    ??? info "Tool calling"

        ```python
        from pydantic import BaseModel, Field


        class GetWeather(BaseModel):
            '''Get the current weather in a given location'''

            location: str = Field(
                ..., description="The city and state, e.g. San Francisco, CA"
            )


        class GetPopulation(BaseModel):
            '''Get the current population in a given location'''

            location: str = Field(
                ..., description="The city and state, e.g. San Francisco, CA"
            )


        model_with_tools = model.bind_tools(
            [GetWeather, GetPopulation]
            # strict = True  # Enforce tool args schema is respected
        )
        ai_msg = model_with_tools.invoke(
            "Which city is hotter today and which is bigger: LA or NY?"
        )
        ai_msg.tool_calls
        ```

        ```python
        [
            {
                "name": "GetWeather",
                "args": {"location": "Los Angeles, CA"},
                "id": "call_6XswGD5Pqk8Tt5atYr7tfenU",
            },
            {
                "name": "GetWeather",
                "args": {"location": "New York, NY"},
                "id": "call_ZVL15vA8Y7kXqOy3dtmQgeCi",
            },
            {
                "name": "GetPopulation",
                "args": {"location": "Los Angeles, CA"},
                "id": "call_49CFW8zqC9W7mh7hbMLSIrXw",
            },
            {
                "name": "GetPopulation",
                "args": {"location": "New York, NY"},
                "id": "call_6ghfKxV264jEfe1mRIkS3PE7",
            },
        ]
        ```

        !!! note "Parallel tool calls"
            [`openai >= 1.32`](https://pypi.org/project/openai/) supports a
            `parallel_tool_calls` parameter that defaults to `True`. This parameter can
            be set to `False` to disable parallel tool calls:

            ```python
            ai_msg = model_with_tools.invoke(
                "What is the weather in LA and NY?", parallel_tool_calls=False
            )
            ai_msg.tool_calls
            ```

            ```python
            [
                {
                    "name": "GetWeather",
                    "args": {"location": "Los Angeles, CA"},
                    "id": "call_4OoY0ZR99iEvC7fevsH8Uhtz",
                }
            ]
            ```

        Like other runtime parameters, `parallel_tool_calls` can be bound to a model
        using `model.bind(parallel_tool_calls=False)` or during instantiation by
        setting `model_kwargs`.

        See `bind_tools` for more.

    ??? info "Mid-conversation tool additions"

        ```python
        from langchain_core.messages import HumanMessage, SystemMessage
        from langchain_openai import ChatOpenAI

        model = ChatOpenAI(model="gpt-6-astra", use_responses_api=True)
        model.invoke(
            [
                HumanMessage("What time is it?"),
                SystemMessage(
                    [
                        {
                            "type": "additional_tools",
                            "role": "developer",
                            "tools": [
                                {
                                    "type": "function",
                                    "name": "get_time",
                                    "description": "Get the current time.",
                                    "parameters": {
                                        "type": "object",
                                        "properties": {},
                                    },
                                }
                            ],
                        }
                    ]
                ),
            ]
        )
        ```

    ??? info "Built-in (server-side) tools"

        You can access [built-in tools](https://platform.openai.com/docs/guides/tools?api-mode=responses)
        supported by the OpenAI Responses API. See [LangChain docs](https://docs.langchain.com/oss/python/integrations/chat/openai#responses-api)
        for more detail.

        ```python
        from langchain_openai import ChatOpenAI

        model = ChatOpenAI(model="...", output_version="responses/v1")

        tool = {"type": "web_search"}
        model_with_tools = model.bind_tools([tool])

        response = model_with_tools.invoke("What was a positive news story from today?")
        response.content
        ```

        ```python
        [
            {
                "type": "text",
                "text": "Today, a heartwarming story emerged from ...",
                "annotations": [
                    {
                        "end_index": 778,
                        "start_index": 682,
                        "title": "Title of story",
                        "type": "url_citation",
                        "url": "<url of story>",
                    }
                ],
            }
        ]
        ```

        !!! version-added "Added in `langchain-openai` 0.3.9"

        !!! version-added "Added in `langchain-openai` 0.3.26: Updated `AIMessage` format"
            [`langchain-openai >= 0.3.26`](https://pypi.org/project/langchain-openai/#history)
            allows users to opt-in to an updated `AIMessage` format when using the
            Responses API. Setting `ChatOpenAI(..., output_version="responses/v1")` will
            format output from reasoning summaries, built-in tool invocations, and other
            response items into the message's `content` field, rather than
            `additional_kwargs`. We recommend this format for new applications.

    ??? info "Managing conversation state"

        OpenAI's Responses API supports management of [conversation state](https://platform.openai.com/docs/guides/conversation-state?api-mode=responses).
        Passing in response IDs from previous messages will continue a conversational
        thread.

        ```python
        from langchain_openai import ChatOpenAI

        model = ChatOpenAI(
            model="...",
            use_responses_api=True,
            output_version="responses/v1",
        )
        response = model.invoke("Hi, I'm Bob.")
        response.text
        ```

        ```txt
        "Hi Bob! How can I assist you today?"
        ```

        ```python
        second_response = model.invoke(
            "What is my name?",
            previous_response_id=response.response_metadata["id"],
        )
        second_response.text
        ```

        ```txt
        "Your name is Bob. How can I help you today, Bob?"
        ```

        !!! version-added "Added in `langchain-openai` 0.3.9"

        !!! version-added "Added in `langchain-openai` 0.3.26"

            You can also initialize `ChatOpenAI` with `use_previous_response_id`.
            Input messages up to the most recent response will then be dropped from request
            payloads, and `previous_response_id` will be set using the ID of the most
            recent response.

            ```python
            model = ChatOpenAI(model="...", use_previous_response_id=True)
            ```

        !!! note "OpenAI-compatible endpoints"

            Some OpenAI-compatible providers/proxies may not support forwarding
            reasoning blocks in request history. If you see request-format
            errors while using reasoning + Responses API, prefer
            `use_previous_response_id=True` (so the server keeps
            conversation state).

    ??? info "Reasoning output"

        OpenAI's Responses API supports [reasoning models](https://platform.openai.com/docs/guides/reasoning?api-mode=responses)
        that expose a summary of internal reasoning processes.

        ```python
        from langchain_openai import ChatOpenAI

        reasoning = {
            "effort": "medium",  # 'low', 'medium', or 'high'
            "summary": "auto",  # 'detailed', 'auto', or None
        }

        model = ChatOpenAI(
            model="...", reasoning=reasoning, output_version="responses/v1"
        )
        response = model.invoke("What is 3^3?")

        # Response text
        print(f"Output: {response.text}")

        # Reasoning summaries
        for block in response.content:
            if block["type"] == "reasoning":
                for summary in block["summary"]:
                    print(summary["text"])
        ```

        ```txt
        Output: 3Â³ = 27
        Reasoning: The user wants to know...
        ```

        !!! version-added "Added in `langchain-openai` 0.3.26: Updated `AIMessage` format"
            [`langchain-openai >= 0.3.26`](https://pypi.org/project/langchain-openai/#history)
            allows users to opt-in to an updated `AIMessage` format when using the
            Responses API. Setting `ChatOpenAI(..., output_version="responses/v1")` will
            format output from reasoning summaries, built-in tool invocations, and other
            response items into the message's `content` field, rather than
            `additional_kwargs`. We recommend this format for new applications.

        !!! note "Troubleshooting with non-OpenAI backends"
            When using a non-OpenAI endpoint via `base_url`, request handling for
            reasoning history can differ. If agent loops fail after tool calls, use:
            `ChatOpenAI(..., use_responses_api=True, use_previous_response_id=True)`.

    ??? info "Structured output"

        ```python
        from pydantic import BaseModel, Field


        class Joke(BaseModel):
            '''Joke to tell user.'''

            setup: str = Field(description="The setup of the joke")
            punchline: str = Field(description="The punchline to the joke")
            rating: int | None = Field(
                description="How funny the joke is, from 1 to 10"
            )


        structured_model = model.with_structured_output(Joke)
        structured_model.invoke("Tell me a joke about cats")
        ```

        ```python
        Joke(
            setup="Why was the cat sitting on the computer?",
            punchline="To keep an eye on the mouse!",
            rating=None,
        )
        ```

        See `with_structured_output` for more info.

    ??? info "JSON mode"

        ```python
        json_model = model.bind(response_format={"type": "json_object"})
        ai_msg = json_model.invoke(
            "Return a JSON object with key 'random_ints' and a value of 10 random ints in [0-99]"
        )
        ai_msg.content
        ```

        ```txt
        '\\n{\\n  "random_ints": [23, 87, 45, 12, 78, 34, 56, 90, 11, 67]\\n}'
        ```

    ??? info "Image input"

        ```python
        import base64
        import httpx
        from langchain.messages import HumanMessage

        image_url = "https://upload.wikimedia.org/wikipedia/commons/thumb/d/dd/Gfp-wisconsin-madison-the-nature-boardwalk.jpg/2560px-Gfp-wisconsin-madison-the-nature-boardwalk.jpg"
        image_data = base64.b64encode(httpx.get(image_url).content).decode("utf-8")
        message = HumanMessage(
            content=[
                {"type": "text", "text": "describe the weather in this image"},
                {
                    "type": "image_url",
                    "image_url": {"url": f"data:image/jpeg;base64,{image_data}"},
                },
            ]
        )

        ai_msg = model.invoke([message])
        ai_msg.content
        ```

        ```txt
        "The weather in the image appears to be clear and pleasant. The sky is mostly blue with scattered, light clouds, suggesting a sunny day with minimal cloud cover. There is no indication of rain or strong winds, and the overall scene looks bright and calm. The lush green grass and clear visibility further indicate good weather conditions."
        ```

    ??? info "Token usage"

        ```python
        ai_msg = model.invoke(messages)
        ai_msg.usage_metadata

        ```txt
        {"input_tokens": 28, "output_tokens": 5, "total_tokens": 33}
        ```

        When streaming, set the `stream_usage` kwarg:

        ```python
        stream = model.stream(messages, stream_usage=True)
        full = next(stream)
        for chunk in stream:
            full += chunk
        full.usage_metadata
        ```

        ```txt
        {"input_tokens": 28, "output_tokens": 5, "total_tokens": 33}
        ```

    ??? info "Logprobs"

        ```python
        logprobs_model = model.bind(logprobs=True)
        ai_msg = logprobs_model.invoke(messages)
        ai_msg.response_metadata["logprobs"]
        ```

        ```txt
        {
            "content": [
                {
                    "token": "J",
                    "bytes": [74],
                    "logprob": -4.9617593e-06,
                    "top_logprobs": [],
                },
                {
                    "token": "'adore",
                    "bytes": [39, 97, 100, 111, 114, 101],
                    "logprob": -0.25202933,
                    "top_logprobs": [],
                },
                {
                    "token": " la",
                    "bytes": [32, 108, 97],
                    "logprob": -0.20141791,
                    "top_logprobs": [],
                },
                {
                    "token": " programmation",
                    "bytes": [
                        32,
                        112,
                        114,
                        111,
                        103,
                        114,
                        97,
                        109,
                        109,
                        97,
                        116,
                        105,
                        111,
                        110,
                    ],
                    "logprob": -1.9361265e-07,
                    "top_logprobs": [],
                },
                {
                    "token": ".",
                    "bytes": [46],
                    "logprob": -1.2233183e-05,
                    "top_logprobs": [],
                },
            ]
        }
        ```

    ??? info "Response metadata"

        ```python
        ai_msg = model.invoke(messages)
        ai_msg.response_metadata
        ```

        ```txt
        {
            "token_usage": {
                "completion_tokens": 5,
                "prompt_tokens": 28,
                "total_tokens": 33,
            },
            "model_name": "gpt-4.1-mini",
            "system_fingerprint": "fp_319be4768e",
            "finish_reason": "stop",
            "logprobs": None,
        }
        ```

    ??? info "Flex processing"

        OpenAI offers a variety of [service tiers](https://platform.openai.com/docs/guides/flex-processing?api-mode=responses).
        The "flex" tier offers cheaper pricing for requests, with the trade-off that
        responses may take longer and resources might not always be available.
        This approach is best suited for non-critical tasks, including model testing,
        data enhancement, or jobs that can be run asynchronously.

        To use it, initialize the model with `service_tier="flex"`:

        ```python
        from langchain_openai import ChatOpenAI

        model = ChatOpenAI(model="...", service_tier="flex")
        ```

        Note that this is a beta feature that is only available for a subset of models.
        See OpenAI [flex processing docs](https://platform.openai.com/docs/guides/flex-processing?api-mode=responses)
        for more detail.

    ??? info "OpenAI-compatible APIs"

        `ChatOpenAI` can be used with OpenAI-compatible APIs like
        [LM Studio](https://lmstudio.ai/), [vLLM](https://github.com/vllm-project/vllm),
        [Ollama](https://ollama.com/), and others.

        To use custom parameters specific to these providers, use the `extra_body` parameter.

        !!! example "LM Studio example with TTL (auto-eviction)"

            ```python
            from langchain_openai import ChatOpenAI

            model = ChatOpenAI(
                base_url="http://localhost:1234/v1",
                api_key="lm-studio",  # Can be any string
                model="mlx-community/QwQ-32B-4bit",
                temperature=0,
                extra_body={
                    "ttl": 300
                },  # Auto-evict model after 5 minutes of inactivity
            )
            ```

        !!! example "vLLM example with custom parameters"

            ```python
            model = ChatOpenAI(
                base_url="http://localhost:8000/v1",
                api_key="EMPTY",
                model="meta-llama/Llama-2-7b-chat-hf",
                extra_body={"use_beam_search": True, "best_of": 4},
            )
            ```

        !!! warning "Model name can trigger Responses API routing"

            The choice between the Chat Completions API (`/v1/chat/completions`)
            and the Responses API (`/v1/responses`) is inferred in part from the
            model name, independent of `base_url`.

            `use_responses_api` should generally be set explicitly to avoid ambiguity,
            especially when using OpenAI-compatible providers:

            ```python
            model = ChatOpenAI(
                base_url="http://localhost:8000/v1",
                api_key="EMPTY",
                model="codex-7b-instruct",
                use_responses_api=False,
            )
            ```

    ??? info "`model_kwargs` vs `extra_body`"

        Use the correct parameter for different types of API arguments:

        **Use `model_kwargs` for:**

        - Standard OpenAI API parameters not explicitly defined as class parameters
        - Parameters that should be flattened into the top-level request payload
        - Examples: `max_completion_tokens`, `stream_options`, `modalities`, `audio`

        ```python
        # Standard OpenAI parameters
        model = ChatOpenAI(
            model="...",
            model_kwargs={
                "stream_options": {"include_usage": True},
                "max_completion_tokens": 300,
                "modalities": ["text", "audio"],
                "audio": {"voice": "alloy", "format": "wav"},
            },
        )
        ```

        **Use `extra_body` for:**

        - Custom parameters specific to OpenAI-compatible providers (vLLM, LM Studio,
            OpenRouter, etc.)
        - Parameters that need to be nested under `extra_body` in the request
        - Any non-standard OpenAI API parameters

        ```python
        # Custom provider parameters
        model = ChatOpenAI(
            base_url="http://localhost:8000/v1",
            model="custom-model",
            extra_body={
                "use_beam_search": True,  # vLLM parameter
                "best_of": 4,  # vLLM parameter
                "ttl": 300,  # LM Studio parameter
            },
        )
        ```

        **Key Differences:**

        - `model_kwargs`: Parameters are **merged into top-level** request payload
        - `extra_body`: Parameters are **nested under `extra_body`** key in request

        !!! warning
            Always use `extra_body` for custom parameters, **not** `model_kwargs`.
            Using `model_kwargs` for non-OpenAI parameters will cause API errors.

    ??? info "Prompt caching optimization"

        OpenAI prompt caching is automatic for eligible prompts. For high-volume
        applications with repetitive prompts, use `prompt_cache_key`
        per invocation to improve cache hit rates and reduce costs:

        ```python
        model = ChatOpenAI(model="...")

        response = model.invoke(
            messages,
            prompt_cache_key="example-key-a",  # Routes to same machine for cache hits
        )

        customer_response = model.invoke(messages, prompt_cache_key="example-key-b")
        support_response = model.invoke(messages, prompt_cache_key="example-key-c")

        # Dynamic cache keys based on context
        cache_key = f"example-key-{dynamic_suffix}"
        response = model.invoke(messages, prompt_cache_key=cache_key)
        ```

        The default `"implicit"` mode keeps OpenAI's automatic breakpoint and
        also uses explicit breakpoints. The `"explicit"` mode uses only the
        breakpoints you provide.

        For models that support explicit cache breakpoints, pass
        request-level cache options and mark supported content blocks
        with `prompt_cache_breakpoint`:

        ```python
        model = ChatOpenAI(model="gpt-5.6-sol")
        response = model.invoke(
            [
                {
                    "role": "system",
                    "content": [
                        {
                            "type": "text",
                            "text": "Stable instructions and examples...",
                            "prompt_cache_breakpoint": {"mode": "explicit"},
                        }
                    ],
                },
                {"role": "user", "content": "Current request"},
            ],
            prompt_cache_key="tenant:acme:support-v1",
            prompt_cache_options={"mode": "explicit", "ttl": "30m"},
        )
        ```

        Set `prompt_cache_options` per invocation, as above, or persist it on
        the model:

        ```python
        model = ChatOpenAI(
            model="gpt-5.6-sol",
            prompt_cache_options={"mode": "explicit", "ttl": "30m"},
        )
        ```

        `prompt_cache_options["mode"]` can be `"implicit"` or `"explicit"`.
        OpenAI limits how many breakpoints can write to the cache in a single
        request. In `"implicit"` mode, the implicit breakpoint on the latest
        message uses one write slot, so up to three explicit breakpoints can
        write. In `"explicit"` mode, up to four explicit breakpoints can write.
        For reads, OpenAI considers up to the latest 50 breakpoints.

        For models before the GPT-5.6 family that support legacy prompt cache
        retention, pass `prompt_cache_retention`. See OpenAI's
        [prompt caching docs](https://platform.openai.com/docs/guides/prompt-caching)
        for the current model support list and retention semantics.

        ```python
        response = model.invoke(messages, prompt_cache_retention="24h")
        ```

        Cache keys help ensure requests with the same prompt prefix are routed
        to machines with existing cache, providing cost reduction and
        latency improvement on cached tokens. Cache reads are available as
        `response.usage_metadata["input_token_details"]["cache_read"]`; cache
        writes are available as `"cache_creation"` when the OpenAI response
        includes `cache_write_tokens`. On the `"priority"` and `"flex"`
        service tiers these keys are prefixed with the tier name
        (e.g. `"priority_cache_read"`).
    Nrd  rN  rb  rn  c                ó
   — ddiS )z(Mapping of secret environment variables.rV  r¸  rÌ   r•  s    r~   Ú
lc_secretszChatOpenAI.lc_secretsÊ  s   € ð !Ð"2Ð3Ð3r€   c                ó
   — g d¢S )zzGet the namespace of the LangChain object.

        Returns:
            `["langchain", "chat_models", "openai"]`
        )Ú	langchainÚchat_modelsr+  rÌ   ©r™  s    r~   Úget_lc_namespacezChatOpenAI.get_lc_namespaceÏ  s
   € ò 6Ð5r€   c                ó¬   — i }| j                   r| j                   |d<   | j                  r| j                  |d<   | j                  r| j                  |d<   |S )z+Get the attributes of the langchain object.r[  rY  r]  )r[  rY  r]  )r’  Ú
attributess     r~   Úlc_attributeszChatOpenAI.lc_attributesØ  s\   € ð &(ˆ
à×#Ò#Ø04×0HÑ0HˆJÐ,Ñ-à×ÒØ,0×,@Ñ,@ˆJÐ(Ñ)à×ÒØ)-×):Ñ):ˆJ�~Ñ&àÐr€   c                 ó   — y)z9Return whether this model can be serialized by LangChain.TrÌ   rë  s    r~   Úis_lc_serializablezChatOpenAI.is_lc_serializableè  s   € ð r€   c                óL   •— t         ‰| �  }d|v r|j                  d«      |d<   |S )rÙ  rn  rd  )rZ  rÜ  r«  )r’  r\  r#  s     €r~   rÜ  zChatOpenAI._default_paramsí  s0   ø€ ô ‘Ñ(ˆØ˜6Ñ!Ø.4¯j©j¸Ó.FˆFÐ*Ñ+àˆr€   r9  c               óþ   •— t        ‰| �  |fd|i|¤Ž}d|v r|j                  d«      |d<   | j                  rEt	        j
                  d| j                  «      r%|j                  dg «      D ]  }|d   dk(  sŒd|d<   Œ |S )	Nr  rn  rd  z^o\dr
  r•   r¢   r£   )rZ  r  r«  r†   ÚreÚmatchr„   )r’  r@  r  r  r  rí   r#  s         €r~   r  zChatOpenAI._get_request_payloadö  s‡   ø€ ô ‘'Ñ.¨vÑK¸DÐKÀFÑKˆð ˜7Ñ"Ø/6¯{©{¸<Ó/HˆGÐ+Ñ,ð �?Š?œrŸx™x¨°·±ÔAØ"Ÿ;™; z°2Ö6�Ø˜6‘? hÓ.Ø&1�G˜F’Oð 7ð ˆr€   c                ó~   •— | j                  i |¥| j                  ¥«      rt        ‰| �  |i |¤ŽS t        ‰| �  |i |¤ŽS )ú+Route to Chat Completions or Responses API.)r²  rT  rZ  r  r)  )r’  rú   r  r#  s      €r~   r)  zChatOpenAI._stream
  sK   ø€ à×"Ñ"Ð#B fÐ#B°×0AÑ0AÐ#BÔCÜ‘7Ñ,¨dÐ=°fÑ=Ð=Ü‰w‰ Ð/¨Ñ/Ð/r€   c               óÒ   •K  — | j                  i |¥| j                  ¥«      rt        ‰| �  |i |¤Ž2 3 d{  –—† }|­–— Œt        ‰| �  |i |¤Ž2 3 d{  –—† }|­–— Œ7 Œ(6 y7 Œ6 y­w)r÷  N)r²  rT  rZ  r  rS  )r’  rú   r  rç  r#  s       €r~   rS  zChatOpenAI._astream  sv   øè ø€ ð ×"Ñ"Ð#B fÐ#B°×0AÑ0AÐ#BÔCÜ$™wÑ9¸4ÐJÀ6ÒJ÷ �eØ”ä$™wÑ/°Ð@¸Ò@÷ �eØ”ð	øÑJðøÑ@ùsI   ƒ/A'²A!¶A·A!ºA'ÁA%ÁA#ÁA%ÁA'ÁA!Á!A'Á#A%Á%A'rš  Fr¦  c               ó.   •— t        ‰| �  |f||||dœ|¤ŽS )aÞ>  Model wrapper that returns outputs formatted to match the given schema.

        Args:
            schema: The output schema. Can be passed in as:

                - an OpenAI function/tool schema,
                - a JSON Schema,
                - a `TypedDict` class,
                - or a Pydantic class.

                If `schema` is a Pydantic class then the model output will be a
                Pydantic instance of that class, and the model-generated fields will be
                validated by the Pydantic class. Otherwise the model output will be a
                dict and will not be validated.

                See `langchain_core.utils.function_calling.convert_to_openai_tool` for
                more on how to properly specify types and descriptions of schema fields
                when specifying a Pydantic or `TypedDict` class.

            method: The method for steering model generation, one of:

                - `'json_schema'`:
                    Uses OpenAI's [Structured Output API](https://platform.openai.com/docs/guides/structured-outputs).
                    See the docs for [supported models](https://platform.openai.com/docs/guides/structured-outputs#supported-models).
                - `'function_calling'`:
                    Uses OpenAI's [tool-calling API](https://platform.openai.com/docs/guides/function-calling)
                    (formerly called function calling).
                - `'json_mode'`:
                    Uses OpenAI's [JSON mode](https://platform.openai.com/docs/guides/structured-outputs#json-mode).
                    Note that if using JSON mode then you must include instructions for
                    formatting the output into the desired schema into the model call.

                Learn more about the [differences between methods](https://platform.openai.com/docs/guides/structured-outputs#function-calling-vs-response-format).

            include_raw:
                If `False` then only the parsed structured output is returned.

                If an error occurs during model output parsing it will be raised.

                If `True` then both the raw model response (a `BaseMessage`) and the
                parsed model response will be returned.

                If an error occurs during output parsing it will be caught and returned
                as well.

                The final output is always a `dict` with keys `'raw'`, `'parsed'`, and
                `'parsing_error'`.
            strict:

                - `True`:
                    Model output is guaranteed to exactly match the schema.
                    The input schema will also be validated according to the
                    [supported schemas](https://platform.openai.com/docs/guides/structured-outputs#supported-schemas).
                - `False`:
                    Input schema will not be validated and model output will not be
                    validated.
                - `None`:
                    `strict` argument will not be passed to the model.

                If schema is specified via `TypedDict` or JSON schema, `strict` is not
                enabled by default. Pass `strict=True` to enable it.

                !!! note
                    `strict` can only be non-null if `method` is `'json_schema'` or `'function_calling'`.
            tools:
                A list of tool-like objects to bind to the chat model. Requires that:

                - `method` is `'json_schema'` (default).
                - `strict=True`
                - `include_raw=True`

                If a model elects to call a
                tool, the resulting `AIMessage` in `'raw'` will include tool calls.

                ??? example

                    ```python
                    from langchain.chat_models import init_chat_model
                    from pydantic import BaseModel


                    class ResponseSchema(BaseModel):
                        response: str


                    def get_weather(location: str) -> str:
                        \"\"\"Get weather at a location.\"\"\"
                        pass

                    model = init_chat_model("openai:gpt-5.5")

                    structured_model = model.with_structured_output(
                        ResponseSchema,
                        tools=[get_weather],
                        strict=True,
                        include_raw=True,
                    )

                    structured_model.invoke("What's the weather in Boston?")
                    ```

                    ```python
                    {
                        "raw": AIMessage(content="", tool_calls=[...], ...),
                        "parsing_error": None,
                        "parsed": None,
                    }
                    ```

            kwargs: Additional keyword args are passed through to the model.

        Returns:
            A `Runnable` that takes same inputs as a
                `langchain_core.language_models.chat.BaseChatModel`. If `include_raw` is
                `False` and `schema` is a Pydantic class, `Runnable` outputs an instance
                of `schema` (i.e., a Pydantic object). Otherwise, if `include_raw` is
                `False` then `Runnable` outputs a `dict`.

                If `include_raw` is `True`, then `Runnable` outputs a `dict` with keys:

                - `'raw'`: `BaseMessage`
                - `'parsed'`: `None` if there was a parsing error, otherwise the type
                    depends on the `schema` as described above.
                - `'parsing_error'`: `BaseException | None`

        !!! warning "Behavior changed in `langchain-openai` 0.3.0"

            `method` default changed from `"function_calling"` to `"json_schema"`.

        !!! warning "Behavior changed in `langchain-openai` 0.3.12"

            Support for `tools` added.

        !!! warning "Behavior changed in `langchain-openai` 0.3.21"

            Pass `kwargs` through to the model.

        ??? note "Example: `schema=Pydantic` class, `method='json_schema'`, `include_raw=False`, `strict=True`"

            Note, OpenAI has a number of restrictions on what types of schemas can be
            provided if `strict = True`. When using Pydantic, our model cannot
            specify any Field metadata (like min/max constraints) and fields cannot
            have default values.

            See [all constraints](https://platform.openai.com/docs/guides/structured-outputs#supported-schemas).

            ```python
            from langchain_openai import ChatOpenAI
            from pydantic import BaseModel, Field


            class AnswerWithJustification(BaseModel):
                '''An answer to the user question along with justification for the answer.'''

                answer: str
                justification: str | None = Field(
                    default=..., description="A justification for the answer."
                )


            model = ChatOpenAI(model="...", temperature=0)
            structured_model = model.with_structured_output(AnswerWithJustification)

            structured_model.invoke(
                "What weighs more a pound of bricks or a pound of feathers"
            )
            ```

            ```python
            AnswerWithJustification(
                answer="They weigh the same",
                justification="Both a pound of bricks and a pound of feathers weigh one pound. The weight is the same, but the volume or density of the objects may differ.",
            )
            ```

        ??? note "Example: `schema=Pydantic` class, `method='function_calling'`, `include_raw=False`, `strict=False`"

            ```python
            from langchain_openai import ChatOpenAI
            from pydantic import BaseModel, Field


            class AnswerWithJustification(BaseModel):
                '''An answer to the user question along with justification for the answer.'''

                answer: str
                justification: str | None = Field(
                    default=..., description="A justification for the answer."
                )


            model = ChatOpenAI(model="...", temperature=0)
            structured_model = model.with_structured_output(
                AnswerWithJustification, method="function_calling"
            )

            structured_model.invoke(
                "What weighs more a pound of bricks or a pound of feathers"
            )
            ```

            ```python
            AnswerWithJustification(
                answer="They weigh the same",
                justification="Both a pound of bricks and a pound of feathers weigh one pound. The weight is the same, but the volume or density of the objects may differ.",
            )
            ```

        ??? note "Example: `schema=Pydantic` class, `method='json_schema'`, `include_raw=True`"

            ```python
            from langchain_openai import ChatOpenAI
            from pydantic import BaseModel


            class AnswerWithJustification(BaseModel):
                '''An answer to the user question along with justification for the answer.'''

                answer: str
                justification: str


            model = ChatOpenAI(model="...", temperature=0)
            structured_model = model.with_structured_output(
                AnswerWithJustification, include_raw=True
            )

            structured_model.invoke(
                "What weighs more a pound of bricks or a pound of feathers"
            )
            ```

            ```python
            {
                "raw": AIMessage(
                    content="",
                    additional_kwargs={
                        "tool_calls": [
                            {
                                "id": "call_Ao02pnFYXD6GN1yzc0uXPsvF",
                                "function": {
                                    "arguments": '{"answer":"They weigh the same.","justification":"Both a pound of bricks and a pound of feathers weigh one pound. The weight is the same, but the volume or density of the objects may differ."}',
                                    "name": "AnswerWithJustification",
                                },
                                "type": "function",
                            }
                        ]
                    },
                ),
                "parsed": AnswerWithJustification(
                    answer="They weigh the same.",
                    justification="Both a pound of bricks and a pound of feathers weigh one pound. The weight is the same, but the volume or density of the objects may differ.",
                ),
                "parsing_error": None,
            }
            ```

        ??? note "Example: `schema=TypedDict` class, `method='json_schema'`, `include_raw=False`, `strict=False`"

            ```python
            from typing_extensions import Annotated, TypedDict

            from langchain_openai import ChatOpenAI


            class AnswerWithJustification(TypedDict):
                '''An answer to the user question along with justification for the answer.'''

                answer: str
                justification: Annotated[
                    str | None, None, "A justification for the answer."
                ]


            model = ChatOpenAI(model="...", temperature=0)
            structured_model = model.with_structured_output(AnswerWithJustification)

            structured_model.invoke(
                "What weighs more a pound of bricks or a pound of feathers"
            )
            ```

            ```python
            {
                "answer": "They weigh the same",
                "justification": "Both a pound of bricks and a pound of feathers weigh one pound. The weight is the same, but the volume and density of the two substances differ.",
            }
            ```

        ??? note "Example: `schema=OpenAI` function schema, `method='json_schema'`, `include_raw=False`"

            ```python
            from langchain_openai import ChatOpenAI

            oai_schema = {
                "name": "AnswerWithJustification",
                "description": "An answer to the user question along with justification for the answer.",
                "parameters": {
                    "type": "object",
                    "properties": {
                        "answer": {"type": "string"},
                        "justification": {
                            "description": "A justification for the answer.",
                            "type": "string",
                        },
                    },
                    "required": ["answer"],
                },
            }

            model = ChatOpenAI(model="...", temperature=0)
            structured_model = model.with_structured_output(oai_schema)

            structured_model.invoke(
                "What weighs more a pound of bricks or a pound of feathers"
            )
            ```

            ```python
            {
                "answer": "They weigh the same",
                "justification": "Both a pound of bricks and a pound of feathers weigh one pound. The weight is the same, but the volume and density of the two substances differ.",
            }
            ```

        ??? note "Example: `schema=Pydantic` class, `method='json_mode'`, `include_raw=True`"

            ```python
            from langchain_openai import ChatOpenAI
            from pydantic import BaseModel


            class AnswerWithJustification(BaseModel):
                answer: str
                justification: str


            model = ChatOpenAI(model="...", temperature=0)
            structured_model = model.with_structured_output(
                AnswerWithJustification, method="json_mode", include_raw=True
            )

            structured_model.invoke(
                "Answer the following question. "
                "Make sure to return a JSON blob with keys 'answer' and 'justification'.\\n\\n"
                "What's heavier a pound of bricks or a pound of feathers?"
            )
            ```

            ```python
            {
                "raw": AIMessage(
                    content='{\\n    "answer": "They are both the same weight.",\\n    "justification": "Both a pound of bricks and a pound of feathers weigh one pound. The difference lies in the volume and density of the materials, not the weight." \\n}'
                ),
                "parsed": AnswerWithJustification(
                    answer="They are both the same weight.",
                    justification="Both a pound of bricks and a pound of feathers weigh one pound. The difference lies in the volume and density of the materials, not the weight.",
                ),
                "parsing_error": None,
            }
            ```

        ??? note "Example: `schema=None`, `method='json_mode'`, `include_raw=True`"

            ```python
            structured_model = model.with_structured_output(
                method="json_mode", include_raw=True
            )

            structured_model.invoke(
                "Answer the following question. "
                "Make sure to return a JSON blob with keys 'answer' and 'justification'.\\n\\n"
                "What's heavier a pound of bricks or a pound of feathers?"
            )
            ```

            ```python
            {
                "raw": AIMessage(
                    content='{\\n    "answer": "They are both the same weight.",\\n    "justification": "Both a pound of bricks and a pound of feathers weigh one pound. The difference lies in the volume and density of the materials, not the weight." \\n}'
                ),
                "parsed": {
                    "answer": "They are both the same weight.",
                    "justification": "Both a pound of bricks and a pound of feathers weigh one pound. The difference lies in the volume and density of the materials, not the weight.",
                },
                "parsing_error": None,
            }
            ```

        r¦  )rZ  rÈ  )r’  rý  r§  r¨  r“  r8  r  r#  s          €r~   rÈ  z!ChatOpenAI.with_structured_output  s6   ø€ ô` ‰wÑ-Øð
àØ#ØØñ
ð ñ
ð 	
r€   )rÐ  zdict[str, str])rÐ  z	list[str]rÑ  rÏ  rÚ  )rú   r   r  r   rÐ  rÖ  )rú   r   r  r   rÐ  rØ  r‚   rÝ  )r
  r  r  r  r[   rn  rÞ  rà  rç  rá  rì  rï  rñ  rÜ  r  r)  rS  rÈ  râ  rã  s   @r~   rå  rå  a  sH  ø… ñcñJ #¨4Ð7NÔO€J�
ÓOØ/àò4ó ð4ð ò6ó ð6ð òó ðð òó ðð ôó ðð "&ñ	à"ðð ð	ð
 ðð 
õõ(0ð	Øð	Ø$'ð	à	+õ	ð /3ðW
ð KXØ!Ø"Ø!ñW
à+ðW
ð Hð	W
ð
 ðW
ð ðW
ð ðW
ð ðW
ð 
7÷W
ñ W
r€   rå  c                ó<   — t        | t        «      xr t        | «      S r‚   )r·   r¼   rU   )Úobjs    r~   r-  r-  µ  s   € Ü�cœ4Ó Ò?Ô%:¸3Ó%?Ð?r€   c                óP   — d| d   | d   t        j                  | d   d¬«      dœdœS )	Nr¥   r—   r–   rú   F)Úensure_ascii©r–   rø   ©r¼   r—   r¥   )ÚjsonÚdumps)rñ   s    r~   ré   ré   ¹  s6   € àØ˜‰oà˜fÑ%ÜŸ™ I¨fÑ$5ÀEÔJñ
ñð r€   c                ó&   — d| d   | d   | d   dœdœS )Nr¥   r—   r–   rú   rþ  rÿ  rÌ   )Úinvalid_tool_calls    r~   rê   rê   Ä  s.   € ð Ø Ñ%à% fÑ-Ø*¨6Ñ2ñ
ñð r€   c                óD  — 	 ddl m} t        | «      rådd l}d}d}	 t        «       j                  | |¬«      }|j                  «        |j                  j                  d«      }|r%t        |«      |kD  rt        j                  d|«       y t        |j                  «      |kD  rt        j                  d|«       y |j                  t!        |j                  «      «      5 }|j"                  \  }}	d d d «       	fS t+        | «      r`| j-                  dd«      \  }}t/        j0                  |«      }|j                  t!        |«      «      5 }|j"                  \  }}	d d d «       ||	fS y # t        $ r t        j	                  d«       Y y w xY w# 1 sw Y   Œ�xY w# |j$                  $ r t        j                  d	|«       Y y |j&                  $ r }
t        j                  d
|
«       Y d }
~
y d }
~
wt(        $ r }
t        j                  d|
«       Y d }
~
y d }
~
ww xY w# 1 sw Y   	fS xY w)Nr   )ÚImagezaUnable to count image tokens. To count image tokens please install `pip install -U pillow httpx`.g      @i   )r^  zcontent-lengthz0Image URL exceeds maximum size limit of %d bytesz,Image URL request timed out after %s secondsz!Image URL returned HTTP error: %sz-Failed to fetch or process image from URL: %sÚ,r¦  )ÚPILr  ÚImportErrorrŸ  ÚinfoÚ_is_urlÚhttpxr   r„   Úraise_for_statusr6  r  r   rï  r6   Úopenr   ÚsizeÚTimeoutExceptionÚHTTPStatusErrorr¬   Ú_is_b64Úsplitrà   Ú	b64decode)Úimage_sourcer  r  r^  Úmax_sizer&  Úcontent_lengthÚimgÚwidthÚheightr²   r{  Úencodedrâ   s                 r~   rŠ  rŠ  Ñ  sñ  € ðÝô ˆ|ÔÛð ˆà#ˆð	Ü,Ó.×2Ñ2°<ÈÐ2ÓQˆHØ×%Ñ%Ô'ð &×-Ñ-×1Ñ1Ð2BÓCˆNÙ¤# nÓ"5¸Ò"@Ü—‘ØFÈôð ô �8×#Ñ#Ó$ xÒ/Ü—‘ØFÈôð à—‘œG H×$4Ñ$4Ó5Ô6¸#Ø #§¡‘��v÷ 7à˜&�=Ð ô ˆ|ÔØ!×'Ñ'¨¨QÓ/‰
ˆˆ7Ü×Ñ Ó(ˆØ�Z‰Zœ ›Ô&¨#ØŸH™H‰MˆE�6÷ 'à�fˆ}ÐØøôk ò Ü�‰ð-ô	
ñ ðú÷D 7Ð6ûð ×%Ñ%ò 	Ü�N‰NÐIÈ7ÔSÙØ×$Ñ$ò 	Ü�N‰NÐ>ÀÔBÜûÜò 	Ü�N‰NÐJÈAÔNÜûð	ú÷ 'à�fˆ}Ðúsk   ‚E$ œA,F Â	.F Â8$F ÃFÃ,F ÅHÅ$FÆFÆFÆF Æ%HÆ;HÇ	G$Ç$HÇ0HÈHÈHc                ón   — t        | |«      \  } }t        |dz  «      }t        | dz  «      }d|z  |z  dz   S )Ni   éª   r†  )Ú_resizer   )r  r  ÚhÚws       r~   r‹  r‹    sA   € ä˜E 6Ó*�M€Eˆ6ÜˆV�c‰\Ó€AÜˆU�S‰[Ó€AØ�!‰G�a‰K˜2ÑÐr€   c                ó´   — 	 t        | «      }t        |j                  |j                  g«      S # t        $ r }t
        j                  d|«       Y d }~yd }~ww xY w)NzUnable to parse URL: %sF)r   rÆ  ÚschemeÚnetlocr¬   rŸ  Údebug)Úsr2  r²   s      r~   r
  r
    sJ   € ðÜ˜!“ˆÜ�F—M‘M 6§=¡=Ð1Ó2Ð2øÜò Ü�‰Ð.°Ô2Üûðús   ‚+. ®	A·AÁAc                ó$   — | j                  d«      S )Nz
data:image)rÈ   )r$  s    r~   r  r    s   € Ø�<‰<˜Ó%Ð%r€   c                ó    — | dkD  s|dkD  r| |kD  r|dz  | z  }d} n
| dz  |z  } d}| dkD  r"|dkD  r| |kD  r| dz  |z  } d}| |fS |dz  | z  }d} | |fS )Ni   i   rÌ   )r  r  s     r~   r  r  !  sŽ   € àˆt‚|�v ’}Ø�6Š>Ø˜t‘m¨Ñ-ˆFØ‰Eà˜T‘\ fÑ,ˆEØˆFàˆs‚{�v ’|Ø�6Š>Ø˜S‘[ VÑ+ˆEØˆFð �&ˆ=Ðð ˜s‘l uÑ,ˆFØˆEØ�&ˆ=Ðr€   r–  c               ó<  — t        | t        «      rt        | «      r| S t        | t        «      rd| v r| j	                  d«      dk(  r| }n}t        | t        «      rd| v r
d| v rd| dœ}n_|€7t        | t        «      r%t        | j	                  d«      t
        «      r| d   }nd}t        | |¬«      }|j                  d	«      |d<   d|dœ}|�T||d   j	                  d«      ur>t        | t        «      r.d| j	                  di «      v rd
| d   d   › d|› d�}t        |«      ‚|S )Nrš  r¼   r–   rý  )r¼   rš  r“  Fr–  Ú
parametersz0Output schema already has 'strict' value set to z: but 'strict' also passed in to with_structured_output as z@. Please make sure that 'strict' is only specified in one place.)	r·   r¼   rU   rª   r„   rj  rQ   r«  rÐ   )rý  r“  rú  r¥   rÓ   s        r~   rž  rž  5  s=  € ô �&œ$ÔÔ$9¸&Ô$AØˆô 	�6œ4Ô Ø˜VÑ#Ø�J‰J�vÓ -Ò/à ‰Ü	�FœDÔ	! f°Ñ&6¸8ÀvÑ;MØ#0ÀÑH‰àˆ>Ü˜&¤$Ô'¬J°v·z±zÀ(Ó7KÌTÔ,RØ Ñ)‘à�Ü-¨f¸VÔDˆØ%Ÿ\™\¨,Ó7ˆ�ÑØ#0ÀÑJˆð 	ÐØ˜/¨-Ñ8×<Ñ<¸XÓFÑFÜ�vœtÔ$Ø˜Ÿ
™
 =°"Ó5Ñ5ð ?Ø�mÑ$ XÑ.Ð/ð 0)Ø)/¨ð 17ð8ð 	ô ˜‹oÐØÐr€   c                ó–  — | j                   j                  d«      x}�t        |t        «      r |di |¤ŽS |S | j                   j                  d«      rt	        | j                   d   «      ‚t        d„ | j                  D «       «      r't        d„ | j                  D «       «      }t	        |«      ‚| j                  ry d| › �}t        |«      ‚)NrH  rJ  c              3  óz   K  — | ]3  }t        |t        «      xr |j                  d «      dk(  xr d|d   v –— Œ5 y­w©r¼   Únon_standardrJ  r¡  N©r·   rª   r„   ©r½  rÁ   s     r~   r¿  z1_oai_structured_outputs_parser.<locals>.<genexpr>f  sO   è ø€ ð ñ +ˆEô 	�5œ$Óò 	(Ø�I‰I�fÓ Ñ/ò	(à˜˜w™Ð'ó	(ñ +ùs   ‚9;c              3  ój   K  — | ]+  }t        |t        «      r|d    dk(  rd|d   v r
|d   d   –— Œ- y­wr+  ©r·   rª   r.  s     r~   r¿  z1_oai_structured_outputs_parser.<locals>.<genexpr>l  sC   è ø€ ð 
á.�Ü˜%¤Ô&Ø�f‘ Ò/Ø˜U 7™^Ñ+ð	 �'‰N˜9Õ%Ù.ùs   ‚13zdStructured Output response does not have a 'parsed' field nor a 'refusal' field. Received message:

rÌ   )
rŸ   r„   r·   rª   ÚOpenAIRefusalErrorr˜  Úcontent_blocksÚnextrœ   rÐ   )Úai_msgrý  rH  rJ  rÓ   s        r~   r»  r»  ]  sÜ   € ð ×*Ñ*×.Ñ.¨xÓ8Ð8ˆÐEÜ�fœdÔ#ÙÑ#˜FÑ#Ð#ØˆØ×Ñ×#Ñ# IÔ.Ü  ×!9Ñ!9¸)Ñ!DÓEÐEÜ
ñ ð ×*Ò*ó	ô ô ñ 
à×.Ò.ó
ó 
ˆô ! Ó)Ð)Ø×ÒØð	'Ø'- hð	0ð ô �S‹/Ðr€   c                  ó   — e Zd ZdZy)r1  aE  Error raised when OpenAI Structured Outputs API returns a refusal.

    When using OpenAI's Structured Outputs API with user-generated input, the model
    may occasionally refuse to fulfill the request for safety reasons.

    See [more on refusals](https://platform.openai.com/docs/guides/structured-outputs/refusals).
    Nr	  rÌ   r€   r~   r1  r1  }  s   „ òr€   r1  c                óZ  — | j                  d«      }|�|nd}| j                  d«      }|�|nd}| j                  d«      }|�|n||z   }|dvrd }|r|› d�nd}| j                  d«      xs i }	d	|	j                  d
«      |› d�|	j                  d«      |› d�|	j                  d«      i}
d	| j                  d«      xs i j                  d
«      |› d�| j                  d«      xs i j                  d«      i}|�>||
j                  |› d�d«      xs dz
  |
|<   ||j                  |› d�d«      xs dz
  ||<   t        |||t        di |
j                  «       D ��ci c]  \  }}|€Œ	||“Œ c}}¤Žt	        di |j                  «       D ��ci c]  \  }}|€Œ	||“Œ c}}¤Ž¬«      S c c}}w c c}}w )NÚprompt_tokensr   Úcompletion_tokensÚtotal_tokens>   ÚflexÚpriorityr{  r™   Úprompt_tokens_detailsrž   Úaudio_tokensÚ
cache_readÚcached_tokensÚcache_creationÚcache_write_tokensÚcompletion_tokens_detailsrq  Úreasoning_tokens©Úinput_tokensÚoutput_tokensr9  Úinput_token_detailsÚoutput_token_detailsrÌ   ©r„   r9   r7   rë   r8   )Úoai_token_usager‡  Ú_inputrE  Ú_outputrF  Ú_totalr9  Úservice_tier_prefixr<  rG  rH  rò   ró   s                 r~   rî  rî  ‡  s6  € ð × Ñ  Ó1€FØ#Ð/‘6°Q€LØ×!Ñ!Ð"5Ó6€GØ&Ð2‘G¸€MØ× Ñ  Ó0€FØ#Ð/‘6°\ÀMÑ5Q€LØÐ/Ñ/ØˆÙ0<˜\˜N¨!Ñ,À"ÐØ+×/Ñ/Ð0GÓHÒNÈBÐàÐ&×*Ñ*¨>Ó:ØÐ
˜zÐ*Ð,A×,EÑ,EÀoÓ,VØÐ
˜~Ð.Ð0E×0IÑ0IØ ó1
ð!Ðð 	�/×%Ñ%Ð&AÓBÒHÀb×MÑMØó
ð Ð
˜yÐ)Ø×ÑÐ ;Ó<ÒBÀß
‰#Ð Ó
!ð"Ðð Ðð -9Ø×#Ñ#Ð':Ð&;¸:Ð$FÈÓJÒOÈañ-
Ð˜LÑ)ð .;Ø ×$Ñ$Ð(;Ð'<¸IÐ%FÈÓJÒOÈañ.
Ð˜\Ñ*ô Ø!Ø#Ø!Ü-ñ 
Ø 3× 9Ñ 9Ô ;ÔMÑ ;™˜˜1¸q¹}ˆq�!‰tÐ ;ÒMñ
ô 0ñ 
Ø 4× :Ñ :Ô <ÔNÑ <™˜˜1ÀÁˆq�!‰tÐ <ÒNñ
ô
ð 
ùó
 Nùó Os   Å
F!Å"F!Æ
F'ÆF'c                óð  — | j                  d«      }|�|nd}| j                  d«      }|�|nd}| j                  d«      }|�|n||z   }|dvrd }|r|› d�nd}|› d�| j                  d	«      xs i j                  d
«      i}	| j                  d«      xs i }
|› d�|
j                  d«      |› d�|
j                  d«      i}|�>||	j                  |› d�d«      xs dz
  |	|<   ||j                  |› d�d«      xs dz
  ||<   t        |||t        di |j                  «       D ��ci c]  \  }}|€Œ	||“Œ c}}¤Žt	        di |	j                  «       D ��ci c]  \  }}|€Œ	||“Œ c}}¤Ž¬«      S c c}}w c c}}w )NrE  r   rF  r9  >   r:  r;  r{  r™   rq  Úoutput_tokens_detailsrC  Úinput_tokens_detailsr>  r?  r@  rA  rD  rÌ   rI  )rJ  r‡  rK  rE  rL  rF  rM  r9  rN  rH  rQ  rG  rò   ró   s                 r~   Ú _create_usage_metadata_responsesrR  ¹  sþ  € ð × Ñ  Ó0€FØ#Ð/‘6°Q€LØ×!Ñ! /Ó2€GØ&Ð2‘G¸€MØ× Ñ  Ó0€FØ#Ð/‘6°\ÀMÑ5Q€LØÐ/Ñ/ØˆÙ0<˜\˜N¨!Ñ,À"ÐàÐ
˜yÐ)Ø×ÑÐ 7Ó8Ò>¸Bß
‰#Ð Ó
!ð"Ðð
 +×.Ñ.Ð/EÓFÒLÈ"ÐàÐ
˜zÐ*Ð,@×,DÑ,DÀ_Ó,UØÐ
˜~Ð.Ð0D×0HÑ0HØ ó1
ð!Ðð Ðð .;Ø ×$Ñ$Ð(;Ð'<¸IÐ%FÈÓJÒOÈañ.
Ð˜\Ñ*ð -9Ø×#Ñ#Ð':Ð&;¸:Ð$FÈÓJÒOÈañ-
Ð˜LÑ)ô Ø!Ø#Ø!Ü-ñ 
Ø 3× 9Ñ 9Ô ;ÔMÑ ;™˜˜1¸q¹}ˆq�!‰tÐ ;ÒMñ
ô 0ñ 
Ø 4× :Ñ :Ô <ÔNÑ <™˜˜1ÀÁˆq�!‰tÐ <ÒNñ
ô
ð 
ùó
 Nùó Os   Ä"
E,Ä-E,Å
E2ÅE2c                ó   — d| v xr | d   dk7  S )Nr¼   r¥   rÌ   )r§   s    r~   Ú_is_builtin_toolrT  ç  s   € Ø�Tˆ>Ò8˜d 6™l¨jÑ8Ð8r€   c                ó|   — d| v xr t        d„ | d   D «       «      }h d£}t        |xs |j                  | «      «      S )Nr8  c              3  ó2   K  — | ]  }t        |«      –— Œ y ­wr‚   )rT  )r½  r§   s     r~   r¿  z%_use_responses_api.<locals>.<genexpr>ì  s   è ø€ ð 4Ù+; 4Ô˜×Ñ+;ùs   ‚>   r½   r…  rq  r‰  rƒ  r;  )r˜  rj  Úintersection)r  Úuses_builtin_toolsÚresponses_only_argss      r~   r²  r²  ë  sR   € Ø  GÐ+ò ´ñ 4Ø+2°7Ò+;ó4ó 1ÐòÐô Ð"ÒOÐ&9×&FÑ&FÀwÓ&OÓPÐPr€   c                óè   — t        t        | «      dz
  dd«      D ]S  }| |   }t        |t        «      sŒ|j                  j                  d«      }|sŒ7|j                  d«      sŒI| |dz   d |fc S  | dfS )aš  Get the last part of the conversation after the last `AIMessage` with an `id`.

    Will return:

    1. Every message after the most-recent `AIMessage` that has a non-empty
        `response_metadata["id"]` (may be an empty list),
    2. That `id`.

    If the most-recent `AIMessage` does not have an `id` (or there is no
    `AIMessage` at all) the entire conversation is returned together with `None`.
    r¦  rû  r—   Úresp_N)Úrangerï  r·   r%   rð  r„   rÈ   )r
  ÚirÓ   Úresponse_ids       r~   r>  r>  ú  s{   € ô ”3�x“= 1Ñ$ b¨"Ö-ˆØ�q‰kˆÜ�cœ9Õ%Ø×/Ñ/×3Ñ3°DÓ9ˆKÚ˜{×5Ñ5°gÕ>Ø  A¡ Ð(¨+Ð5Ò5ð .ð �Tˆ>Ðr€   c                óx  — dD ]  }||v sŒ|j                  |«      |d<   Œ d|v rd|vrd|j                  d«      i|d<   |j                  dd «       |j                  d«      xs d}|j                  d	«      r=d
|vr9|j                  d«      xs i j                  d«      dk7  r|j                  dd «       t        | |j                  d«      ¬«      |d<   |j                  dd «      x}r¦g }|D ]š  }|d   dk(  rGd|v rC|j	                  «       D ��ci c]  \  }}|dvsŒ||“Œ }	}}|j                  ddi|d   ¥|	¥«       ŒR|d   dk(  r0d|v rd}
t        |
«      ‚|j                  d«      rd|vr	i |¥ddi¥}n	 |j                  |«       Œœ ||d<   |j                  dd «      x}r.t        |t        «      r|d   dk(  rd|v rddi|d   ¥|d<   n||d<   t        |j                  d«      t        «      r|d   j                  «       |d<   |j                  dd «      x}rà|j                  dd «      }|j                  d«      st        |«      r||d<   n¬t        |«      r|j                  «       }d}n|}|ddik(  r,d|v rt        |d   t        «      rddi|d   d <   ncd ddii|d<   nYt        ||¬!«      x}rIt        |t        «      r9|d   d"k(  r1dd"i|d"   ¥}d|v rt        |d   t        «      r	||d   d <   n	d |i|d<   n	 |j                  d#d «      }|�(d|v rt        |d   t        «      r
||d   d#<   |S d#|i|d<   |S c c}}w )$N)rn  rd  Úmax_output_tokensro  rq  rª  r  rM  r™   r§  r¨  r©  rQ  rˆ  ©rˆ  Úinputr8  r¼   r¥   r—  r�   Úpartial_imagesz—Partial image generation is not yet supported via the LangChain ChatOpenAI client. Please drop the 'partial_images' key from the image_generation tool.rÚ  r¦  r’  r½   rú  r“  Útext_formatTr®  Úformatr–  rš  rr  )r«  r„   rÈ   Ú_construct_responses_api_inputrë   r«   r‰  r·   rª   r…   r-  Úmodel_json_schemarž  )r
  r  Úlegacy_token_paramrM  r8  Ú	new_toolsr§   rò   ró   ÚextrarÓ   r’  rý  r“  Úschema_dictrú  Úformat_valuerr  s                     r~   r?  r?    så  € ó FÐØ Ò(Ø+2¯;©;Ð7IÓ+JˆGÐ'Ò(ð Fð ˜WÑ$¨¸GÑ)CØ (¨'¯+©+Ð6HÓ*IÐJˆ�Ñð ‡K�K�˜Ôð
 �K‰K˜Ó Ò& B€Eà×Ñ˜Ô!Ø˜5Ñ Ø�[‰[˜Ó%Ò+¨×0Ñ0°Ó:¸fÒDà�‰�M 4Ô(ä5Ø˜Ÿ™ GÓ,ô€GˆGÑð —‘˜G TÓ*Ð*€uÐ*Øˆ	ÛˆDð �F‰|˜zÒ)¨j¸DÑ.@Ø*.¯*©*¬,ÔX©,¡$ ! Q¸!ÐCWÒ:W˜˜A™¨,�ÑXØ× Ñ  &¨*Ð!R¸¸ZÑ8HÐ!RÈEÐ!RÕSà˜‘<Ð#5Ò5à'¨4Ñ/ð$ð ô 2°#Ó6Ð6Ø—{‘{ 8Ô,Ð1AÈÑ1Mð  = $Ð<Ð(8¸!Ñ<™àà× Ñ  Õ&ð1 ð4 %ˆ�ÑØ—k‘k -°Ó6Ð6€{Ð6ô �{¤DÔ)Ø˜FÑ# zÒ1Ø˜kÑ)à&,¨jÐ%T¸KÈ
Ñ<SÐ%TˆG�MÒ"à%0ˆG�MÑ"ä�'—+‘+˜fÓ%¤tÔ,Ø! &™/×.Ñ.Ó0ˆ�‰ð —‘Ð.°Ó5Ð5€vÐ5ð —‘˜X tÓ,ˆØ�{‰{˜8Ô$Ô);¸FÔ)CØ%+ˆG�MÒ"ä! &Ô)Ø$×6Ñ6Ó8�Ø‘à$�Ø˜v }Ð5Ò5Ø˜WÑ$¬°G¸F±OÄTÔ)JØ17¸Ð0G�G˜F‘O HÒ-à'/°&¸-Ð1HÐ&I�G˜F’Oô (JØ#¨Fô(ð �Oð ô   ´Ô6Ø$ VÑ,°Ò=à &¨ÐX¸ÈÑ9WÐX�Ø˜WÑ$¬°G¸F±OÄTÔ)JØ0<�G˜F‘O HÒ-à'/°Ð&>�G˜F’Oàà—‘˜K¨Ó.€IØÐØ�WÑ¤¨G°F©O¼TÔ!BØ+4ˆG�F‰O˜KÑ(ð €Nð  +¨IÐ6ˆG�F‰Oà€Nùóa Ys   ÄL6ÄL6c                ó‚   — | j                  d«      dk(  r*d| v r&| j                  «       }|j                  d«      |d<   |S | S )Nr¼   Úfile_citationrù   Ú
file_index©r„   r…   r«  ©Ú
annotationÚnew_annotations     r~   Ú_format_annotation_to_lcrt  ‡  sI   € ð ‡~�~�fÓ Ò0°WÀ
Ñ5JØ#Ÿ™Ó*ˆØ'5×'9Ñ'9¸'Ó'Bˆ�|Ñ$ØÐØÐr€   c                ó‚   — | j                  d«      dk(  r*d| v r&| j                  «       }|j                  d«      |d<   |S | S )Nr¼   rn  ro  rù   rp  rq  s     r~   Ú_format_annotation_from_lcrv  ‘  sG   € Ø‡~�~�fÓ Ò0°\ÀZÑ5OØ#Ÿ™Ó*ˆØ"0×"4Ñ"4°\Ó"Bˆ�wÑØÐØÐr€   c                ó   — | d   dk(  rd| d   dœ}d| v r| d   |d<   |S | d   dk(  r8d| d   d   d	œ}| d   j                  d
«      r| d   d
   |d
<   d| v r| d   |d<   |S | d   dk(  rddi| d   ¥}d| v r| d   |d<   |S | S )z†Convert chat completions content blocks to Responses API format.

    Only handles text, image, file blocks. Others pass through.
    r¼   r½   Ú
input_textr¾   rµ   rã   Úinput_imagerä   rå   r„  r‡  Ú
input_file)r„   )rÁ   Ú	new_blocks     r~   Ú-_convert_chat_completions_blocks_to_responsesr|  ™  sï   € ð ˆV�}˜Òð *°5¸±=ÑAˆ	Ø$¨Ñ-Ø38Ð9RÑ3SˆIÐ/Ñ0ØÐØˆV�}˜Ò#ð "Ø˜{Ñ+¨EÑ2ñ
ˆ	ð �Ñ×!Ñ! (Ô+Ø"'¨Ñ"4°XÑ">ˆI�hÑØ$¨Ñ-Ø38Ð9RÑ3SˆIÐ/Ñ0ØÐØˆV�}˜ÒØ˜\Ð;¨U°6©]Ð;ˆ	Ø$¨Ñ-Ø38Ð9RÑ3SˆIÐ/Ñ0ØÐØ€Lr€   c                ó¼   — t        | t        «      r| S t        | t        «      r+t        d„ | D «       «      r| D �cg c]  }t	        |«      ‘Œ c}S t        | «      S c c}w )Nc              3  óf   K  — | ])  }t        |t        «      xr |j                  d «      dv –— Œ+ y­w)r¼   )rx  ry  rz  r½   rã   r‡  Nr-  r.  s     r~   r¿  z5_ensure_valid_tool_message_content.<locals>.<genexpr>¾  sC   è ø€ ð -ñ !ˆEô 	�5œ$Óò 		
Ø�I‰I�fÓð
ð
ó		
ñ !ùs   ‚/1)r·   r­   r¿   rÆ  r|  rL   )Útool_outputrÁ   s     r~   Ú"_ensure_valid_tool_message_contentr€  »  sk   € Ü�+œsÔ#ØÐÜ�+œtÔ$¬ñ -ñ !ó-ô *ñ %ó
á$�ô :¸%Õ@Ø$ñ
ð 	
ô �kÓ"Ð"ùò	
s   ¹Ac                óf  — d }t        | j                  t        «      r·| j                  D ]§  }| j                  j	                  d«      dk(  r6t        |t
        «      r&|j	                  d«      dk(  r| j                  d|dœ} n�t        |t
        «      sŒh|j	                  d«      dk(  sŒ}|j	                  di «      j	                  d«      dk(  sŒ¢|d   } n= n;| j                  j	                  d«      dk(  r| j                  dd| j                  dœdœ}|� d| j                  v r| j                  d   |d<   |S )	Nr¼   Úcomputer_call_outputry  )Úcall_idr¼   rá  r,  r¡  rå   Úacknowledged_safety_checks)r·   r6   r¿   rŸ   r„   rª   r¨   )rí   r‚  rÁ   s      r~   Ú'_make_computer_call_output_from_messager…  Ò  s6  € ð 37ÐÜ�'—/‘/¤4Ô(Ø—_”_ˆEà×)Ñ)×-Ñ-¨fÓ5Ð9OÒOÜ˜u¤dÔ+Ø—I‘I˜fÓ%¨Ò6ð  '×3Ñ3Ø2Ø#ñ(Ð$ñ
 ä˜5¤$Õ'Ø—I‘I˜fÓ%¨Ó7Ø—I‘I˜g rÓ*×.Ñ.¨vÓ6Ð:PÓPà',¨W¡~Ð$Ùñ' %ð( 
×	"Ñ	"×	&Ñ	& vÓ	.Ð2HÒ	Hð ×+Ñ+Ø*Ø,¸7¿?¹?ÑKñ 
Ðð 	Ð(Ø(¨G×,EÑ,EÑEà=D×=VÑ=VØ(ñ>
ÐÐ9Ñ:ð  Ðr€   c                ód  — d }| j                   D ]ž  }t        |t        «      r:|j                  d«      dk(  r&d| j                  |j                  d«      xs ddœ} |S t        |t        «      sŒ^|j                  d«      dk(  sŒs|j                  di «      j                  d«      dk(  sŒ˜|d   } |S  |S )Nr¼   Úcustom_tool_call_outputrá  r™   )r¼   rƒ  rá  r,  r¡  )r6   r·   rª   r„   r¨   )rí   Úcustom_tool_outputrÁ   s      r~   Ú%_make_custom_tool_output_from_messager‰  ü  sº   € ØÐØ—”ˆÜ�eœTÔ" u§y¡y°Ó'8Ð<UÒ'Uà1Ø"×/Ñ/ØŸ)™) HÓ-Ò3°ñ"Ðð
 ð Ðô �uœdÕ#Ø—	‘	˜&Ó! ^Ó3Ø—	‘	˜' 2Ó&×*Ñ*¨6Ó2Ð6OÓOà!& w¡ÐØàÐð! !ð  Ðr€   c                ó4  — | j                  «       D ��ci c]  \  }}|dk7  sŒ||“Œ }}}d|v r^t        |d   t        «      rKg }|d   D ]<  }|j                  «       D ��ci c]  \  }}|dk7  sŒ||“Œ }}}|j                  |«       Œ> ||d<   |S c c}}w c c}}w )z�When streaming, `langchain-core` uses `index` to aggregate text blocks.

    OpenAI API does not support this key, so we need to remove it.
    rù   Úsummary)rë   r·   r¿   r«   )rÁ   rò   ró   r{  Únew_summaryÚ	sub_blockÚnew_sub_blocks          r~   Ú_pop_index_and_sub_indexr�    s­   € ð
 #(§+¡+¤-Ô@¡-™$˜!˜Q°1¸³<��A‘ -€IÑ@Ø�IÑ¤*¨Y°yÑ-AÄ4Ô"HØˆØ" 9Ô-ˆIØ.7¯o©oÔ.?ÔPÑ.?¡d a¨À1ÈÃ<˜Q ™TÐ.?ˆMÑPØ×Ñ˜}Õ-ð .ð  +ˆ	�)ÑØÐùó Aùó Qs   ”B¢BÁBÁ,Bra  c          
     óF  — g }| D �]‰  }t        |t        «      r’t        |«      }t        |d¬«      }t        |j	                  d«      t
        «      rÂt        d„ |d   D «       «      r­|j                  D �cg c]  }d|d   |d   |j	                  d«      d	œ‘Œ  }}t        |d   |«      |d<   ngt        |d¬«      }t        |d   t
        «      rGt        |d   «      D ]6  \  }}t        |t        «      sŒ|j	                  d
«      dk(  sŒ,|d   |d   |<   Œ8 d|v r|j                  d«       |d   dk(  rz|d   }	t        t        t        |«      «      }
t        |«      }|
r|j!                  |
«       �Œh|r|j!                  |«       �Œ}t#        |	«      }	d|	|d   dœ}|j!                  |«       �Œ¤|d   dk(  �r²t        |j	                  d«      t
        «      �rß|d   D �]Õ  }t        |t        «      sŒ|j	                  d
«      x}sŒ)|dv rÿ|j	                  d«      }|j	                  d«      }|dv rE|j	                  d«      }|€Œgd||j	                  d«      xs g D �cg c]  }t%        |«      ‘Œ c}dœ}n|dk(  rd|d   dœ}|D ]A  }|j	                  d«      x}sŒ||k(  sŒd|vrg |d<   |d   j!                  «       |�||d<    Œê dgddœ}|dur|r|j'                  t(        «      s||d<   |�||d<   |j!                  |«       �Œ,|d k(  r3|dus|j	                  d!«      s�ŒH|j!                  t+        |«      «       �Œd|d"v r|j!                  t+        |«      «       �Œ„|d#k(  rM|dur|j!                  d#|d   d$œ«       �Œ¦t+        |«      }t-        |«      d
dhz
  s�ŒÃ|j!                  |«       �ŒÖ�ŒØ n<t        |j	                  d«      t.        «      r|j!                  ddd|d   g dœgd%œ«       |j                  d&d«      x}s�Œþ|D �ch c]  }|j	                  d
«      d'v r	d(|v r|d(   ’Œ  }}|D ]1  }|d   |vsŒd)|d*   d   |d*   d+   |d   d,œ}|j!                  |«       Œ3 �Œ_|d   d-v �rt        |d   t
        «      rçg }d.}|d   D ]·  }|d
   d/v r|j!                  t1        |«      «       Œ%|d
   d0v r|j!                  |«       Œ>|d
   |v r|j!                  |«       ŒW|d
   t2        k(  r#t        |t4        «      sŒt|j!                  |«       Œ†t7        |d   «      r$t9        j:                  d1|d
   ›d2�t<        d3¬4«       Œ¸Œ¹ ||d<   |d   s�ŒId|d
<   |j!                  |«       �Œad|d
<   |j!                  |«       �Œy|j!                  |«       �ŒŒ |S c c}w c c}w c c}w )5ae  Construct the input for the OpenAI Responses API.

    Args:
        messages: Conversation history to serialize into Responses API input items.
        store: Mirrors the request's `store` flag, controlling stateless-replay
            behavior.

            When `False`, the server does not persist response items, so
            previously returned item IDs cannot be resolved on the next turn.
            Assistant message IDs (`msg_*`) are therefore omitted and reasoning
            blocks are dropped unless they carry `encrypted_content` (which can be
            replayed without server-side storage).

            When `True` or `None` (the default, matching the server's
            stored-by-default behavior), item IDs and reasoning blocks
            are preserved.

    Returns:
        A list of Responses API input items derived from `messages`.
    rÛ   rÜ   r6   c              3  ó<   K  — | ]  }t        |t        «      –— Œ y ­wr‚   r0  r.  s     r~   r¿  z1_construct_responses_api_input.<locals>.<genexpr><  s   è ø€ ð <Ù5C¨E”
˜5¤$×'±^ùs   ‚rñ   r–   rú   r—   ©r¼   r–   rú   r—   r¼   r,  r¡  r•   r§   Úfunction_call_outputr¨   )r¼   rá  rƒ  rš   )r½   Úoutput_textrJ  Úphase)r½   r”  r½   Nr”  r   )r¼   r½   r   rJ  ©r¼   rJ  rí   )r¼   r6   r•   Frq  Úencrypted_content)Ú
compactionÚweb_search_callÚfile_search_callr›   Úcomputer_callÚcustom_tool_callrÚ   Úmcp_callÚmcp_list_toolsÚmcp_approval_requestÚtool_search_callÚtool_search_outputÚapply_patch_callÚapply_patch_call_outputÚimage_generation_call)r¼   r—   )r¼   r•   r6   rœ   )r›   rœ  rƒ  r›   r¥   rø   )r¼   r–   rø   rƒ  )r˜   r¢   r£   )Úmcp_approval_responser¡  r£  Úconfiguration_update)r½   rã   r‡  )rx  ry  rz  zContent block z| was dropped from a system message: the Responses API has no input item of that type, so it cannot be placed in the request.é   )Ú
stacklevel)r·   r%   r:   rö   r„   r¿   rÆ  rœ   rn   Ú	enumeraterª   r«  r…  r   r3   r‰  r«   r€  rv  rÈ   rV   r�  Úsetr­   r|  rÏ   r0   rÍ   r  r  ÚUserWarning)r
  rˆ  r@  Úlc_msgrÓ   rñ   Útcsr]  rÁ   r  r‚  rˆ  r“  Ú
block_typeÚmsg_idr•  r½   rr  r{  ÚitemÚitem_idÚnew_itemr¤  rœ   Úcontent_call_idsr›   Ú
new_blocksÚnon_message_item_typess                               r~   rf  rf     sJ  € ð. €FÜˆÜ�fœiÔ(Ü1°&Ó9ˆFÜ*¨6°{ÔCˆCÜ˜#Ÿ'™' )Ó,¬dÔ3¼ñ <Ø58¸²^ó<ô 9ð &,×%6Ò%6ó-ñ &7˜	ð !,Ø )¨&Ñ 1Ø )¨&Ñ 1Ø'Ÿm™m¨DÓ1ó	ð &7ð ð -ô "?¸sÀ9¹~ÈsÓ!S��I’ä*¨6°{ÔCˆCä˜#˜i™.¬$Ô/Ü )¨#¨i©.Ö 9‘H�A�uÜ! %¬Õ.°5·9±9¸VÓ3DÈÓ3VØ,1°'©N˜˜I™ qÒ)ð !:ð �S‰=Ø�G‰G�FŒOØˆv‰;˜&Ò Ø˜i™.ˆKÜ#JÜ”[ &Ó)ó$Ð ô "GÀvÓ!NÐÙ#Ø—‘Ð2Ö3Ù#Ø—‘Ð0Ö1ä@ÀÓM�à2Ø)Ø" >Ñ2ñ(Ð$ð
 —‘Ð2Ö3Ø�‰[˜KÓ'Ü˜#Ÿ'™' )Ó,¬dÕ3Ø  �^�EÜ! %¬Õ.À%Ç)Á)ÈFÓBSÐ4S°JÑ4Sà%Ð)KÑKØ%*§Y¡Y¨t£_˜FØ$)§I¡I¨gÓ$6˜EØ)Ð-DÑDà',§y¡y°Ó'8 Ø#' <à$,à,9Ø,0ð ;@¿)¹)ÀMÓ:RÒ:XÐVXÐ:Xó4&á:X¨Jô )CÀ:Õ(NØ:Xñ4&ñ-"¡	ð ",¨yÒ!8à,5Ø/4°YÑ/?ñ-" 	ó )/ Ø/3¯x©x¸«~Ð$= GÑ$=À7ÈfÓCTà'0¸Ñ'<Ø:<¨¨Y©Ø$(¨¡O×$:Ñ$:¸9Ô$EØ',Ð'8Ø8=¨¨W©Ù$)ð )/ð -6Ø09¨{Ø,7ñ2" ð %*°Ñ$6Ù(.Ø,2×,=Ñ,=¼nÔ,Mð
 6< H¨T¡NØ#(Ð#4Ø8= H¨WÑ$5Ø &§¡¨hÖ 7Ø'¨;Ò6Ø$¨EÑ1°U·Y±YÐ?RÖ5SØ &§¡Ô.FÀuÓ.MÖ NØ'ð ,ñ ð  #ŸM™MÔ*BÀ5Ó*IÖJØ'Ð+BÒBà$¨EÑ1Ø &§¡Ø-DÈEÐRVÉKÑ$Xö!"ô 9QÐQVÓ8WÐ 5Ü#&Ð'<Ó#=ÀÈÀÔ#NØ$*§M¡MÐ2GÖ$Há ño ,ôp ˜CŸG™G IÓ.´Ô4Ø—‘à )Ø +ð )6Ø(+¨I©Ø/1ñð$ñ
ôð !ŸW™W \°4Ó8Ð8ˆzÒ8ñ "(ó$á!'˜Ø—y‘y Ó(Ð,QÑQØ! UÑ*ð ˜)Ó$Ø!'ð !ð $ó ",�IØ  ‘Ð.>Ò>à$3Ø$-¨jÑ$9¸&Ñ$AØ)2°:Ñ)>¸{Ñ)KØ'0°¡ñ	)˜ð Ÿ™ mÕ4ò ",ð �‰[Ð;Ò;Ü˜#˜i™.¬$Ô/Ø�
ð*Ð&ð ! œ^�EØ˜V‘}Ð(EÑEØ"×)Ñ)ÜIÈ%ÓPõð ˜v™Ð*UÑUØ"×)Ñ)¨%Õ0Ø˜v™Ð*@Ñ@ØŸ™ eÕ,Ø˜v™Ô*FÒFÜ% f¬mÕ<Ø"ŸM™M¨%Õ0Ü(¨¨V©Ô5ô
 !Ÿ™Ø,¨U°6©]Ð,=ð >Sð Sô (Ø'(öð ð3 ,ð4 ",��I‘Ø�y”>Ø"+�C˜‘KØ—M‘M #Ö&à'��F‘Ø—‘˜cÖ"à�M‰M˜#Öðg ðj €Mùò]-ùòn4&ùòt$s   Á3#VÉVÐ#Vc                ó  — t        | d«      r| j                  S | j                  D ��cg c]=  }|j                  dk(  r,|j                  D ]  }|j                  dk(  r|j
                  ‘Œ Œ? }}}dj                  |«      S c c}}w )zrSafe output text extraction.

    Context: OpenAI SDK deleted `response.output_text` momentarily in `1.99.2`.
    r”  rí   r™   )r$  r”  rá  r¼   r6   r½   Újoin)r&  rá  r6   Útextss       r~   Ú_get_output_textr¹    s„   € ô
 ˆx˜Ô'Ø×#Ñ#Ð#ð —o’oôá%ˆFØ�;‰;˜)Ò#Ø—~”~ˆGØ�<‰<˜=Ò(ð	 	�‹ð &ð 	Ø%ð 
ñ ð �7‰7�5‹>Ðùós   ¨AA>c                ó&	  — | j                   rt        | j                   «      ‚|€d}| j                  ddd¬«      j                  «       D ��ci c]  \  }}|dv r||“Œ }}}|r|j	                  |«       d|d	<   |j                  d
«      |d<   | j                  r/t        | j                  j                  «       | j                  «      }nd}g }g }	g }
i }| j                  D �]ˆ  }|j                  dk(  �r
t        |dd«      }|j                  D ]ì  }|j                  dk(  r™d|j                  t        |j                  t         «      r1|j                  D �cg c]  }t#        |j                  «       «      ‘Œ c}ng |j$                  dœ}|�||d<   |j'                  |«       t)        |d«      r|j*                  |d<   |j                  dk(  sŒ»d|j,                  |j$                  dœ}|�||d<   |j'                  |«       Œî �Œ|j                  dk(  r¿|j                  dd¬«      }d|v r|j/                  d«      |d<   |j'                  |«       	 t1        j2                  |j4                  d¬«      }d}|€.d|j:                  ||j<                  dœ}|	j'                  |«       �Œ½d|j:                  ||j<                  |dœ}|
j'                  |«       �Œì|j                  dk(  r\|j'                  |j                  dd¬«      «       d|j:                  d|j>                  i|j<                  dœ}|	j'                  |«       �ŒW|j                  dv s�Œg|j'                  |j                  dd¬«      «       �Œ‹ tA        | «      }|�‰d|vr…|rƒ| j                  rw| j                  j                  «       x}r[|j                  d i «      x}rG|j                  d!«      d"k(  r3	 t1        j2                  |«      }|rtC        |«      r	 |d'i |¤Ž}n|}||d<   tE        || j$                  ||||	|
¬#«      }|d$k(  rtG        |«      }tI        tK        |¬%«      g¬&«      S c c}}w c c}w # t6        $ r"}|j4                  }t9        |«      }Y d}~�Œ	d}~ww xY w# t0        j6                  $ r Y Œ‘w xY w)(z;Construct `ChatResponse` from OpenAI Response API response.Nr6  Tr   F)Úexclude_noner—  r  )	Ú
created_atr—   Úincomplete_detailsrþ  ÚobjectÚstatusr˜   rM  r‡  r+  rí  rM  r†   rí   r•  r”  r½   )r¼   r½   r   r—   rH  rJ  )r¼   rJ  r—   r›   ©r»  r—  Úasync_r“   r–  rñ   r’  r  )r¼   r–   rú   r—   rI  rœ  Ú__arg1)rq  r˜  r™  rš  r›  rÚ   r�  rž  rŸ  r¤  r   r¡  r¢  r£  re  r¼   rš  )r6   r—   rè  rð  rŸ   rœ   r    Úv0©rí   )r/  rÌ   )&rI  rÐ   r"  rë   Úupdater„   rå  rR  r‡  rá  r¼   r7  r6   r½   r·   r   r¿   rt  r—   r«   r$  rH  rJ  r«  r   Úloadsrø   r   r­   r–   rƒ  rb  r¹  r-  r%   ro   rE   rC   )r&  rý  rþ  r�  rò   ró   rð  rè  r2  rœ   r    rŸ   rá  r•  r6   rr  rÁ   Úrefusal_blockÚfunction_call_blockrú   rI  r²   rñ   r”  Útext_configÚformat_Úparsed_dictrH  rí   s                                r~   r.  r.  !  sÀ  € ð ‡~‚~Ü˜Ÿ™Ó(Ð(àÐð (ˆð
 ×'Ñ'Ø F°Uð (ó 
ç
‰%‹'ðôñ‰DˆAˆqð ð
ñ
ð 	
ˆ1‰ðð ñ ñ* Ø× Ñ  Ô*à*2ÐÐ&Ñ'Ø&7×&;Ñ&;¸GÓ&DÐ�lÑ#Ø‡~‚~Ü9Ø�N‰N×%Ñ%Ó'¨×)>Ñ)>ó
‰ð ˆà€NØ€JØÐØ ÐØ—/•/ˆØ�;‰;˜)Ó#Ü˜F G¨TÓ2ˆEØ!Ÿ>œ>�Ø—<‘< =Ò0à &Ø '§¡ô
 & g×&9Ñ&9¼4Ô@ð /6×.AÒ.Aó(á.A 
ô 5°Z×5JÑ5JÓ5LÕMØ.Aò(ð
  Ø$Ÿi™iñ
�Eð Ð(Ø).˜˜g™Ø"×)Ñ)¨%Ô0Ü˜w¨Ô1Ø6=·n±nÐ)¨(Ñ3Ø—<‘< 9Ó,à )Ø#*§?¡?Ø$Ÿi™iñ%�Mð
 Ð(Ø16˜ gÑ.Ø"×)Ñ)¨-Õ8ò5 *ð6 �[‰[˜OÒ+Ø"(×"3Ñ"3ÀÈFÐ"3Ó"SÐð Ð.Ñ.Ø/B×/FÑ/FÀxÓ/PÐ# GÑ,Ø×!Ñ!Ð"5Ô6ðÜ—z‘z &×"2Ñ"2¸5ÔA�Ø�ð ˆ}à'Ø"ŸK™KØ Ø Ÿ.™.ñ	�	ð ×!Ñ! )Ö,ð 0Ø"ŸK™KØ Ø Ÿ.™.Ø"ñ�	ð #×)Ñ)¨)Ö4Ø�[‰[Ð.Ò.Ø×!Ñ! &×"3Ñ"3ÀÈFÐ"3Ó"SÔTà#ØŸ™Ø! 6§<¡<Ð0Ø—n‘nñ	ˆIð ×Ñ˜iÖ(Ø�[‰[ð 
ó 
ð  ×!Ñ! &×"3Ñ"3ÀÈFÐ"3Ó"SÖTðk "ôL # 8Ó,€KàÐØÐ-Ñ-ÙØ�MŠMØ$ŸM™M×4Ñ4Ó6Ð6ˆ[Ð6Ø#Ÿ™¨°"Ó5Ð5ˆWÐ5Ø�[‰[˜Ó  MÒ1ð	ÜŸ*™* [Ó1ˆKÙÔ,¨VÔ4ÙÑ. +Ñ.‘à$�Ø*0Ð˜hÑ'ô ØØ�;‰;Ø%Ø+Ø+ØØ-ô€Gð ˜ÒÜ,¨WÓ5ˆä¤>¸'Ô#BÐ"CÔDÐDùóWùòZ(øô@ #ò Ø×'Ñ'�Ü˜A›–ûðûô^ ×#Ñ#ò 	Ùð	ús6   ÁQÅ QÉ#QÏ2Q: Ñ	Q7ÑQ2Ñ2Q7Ñ:RÒRc                óô   — t        | t        «      rddlm} 	  |j                  | «      S | S # t
        $ rB}t        j                  d| j                  d«      |«        |j                  di | ¤ŽcY d }~S d }~ww xY w)Nr   rs   zÍOpenAI Responses payload failed SDK validation (response id=%s); falling back to non-validating construct. This usually means the OpenAI API has drifted ahead of the installed `openai` package. Details: %sr—   rÌ   )
r·   rª   Úopenai.types.responsesrt   Úmodel_validater]   rŸ  r   r„   Úmodel_construct)Úresprt   r²   s      r~   Ú_coerce_chunk_responserÑ  ß  s{   € ä�$œÔÝ3ð	4Ø*�8×*Ñ*¨4Ó0Ð0ð €Køô ò 	4ô �N‰Nð:ð —‘˜“Øôð ,�8×+Ñ+Ñ3¨dÑ3Õ3ûð	4ús   ˜, ¬	A7µ7A2Á,A7Á2A7c           	     óŽ  ‡‡‡— d@dAˆˆˆfd„}|€d}g }	g }
i }|xs i }d|d<   d }d }d }| j                   dk(  r> || j                  | j                  «       |	j                  d| j                  ‰dœ«       �n
| j                   dk(  r‚ || j                  | j                  «       t        | j                  t        «      r| j                  }n| j                  j                  d	d
¬«      }|	j                  dt        |«      g‰dœ«       �ny| j                   dk(  r? || j                  | j                  «       |	j                  dd| j                  ‰dœ«       �n+| j                   dk(  r2t        | j                  «      }|j                  }|j                  |d<   �nê| j                   dk(  rGt        | j                  «      }t        |j                  xs d|j                  › d�«      }t!        |«      ‚| j                   dk(  r>| j"                  r| j"                  › d| j$                  › �n| j$                  }t!        |«      ‚| j                   dv r­t        | j                  «      }t'        t(        t+        |||¬«      j,                  d   j$                  «      }|j.                  j1                  d«      x}r||d<   |j2                  }|j4                  j7                  «       D ��ci c]  \  }}|dk7  sŒ||“Œ }}}d}�nŒ| j                   dk(  r|| j8                  j                   dk(  rc|dk(  r| j8                  j                  }�nGt;        | j8                  dd «      x}r+ || j                  d«       |	j                  dd|‰d œ«       �n�n| j                   dk(  �rR| j8                  j                   d!k(  �r8 || j                  «       |
j                  d"| j8                  j<                  | j8                  j>                  | j8                  j@                  ‰d#œ«       d!| j8                  j<                  | j8                  j>                  | j8                  j@                  | j8                  j                  ‰d$œ}t;        | j8                  d%d «      �| j8                  jB                  |d%<   t;        | j8                  d&d «      }|€t;        | j8                  d'd «      }|�||d'<   |	j                  |«       �nŸ| j                   d(k(  r_| j8                  j                   d)v rG || j                  «       | j8                  j                  d	d
¬«      }‰|d*<   |	j                  |«       �n1| j                   d(k(  rÈ| j8                  j                   d+k(  r¯ || j                  «       | j8                  j                  d	d
¬«      }‰|d*<   |	j                  |«       |
j                  d"| j8                  j<                  tE        jF                  d,| j8                  jH                  i«      | j8                  j@                  ‰d#œ«       �nZ| j                   d-k(  rR || j                  «       |
j                  d"| j                  ‰d.œ«       |	j                  d!| j                  ‰d/œ«       �nù| j                   d0k(  r |	j                  d1| jJ                  d2œ«       �nÊ| j                   dk(  rt| j8                  j                   d3k(  r[ || j                  «       dŠ| j8                  j                  d	d
¬«      }|jM                  d4d «       ‰|d*<   |	j                  |«       �nG| j                   d(k(  r�| j8                  j                   d3k(  rh| j8                  jN                  rR || j                  «       |	j                  d3| j8                  j                  g | j8                  jN                  ‰d5œ«       n·| j                   d6k(  rB || j                  «       |	j                  | jP                  d7dd8œg‰d3| j                  d9œ«       nf| j                   d:k(  rnV| j                   d;k(  rA || j                  «       |	j                  | jP                  d7| j                  d8œg‰d3d<œ«       n‰‰‰d fS tS        |	|
|||||¬=«      }|dk(  rt'        tR        tU        ||¬>«      «      }‰‰‰tW        |¬?«      fS c c}}w )BNc                óJ   •— |€‰| k7  r‰dz  Š| Šy‰| k7  s‰|k7  r‰dz  Š|Š| Šy)aò  Advance indexes tracked during streaming.

        Example: we stream a response item of the form:

        ```python
        {
            "type": "message",  # output_index 0
            "role": "assistant",
            "id": "msg_123",
            "content": [
                {"type": "output_text", "text": "foo"},  # sub_index 0
                {"type": "output_text", "text": "bar"},  # sub_index 1
            ],
        }
        ```

        This is a single item with a shared `output_index` and two sub-indexes, one
        for each content block.

        This will be processed into an `AIMessage` with two text blocks:

        ```python
        AIMessage(
            [
                {"type": "text", "text": "foo", "id": "msg_123"},  # index 0
                {"type": "text", "text": "bar", "id": "msg_123"},  # index 1
            ]
        )
        ```

        This function just identifies updates in output or sub-indexes and increments
        the current index accordingly.
        Nr¦  rÌ   )Ú
output_idxÚsub_idxr  r  r  s     €€€r~   Ú_advancez>_convert_responses_chunk_to_generation_chunk.<locals>._advance   sM   ø€ ðF ˆ?Ø# zÒ1Ø Ñ"�ð
  *Ñð %¨
Ò2Ð8IÈWÒ8TØ Ñ"�Ø 'ÐØ)Ñr€   r6  r+  rí  zresponse.output_text.deltar½   )r¼   r½   rù   z%response.output_text.annotation.addedTr   rÀ  )r¼   r   rù   zresponse.output_text.doner™   )r¼   r½   r—   rù   zresponse.createdr—   zresponse.failedz	Response z failed.rI  rF  )zresponse.completedzresponse.incomplete)rý  r�  r   rH  Úlastzresponse.output_item.addedrí   rÃ  r•  )r¼   r½   r•  rù   r›   r<   )r¼   r–   rú   r—   rù   )r¼   r–   rø   rƒ  r—   rù   Ú	namespacerÁ  r“   zresponse.output_item.done)r˜  r™  rš  r›  rÚ   r�  rž  rŸ  r¤  r   r¡  r¢  r£  rù   rœ  rÂ  z&response.function_call_arguments.delta)r¼   rú   rù   )r¼   rø   rù   zresponse.refusal.donerJ  r–  rq  r—  )r¼   r—   r‹  r—  rù   z%response.reasoning_summary_part.addedÚsummary_text)rù   r¼   r½   )r‹  rù   r¼   r—   z,response.image_generation_call.partial_imagez%response.reasoning_summary_text.delta)r‹  rù   r¼   )r6   rû   rè  rð  rŸ   r—   Úchunk_position)rÿ  rÄ  r‚   )rÔ  r  rÕ  rb  rÐ  rÓ  ),r¼   Úoutput_indexÚcontent_indexr«   rë  r·   rr  rª   r"  rt  r±  rÑ  r&  r—   r­   rI  rÐ   Úcoderí   r   r%   r.  r/  rŸ   r„   rè  rð  rë   r°  r7  r–   rø   rƒ  rØ  r   r  rb  rJ  r«  r—  Úsummary_indexr&   ro   rD   )rç  r  r  r  rý  rþ  rÿ  r�  rÖ  r6   rû   rŸ   rð  rè  rÚ  r—   rr  r&  Ú	error_msgrÓ   rH  rò   ró   r•  Úfunction_call_contentÚ
async_flagr  rq  rí   s    ```                         r~   r  r  ö  sæ  ú€ ÷**ð **ðX Ðð (ˆà€GØÐØ ÐØ š BÐØ*2ÐÐ&Ñ'Ø€NØ-1€NØ	€BØ‡z�zÐ1Ò1Ù�×#Ñ# U×%8Ñ%8Ô9Ø�‰ °·±ÀmÑTÖUØ	�‰Ð>Ò	>Ù�×#Ñ# U×%8Ñ%8Ô9Ü�e×&Ñ&¬Ô-à×)Ñ)‰Jà×)Ñ)×4Ñ4À$ÈVÐ4ÓTˆJà�‰àÜ 8¸Ó DÐEØ&ñö	
ð 
�‰Ð2Ò	2Ù�×#Ñ# U×%8Ñ%8Ô9Ø�‰àØØ—m‘mØ&ñ	ö	
ð 
�‰Ð)Ò	)Ü)¨%¯.©.Ó9ˆØ�[‰[ˆØ"*§+¡+Ð˜$ÓØ	�‰Ð(Ò	(Ü)¨%¯.©.Ó9ˆÜ˜Ÿ™ÒK¨I°h·k±k°]À(Ð*KÓLˆ	Ü˜Ó#Ð#Ø	�‰�wÒ	Ø8=¿
º
�u—z‘z�l " U§]¡] OÑ4ÈÏÉˆ	Ü˜Ó#Ð#Ø	�‰ÐDÑ	DÜ)¨%¯.©.Ó9ˆÜÜä7Ø V¸Nô÷ ‘˜Qñ ÷ ‘ó	
ˆð ×*Ñ*×.Ñ.¨xÓ8Ð8ˆ6Ð8Ø*0Ð˜hÑ'Ø×+Ñ+ˆà ×2Ñ2×8Ñ8Ô:ô
Ù:‘T�Q˜¸aÀ4»iˆAˆq‰DÐ:ð 	ñ 
ð  ŠØ	�‰Ð3Ò	3¸¿
¹
¿¹È9Ò8TØ˜TÒ!Ø—‘—‘ŠBÜ˜eŸj™j¨'°4Ó8Ð8ˆUÐ8Ù�U×'Ñ'¨Ô+Ø�N‰Nà"ØØ"Ø*ñ	öñ à�
‰
Ð2Ó2Ø�J‰J�O‰O˜Ó.á�×#Ñ#Ô$Ø×Ñà)ØŸ
™
Ÿ™ØŸ
™
×,Ñ,Ø—j‘j×(Ñ(Ø&ñô	
ð $Ø—J‘J—O‘OØŸ™×-Ñ-Ø—z‘z×)Ñ)Ø—*‘*—-‘-Ø"ñ'
Ðô �5—:‘:˜{¨DÓ1Ð=Ø16·±×1EÑ1EÐ! +Ñ.ä˜UŸZ™Z¨°4Ó8ˆ
ØÐÜ  §¡¨W°dÓ;ˆJØÐ!Ø-7Ð! 'Ñ*Ø�‰Ð,Ö-Ø	�‰Ð2Ò	2°u·z±z·±ð Kñ 8ñ 	�×#Ñ#Ô$Ø—j‘j×+Ñ+¸ÀFÐ+ÓKˆØ,ˆ�GÑØ�‰�{Ö#à�
‰
Ð1Ò1Ø�J‰J�O‰OÐ1Ò1á�×#Ñ#Ô$Ø—j‘j×+Ñ+¸ÀFÐ+ÓKˆØ,ˆ�GÑØ�‰�{Ô#Ø×Ñà)ØŸ
™
Ÿ™ÜŸ
™
 H¨e¯j©j×.>Ñ.>Ð#?Ó@Ø—j‘j×(Ñ(Ø&ñö	
ð 
�‰Ð?Ò	?Ù�×#Ñ#Ô$Ø×ÑØ&°·±ÀmÑTô	
ð 	�‰Ø$°5·;±;ÈÑWö	
ð 
�‰Ð.Ò	.Ø�‰ 	°e·m±mÑDÖEØ	�‰Ð3Ò	3¸¿
¹
¿¹È;Ò8VÙ�×#Ñ#Ô$ØÐØ—J‘J×)Ñ)°tÀ&Ð)ÓIˆ	ð 	�‰Ð)¨4Ô0Ø*ˆ	�'ÑØ�‰�yÖ!à�
‰
Ð1Ò1Ø�J‰J�O‰O˜{Ò*Ø�J‰J×(Ò(á�×#Ñ#Ô$Ø�‰à#Ø—j‘j—m‘mØØ%*§Z¡Z×%AÑ%AØ&ñõ	
ð 
�‰Ð>Ò	>Ù�×#Ñ#Ô$Ø�‰ð $×1Ñ1¸>ÐSUÑVðð 'Ø#Ø—m‘mñõ
	
ð 
�‰ÐEÒ	EàØ	�‰Ð>Ò	>Ù�×#Ñ#Ô$Ø�‰ð "'×!4Ñ!4Ø .Ø %§¡ñðð 'Ø#ñ
õ	
ð Ð2Ð4EÀtÐKÐKäØØ)Ø%Ø+Ø+ØØ%ô€Gð ˜ÒÜÜÜ& w¸mÔLó
ˆð 	ØØÜ GÔ,ð	ð ùóU
s   ËcË'c)rÐ  zhttpx.Client)r†   r­   rÐ  rr   )r®   úMapping[str, Any]rÐ  r'   )r¸   rS  r¹   rS  rÐ  rS  )r6   ústr | list[dict]rÐ  rã  )r•   rX  rÐ  rj  )r6   r   rÑ   r­   rÐ  rÓ  )rÖ   N)r6   r   rÝ   ú(Literal['chat/completions', 'responses']r•   rX  rÐ  r   )rÖ   )rí   r'   rÝ   rä  rÐ  rª   )r®   râ  rý   ztype[BaseMessageChunk]rÐ  r(   )r  ú
int | dictr  rå  rÐ  rå  )r²   zopenai.BadRequestErrorrÐ  rÓ  )r²   zopenai.APIErrorrÐ  rÓ  )r8  rS  r9  r   rÐ  rÓ  )r†   rX  rÐ  rj  )rû  r   rÐ  rj  )rñ   r2   rÐ  rª   )r  r/   rÐ  rª   )r  r­   rÐ  ztuple[int, int] | None)r  r  r  r  rÐ  r  )r$  r­   rÐ  rj  )r  r  r  r  rÐ  ztuple[int, int])rý  zdict[str, Any] | typer“  r`  rÐ  zdict | TypeBaseModel)r4  r%   rý  z	type[_BM]rÐ  zPydanticBaseModel | Noner‚   )rJ  rª   r‡  rX  rÐ  r9   )r§   rª   rÐ  rj  rÙ  )r
  rÛ  rÐ  z(tuple[Sequence[BaseMessage], str | None])r
  rÛ  r  rª   rÐ  rª   )rr  rS  rÐ  rS  )rÁ   rS  rÐ  rS  )r  r   rÐ  rã  )rí   r3   rÐ  rp  )rí   r3   rÐ  rÒ  )rÁ   rª   rÐ  rª   )r
  rÛ  rˆ  r`  rÐ  r¿   )r&  rt   rÐ  r­   )NNN)
r&  rt   rý  útype[_BM] | Nonerþ  rÒ  r�  rX  rÐ  rE   )rÐ  r   rÐ  r   )NNFN)rç  r   r  r  r  r  r  r  rý  ræ  rþ  rÒ  rÿ  rj  r�  rX  rÐ  z0tuple[int, int, int, ChatGenerationChunk | None])úr  Ú
__future__r   rà   r   ÚloggingrÃ  rô  Ússlrw  r  Úcollections.abcr   r   r   r   r   r	   Ú	functoolsr
   Úior   r   Úmathr   Úoperatorr   Útypingr   r   r   r   r   r   Úurllib.parser   Úcertifir+  rn  Úlangchain_core.callbacksr   r   Úlangchain_core.exceptionsr   r   r   r   r   r   r   r   r    Úlangchain_core.language_modelsr!   r"   Ú*langchain_core.language_models.chat_modelsr#   r$   Úlangchain_core.messagesr%   r&   r'   r(   r)   r*   r+   r,   r-   r.   r/   r0   r1   r2   r3   r4   r5   r6   ÚtypesÚlangchain_core.messages.air7   r8   r9   Ú0langchain_core.messages.block_translators.openair:   r;   Úlangchain_core.messages.toolr<   Úlangchain_core.output_parsersr=   r>   Ú*langchain_core.output_parsers.openai_toolsr?   r@   rA   rB   Úlangchain_core.outputsrC   rD   rE   Úlangchain_core.runnablesrF   rG   rH   rI   Úlangchain_core.runnables.configrJ   Úlangchain_core.toolsrK   Úlangchain_core.tools.baserL   Úlangchain_core.utilsrM   Úlangchain_core.utils._gatewayrN   rO   rP   Ú%langchain_core.utils.function_callingrQ   rR   Úlangchain_core.utils.pydanticrS   rT   rU   Úlangchain_core.utils.utilsrV   rW   rX   ÚpydanticrY   rZ   r[   r\   r]   r^   r_   Úpydantic.v1r¹  Útyping_extensionsr`   Úlangchain_openai._versionra   Ú*langchain_openai.chat_models._client_utilsrb   rc   rd   re   rf   rg   rh   ri   rj   rk   rl   Ú$langchain_openai.chat_models._compatrm   rn   ro   rp   Úlangchain_openai.data._profilesrq   r  rr   rÍ  rt   Ú	getLoggerr
  rŸ  Úcreate_default_contextÚwherer}   rv   rÞ  r   rƒ   rˆ   r�  rœ  r³   rº   rÃ   rÏ   rÊ   rÍ   rÔ   rç   rö   rÿ   r  r  r  r  r  r,  r  r-  r  r  r.  r  r/  r  r0  r  r2  r  r1  r!  r(  r4  r;  r>  r@  rA  rª   r­   r¼   rC  rD  rF  rå  r-  ré   rê   rŠ  r‹  r
  r  r  rž  r»  r¬   r1  rî  rR  rT  r²  r>  r?  rt  rv  r|  r€  r…  r‰  r�  rf  r¹  r.  rÑ  r  rÌ   r€   r~   Ú<module>r     s*  ðòõ #ã Û Û Û 	Û 	Û 
Û 
Û ÷÷ õ Ý Ý  Ý Ý ÷÷ õ "ã Û Û ÷÷
÷ 
õ 
÷÷÷÷ ÷ ÷ õ õ& 5÷ñ ÷
õ 9ß P÷ó ÷ SÑ R÷ó õ <Ý )Ý 0Ý 9÷ñ ÷
÷ñ ÷
 UÑ T÷÷ ñ õ 1Ý "å 1÷÷ ÷ ñ ÷ó õ 6áÛÝ;Ý/à	ˆ×	Ò	˜8Ó	$€ð 0�S×/Ò/°}°w·}²}³ÔGÐ à$(€Ð!Ó (óñ Ð+¨YÓ7€óð

€ð 6Ð ó@LðFØ ðØ3Aðàóó(ð2  2Ð Ø Nó.ó+ó"ð> 5GØðXØðXà	1ðXð ðXð 	ó	Xðz 5GðOØðOà	1ðOð 
óOðd52Øð52Ø-Cð52àó52ðpØ#ðØ0:ðàóô8L ×!7Ò!7Ð9Mô LôE F§O¢OÐ5Iô EôM × :Ò :Ð<Tô MôIØ
× Ò Ð"<ôIôJ × 6Ò 6Ð8Pô JôH˜v×3Ò3Ð5Gô HôI˜6×0Ò0Ð2Eô IôE�V×/Ò/°ô EôI˜F×5Ò5Ð7Kô IôF˜×/Ò/Ð1Bô Fó"óJ
ó>Jð Ð óXñ ˆe˜9Ô%€Ø"& s¨C x¡.°4¸±9Ñ"<¸tÑ"CÐ �iÓ CØ! C™Z€�Ó 'ôO!
�]ô O!
ôdBQ
�ô Q
óh*@óð
Ø&ð
à	ó
ó8óvóó&óð* =Añ%Ø!ð%Ø.9ð%àó%ðPØðØ(ðàóô@˜ô ð 7;ð/Øð/Ø)3ð/àó/ðf 7;ð+Øð+Ø)3ð+àó+ó\9óQðØ#ðà-óð2qØ#ðqØ.2ðqà	óqóhóðØðàóóD#ð.' Øð' àó' óTó*ð  >BñmØ#ðmØ/:ðmà	ómó`ð&  $Ø Ø!%ð	{EØð{Eàð{Eð ð{Eð ð	{Eð
 ó{Eó|ð8  $Ø ØØ!%ðiØðiàðið ðið ð	ið
 ðið ðið ðið ðið 6ôir€   