
    $h                      S r SSKJr  SSKrSSKrSSKrSSKrSSKrSSKrSSK	r	SSK
r
SSKJrJrJrJr  SSKJr  SSKJr  SSKJr  SSKJr  SS	KJr  SS
KJrJrJrJrJrJrJ r J!r!J"r"  SSK#J$r$  SSK%r%SSK&r&SSK'r'SSK(J)r)  SSK*J+r+J,r,  SSK-J.r.  SSK/J0r0J1r1J2r2J3r3  SSK4J5r5J6r6J7r7J8r8J9r9J:r:J;r;J<r<J=r=J>r>J?r?J@r@JArAJBrBJCrCJDrDJErEJFrF  SSKGJHrHJIrIJJrJ  SSKKJLrL  SSKMJNrNJOrO  SSKPJQrQJRrRJSrSJTrT  SSKUJVrVJWrWJXrX  SSKYJZrZJ[r[J\r\J]r]  SSK^J_r_  SSK`Jara  SSKbJcrc  SSKdJere  SSKfJgrgJhrh  SSKiJjrjJkrkJlrl  SSKmJnrnJoroJprp  SSKqJrrrJsrsJtrtJuruJvrv  SSKwJrrx  SS KyJzrz  SS!K{J|r|J}r}  SS"K~JrJr  \(       a  SS#KJr  \GR                  " \5      r\GR                  " \%GR                  " 5       S$9rS%rSPS& jrSQS' jrSRS( jr      SSS) jr      STS* jrSUS+ jr " S, S-\5      r\ " S.\rS/9r\!\\\4   \\   \4   r\!\\4   r " S0 S1\5      r " S2 S3\05      r " S4 S5\5      rSVS6 jrSWS7 jr    SXS8 jrSYS9 jrSZS: jrS[S; jrS[S< jrS\S= jrSS>.     S]S? jjr      S^S@ jr " SA SB\5      rS_SC jrS_SD jrS`SE jrSaSF jr    SbSG jr      ScSH jrSdSI jrSeSJ jrSfSK jrSgSL jrShSM jr   Si         SjSN jjr    Sk                 SlSO jjrg)mzOpenAI chat wrapper.    )annotationsN)AsyncIteratorIteratorMappingSequence)partial)BytesIO)JSONDecodeError)ceil)
itemgetter)	TYPE_CHECKINGAnyCallableLiteralOptional	TypedDictTypeVarUnioncast)urlparse)
deprecated)AsyncCallbackManagerForLLMRunCallbackManagerForLLMRun)LanguageModelInput)BaseChatModelLangSmithParamsagenerate_from_streamgenerate_from_stream)	AIMessageAIMessageChunkBaseMessageBaseMessageChunkChatMessageChatMessageChunkFunctionMessageFunctionMessageChunkHumanMessageHumanMessageChunkInvalidToolCallSystemMessageSystemMessageChunkToolCallToolMessageToolMessageChunkconvert_to_openai_data_blockis_data_content_block)InputTokenDetailsOutputTokenDetailsUsageMetadata)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)convert_to_openai_functionconvert_to_openai_tool)PydanticBaseModelTypeBaseModelis_basemodel_subclass)_build_model_kwargsfrom_envsecret_from_env)	BaseModel
ConfigDictField	SecretStrmodel_validator)rN   )Self)_get_default_async_httpx_client_get_default_httpx_client)_convert_from_v03_ai_message_convert_to_v03_ai_message)Response)cafile)file_searchweb_search_previewcomputer_use_previewcode_interpretermcpimage_generationc           
     <   U R                  S5      nU R                  S5      nU R                  S5      nUS:X  a  [        U R                  SS5      X2S9$ US:X  a  U R                  SS5      =(       d    Sn0 nU R                  S	5      =n(       a  [        U5      US	'   / n/ nU R                  S
5      =n	(       a'  XS
'   U	 H  n
 UR                  [	        U
SS95        M     U R                  S5      =n(       a  XS'   [        UUUUUUS9$ US;   a)  US:X  a  SU0nO0 n[        U R                  SS5      UUUS9$ US:X  a8  [        U R                  SS5      [        [        U R                  S5      5      US9$ US:X  aJ  0 nSU ;   a  U S   US'   [        U R                  SS5      [        [        U R                  S5      5      UUUS9$ [        U R                  SS5      XS9$ ! [
         a0  nUR                  [        U
[        U5      5      5         SnAGMW  SnAff = f)ztConvert a dictionary to a LangChain message.

Args:
    _dict: The dictionary.

Returns:
    The LangChain message.
rolenameidusercontent )re   rc   rb   	assistantfunction_call
tool_callsT)	return_idNaudio)re   additional_kwargsrb   rc   ri   invalid_tool_callssystem	developerrp   __openai_role__)re   rb   rc   rl   functionre   rb   rc   tooltool_call_id)re   ru   rl   rb   rc   re   ra   rc   )getr'   dictappendr:   	Exceptionr9   strr   r*   r%   r   r-   r#   )_dictra   rb   id_re   rl   rh   ri   rm   raw_tool_callsraw_tool_callerk   s                Y/var/www/html/shao/venv/lib/python3.13/site-packages/langchain_openai/chat_models/base.py_convert_dict_to_messager      sI    99VD99VD
))D/Cv~EIIi$<PP		 ))Ir*0b"$!IIo66=615m1Do.
"YY|44>4.<l+!/%%omt&TU "0 IIg&&5&).g&/!1
 	
 
(	(;!2D 9 "IIi,/	
 	
 
	IIi,4UYYv=N3OTW
 	
 
U?(-ff%IIi,c599^#<=/
 	
 599Y#;$OOS ! &--.}c!fE s   G!!
H+$HHc           	     \   U (       Ga  [        U [        5      (       Ga  / nU  GH  n[        U[        5      (       a  SU;   a  US   S;   a  M*  [        U[        5      (       a,  [        U5      (       a  UR	                  [        U5      5        Mk  [        U[        5      (       a  UR                  S5      S:X  a  UR                  S5      =n(       a  [        U[        5      (       a  UR                  S5      S:X  aO  UR                  S5      =n(       a7  UR                  S5      =n(       a  UR	                  SS	S
U SU 30S.5        GM&  UR                  S5      S	:X  a1  UR                  S	5      =n(       a  UR	                  SS	U0S.5        GMl  GMo  UR	                  U5        GM     U$ U nU$ )zFormat message content.type)tool_usethinkingreasoning_contentimagesourcebase64
media_typedata	image_urlurlzdata:z;base64,r   r   )
isinstancelistrx   r0   ry   r/   rw   )re   formatted_contentblockr   r   r   r   s          r   _format_message_contentr      s   :gt,,E 5$''eO&M%RRE4((-B5-I-I!(()Ee)LM 5$''IIf%0$yy22V2vt,,::f%1#)::l#;;Z;!'F!333%,,$/*/5HTF1S)T ZZ'50VZZ=N6Nc6N%,,!,E3<H !((/E L  $    c                   S[        U R                  5      0nU R                  =(       d    U R                  R	                  S5      =nb  X!S'   [        U [        5      (       a  U R                  US'   U$ [        U [        5      (       a  SUS'   U$ [        U [        5      (       Gad  SUS'   U R                  (       d  U R                  (       aO  U R                   Vs/ sH  n[        U5      PM     snU R                   Vs/ sH  n[        U5      PM     sn-   US'   OSU R                  ;   a\  U R                  S   US'   1 SknUS    VVVs/ sH.  nUR                  5        VVs0 sH  u  pgXd;   d  M  Xg_M     snnPM0     snnnUS'   O$S	U R                  ;   a  U R                  S	   US	'   O S	U;   d  SU;   a  US   =(       d    SUS'   S
U R                  ;   a/  U R                  S
   nSU;   a  SU R                  S
   S   0OUn	XS
'   U$ [        U [        5      (       a!  U R                  R	                  SS5      US'   U$ [        U [         5      (       a  SUS'   U$ [        U ["        5      (       aD  SUS'   U R$                  US'   1 Skn
UR                  5        VVs0 sH  u  pgXj;   d  M  Xg_M     nnnU$ ['        SU  35      es  snf s  snf s  snnf s  snnnf s  snnf )zvConvert a LangChain message to a dictionary.

Args:
    message: The LangChain message.

Returns:
    The dictionary.
re   rb   Nra   rd   rg   ri   >   rc   r   rr   rh   rk   rc   rq   ro   rr   rt   ru   >   ra   re   ru   zGot unknown type )r   re   rb   rl   rw   r   r#   ra   r'   r   ri   rm   !_lc_tool_call_to_openai_tool_call)_lc_invalid_tool_call_to_openai_tool_callitemsr*   r%   r-   ru   	TypeError)messagemessage_dictrb   tctool_call_supported_props	tool_callkv	raw_audiork   supported_propss              r   _convert_message_to_dictr      s    %./Fw/W#XLE 9 9 = =f EER#V ';''&||Vj i 
G\	*	*%Vf e 
GY	'	'*V!;!;@G@R@R*@R"1"5@R* "444B :"=4*L& W666)0)B)B<)PL&(B% ".l!;*!;I #,//"3V"3$!q7U"3V!;*L&  9 99 -4,E,Eo,VL)l*ll.J&29&=&EL#g///  11':I 9$ w009$?@ 
 %*!  
G]	+	+&88<<x 
V  
G_	-	-)V  
G[	)	)%V'.';';^$=)5););)=V)=AU)=V  +G9566]* W*F Ws6   K>K
K"
K0K6K
K)KKc           
        U R                  S5      n[        [        U R                  S5      5      n[        [        U R                  S5      =(       d    S5      n0 nU R                  S5      (       a#  [        U S   5      nSU;   a  US   c  SUS'   XeS'   / nU R                  S5      =n(       aV  XS'    U V	s/ sHE  n	[	        U	S   R                  S5      U	S   R                  S	5      U	R                  S5      U	S
   S9PMG     nn	US:X  d
  U[        :X  a	  [        XBS9$ US:X  d
  U[        :X  a  [        UUUUS9$ US;   d
  U[        :X  a  US:X  a  SS0nO0 n[        XBUS9$ US:X  d
  U[        :X  a  [        X@S   US9$ US:X  d
  U[        :X  a  [        X@S   US9$ U(       d
  U[        :X  a
  [        XCUS9$ U" XBS9$ s  sn	f ! [
         a     Nf = f)Nrc   ra   re   rf   rh   rb   ri   rr   	argumentsindex)rb   argsrc   r   rd   )re   rc   rg   )re   rl   rc   tool_call_chunksrn   rp   rq   )re   rc   rl   rs   rt   ru   )re   ru   rc   rv   )rw   r   r{   rx   r4   KeyErrorr(   r    r+   r&   r.   r$   )
r|   default_classr}   ra   re   rl   rh   r   r~   rtcs
             r   _convert_delta_to_message_chunkr   A  s    ))D/CUYYv&'D3		),23G yy!!U?34]"}V'<'D$&M&!-:/*<00~0*8,'	 *  *C  Z,,V4Z,,[9wwt}g,	 *    v~*;; 99		 ?/-	
 	
 
(	(M=O,O;!2K @ "!7H
 	
 
	}0DD#G-CPP	=,<<*?C
 	
 
"22sCCW55M   		s%   3G  7AF;G  ;G   
GGc                   [        U[        5      (       a<  [        U [        5      (       d#  [        S[        U5       S[        U 5       35      eX-   $ [        U[        5      (       aw  [        U [        5      (       d#  [        S[        U5       S[        U 5       35      eUR                  5        VVs0 sH"  u  p#U[        U R                  US5      U5      _M$     snn$ [        R                  " S[        U5       35        U$ s  snnf )Nz%Got different types for token usage: z and r   z!Unexpected type for token usage: )
r   int
ValueErrorr   rx   r   _update_token_usagerw   warningswarn)overall_token_usage	new_usager   r   s       r   r   r   z  s   
 )S!!-s337	?#5.A)B(CE  ..	It	$	$-t447	?#5.A)B(CE  ")
) "#6#:#:1a#@!DD)
 	

 	9$y/9JKL
s   2(Dc                    SU R                   ;   a  Sn[        R                  " U5        U eSU R                   ;   a  Sn[        R                  " U5        U ee )NzH'response_format' of type 'json_schema' is not supported with this modelzThis 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   s     r   _handle_openai_bad_requestr     s[    R	
3 	 	g	-	:[ 	 	gr   c                       \ rS rSr% S\S'   Srg)_FunctionCalli  r{   rb    N__name__
__module____qualname____firstlineno____annotations____static_attributes__r   r   r   r   r     s    
Ir   r   _BM)boundc                  4    \ rS rSr% S\S'   S\S'   S\S'   Srg	)
_AllReturnTypei  r!   rawzOptional[_DictOrPydantic]parsedzOptional[BaseException]parsing_errorr   Nr   r   r   r   r   r     s    	%%**r   r   c                    ^  \ rS rSr% \" SSS9rS\S'   \" SSS9rS\S'   \" SSS9rS\S'   \" SSS9r	S\S	'   \" S
SS9r
S\S'    SrS\S'    \" \S9rS\S'    \" S\" SSS9S9rS\S'   \" SSS9rS\S'    \" SSS9rS\S'    \" \" SSS9S9rS\S '   \" SS!S9rS"\S#'    S$rS%\S&'    SrS'\S('    SrS\S)'    SrS\S*'    SrS'\S+'    SrS,\S-'    SrS'\S.'    SrS/\S0'    S$rS%\S1'    SrS'\S2'    SrS\S3'    \" SS9r S'\S4'    Sr!S\S5'    Sr"S6\S7'    Sr#S\S8'    Sr$S\S9'    Sr%S:\S;'   Sr&S<\S='   \" SSS9r'S>\S?'    \" SSS9r(S>\S@'    \" SSAS9r)SB\SC'    Sr*SD\SE'    S$r+S%\SF'    \" SS9r,S6\SG'    Sr-SH\SI'    Sr.S\SJ'    Sr/S,\SK'    Sr0S\SL'    S$r1S%\SM'    Sr2S,\SN'    SOr3SP\SQ'    \4" SSR9r5\6" SSST9\7S|SU j5       5       r8\6" SSST9\7S|SV j5       5       r9\6" SWST9S}SX j5       r:\;S~SY j5       r<SSZ jr=        SS[ jr>  S         SS\ jjr?  S         SS] jjr@ S     SS^ jjrA  SSS_.           SS` jjjrB  S         SSa jjrCSSb jrDSSc.       SSd jjrE S     SSe jjrF  SSS_.           SSf jjjrG  S         SSg jjrH\;S~Sh j5       rI S     SU 4Si jjjrJ S     SSj jjrK\;SSk j5       rLSSl jrMSU 4Sm jjrN S     SU 4Sn jjjrO\P" SoSpSqSr9 S       SU 4Ss jjj5       rQSSSSt.           SU 4Su jjjrR SSvS$SSSw.             SSx jjjrSSSy jrT    SSz jrUS{rVU =rW$ )BaseChatOpenAIi  NT)defaultexcluder   clientasync_clientroot_clientroot_async_clientgpt-3.5-turbomodelr   aliasr{   
model_namezOptional[float]temperature)default_factorydict[str, Any]model_kwargsapi_keyOPENAI_API_KEY)r   )r   r   zOptional[SecretStr]openai_api_keybase_urlzOptional[str]openai_api_baseorganizationopenai_organizationOPENAI_PROXYopenai_proxytimeoutz,Union[float, tuple[float, float], Any, None]request_timeoutFboolstream_usageOptional[int]max_retriespresence_penaltyfrequency_penaltyseedOptional[bool]logprobstop_logprobszOptional[dict[int, int]]
logit_bias	streamingntop_p
max_tokensreasoning_effortzOptional[dict[str, Any]]	reasoning	verbositytiktoken_model_namezUnion[Mapping[str, str], None]default_headersz!Union[Mapping[str, object], None]default_queryzUnion[Any, None]http_clienthttp_async_clientstop_sequenceszOptional[Union[list[str], str]]stopzOptional[Mapping[str, Any]]
extra_bodyinclude_response_headersdisabled_paramsOptional[list[str]]includeservice_tierstore
truncationuse_previous_response_iduse_responses_apiv0Literal['v0', 'responses/v1']output_version)populate_by_namebefore)modec                2    [        U 5      n[        X5      nU$ )z>Build extra kwargs from additional params that were passed in.)rE   rK   )clsvaluesall_required_field_namess      r   build_extraBaseChatOpenAI.build_extra  s     $<C#@ $VFr   c                0   UR                  S5      =(       d    UR                  S5      =(       d    SnUR                  S5      (       a  SU;  a  SUS'   UR                  S5      (       a,  UR                  S5      nUb  US:w  a  UR                  SS5        U$ )	zValidate temperature parameter for different models.

- o1 models only allow temperature=1
- gpt-5 models only allow temperature=1 or unset (defaults to 1)
r   r   rf   o1r      gpt-5N)rw   
startswithpop)r  r  r   r   s       r   validate_temperature#BaseChatOpenAI.validate_temperature  s     

<(EFJJw,?E2 D!!m6&A$%F=! G$$ **]3K&;!+;

=$/r   afterc                Z   U R                   b  U R                   S:  a  [        S5      eU R                   b,  U R                   S:  a  U R                  (       a  [        S5      eU R                  =(       d3    [        R
                  " S5      =(       d    [        R
                  " S5      U l        U R                  =(       d    [        R
                  " S5      U l        U R                  (       a  U R                  R                  5       OSU R                  U R                  U R                  U R                  U R                  S.nU R                  b  U R                  US	'   U R                  (       a]  U R                  (       d  U R                  (       a;  U R                  nU R                  nU R                  n[        S
U< SU< SU< 35      eU R                   (       d  U R                  (       a9  U R                  (       d(   SSKnUR'                  U R                  [(        S9U l        SU R                  =(       d     [+        U R                  U R                  5      0n[,        R.                  " S0 UDUD6U l        U R0                  R2                  R4                  U l        U R6                  (       d  U R                  (       a9  U R                  (       d(   SSKnUR9                  U R                  [(        S9U l        SU R                  =(       d     [;        U R                  U R                  5      0n[,        R<                  " S0 UDUD6U l        U R>                  R2                  R4                  U l        U $ ! [$         a  n[%        S5      UeSnAff = f! [$         a  n[%        S5      UeSnAff = f)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_ORGANIZATIONOPENAI_API_BASE)r   r   r   r   r   r   r   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=r   zRCould not import httpx python package. Please install it with `pip install httpx`.)proxyverifyr   r   ) r   r   r   r   osgetenvr   r   get_secret_valuer   r   r   r   r   r   r   r   httpxImportErrorClientglobal_ssl_contextrU   openaiOpenAIr   chatcompletionsr   AsyncClientrT   AsyncOpenAIr   )	selfclient_paramsr   r   r   r&  r   sync_specificasync_specifics	            r   validate_environment#BaseChatOpenAI.validate_environment  s5    66$&&1*455VVDFFQJ4>>:;; $$ 0yy)0yy./ 	 
  $33SryyAR7S ;?:M:M##446SW 44,,++#33!//	
 '+/+;+;M-($"2"2d6L6L,,L**K $ 6 6!/K>1F4E3GI 
 {{  )9)9  $)<<++4F $0 $  t//  Y,T-A-A4CWCWXM  &}}N}NND**//;;DK    )?)?  */):):++4F *; *& t55  2(($*>*>N &,%7%7 && &D" !% 6 6 ; ; G GDK # %F $ # %F s0   ?M1 N 1
N;NN
N*N%%N*c                   0 SU R                   _SU R                  _SU R                  _SU R                  _SU R                  _SU R
                  _SU R                  _SU R                  =(       d    S	_S
U R                  _SU R                  _SU R                  _SU R                  _SU R                  _SU R                  _SU R                  _SU R                  _SU R                   _U R"                  U R$                  S.EnU R&                  U R(                  S.UR+                  5        VVs0 sH  u  p#Uc  M
  X#_M     snnEU R,                  EnU$ s  snnf )2Get the default parameters for calling OpenAI API.r   r   r   r   r   r   r   r   Nr   r   r   r   r   r   r   r  r  )r  r  )r   stream)r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r  r  r  r  r   r   r   r   )r0  exclude_if_noner   r   paramss        r   _default_paramsBaseChatOpenAI._default_params0  s   
 5 5
!7!7
 DII
 TZZ	

 
 D--
 $//
 DII%
 $//
 $//
 
 4++
  5 5
 
 
  t||!
" D--#
$ //ZZ'
. __nn
 !0 5 5 7I 71tqt 7I
 	
 	 Js   -E9Ec                "   0 nS nU Hk  nUc  M  UR                  S5      nUb9  UR                  5        H%  u  pgUc  M
  Xb;   a  [        X&   U5      X&'   M!  XrU'   M'     Ub  MZ  UR                  S5      nMm     X R                  S.nU(       a  X8S'   U$ )Ntoken_usagesystem_fingerprint)r>  r   )rw   r   r   r   )	r0  llm_outputsr   r?  outputr>  r   r   combineds	            r   _combine_llm_outputs#BaseChatOpenAI._combine_llm_outputsR  s    $&!!F~ **]3K&'--/DAy /1D/2A2+. 23A. 0 ")%+ZZ0D%E"! "" $7ooV-?)*r   c                   UR                  S5      S:X  a  g UR                  S5      nUR                  S/ 5      =(       d"    UR                  S0 5      R                  S/ 5      nU(       a  [        U5      OS n[        U5      S:X  a  [        U" SUS9US	9nU$ US   nUS
   c  g [	        US
   U5      n	U(       a  0 UEO0 n
UR                  S5      =n(       aX  XS'   UR                  S5      =n(       a  XS'   UR                  S5      =n(       a  XS'   UR                  S5      =n(       a  XS'   UR                  S5      nU(       a  XS'   U(       a  [        U	[        5      (       a  Xil        [        X=(       d    S S	9nU$ )Nr   zcontent.deltausagechoiceschunkr   rf   )re   usage_metadatar   generation_infodeltafinish_reasonr   r   r?  r  r   )rw   _create_usage_metadatalenr<   r   r   r    rI  )r0  rH  default_chunk_classbase_generation_infor>  rG  rI  generation_chunkchoicemessage_chunkrK  rM  r   r?  r  r   s                   r   "_convert_chunk_to_generation_chunk1BaseChatOpenAI._convert_chunk_to_generation_chunkk  s    99V/ii(IIi$ 9yy"%)))R8 	 4?";/D 	 w<12+B~V 4  $#'?"77O0
 7K212PR"JJ77=7/<O,"YYw//z/0:-%*YY/C%DD!D8J 45$yy88|82>/::j)*2J'jGG+9(.!3Jd
  r   c              +    #    SUS'   U R                   " U4SU0UD6nU R                  (       aX  U R                  R                  R                  R
                  " S0 UD6nUR                  5       nS[        UR                  5      0nO(U R                  R                  R
                  " S0 UD6n0 nUR                  S5      n	U n
SnSnSnSnSnU
 Hy  nU(       a  UO0 n[        UUUUU	UUU R                  S9u  nnnnU(       d  M6  U(       a  UR                  UR                  US	9  SnS
UR                  R                  ;   a  SnUv   M{     S S S 5        g ! , (       d  f       g = f7fNTr8  r   headersresponse_formatF)schemametadatahas_reasoningr
  rH  r   r   )_get_request_payloadr   r   with_raw_response	responsescreateparserx   rY  rw   ,_convert_responses_chunk_to_generation_chunkr
  on_llm_new_tokentextr   rl   r0  messagesr   run_managerkwargspayloadraw_context_managercontext_managerrY  original_schema_objresponseis_first_chunkcurrent_indexcurrent_output_indexcurrent_sub_indexr^  rH  r]  rR  s                      r   _stream_responses BaseChatOpenAI._stream_responses  s      x++HJ4J6J(("&"2"2"D"D"N"N"U"U ## 2779O $':'B'B"CDG"..88??J'JOG$jj):;!NM#%  "!M!&47" A!(%.%"/#'#6#6	!(%$ $#"#44,119I 5  &+N"&6&>&>&P&PP(,**3 " __s%   B?E%?EAE	E%
E"E%c               T  #    SUS'   U R                   " U4SU0UD6nU R                  (       a`  U R                  R                  R                  R
                  " S0 UD6I S h  vN nUR                  5       nS[        UR                  5      0nO0U R                  R                  R
                  " S0 UD6I S h  vN n0 nUR                  S5      n	U IS h  vN n
SnSnSnSnSnU
  S h  vN nU(       a  UO0 n[        UUUUU	UUU R                  S9u  nnnnU(       d  M<  U(       a"  UR                  UR                  US	9I S h  vN   SnS
UR                  R                  ;   a  SnU7v   M   GN N N N N2
 S S S 5      IS h  vN    g ! , IS h  vN  (       d  f       g = f7frX  )r`  r   r   ra  rb  rc  rd  rx   rY  rw   re  r
  rf  rg  r   rl   rh  s                      r   _astream_responses!BaseChatOpenAI._astream_responses  s      x++HJ4J6J((,,>>HHOO    
 2779O $':'B'B"CDG$($:$:$D$D$K$K$Vg$VVOG$jj):;"?h!NM#%  "!M' +e&47" A!(%.%"/#'#6#6	!(%$ $#")::,119I ;    &+N"&6&>&>&P&PP(,**U W #+&'  ( #?????s   AF(!E0"AF(7E38F(E5F(F&E;*E7+E;.0F"$FE9)F0F(3F(5F(7E;9F;F<F(F
F(F%FF%!F(c                   UUR                  S0 5      R                  S5      U R                  R                  S0 5      R                  S5      U R                  /nU H  n[        U[        5      (       d  M  Us  $    U R                  $ )zDetermine 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_usage)rw   r   r   r   r   )r0  r   rk  stream_usage_sourcesr   s        r   _should_stream_usage#BaseChatOpenAI._should_stream_usage  s     JJ',00A!!"2B7;;OL	 
 +F&$'' +    r   )r   c             +  8  #    SUS'   U R                   " U40 UD6nU(       a  SU0US'   U R                  " U4SU0UD6n[        n0 nSU;   au  U R                  (       a  [        R
                  " S5        UR                  S5        U R                  R                  R                  R                  R                  " S0 UD6n	U	n
O}U R                  (       aN  U R                  R                  R                  " S0 UD6nUR                  5       nS[!        UR"                  5      0nOU R                  R                  " S0 UD6nUn
 U
 nSnU H  n[%        U[         5      (       d  UR'                  5       nU R)                  UUU(       a  UO0 5      nUc  MI  UR*                  R,                  nUR.                  =(       d    0 R1                  S	5      nU(       a  UR3                  UR4                  UUS
9  SnUv   M     S S S 5        [=        WS5      (       aN  SU;   aG  UR?                  5       nU RA                  U5      nU(       a  UR3                  UR4                  US9  Uv   g g g ! , (       d  f       Nn= f! [6        R8                   a  n[;        U5         S nANS nAff = f7fNTr8  r|  r{  r   rZ  LCannot currently include response headers when response_format is specified.rY  r   )rH  r   Fget_final_completionr_  r   )!r~  r`  r    r   r   r   r  r   betar,  r-  r8  r   ra  rc  rd  rx   rY  r   
model_dumprU  r   	__class__rK  rw   rf  rg  r*  BadRequestErrorr   hasattrr  %_get_generation_chunk_from_completionr0  ri  r   rj  r   rk  rl  rP  rQ  response_streamrn  raw_responserp  rq  rH  rR  r   r   final_completions                      r   _streamBaseChatOpenAI._stream"  s      x00HH(7'FF#$++HJ4J6J6D!',,! KK!"..3388DDKKVgVO-O,,#{{<<CCNgN'--/(148L8L3M'N$;;--88&O	* H!%%E%eT22 % 0 0 2'+'N'N+0>,B($
 (/ *:*B*B*L*L' 0 @ @ FBKKJWH"#44,11"2%- 5 
 &+N**' & !0 83449Jg9U'<<>#II   ,,$))1A -  #" :V41 !, %% 	*&q))	*sV   D<J?I. B4I5I. =A J
I+'I. *J+I. .JJJJJc                   U R                   (       a   U R                  " U4X#S.UD6n[        U5      $ U R                  " U4SU0UD6nS nSU;   au  U R                  (       a  [
        R                  " S5        UR                  S5         U R                  R                  R                  R                  R                  " S0 UD6nGOU R!                  U5      (       a  UR#                  S5      n
U
(       a7  [%        U
5      (       a'  U R                  R&                  R                  " S0 UD6nOU R                  (       aX  U R                  R(                  R&                  R*                  " S0 UD6nUR                  5       nS[-        UR.                  5      0nO&U R                  R&                  R*                  " S0 UD6n[1        UU
UU R2                  S9$ U R                  (       aN  U R4                  R(                  R*                  " S0 UD6nUR                  5       nS[-        UR.                  5      0nOU R4                  R*                  " S0 UD6nU R7                  WU5      $ ! [        R                   a  n	[        U	5         S n	A	N6S n	A	ff = f	N)r   rj  r   rZ  r  r8  rY  )r\  r]  r
  r   )r   r  r   r`  r   r   r   r  r   r  r,  r-  rd  r*  r  r   _use_responses_apirw   _is_pydantic_classrb  ra  rc  rx   rY  '_construct_lc_result_from_responses_apir
  r   _create_chat_resultr0  ri  r   rj  rk  stream_iterrl  rK  rp  r   ro  r  s               r   	_generateBaseChatOpenAI._generateh  s7    >>,,#@FK (44++HJ4J6J',,! KK!.++0055AAGGR'R $$W--"(**->"?"'9:M'N'N++55;;FgF00#'#3#3#E#E#O#O#V#V $!$L  ,113H'0$|7K7K2L&MO#//99@@K7KH:*(#22	  **;;88??J'JL#))+H($|/C/C*DEO{{))4G4H''/BB7 )) .*1--.s   :I J/I??Jc                   [        U R                  [        5      (       a  U R                  $ U R                  S:X  a  gU R                  b  gU R
                  b  gU R                  b  gU R                  (       a  g[        U5      $ )Nzresponses/v1T)	r   r  r   r
  r  r   r  r  r  )r0  rl  s     r   r  !BaseChatOpenAI._use_responses_api  sp    d,,d33)))  N2\\%^^'__(**%g..r   r   c                  U R                  U5      R                  5       nUb  X#S'   0 U R                  EUEnU R                  U5      (       aO  U R                  (       a0  [        U5      u  pgU(       a  UOUnU(       a  XuS'   [        X5      nU$ [        XE5      n U$ U V	s/ sH  n	[        U	5      PM     sn	US'   U$ s  sn	f )Nr   previous_response_idri  )_convert_inputto_messagesr;  r  r  _get_last_messages _construct_responses_api_payloadr   )
r0  input_r   rk  ri  rl  last_messagesr  payload_to_usems
             r   r`  #BaseChatOpenAI._get_request_payload  s     &&v.::<!6N4T))4V4""7++,,6H6R32FH'6J23:>S
  ;8M  IQ"Q1#;A#>"QGJ #Rs    B<c                   / n[        U[        5      (       a  UOUR                  5       nUR                  S5      (       a  [	        UR                  S5      5      e US   nUc  [        S5      eUR                  S5      nU H  n[        US   5      n	U(       a%  [        U	[        5      (       a  [        U5      U	l        U=(       d    0 nUR                  S5      b  UR                  S5      OUR                  S5      US'   SU;   a  US   US'   [        XS	9n
UR                  U
5        M     UUR                  S
U R                  5      UR                  SS5      S.nSU;   a  US   US'   SU;   a  US   US'   [        U[        R                   5      (       a  [#        USS 5      (       a  UR$                  S   R&                  n	[)        U	S5      (       a&  U	R*                  US   R&                  R,                  S'   [)        U	S5      (       a&  U	R.                  US   R&                  R,                  S'   [1        X;S9$ ! [
         a"  n[        SUR                  5        35      UeS nAff = f)NerrorrG  z Response missing `choices` key: z0Received response with null value for `choices`.rF  r   rM  r   rJ  r   r?  rf   )r>  r   r?  rc   r  r   r   refusal)generations
llm_output)r   rx   r  rw   r   r   keysr   r   r   rN  rI  r;   ry   r   r*  rN   getattrrG  r   r  r   rl   r  r=   )r0  rp  rK  r  response_dictrG  r   r>  resr   genr  s               r   r  "BaseChatOpenAI._create_chat_result  sa   
  #8T22H8K8K8M 	 W%%]..w788	#I.G ?NOO#''0C.s9~>Gz'9==)?)L&-3O 77?+7 ($((9 O,
 S .1*o
+ RCs#  ''++GT__E"/"3"34H""M


 = ,T2Jt]*)6~)FJ~&h 0 011gi7
 7
 &&q)11Gw))EL^^A&&88Bw	**FMooA&&88CkIIW  	2=3E3E3G2HI	s   H9 9
I%I  I%c                #    SUS'   U R                   " U40 UD6nU(       a  SU0US'   U R                  " U4SU0UD6n[        n0 nSU;   au  U R                  (       a  [        R
                  " S5        UR                  S5        U R                  R                  R                  R                  R                  " S0 UD6n	U	n
OU R                  (       aV  U R                  R                  R                  " S0 UD6I S h  vN nUR                  5       nS[!        UR"                  5      0nO$U R                  R                  " S0 UD6I S h  vN nUn
 U
 IS h  vN nSnU  S h  vN n[%        U[         5      (       d  UR'                  5       nU R)                  UUU(       a  UO0 5      nUc  MO  UR*                  R,                  nUR.                  =(       d    0 R1                  S	5      nU(       a#  UR3                  UR4                  UUS
9I S h  vN   SnU7v   M   GN N N N N
 S S S 5      IS h  vN    OF! , IS h  vN  (       d  f       O/= f! [6        R8                   a  n[;        U5         S nAOS nAff = f[=        WS5      (       aa  SU;   aZ  UR?                  5       I S h  vN  nU RA                  U5      nU(       a#  UR3                  UR4                  US9I S h  vN    U7v   g g g 7fr  )!r~  r`  r    r   r   r   r  r   r  r,  r-  r8  r   ra  rc  rd  rx   rY  r   r  rU  r   r  rK  rw   rf  rg  r*  r  r   r  r  r  r  s                      r   _astreamBaseChatOpenAI._astream  s      x00HH(7'FF#$++HJ4J6J6D!',,! KK!"4499>>JJQQ O .O,,%)%6%6%H%H%O%O &&   (--/(148L8L3M'N$!%!2!2!9!9!DG!DD&O	*&(!%#+ +%%eT22 % 0 0 2'+'N'N+0>,B($
 (/ *:*B*B*L*L' 0 @ @ FBKKJWH")::,11"2%- ;   
 &+N**=  E '+ $, ', %% 	*&q))	*83449Jg9U%-%B%B%DDD#II   !22$))1A 3    #" :V4s   C9K1;H<AK1HK1I HI H8H%"H!#H%&B&H8H#H8K1K1I !H%#H8%H8&I 1H42I 7K18I>I?II K1I I;&I61K16I;;-K1(J+):K1#K&$K1c                  #    U R                   (       a(  U R                  " U4X#S.UD6n[        U5      I S h  vN $ U R                  " U4SU0UD6nS nSU;   a}  U R                  (       a  [
        R                  " S5        UR                  S5         U R                  R                  R                  R                  R                  " S0 UD6I S h  vN nGOU R!                  U5      (       Ga  UR#                  S5      n
U
(       a?  [%        U
5      (       a/  U R                  R&                  R                  " S0 UD6I S h  vN nOU R                  (       a`  U R                  R(                  R&                  R*                  " S0 UD6I S h  vN nUR                  5       nS[-        UR.                  5      0nO.U R                  R&                  R*                  " S0 UD6I S h  vN n[1        UU
UU R2                  S9$ U R                  (       aV  U R4                  R(                  R*                  " S0 UD6I S h  vN nUR                  5       nS[-        UR.                  5      0nO$U R4                  R*                  " S0 UD6I S h  vN n[7        S U R8                  WU5      I S h  vN $  GNm GN! [        R                   a  n	[        U	5         S n	A	NJS n	A	ff = f GN GNQ N N N` NB7fr  )r   r  r   r`  r   r   r   r  r   r  r,  r-  rd  r*  r  r   r  rw   r  rb  ra  rc  rx   rY  r  r
  r   rB   r  r  s               r   
_agenerateBaseChatOpenAI._agenerateQ  s     >>--#@FK /{;;;++HJ4J6J',,! KK!.!%!7!7!<!<!A!A!M!M!S!S "" 
 $$W--"(**->"?"'9:M'N'N!%!7!7!A!A!G!G!R'!RR00"44FFPPWW %  !
  ,113H'0$|7K7K2L&MO%)%;%;%E%E%L%L%Ww%WWH:*(#22	  **!%!2!2!D!D!K!K!Vg!VVL#))+H($|/C/C*DEO!..55@@@H$$**Ho
 
 	
W < )) .*1--.
 S  X W A
s   5K$J$AK$=J* J'J* A*K$>K?A	K$K	AK$KAK$3K4AK$?K  K$K" K$'J* *K>K	K$KK$K$K$K$ K$"K$c                6    SU R                   0U R                  E$ )zGet the identifying parameters.r   )r   r;  r0  s    r   _identifying_params"BaseChatOpenAI._identifying_params  s     dooF1E1EFFr   c                \  > SU R                   0[        TU ]	  US9EU R                  EUEnUR	                  S5      =n(       ad  [        U[        5      (       aO  U Vs/ sH?  n[        U[        5      (       a%  UR	                  S5      S:X  a  SU;   a  0 UESS0EOUOUPMA     snUS'   U$ s  snf )z,Get the parameters used to invoke the model.r   r  toolsr   r^   rY  z**REDACTED**)r   super_get_invocation_paramsr;  rw   r   r   rx   )r0  r   rk  r:  r  rt   r  s         r   r  %BaseChatOpenAI._get_invocation_params  s    
 T__
g,$,7
 ""
 	
 ZZ((E(j.E.E
 "	 "D dD))dhhv.>%.G 9BT8I4D4)^4t "	F7O s   AB)c           	     n   U R                   " SSU0UD6n[        SU R                  SUR                  SU R                  5      S9nUR                  SU R
                  5      =(       d    UR                  SU R
                  5      =n(       a  XTS'   U=(       d    UR                  SS	5      =n(       a  XdS
'   U$ )z Get standard params for tracing.r   r*  r,  r   )ls_providerls_model_namels_model_typels_temperaturer   max_completion_tokensls_max_tokensNls_stopr   )r  r   r   rw   r   r   )r0  r   rk  r:  	ls_paramsr  r  s          r   _get_ls_paramsBaseChatOpenAI._get_ls_params  s     ,,A$A&A# // !::mT5E5EF	
	 #JJ|T__E 
#T__J
 
= 
 *7o&6fjj6676#*i r   c                    g)zReturn type of chat model.zopenai-chatr   r  s    r   	_llm_typeBaseChatOpenAI._llm_type  s     r   c                   U R                   b  U R                   nOU R                  n [        R                  " U5      nX4$ ! [         a    SnU R                  R                  S5      (       d@  U R                  R                  S5      (       d   U R                  R                  S5      (       a  Sn[        R                  " U5      n X4$ f = f)Ncl100k_basezgpt-4ozgpt-4.1r  
o200k_base)r   r   tiktokenencoding_for_modelr   r  get_encoding)r0  r   encodingencoders       r   _get_encoding_model"BaseChatOpenAI._get_encoding_model  s    ##/,,EOOE
	62259H   	6#G**844??--i88??--g66&,,W5H	6s   A BC
	C
c                   > U R                   b  U R                  U5      $ [        R                  S   S::  a  [        TU ]  U5      $ U R                  5       u  p#UR                  U5      $ )z9Get the tokens present in the text with tiktoken package.r     )custom_get_token_idssysversion_infor  get_token_idsr  encode)r0  rg  _encoding_modelr  s       r   r  BaseChatOpenAI.get_token_ids  se    $$0,,T22A!#7(.. 446$$T**r   c           
     P  > Ub  [         R                  " S5        [        R                  S   S::  a  [        TU ]  U5      $ U R                  5       u  p4UR                  S5      (       a  SnSnOVUR                  S5      (       d,  UR                  S5      (       d  UR                  S	5      (       a  S
nSnO[        SU S35      eSnU Vs/ sH  n[        U5      PM     n	nU	 GH  n
Xu-  nU
R                  5        GH  u  pUS:X  a  US
-  nM  [        U[        5      (       Ga2  U GH*  n[        U[        5      (       d	  US   S:X  a;  [        U[        5      (       a  US   OUnU[        UR!                  U5      5      -  nM]  US   S:X  aF  US   R#                  S5      S:X  a  US-  nM  [%        US   S   5      nU(       d  M  U['        U6 -  nM  US   S:X  aH  U[        UR!                  US   S   5      5      -  nU[        UR!                  US   S   5      5      -  nM  US   S:X  a  [         R                  " S5        GM  [)        SU 35      e   O0U(       d  GMe  U[        UR!                  [        U5      5      5      -  nUS:X  d  GM  Xv-  nGM     GM     US
-  nU$ s  snf )a  Calculate num tokens for ``gpt-3.5-turbo`` and ``gpt-4`` with ``tiktoken`` package.

**Requirements**: 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 BaseTools
        to be converted to tool schemas.
zECounting tokens in tool schemas is not yet supported. Ignoring tools.r  r  zgpt-3.5-turbo-0301   r[  r   gpt-4r     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   ru   r   rg  r   detaillowU   r   rr   r   rb   filezEToken counts for file inputs are not supported. Ignoring file inputs.z!Unrecognized content block type

)r   r   r  r  r  get_num_tokens_from_messagesr  r  NotImplementedErrorr   r   r   r   r{   rx   rO  r  rw   _url_to_size_count_image_tokensr   )r0  ri  r  r   r  tokens_per_messagetokens_per_name
num_tokensr  messages_dictr   keyvaluevalrg  
image_sizer  s                   r   r  +BaseChatOpenAI.get_num_tokens_from_messages  s   . MMW A!#77AA224011!" O_--((((!"O%"G $LL  
>FGh1!4hG$G,J%mmo
 .(!OJeT**$%c3//3v;&3H2<S$2G2G3v;SD&#hood.C*DDJ [K7";/33H=F *b 0
-9#k:J5:Q-R
'1$, *.A:.N N
 ![J6&# (J0L M+ J '#hooc*of>U.V*WWJ [F2$MM!8 !","EcU K# 5  %:  #hooc%j&A"BBJ&=1JY . %` 	a
e Hs   
J#z0.2.1z7langchain_openai.chat_models.base.ChatOpenAI.bind_toolsz1.0.0)sincealternativeremovalc                  > U Vs/ sH  n[        U5      PM     nnUb  [        U[        5      (       a
  US;  a  SU0OUn[        U[        5      (       a  [	        U5      S:w  a  [        S5      e[        U[        5      (       a'  US   S   US   :w  a  [        SU SUS   S    S35      e0 UES	U0En[        TU ]  " SS
U0UD6$ s  snf )as  Bind functions (and other objects) to this chat model.

Assumes model is compatible with OpenAI function-calling API.

.. note::
    Using ``bind_tools()`` is recommended instead, as the ``functions`` and
    ``function_call`` request parameters are officially marked as deprecated by
    OpenAI.

Args:
    functions: A list of function definitions to bind to this chat model.
        Can be  a dictionary, pydantic model, or callable. Pydantic
        models and callables will be automatically converted to
        their schema dictionary representation.
    function_call: Which function to require the model to call.
        Must be the name of the single provided function or
        ``'auto'`` to automatically determine which function to call
        (if any).
    **kwargs: Any additional parameters to pass to the
        :class:`~langchain.runnable.Runnable` constructor.
)autononerb   r  zGWhen specifying `function_call`, you must provide exactly one function.r   zFunction call z3 was specified, but the only provided function was .rh   	functionsr   )rF   r   r{   rx   rO  r   r  bind)r0  r   rh   rk  fnformatted_functionsr  s         r   bind_functionsBaseChatOpenAI.bind_functions?  s   F IRR	"9"=	R$ mS11!)99 ' #	  -..37J3Kq3P   
 =$//'*62mF6KK $]O 4--@-CF-K,LAO  @??Fw|D&9DVDD- Ss   C)tool_choicestrictparallel_tool_callsc                  > Ub  XES'   U Vs/ sH  n[        XcS9PM     nn/ nU H>  nSU;   a  UR                  US   S   5        M"  SU;   a  UR                  US   5        M>  M@     U(       a{  [        U[        5      (       a&  X(;   a  SSU0S.nOUU[        ;   a  SU0nOFUS:X  a  SnO=O<[        U[
        5      (       a  SnO$[        U[        5      (       a  O[        S	U 35      eX%S
'   [        T	U ]$  " SSU0UD6$ s  snf )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
        :meth:`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).
    kwargs: Any additional parameters are passed directly to
        :meth:`~langchain_openai.chat_models.base.ChatOpenAI.bind`.

.. versionchanged:: 0.1.21

    Support for ``strict`` argument added.

r  r  rr   rb   )r   rr   r   anyrequiredzEUnrecognized tool_choice type. Expected str, bool or dict. Received: r  r  r   )
rG   ry   r   r{   WellKnownToolsr   rx   r   r  r  )
r0  r  r  r  r  rk  rt   formatted_tools
tool_namesr  s
            r   
bind_toolsBaseChatOpenAI.bind_toolsz  s9   X *,?()DI
DID"47E 	 
 
#DT!!!$z"26":;4!!$v,/ $ +s++, *%+[$9#K !N2#);"7K !E)",KK..(K.. !!,/  %0=!w|</<V<<K
s   C;function_calling)methodinclude_rawr  r  c                  Ub  US:X  a  [        S5      e[        U5      nUS:X  a  U(       a-  [        U[        5      (       a  [        R
                  " S5        SnU R                  (       av  U R                  R                  S5      (       d0  U R                  R                  S5      (       d  U R                  S:X  a&  [        R
                  " S	U R                   S
35        SnUS:X  ax  Uc  [        S5      e[        U5      S   S   nU R                  " S(0 0 [        USUX$S.US.S9EUED6n	U R                  " U/40 U	D6n
U(       a  [        U/SS9nGO$[        USS9nGOUS:X  a@  U R                  " S(0 0 [        SS0SU0US.S9EUED6n
U(       a	  [        US9O	[!        5       nOUS:X  a  Uc  [        S5      e[#        XS9n0 [        S(UX$S.[        U5      S.S.UD6En	U(       a  U Vs/ sH  n[        XS9PM     snU	S'   U R                  " S(0 U	D6n
U(       aA  [%        ['        [(        [+        [,        U5      S95      R/                  [+        [,        U5      S9nO[!        5       nO[        SU S35      eU(       aT  [0        R2                  " [5        S 5      U-  S! S"9n[0        R2                  " S# S$9nUR7                  U/S%S&9n[9        U
S'9U-  $ X-  $ s  snf ))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 (support added in 0.1.20),
        - 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 :meth:`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 (formerly called function calling)
            `API <https://platform.openai.com/docs/guides/function-calling>`__
        - ``'json_schema'``:
            Uses OpenAI's Structured Output `API <https://platform.openai.com/docs/guides/structured-outputs>`__
            Supported for ``'gpt-4o-mini'``, ``'gpt-4o-2024-08-06'``, ``'o1'``, and later
            models.
        - ``'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 the methods and which models
        support which methods `here <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?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.

        .. dropdown:: Example

            .. code-block:: 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

                llm = init_chat_model("openai:gpt-4o-mini")

                structured_llm = llm.with_structured_output(
                    ResponseSchema,
                    tools=[get_weather],
                    strict=True,
                    include_raw=True,
                )

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

            .. code-block:: 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 :class:`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'``: Optional[BaseException]

.. versionchanged:: 0.1.20

    Added support for TypedDict class ``schema``.

.. versionchanged:: 0.1.21

    Support for ``strict`` argument added.
    Support for ``method="json_schema"`` added.

.. versionchanged:: 0.3.12
    Support for ``tools`` added.

.. versionchanged:: 0.3.21
    Pass ``kwargs`` through to the model.

	json_modez<Argument `strict` is not supported with `method`='json_mode'json_schemazReceived 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.rr   rb   F)r  r  )rk  r\  )r  r  r  ls_structured_output_formatT)r  first_tool_only)key_namer  r   json_objectr  )rZ  r  )pydantic_objectr
  r  )r\  )output_typez\Unrecognized method argument. Expected one of 'function_calling' or 'json_mode'. Received: ''r   c                    g Nr   r  s    r   <lambda>7BaseChatOpenAI.with_structured_output.<locals>.<lambda>  s    RVr   )r   r   c                    g r   r   r!  s    r   r"  r#    s    dr   )r   r   )exception_key)r   r   )r   r  
issubclassBaseModelV1r   r   r   r  rG   _filter_disabled_paramsrx   r  r8   r7   r  r6   r5   "_convert_to_openai_response_formatr?   r   _oai_structured_outputs_parserr   r   
with_typesrA   assignr   with_fallbacksr@   )r0  r\  r  r  r  r  rk  is_pydantic_schema	tool_namebind_kwargsllmoutput_parserrZ  tparser_assignparser_noneparser_with_fallbacks                    r   with_structured_output%BaseChatOpenAI.with_structured_output  sb   V &K"7N  07]" #z&+'F'F? ,**733??--h77??g-A$//AR S? ? ,''~ %  /v6zB6JI66 $-,1%17&J&,5	 K //6(:k:C!*=!($(+
 !9&! {")) 	)/(?'/&8&,5	 	C & %V<%' 
 }$~ %  AWO	 $3-3"F"8"@1 	K FK(FK*1<e(G$ ))*k*C! .:4fCUV!*dF);*<  !1 2++1(!5 
 /66!%(=8M .44NKK#0#?#?_ $@ $  3'*>>>&&5(s   +Kc                    U R                   (       d  U$ 0 nUR                  5        H<  u  p4X0R                   ;   a$  U R                   U   b  X@R                   U   ;   a  M8  XBU'   M>     U$ r   )r   r   )r0  rk  filteredr   r   s        r   r(  &BaseChatOpenAI._filter_disabled_params  sg    ##MLLNDA((($$Q'/18L8LQ8O3O   # r   c                D   U R                  U5      nUR                  S   R                  n[        U[        5      (       a8  UR
                  nSUR                  ;   a  UR                  R                  S5        OSn[        SUR                  US9n[        XRR                  S9$ )zDGet chunk from completion (e.g., from final completion of a stream).r   ri   Nrf   )re   rl   rI  rJ  )r  r  r   r   r   rI  rl   r  r    r<   r  )r0  
completionchat_resultchat_messagerI  r   s         r   r  4BaseChatOpenAI._get_generation_chunk_from_completion  s     ..z:"..q199lI..)88N|===..22<@!N *<<)

 #-C-C
 	
r   )r   r   r   r   r   r   r   r   )r  r   returnr   )rA  rS   rA  r   )r@  zlist[Optional[dict]]rA  rx   )rH  rx   rP  r   rQ  Optional[dict]rA  zOptional[ChatGenerationChunk])NN)
ri  list[BaseMessage]r   r  rj  "Optional[CallbackManagerForLLMRun]rk  r   rA  Iterator[ChatGenerationChunk])
ri  rD  r   r  rj  'Optional[AsyncCallbackManagerForLLMRun]rk  r   rA  "AsyncIterator[ChatGenerationChunk]r   )r   r   rk  r   rA  r   )ri  rD  r   r  rj  rE  r   r   rk  r   rA  rF  )
ri  rD  r   r  rj  rE  rk  r   rA  r=   rl  rx   rA  r   r  r   r   r  rk  r   rA  rx   )rp  zUnion[dict, openai.BaseModel]rK  rC  rA  r=   )ri  rD  r   r  rj  rG  r   r   rk  r   rA  rH  )
ri  rD  r   r  rj  rG  rk  r   rA  r=   )r   r  rk  r   rA  r   )r   r  rk  r   rA  r   )rA  r{   )rA  ztuple[str, tiktoken.Encoding])rg  r{   rA  z	list[int])ri  rD  r  zCOptional[Sequence[Union[dict[str, Any], type, Callable, BaseTool]]]rA  r   )r   zDSequence[Union[dict[str, Any], type[BaseModel], Callable, BaseTool]]rh   z<Optional[Union[_FunctionCall, str, Literal['auto', 'none']]]rk  r   rA  )Runnable[LanguageModelInput, BaseMessage])r  z9Sequence[Union[dict[str, Any], type, Callable, BaseTool]]r  zLOptional[Union[dict, str, Literal['auto', 'none', 'required', 'any'], bool]]r  r   r  r   rk  r   rA  rK  )r\  Optional[_DictOrPydanticClass]r  7Literal['function_calling', 'json_mode', 'json_schema']r  r   r  r   r  zOptional[list]rk  r   rA  -Runnable[LanguageModelInput, _DictOrPydantic])rk  r   rA  r   )r=  zopenai.BaseModelrA  r<   )Xr   r   r   r   rP   r   r   r   r   r   r   r   rx   r   rM   r   r   r   rL   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  r  r  r
  rO   model_configrR   classmethodr  r  r4  propertyr;  rC  rU  ru  rx  r~  r  r  r  r`  r  r  r  r  r  r  r  r  r  r  r   r  r  r7  r(  r  r   __classcell__r  s   @r   r   r     s   d3FC3dD9L#9T48K8"4>s>O7CJC#'K'+#(#>L.>V*/9ISW)X+N'  &+4z%JO]J_).t>)RRP"' >#L-  EJIEOA L$
 "&K%<(,o,$)--;D-#Hn#%"&L-&# ,0J(/PIt/A}A!E?!D %d 3J3/&*m*
 +/I'.  $I}#	 *.-J 7;O3:7;M4; %*$$EK!E +0d*K'KW,1$FV,WD
)W!.2J+2& &+d*Z05d0CO-C" $(G ' #'L-& !E>  !%J$ &+d*!F )-~, 59N18$ t4L(#  $ (#  $* '"M #M^  B26 6  "6  -	6 
 
'6 v %):>	3+#3+ "3+ 8	3+
 3+ 
'3+p %)?C	5+#5+ "5+ =	5+
 5+ 
,5+p .2!*!=@!	!, %):>	D# (,D##D# "D# 8	D# %D# D# 
'D#R %):>	2C#2C "2C 8	2C
 2C 
2Ch/( %)	" "	
  
: +/?J/?J (?J 
	?JH %)?C	H# (,H##H# "H# =	H# %H# H# 
,H#Z %)?C	8
#8
 "8
 =	8

 8
 
8
t G G
 +/':=	 , +/':=	&  $+ d#d
d 
d dL M 4EW4E
4E 4E 
34E
4Ex !%.2S=HS=
	S= S= ,S= S= 
3S= S=n 26K' !!% $K'.K'
	K' K' K' K' K' 
7K'Z
*
	
 
r   r   c                  0  ^  \ rS rSr% Sr\" SSS9rS\S'    \SS j5       r	\
SS	 j5       r\SS
 j5       r\
SS j5       r\SU 4S jj5       rSS.       SU 4S jjjrSU 4S jjr      SU 4S jjr SSSSS.           SU 4S jjjjrSrU =r$ )
ChatOpenAIi  uZ  OpenAI chat model integration.

.. dropdown:: Setup
    :open:

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

    .. code-block:: bash

        pip install -U langchain-openai
        export OPENAI_API_KEY="your-api-key"

.. dropdown:: Key init args — completion params

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

    See full list of supported init args and their descriptions in the params section.

.. dropdown:: Key init args — client params

    timeout: Union[float, Tuple[float, float], Any, None]
        Timeout for requests.
    max_retries: Optional[int]
        Max number of retries.
    api_key: Optional[str]
        OpenAI API key. If not passed in will be read from env var ``OPENAI_API_KEY``.
    base_url: Optional[str]
        Base URL for API requests. Only specify if using a proxy or service
        emulator.
    organization: Optional[str]
        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 in the params section.

.. dropdown:: Instantiate

    .. code-block:: python

        from langchain_openai import ChatOpenAI

        llm = ChatOpenAI(
            model="gpt-4o",
            temperature=0,
            max_tokens=None,
            timeout=None,
            max_retries=2,
            # api_key="...",
            # base_url="...",
            # organization="...",
            # other params...
        )

    .. note::
        Any param which is not explicitly supported will be passed directly to the
        ``openai.OpenAI.chat.completions.create(...)`` API every time to the model is
        invoked. For example:

        .. code-block:: 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)

.. dropdown:: Invoke

    .. code-block:: python

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

    .. code-block:: pycon

        AIMessage(
            content="J'adore la programmation.",
            response_metadata={
                "token_usage": {
                    "completion_tokens": 5,
                    "prompt_tokens": 31,
                    "total_tokens": 36,
                },
                "model_name": "gpt-4o",
                "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},
        )

.. dropdown:: Stream

    .. code-block:: python

        for chunk in llm.stream(messages):
            print(chunk.text(), end="")

    .. code-block:: 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",
        )

    .. code-block:: python

        stream = llm.stream(messages)
        full = next(stream)
        for chunk in stream:
            full += chunk
        full

    .. code-block:: python

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

.. dropdown:: Async

    .. code-block:: python

        await llm.ainvoke(messages)

        # stream:
        # async for chunk in (await llm.astream(messages))

        # batch:
        # await llm.abatch([messages])

    .. code-block:: python

        AIMessage(
            content="J'adore la programmation.",
            response_metadata={
                "token_usage": {
                    "completion_tokens": 5,
                    "prompt_tokens": 31,
                    "total_tokens": 36,
                },
                "model_name": "gpt-4o",
                "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,
            },
        )

.. dropdown:: Tool calling

    .. code-block:: 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"
            )


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

    .. code-block:: 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::
        ``openai >= 1.32`` supports a ``parallel_tool_calls`` parameter
        that defaults to ``True``. This parameter can be set to ``False`` to
        disable parallel tool calls:

        .. code-block:: python

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

        .. code-block:: 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 ``llm.bind(parallel_tool_calls=False)`` or during instantiation by
    setting ``model_kwargs``.

    See ``ChatOpenAI.bind_tools()`` method for more.

.. dropdown:: Built-in tools

    .. versionadded:: 0.3.9

    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://python.langchain.com/docs/integrations/chat/openai/>`__ for more
    detail.

    .. note::
        ``langchain-openai >= 0.3.26`` allows users to opt-in to an updated
        AIMessage format when using the Responses API. Setting

        ..  code-block:: python

            llm = ChatOpenAI(model="...", 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.

    .. code-block:: python

        from langchain_openai import ChatOpenAI

        llm = ChatOpenAI(model="gpt-4.1-mini", output_version="responses/v1")

        tool = {"type": "web_search_preview"}
        llm_with_tools = llm.bind_tools([tool])

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

    .. code-block:: 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>",
                    }
                ],
            }
        ]

.. dropdown:: Managing conversation state

    .. versionadded:: 0.3.9

    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. See LangChain
    `conversation docs <https://python.langchain.com/docs/integrations/chat/openai/>`__ for more
    detail.

    .. code-block:: python

        from langchain_openai import ChatOpenAI

        llm = ChatOpenAI(
            model="gpt-4.1-mini",
            use_responses_api=True,
            output_version="responses/v1",
        )
        response = llm.invoke("Hi, I'm Bob.")
        response.text()

    .. code-block:: python

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

    .. code-block:: python

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

    .. code-block:: python

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

    .. versionadded:: 0.3.26

    You can also initialize ChatOpenAI with :attr:`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.

    .. code-block:: python

        llm = ChatOpenAI(model="gpt-4.1-mini", use_previous_response_id=True)

.. dropdown:: 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.

    .. note::
        ``langchain-openai >= 0.3.26`` allows users to opt-in to an updated
        AIMessage format when using the Responses API. Setting

        ..  code-block:: python

            llm = ChatOpenAI(model="...", 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.

    .. code-block:: python

        from langchain_openai import ChatOpenAI

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

        llm = ChatOpenAI(
            model="o4-mini", reasoning=reasoning, output_version="responses/v1"
        )
        response = llm.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"])

    .. code-block:: none

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

.. dropdown:: Structured output

    .. code-block:: python

        from typing import Optional

        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: Optional[int] = Field(
                description="How funny the joke is, from 1 to 10"
            )


        structured_llm = llm.with_structured_output(Joke)
        structured_llm.invoke("Tell me a joke about cats")

    .. code-block:: python

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

    See ``ChatOpenAI.with_structured_output()`` for more.

.. dropdown:: JSON mode

    .. code-block:: python

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

    .. code-block:: python

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

.. dropdown:: Image input

    .. code-block:: python

        import base64
        import httpx
        from langchain_core.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 = llm.invoke([message])
        ai_msg.content

    .. code-block:: python

        "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."

.. dropdown:: Token usage

    .. code-block:: python

        ai_msg = llm.invoke(messages)
        ai_msg.usage_metadata

    .. code-block:: python

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

    When streaming, set the ``stream_usage`` kwarg:

    .. code-block:: python

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

    .. code-block:: python

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

    Alternatively, setting ``stream_usage`` when instantiating the model can be
    useful when incorporating ``ChatOpenAI`` into LCEL chains-- or when using
    methods like ``.with_structured_output``, which generate chains under the
    hood.

    .. code-block:: python

        llm = ChatOpenAI(model="gpt-4o", stream_usage=True)
        structured_llm = llm.with_structured_output(...)

.. dropdown:: Logprobs

    .. code-block:: python

        logprobs_llm = llm.bind(logprobs=True)
        ai_msg = logprobs_llm.invoke(messages)
        ai_msg.response_metadata["logprobs"]

    .. code-block:: python

        {
            "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": [],
                },
            ]
        }

.. dropdown:: Response metadata

    .. code-block:: python

        ai_msg = llm.invoke(messages)
        ai_msg.response_metadata

    .. code-block:: python

        {
            "token_usage": {
                "completion_tokens": 5,
                "prompt_tokens": 28,
                "total_tokens": 33,
            },
            "model_name": "gpt-4o",
            "system_fingerprint": "fp_319be4768e",
            "finish_reason": "stop",
            "logprobs": None,
        }

.. dropdown:: Flex processing

    OpenAI offers a variety of
    `service tiers <https://platform.openai.com/docs/guides/flex-processing>`_.
    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"``:

    .. code-block:: python

        from langchain_openai import ChatOpenAI

        llm = ChatOpenAI(model="o4-mini", 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>`__
    for more detail.

.. dropdown:: 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.

    **LM Studio example** with TTL (auto-eviction):

    .. code-block:: python

        from langchain_openai import ChatOpenAI

        llm = 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
        )

    **vLLM example** with custom parameters:

    .. code-block:: python

        llm = 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},
        )

.. dropdown:: 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``

    .. code-block:: python

        # Standard OpenAI parameters
        llm = ChatOpenAI(
            model="gpt-4o",
            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, etc.)
    - Parameters that need to be nested under ``extra_body`` in the request
    - Any non-standard OpenAI API parameters

    .. code-block:: python

        # Custom provider parameters
        llm = 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

    .. important::

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

.. dropdown:: Prompt caching optimization

    For high-volume applications with repetitive prompts, use ``prompt_cache_key``
    per-invocation to improve cache hit rates and reduce costs:

    .. code-block:: python

        llm = ChatOpenAI(model="gpt-4o-mini")

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

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

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

    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.

Nr  r   r   r   c                
    SS0$ )Nr   r   r   r  s    r   
lc_secretsChatOpenAI.lc_secrets
  s     "233r   c                
    / SQ$ )z*Get the namespace of the langchain object.)	langchainchat_modelsr*  r   r  s    r   get_lc_namespaceChatOpenAI.get_lc_namespace
  s
     65r   c                    0 nU R                   (       a  U R                   US'   U R                  (       a  U R                  US'   U R                  (       a  U R                  US'   U$ )Nr   r   r   )r   r   r   )r0  
attributess     r   lc_attributesChatOpenAI.lc_attributes
  sZ    %'
##040H0HJ,-,0,@,@J())-):):J~&r   c                    g)z9Return whether this model can be serialized by LangChain.Tr   r\  s    r   is_lc_serializableChatOpenAI.is_lc_serializable
  s     r   c                P   > [         TU ]  nSU;   a  UR                  S5      US'   U$ )r7  r   r  )r  r;  r  )r0  r:  r  s     r   r;  ChatOpenAI._default_params  s0     (6!.4jj.FF*+r   r  c               "  > [         TU ]  " U4SU0UD6nSU;   a  UR                  S5      US'   U R                  (       aO  [        R
                  " SU R                  5      (       a)  UR                  S/ 5       H  nUS   S:X  d  M  SUS'   M     U$ )	Nr   r   r  z^o\dri  ra   ro   rp   )r  r`  r  r   rematchrw   )r0  r  r   rk  rl  r   r  s         r   r`  ChatOpenAI._get_request_payload  s     '.vKDKFK 7"/6{{</HG+, ??rxxAA";;z266?h.&1GFO 7 r   c                   > U R                  0 UEU R                  E5      (       a  [        TU ]  " U0 UD6$ [        TU ]  " U0 UD6$ )+Route to Chat Completions or Responses API.)r  r   r  ru  r  )r0  r   rk  r  s      r   r  ChatOpenAI._stream,  sN    ""#Bf#B0A0A#BCC7,d=f==7?D3F33r   c                  >#    U R                  0 UEU R                  E5      (       a   [        TU ]  " U0 UD6  Sh  vN nU7v   M  [        TU ]  " U0 UD6  Sh  vN nU7v   M   N+
 g N
 g7f)rm  N)r  r   r  rx  r  )r0  r   rk  rH  r  s       r   r  ChatOpenAI._astream3  sv      ""#Bf#B0A0A#BCC$w94J6J e$w/@@ e	J@sJ   5A0A*A(A* A0A.A,A. A0(A**A0,A..A0r  Fr  r  r  c               ,   > [         TU ]  " U4X#US.UD6$ )a7  Model wrapper that returns outputs formatted to match the given schema.

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

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

        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 :meth:`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>`__.
            Supported for ``'gpt-4o-mini'``, ``'gpt-4o-2024-08-06'``, ``'o1'``, and later
            models.
        - ``'function_calling'``:
            Uses OpenAI's tool-calling (formerly called function calling)
            `API <https://platform.openai.com/docs/guides/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 the methods and which models
        support which methods `here <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?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.

        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.

        .. dropdown:: Example

            .. code-block:: 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

                llm = init_chat_model("openai:gpt-4o-mini")

                structured_llm = llm.with_structured_output(
                    ResponseSchema,
                    tools=[get_weather],
                    strict=True,
                    include_raw=True,
                )

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

            .. code-block:: 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 :class:`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'``: Optional[BaseException]

.. versionchanged:: 0.1.20

    Added support for TypedDict class ``schema``.

.. versionchanged:: 0.1.21

    Support for ``strict`` argument added.
    Support for ``method="json_schema"`` added.

.. versionchanged:: 0.3.0

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

.. versionchanged:: 0.3.12
    Support for ``tools`` added.

.. versionchanged:: 0.3.21
    Pass ``kwargs`` through to the model.

.. dropdown:: 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 `here <https://platform.openai.com/docs/guides/structured-outputs/supported-schemas>`__.

    .. code-block:: python

        from typing import Optional

        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: Optional[str] = Field(
                default=..., description="A justification for the answer."
            )


        llm = ChatOpenAI(model="gpt-4o", temperature=0)
        structured_llm = llm.with_structured_output(AnswerWithJustification)

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

        # -> 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.'
        # )

.. dropdown:: Example: schema=Pydantic class, method="function_calling", include_raw=False, strict=False

    .. code-block:: python

        from typing import Optional

        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: Optional[str] = Field(
                default=..., description="A justification for the answer."
            )


        llm = ChatOpenAI(model="gpt-4o", temperature=0)
        structured_llm = llm.with_structured_output(
            AnswerWithJustification, method="function_calling"
        )

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

        # -> 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.'
        # )

.. dropdown:: Example: schema=Pydantic class, method="json_schema", include_raw=True

    .. code-block:: 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


        llm = ChatOpenAI(model="gpt-4o", temperature=0)
        structured_llm = llm.with_structured_output(
            AnswerWithJustification, include_raw=True
        )

        structured_llm.invoke(
            "What weighs more a pound of bricks or a pound of feathers"
        )
        # -> {
        #     '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
        # }

.. dropdown:: Example: schema=TypedDict class, method="json_schema", include_raw=False, strict=False

    .. code-block:: python

        # IMPORTANT: If you are using Python <=3.8, you need to import Annotated
        # from typing_extensions, not from typing.
        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[
                Optional[str], None, "A justification for the answer."
            ]


        llm = ChatOpenAI(model="gpt-4o", temperature=0)
        structured_llm = llm.with_structured_output(AnswerWithJustification)

        structured_llm.invoke(
            "What weighs more a pound of bricks or a pound of feathers"
        )
        # -> {
        #     '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.'
        # }

.. dropdown:: Example: schema=OpenAI function schema, method="json_schema", include_raw=False

    .. code-block:: 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']
           }
       }

        llm = ChatOpenAI(model="gpt-4o", temperature=0)
        structured_llm = llm.with_structured_output(oai_schema)

        structured_llm.invoke(
            "What weighs more a pound of bricks or a pound of feathers"
        )
        # -> {
        #     '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.'
        # }

.. dropdown:: Example: schema=Pydantic class, method="json_mode", include_raw=True

    .. code-block::

        from langchain_openai import ChatOpenAI
        from pydantic import BaseModel

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

        llm = ChatOpenAI(model="gpt-4o", temperature=0)
        structured_llm = llm.with_structured_output(
            AnswerWithJustification,
            method="json_mode",
            include_raw=True
        )

        structured_llm.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?"
        )
        # -> {
        #     '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
        # }

.. dropdown:: Example: schema=None, method="json_mode", include_raw=True

    .. code-block::

        structured_llm = llm.with_structured_output(method="json_mode", include_raw=True)

        structured_llm.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?"
        )
        # -> {
        #     '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
        # }

rq  )r  r7  )r0  r\  r  r  r  rk  r  s         r   r7  !ChatOpenAI.with_structured_output>  s-    F w-
!6
MS
 	
r   r   )rA  zdict[str, str])rA  z	list[str]rB  )rA  r   rJ  )r   r   rk  r   rA  rF  )r   r   rk  r   rA  rH  r   )r\  rL  r  rM  r  r   r  r   rk  r   rA  rN  )r   r   r   r   __doc__rP   r   r   rQ  rW  rP  r]  ra  rd  r;  r`  r  r  r7  r   rR  rS  s   @r   rU  rU    s?   jX !&d:Q RJR/4 4 6 6       %)	" "	
  
 (4		$'		+	 26e
 KX!!%e
.e
 H	e

 e
 e
 e
 
7e
 e
r   rU  c                F    [        U [        5      =(       a    [        U 5      $ r   )r   r   rJ   )objs    r   r  r    s    c4 ?%:3%??r   c                L    SU S   U S   [         R                  " U S   SS9S.S.$ )	Nrr   rc   rb   r   F)ensure_asciirb   r   r   rc   rr   )jsondumps)r   s    r   r   r     s6    of%If$5EJ
 r   c                &    SU S   U S   U S   S.S.$ )Nrr   rc   rb   r   ry  rz  r   )invalid_tool_calls    r   r   r     s.     %%f-*62
 r   c                >    SSK Jn  [        U 5      (       aY   SS KnUR                  U 5      nUR                  5         UR                  [        UR                  5      5      R                  u  pEXE4$ [        U 5      (       aS  U R                  SS5      u  pg[        R                   " U5      nUR                  [        U5      5      R                  u  pEXE4$ g ! [         a    [        R	                  S5         g f = f! [         a    [        R	                  S5         g f = f)Nr   )ImagezaUnable to count image tokens. To count image tokens please install `pip install -U pillow httpx`.zZUnable to count image tokens. To count image tokens please install `pip install -U httpx`.,r  )PILr  r'  loggerinfo_is_urlr&  rw   raise_for_statusopenr	   re   size_is_b64splitr   	b64decode)	image_sourcer  r&  rp  widthheightr  encodedr   s	            r   r  r    s    |	 99\*!!#

78+;+;#<=BB}			!''Q/
(

74=166}3  -	
   	KK* 	s"   C C: C76C7:DDc                j    [        X5      u  p[        US-  5      n[        U S-  5      nSU-  U-  S-   $ )Ni      r  )_resizer   )r  r  hws       r   r  r    s=    E*MEVc\AUS[A!GaK2r   c                     [        U 5      n[        UR                  UR                  /5      $ ! [         a"  n[
        R                  SU 35         S nAgS nAff = f)NzUnable to parse URL: F)r   allschemenetlocrz   r  debug)sresultr   s      r   r  r    sO    !FMM6==122 ,QC01s   +. 
AAAc                $    U R                  S5      $ )Nz
data:image)r  )r  s    r   r  r    s    <<%%r   c                    U S:  d  US:  a  X:  a  US-  U -  nSn O
U S-  U-  n SnU S:  a"  US:  a  X:  a  U S-  U-  n SnX4$ U S-  U-  nSn X4$ )Ni   i   r   )r  r  s     r   r  r    s    t|v}>tm-FET\f,EFs{v|>S[V+EF = ckf,FE=r   r
  c               d   [        U [        5      (       a  [        U 5      (       a  U $ [        U [        5      (       a  SU ;   a  U R	                  S5      S:X  a  U nO[        U [        5      (       a  SU ;   a  SU ;   a  SU S.nOfUcA  [        U [        5      (       a*  [        U R	                  S5      [
        5      (       a  U S   nOSn[        XS9nUR                  S	5      US'   SUS.nUbE  XS   R	                  S5      La/  [        U [        5      (       a  S
U S   S    SU S3n[        U5      eU$ )Nr  r   rb   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   rJ   rx   rw   r   rF   r  r   )r\  r  rZ  rr   msgs        r   r)  r)  
  s;    &$$9&$A$A 	64  V#JJv-/ 	FD	!	!f&68v;M#0H>&$''Jvzz(7KT,R,R)-fD%\\,7#0J 	-8<<XFFvt$$ ?m$X./ 0))/ 178 	 or   c                4   U R                   R                  S5      =n(       a  [        U[        5      (       a  U" S0 UD6$ U$ U R                   R                  S5      (       a  [	        U R                   S   5      eU R
                  (       a  g [        SU  35      e)Nr   r  zdStructured Output response does not have a 'parsed' field nor a 'refusal' field. Received message:

r   )rl   rw   r   rx   OpenAIRefusalErrorri   r   )ai_msgr\  r   s      r   r*  r*  1  s     ))--h77v7fd###F##M		!	!	%	%i	0	0 !9!9)!DEE			++1(4
 	
r   c                      \ rS rSrSrSrg)r  iD  aU  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 here for more on refusals:
https://platform.openai.com/docs/guides/structured-outputs/refusals

.. versionadded:: 0.1.21
r   N)r   r   r   r   rt  r   r   r   r   r  r  D  s    	r   r  c                   U R                  S5      =(       d    SnU R                  S5      =(       d    SnU R                  S5      =(       d    X-   nU R                  S5      =(       d    0 R                  S5      U R                  S5      =(       d    0 R                  S5      S.nU R                  S	5      =(       d    0 R                  S5      U R                  S	5      =(       d    0 R                  S
5      S.n[        UUU[        S0 UR                  5        VVs0 sH  u  pgUc  M
  Xg_M     snnD6[	        S0 UR                  5        VVs0 sH  u  pgUc  M
  Xg_M     snnD6S9$ s  snnf s  snnf )Nprompt_tokensr   completion_tokenstotal_tokensprompt_tokens_detailsaudio_tokenscached_tokens)rk   
cache_readcompletion_tokens_detailsreasoning_tokens)rk   r   input_tokensoutput_tokensr  input_token_detailsoutput_token_detailsr   rw   r3   r1   r   r2   )oai_token_usager  r  r  r  r  r   r   s           r   rN  rN  Q  sm   "&&7<1L#''(;<AM"&&~6V,:VL!%%&=>D"II
 '**+BCIrNN
	! "%%&ABHbMM
 &))*EFL"QQ
	" !#!- 
 3 9 9 ;M ;qtqt ;M
 0 
 4 : : <N <tqt <N

 

 N Os   E$%E$
E*E*c                   U R                  SS5      nU R                  SS5      nU R                  SX-   5      nSU R                  S5      =(       d    0 R                  S5      0nSU R                  S	5      =(       d    0 R                  S
5      0n[        UUU[        S0 UR                  5        VVs0 sH  u  pgUc  M
  Xg_M     snnD6[	        S0 UR                  5        VVs0 sH  u  pgUc  M
  Xg_M     snnD6S9$ s  snnf s  snnf )Nr  r   r  r  r   output_tokens_detailsr  r  input_tokens_detailsr  r  r   r  )r  r  r  r  r  r  r   r   s           r    _create_usage_metadata_responsesr  r  s   "&&~q9L#'';M"&&~|7STLo))*ABHbMM
" 	**+ABHbMM
!
 !#!- 
 3 9 9 ;M ;qtqt ;M
 0 
 4 : : <N <tqt <N

 

 N Os   1C<=C<"D.Dc                *    SU ;   =(       a    U S   S:g  $ )Nr   rr   r   )rt   s    r   _is_builtin_toolr    s    T>8d6lj88r   c                    SU ;   =(       a    [        S U S    5       5      n1 Skn[        U=(       d    UR                  U 5      5      $ )Nr  c              3  6   #    U H  n[        U5      v   M     g 7fr   )r  ).0rt   s     r   	<genexpr>%_use_responses_api.<locals>.<genexpr>  s      4+;4+;s   >   rg  r  r   r  r  )r  r   intersection)rl  uses_builtin_toolsresponses_only_argss      r   r  r    sR     G+  4+27+;4 1 "O&9&F&Fw&OPPr   c                    [        [        U 5      S-
  SS5       HO  nX   n[        U[        5      (       d  M  UR                  R                  S5      nU(       a  XS-   S U4s  $ U S4s  $    U S4$ )a-  
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[  rc   N)rangerO  r   r   response_metadatarw   )ri  ir  response_ids       r   r  r    sw     3x=1$b"-kc9%%//33D9KA(+55~% . T>r   c                D   S H  nX!;   d  M
  UR                  U5      US'   M      SU;   a  SU;  a  SUR                  S5      0US'   UR                  SS5      nUR                  S5      (       a  UR                  S	S 5        [        U 5      US
'   UR                  SS 5      =n(       a  / nU Hz  nUS   S:X  a   SU;   a  UR	                  SS0US   E5        M,  US   S:X  a4  SU;   a  [        S5      eUR                  S5      (       a  SU;  a  SUS'   O UR	                  U5        M|     XQS'   UR                  SS 5      =n(       a5  [        U[        5      (       a  US   S:X  a  SU;   a  SS0US   EUS'   OXqS'   UR                  SS 5      =n(       a  UR                  S5      (       a  US   n	[        SU< SU	< 35      eUR                  SS 5      n
UR                  S5      (       d  [        U5      (       a  XS'   Ou[        U5      (       a  UR                  5       nSn
OUnUSS0:X  a
  SSS00US'   O>[        XS9=n(       a-  [        U[        5      (       a  US   S:X  a  SSS0US   E0US'   O UR                  SS 5      nUb  SU;  a	  SSS00US'   XS   S'   U$ ) N)r   r  max_output_tokensr   r   effortr   rf   r  r   inputr  r   rr   r_   partial_imageszPartial image generation is not yet supported via the LangChain ChatOpenAI client. Please drop the 'partial_images' key from the image_generation tool.r8  r  r  rZ  rg  zNCan specify at most one of 'response_format' or 'text', received both:
schema=z
text=r  text_formatTr  formatr
  r  r   )r  rw   r  _construct_responses_api_inputry   r  r   rx   r   r  model_json_schemar)  )ri  rl  legacy_token_paramr   r  	new_toolsrt   r  r\  rg  r  schema_dictrZ  r   s                 r   r  r    s    F(+2;;7I+JG'( F W$G)C ('++6H*IJ KK$E  M4(5h?GGGT**u*	D F|z)jD.@  &*!IZ8H!IJ<#55'4/1$  !X..3C43O 23-.  &- 0 %kk-66{6 {D))F#z1k)&,j%TK
<S%TGM"%0M" .55v5;;v6?DIXw(  Xt,{{8$$);F)C)C%+M"!&))$668$v}55#+fm-D"E (J#( O   66$V,= v}W8VW# K.I '&&)9:GFO'0$Nr   c                   U R                   SS.n[        U R                  [        5      (       a  [	        S U R                   5       5      nOSU R                  S.nX!S'   SU R
                  ;   a  U R
                  S   US'   U$ )Ncomputer_call_output)call_idr   c              3  V   #    U H   n[        [        U5      S    S:X  d  M  Uv   M"     g7f)r   input_imageN)r   rx   )r  r   s     r   r  :_make_computer_call_output_from_message.<locals>.<genexpr>#  s-      
(D% (M9 E(s   )	)r  r   rA  acknowledged_safety_checks)ru   r   re   r   nextrl   )r   r  rA  s      r   '_make_computer_call_output_from_messager    s    ''&" '//4(( 
 
 
 (gooF%+"#w'@'@@=D=V=V(>
9:  r   c                    S nU R                    HZ  n[        U[        5      (       d  M  UR                  S5      S:X  d  M1  SU R                  UR                  S5      =(       d    SS.n  U$    U$ )Nr   custom_tool_call_outputrA  rf   )r   r  rA  )re   r   rx   rw   ru   )r   custom_tool_outputr   s      r   %_make_custom_tool_output_from_messager  3  sl    eT""uyy'8<U'U1"//))H-3"
  ! r   c                L   U R                  5        VVs0 sH  u  pUS:w  d  M  X_M     nnnSU;   af  [        US   [        5      (       aN  / nUS    H?  nUR                  5        VVs0 sH  u  pUS:w  d  M  X_M     nnnUR                  U5        MA     XCS'   U$ s  snnf s  snnf )zWhen streaming, langchain-core uses the ``index`` key to aggregate
text blocks. OpenAI API does not support this key, so we need to remove it.
r   summary)r   r   r   ry   )r   r   r   	new_blocknew_summary	sub_blocknew_sub_blocks          r   _pop_index_and_sub_indexr  A  s     #(++-@-$!1<-I@I*Yy-A4"H"H"9-I.7oo.?P.?da1<TQT.?MP}- .  +) A Qs   BB'B 6B c           	     	   / nU  GHx  n[        U[        5      (       a  [        U5      n[        U5      nSU;   a  UR	                  S5        US   S:X  a  US   n[        U5      nU(       a  UR                  U5        My  UR                  R                  S5      S:X  a,  [        [        [        U5      5      nUR                  U5        M  [        U[        5      (       d  [        U5      nSUUS   S	.nUR                  U5        GM  US   S
:X  Ga%  [        UR                  S5      [        5      (       Ga3  US    GH(  n[        U[        5      (       d  M  UR                  S5      =n	(       d  M5  U	S;   a  UR                  S5      n
U	S;   a"  SUS   UR                  S5      =(       d    / S.nOU	S:X  a  SUS   S.nU HD  nUR                  S5      =n(       d  M  X:X  d  M$  SU;  a  / US'   US   R                  W5          M     UR                  SW/S
U
S.5        M  U	S;   a  UR                  [!        U5      5        GM  U	S:X  a  UR                  SUS   S.5        GM(  GM+     O@[        UR                  S5      [        5      (       a  UR                  SS
SUS   S./S.5        UR	                  SS5      =n(       aq  U Vs1 sH'  nUR                  S5      S;   d  M  SU;   d  M"  US   iM)     nnU H5  nUS   U;  d  M  SUS    S   US    S!   US   S".nUR                  U5        M7     GM-  GM0  US   S#;   Ga-  [        US   [        5      (       Ga   / nS$nUS    H  nUS   S:X  a  UR                  S%US   S.5        M%  US   S&:X  aB  S'US&   S(   S).nUS&   R                  S*5      (       a  US&   S*   US*'   UR                  U5        Mp  US   S+:X  a  SS,0US+   EnUR                  U5        M  US   S-;   a  UR                  U5        M  US   U;   a  UR                  U5        M  M     UUS'   US   (       a  UR                  U5        GMP  GMS  UR                  U5        GMg  UR                  U5        GM{     U$ s  snf ).z1Construct the input for the OpenAI Responses API.rb   ra   rt   re   r   r  function_call_outputru   )r   rA  r  rg   )rg  output_textr  rc   )rg  r  r  rg  r   )r   rg  r   r  r   r  r   )r   re   ra   rc   )
r   web_search_callfile_search_callrh   computer_callcustom_tool_callcode_interpreter_callmcp_callmcp_list_toolsmcp_approval_requestimage_generation_call)r   rc   )r   rg  )r   ra   re   ri   N)rh   r  r  rh   rr   r   )r   rb   r   r  )rd   ro   rp   )mcp_approval_response
input_textr   r  r   r   r  r  
input_file)r  r  r  )r   r   rV   r   r  r  ry   rl   rw   r  r   r-   r{   rD   r   rx   r  )ri  r  lc_msgr  tool_outputr  r  r  r   
block_typemsg_idr  itemitem_idri   content_call_idsr   rh   
new_blocksnon_message_item_typess                       r   r  r  O  s   Ffi((1&9F&v.S=GGFOv;& i.K!Fv!N!01))--f59OO'Nf-($ 23!+s33",["9K2)">2($
 23[K'#''),d33 ^E!%..%))FBS4SJ4S%)KK%*YYt_F)-DD,9,1&M3899]3K3Qr-"	
 ",y!8,5/4Y/?-"	 )//3xx~$=G$=7CT'0'<:<Y$(O$:$:9$E$) )/ !'094=;0;.4	%&!" ( ,  #MM*B5*IJ'+BB"MM)@d T !i ,j CGGI.44 ) +-:C	N$S#T !WW\488z8 "($!'yy(,QQ % "U* %E)$!' ! $ ",I .>>$3$-j$9&$A)2:)>{)K'0	) m4 ", 9" [;;#i.$//
)C& ^E V}."))<v*WX v+5$1).{);E)B%	 !-11(;;272DX2NIh/")))4v&0%+\$KU6]$K	")))4v*UU"))%0v*@@e,/ ,0 ",Iy>MM#& " c"MM#] ` Mi$s   R!R)	Rc                ,   [        U S5      (       a  U R                  $ / nU R                   HU  nUR                  S:X  d  M  UR                   H0  nUR                  S:X  d  M  UR                  UR                  5        M2     MW     SR                  U5      $ )z1OpenAI SDK deleted response.output_text in 1.99.2r  r   rf   )r  r  rA  r   re   ry   rg  join)rp  textsrA  re   s       r   _get_output_textr    st    x''###E//;;)#!>><<=0LL. * " 775>r   c           
        U R                   (       a  [        U R                   5      eU R                  SSS9R                  5        VVs0 sH  u  pEUS;   d  M  XE_M     nnnU(       a  UR	                  U5        UR                  S5      US'   U R                  (       a$  [        U R                  R                  5       5      nOSn/ n/ n	/ n
0 nU R                   GH7  nUR                  S:X  a  UR                   H  nUR                  S	:X  at  S
UR                  UR                   Vs/ sH  nUR                  5       PM     snUR                  S.nUR                  U5        [        US5      (       a  UR                   US'   UR                  S:X  d  M  UR                  SUR"                  UR                  S.5        M     M  UR                  S:X  a  UR                  UR                  SSS95         [$        R&                  " UR(                  SS9nSnUc/  SUR.                  UUR0                  S.nU	R                  U5        GMk  SUR.                  UUR0                  US.nU
R                  U5        GM  UR                  S:X  aZ  UR                  UR                  SSS95        SUR.                  SUR2                  0UR0                  S.nU	R                  U5        GM  UR                  S;   d  GM  UR                  UR                  SSS95        GM:     [5        U 5      nUb  SU;  a  U(       a  U R                  (       a  U R                  R                  5       =n(       al  UR                  S0 5      =n(       aS  UR                  S5      S:X  a>   [$        R&                  " U5      nU(       a  [7        U5      (       a	  U" S 0 UD6nOUnUUS'   [9        UU R                  UUUU	U
S9nUS:X  a  [;        U5      nO [=        [?        US9/S9$ s  snnf s  snf ! [*         a"  nUR(                  n[-        U5      n SnAGN+SnAff = f! [$        R*                   a     Nf = f)!z9Construct ChatResponse from OpenAI Response API response.Tr{  exclude_noner  )	
created_atrc   incomplete_detailsr]  objectstatusrd   r   r  r   r   Nr   r  rg  )r   rg  r   rc   r   r  )r   r  rc   rh   Fr
  r   )r   rb   r   rc   r~  )r   rb   r   rc   r  r  __arg1)	r   r  r  r  r  r  r  r  r  r  r   r  )re   rc   rI  r  rl   ri   rm   r  r   )r  r   ) r  r   r  r   updaterw   rF  r  rA  r   re   rg  r   rc   ry   r  r   r  r{  loadsr   r
   r{   rb   r  r  r  r  r   rW   r=   r;   )rp  r\  r]  r
  r   r   r  rI  content_blocksri   rm   rl   rA  re   
annotationr   r   r  r   r   r  text_configformat_parsed_dictr   r   s                             r   r  r    s    ~~(( ''T'GMMOODA

 	O  $   *&7&;&;G&Dl#~~9(..:S:S:UVNJ //;;)#!>><<=0 & ' /6.A.A(.A
 '113.A( %iiE #))%0w116=nn)(3<<9,"))!*wfiiX *$ [[O+!!&"3"3F"3"STzz&"2"25A }'"KK  ..		 !!), 0"KK  .."	 #)))4[[..!!&"3"3F"3"ST#!6<<0nn	I i([[ 

 

 !!&"3"3F"3"STC "d #8,K--MM$MM4466[6#"55W5[[ M1	**[1K,V44.+.$*0h' ;;%++-G ,W5>'#B"CDDcL($ # ''AT ## 		s<   P	P	$P/!P=Q 
Q P;;Q QQc           	     6  ^^^ S/S0UUU4S jjjn/ n	/ n
0 nU(       a  UnO0 nS nS nU R                   S:X  a>  U" U R                  U R                  5        U	R                  SU R                  TS.5        GOU R                   S:X  az  U" U R                  U R                  5        [        U R                  [        5      (       a  U R                  nOU R                  R                  SSS9nU	R                  U/TS	.5        GO\U R                   S
:X  a   U	R                  U R                  TS.5        GO,U R                   S:X  a1  U R                  R                  nU R                  R                  US'   GOU R                   S:X  a  [        [        [        U R                  XGS9R                  S   R                   5      nUR"                  R%                  S5      =n(       a  UUS'   UR&                  nUR(                  R+                  5        VVs0 sH  u  nnUS:w  d  M  UU_M     nnnGO6U R                   S:X  a:  U R,                  R                   S:X  a   US:X  a  U R,                  R                  nGOGOU R                   S:X  a  U R,                  R                   S:X  a  U" U R                  5        U
R                  SU R,                  R.                  U R,                  R0                  U R,                  R2                  TS.5        U	R                  SU R,                  R.                  U R,                  R0                  U R,                  R2                  U R,                  R                  TS.5        GOU R                   S:X  a^  U R,                  R                   S;   aD  U" U R                  5        U R,                  R                  SSS9nTUS'   U	R                  U5        GOU R                   S:X  a  U R,                  R                   S:X  a  U" U R                  5        U R,                  R                  SSS9nTUS'   U	R                  U5        U
R                  SU R,                  R.                  [4        R6                  " SU R,                  R8                  05      U R,                  R2                  TS.5        GOU R                   S:X  aR  U" U R                  5        U
R                  SU R                  TS.5        U	R                  SU R                  TS .5        GOLU R                   S!:X  a   U	R                  S"U R:                  S#.5        GOU R                   S:X  a]  U R,                  R                   S$:X  aC  U" U R                  5        U R,                  R                  SSS9nTUS'   U	R                  U5        OU R                   S%:X  a7  U" U R                  5        U	R                  U R<                  S&S'S(./TS$S).5        OhU R                   S*:X  a  OWU R                   S+:X  aA  U" U R                  5        U	R                  U R<                  S&U R                  S(./TS$S).5        OTTTS 4$ [?        U	U
UUUUS,9nUS:X  a  [        [>        [A        UUS-95      nO TTT[C        US.94$ s  snnf )1Nc                R   > Uc  TU :w  a  TS-  mU mgTU :w  d  TU:w  a  TS-  mUmU mg)as  Advance indexes tracked during streaming.

Example: we stream a response item of the form:

.. code-block:: 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:

.. code-block:: 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_idxrr  rs  rt  s     r   _advance>_convert_responses_chunk_to_generation_chunk.<locals>._advance  sM    H ?#z1"
  * %
28IW8T" ')r   zresponse.output_text.deltarg  )r   rg  r   z%response.output_text.annotation.addedTr{  r  )r   r   zresponse.output_text.done)rc   r   zresponse.createdrc   zresponse.completed)r\  r
  r   r   zresponse.output_item.addedr   r  rh   r4   )r   rb   r   rc   r   )r   rb   r   r  rc   r   zresponse.output_item.done)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.doner  r  r   z%response.reasoning_summary_part.addedsummary_textrf   )r   r   rg  )r  r   r   z,response.image_generation_call.partial_imagez%response.reasoning_summary_text.delta)re   r   rI  r  rl   rc   )r^  r  r   )r  r   r  r   rA  None)"r   output_indexcontent_indexry   rL  r   r  rx   r  r  rp  rc   r   r   r  r  r   rl   rw   rI  r  r   r  rb   r   r  r{  r|  r  r  summary_indexr    rW   r<   )rH  rr  rs  rt  r\  r]  r^  r
  r  re   r   rl   r  rI  rc   r  r  r   r   r   r  r   r   s    ```                   r   re  re    s   +* +*Z G $N	Bzz11##U%8%89mTU	>	>##U%8%89e&&--))J))44$V4TJ
|mLM	2	2emmmDE	)	)^^"'.."3"3$	+	+7NN6 Q  	
 **..x8868*0h'++ 2288:
:TQa4iDAqD: 	 
 
3	3

98TT!B

22JJOO.##$)



,,jj((&	
 	'

"ZZ11 ::--jjmm&		
 
2	2uzz 	K 	8 	##$jj++F+K,G{#

11JJOO11##$jj++F+K,G{#)



Hejj.>.>#?@jj((&	
 
?	?##$&mT	
 	$5;;W	
 
.	.	emmDE	3	3

;8V##$JJ))t&)I	*	'y!	>	>##$ $11>SUV '#		
 
E	E	>	>##$ "'!4!4 . % '#
	
 24EtKK)%++G &wmL

 	G,	 }
s   ZZ)r|   Mapping[str, Any]rA  r!   )re   r   rA  r   )r   r!   rA  rx   )r|   r!  r   ztype[BaseMessageChunk]rA  r"   )r   Union[int, dict]r   r"  rA  r"  )r   zopenai.BadRequestErrorrA  r  )rv  r   rA  r   )r   r,   rA  rx   )r~  r)   rA  rx   )r  r{   rA  zOptional[tuple[int, int]])r  r   r  r   rA  r   )r  r{   rA  r   )r  r   r  r   rA  ztuple[int, int])r\  zUnion[dict[str, Any], type]r  r   rA  zUnion[dict, TypeBaseModel])r  r   r\  z	type[_BM]rA  zOptional[PydanticBaseModel])r  rx   rA  r3   )rt   rx   rA  r   rI  )ri  Sequence[BaseMessage]rA  z+tuple[Sequence[BaseMessage], Optional[str]])ri  r#  rl  rx   rA  rx   )r   r-   rA  rx   )r   r-   rA  rC  )r   rx   rA  rx   )ri  r#  rA  r   )rp  rX   rA  r{   )NNr  )
rp  rX   r\  Optional[type[_BM]]r]  rC  r
  r	  rA  r=   )NNFr  )rH  r   rr  r   rs  r   rt  r   r\  r$  r]  rC  r^  r   r
  r	  rA  z3tuple[int, int, int, Optional[ChatGenerationChunk]])rt  
__future__r   r   r{  loggingr#  ri  sslr  r   collections.abcr   r   r   r   	functoolsr   ior	   r
   mathr   operatorr   typingr   r   r   r   r   r   r   r   r   urllib.parser   certifir*  r  langchain_core._api.deprecationr   langchain_core.callbacksr   r   langchain_core.language_modelsr   *langchain_core.language_models.chat_modelsr   r   r   r   langchain_core.messagesr   r    r!   r"   r#   r$   r%   r&   r'   r(   r)   r*   r+   r,   r-   r.   r/   r0   langchain_core.messages.air1   r2   r3   langchain_core.messages.toolr4   langchain_core.output_parsersr5   r6   *langchain_core.output_parsers.openai_toolsr7   r8   r9   r:   langchain_core.outputsr;   r<   r=   langchain_core.runnablesr>   r?   r@   rA   langchain_core.runnables.configrB   langchain_core.toolsrC   langchain_core.tools.baserD   langchain_core.utilsrE   %langchain_core.utils.function_callingrF   rG   langchain_core.utils.pydanticrH   rI   rJ   langchain_core.utils.utilsrK   rL   rM   pydanticrN   rO   rP   rQ   rR   pydantic.v1r'  typing_extensionsrS   *langchain_openai.chat_models._client_utilsrT   rU   $langchain_openai.chat_models._compatrV   rW   openai.types.responsesrX   	getLoggerr   r  create_default_contextwherer)  r  r   r   r   r   r   r   r   r   rx   r{   r   _DictOrPydanticClass_DictOrPydanticr   r   rU  r  r   r   r  r  r  r  r  r)  r*  rz   r  rN  r  r  r  r  r  r  r  r  r  r  r  re  r   r   r   <module>rM     s    "    	 	 
 
  F F      
 
 
 "    6 >     ( 
 9 P  S R  < ) 0 9 
 V U M M 0 "
 /			8	$ //w}}G EPP*ZDN6666-C6666r)6F64I  e9%T#s(^T#Y<= c	"+Y +A
] A
H2a
 a
H%@
&
	
>&* FJ$'$4B$$N

(
 
&
 
B69Q#00b#b.2b	bJ .Sl  #'#48	[E[E[E [E 2	[E
 [EF #'#48aaa a 	a
  a a a 2a 9ar   