
    h                   h   d Z ddlmZ ddlZddlZddlZddlZddlZddlZddl	Z	ddl
Z
ddlmZmZmZmZ ddlmZ ddlmZ ddlmZ ddlmZ dd	lmZ dd
lmZmZmZmZmZmZm Z m!Z!m"Z" ddl#m$Z$ ddl%Z%ddl&Z&ddl'Z'ddl(m)Z) ddl*m+Z+m,Z, ddl-m.Z. ddl/m0Z0m1Z1m2Z2m3Z3 ddl4m5Z5m6Z6m7Z7m8Z8m9Z9m:Z:m;Z;m<Z<m=Z=m>Z>m?Z?m@Z@mAZAmBZBmCZCmDZDmEZEmFZF ddlGmHZHmIZImJZJ ddlKmLZL ddlMmNZNmOZO ddlPmQZQmRZRmSZSmTZT ddlUmVZVmWZWmXZX ddlYmZZZm[Z[m\Z\m]Z] ddl^m_Z_ ddl`maZa ddlbmcZc ddldmeZe ddlfmgZgmhZh ddlimjZjmkZkmlZl ddlmmnZnmoZompZp ddlqmrZrmsZsmtZtmuZumvZv ddlwmrZx dd lymzZz dd!l{m|Z|m}Z} dd"l~mZmZ erdd#lmZ  ej                  e      Z ej                   e%j                         $      Zd%ZdPd&ZdQd'ZdRd(Z	 	 	 	 	 	 dSd)Z	 	 	 	 	 	 dTd*ZdUd+Z G d, d-e      Z e d.er/      Ze!eeef   ee   ef   Ze!eef   Z G d0 d1e      Z G d2 d3e0      Z G d4 d5e      ZdVd6ZdWd7Z	 	 	 	 dXd8ZdYd9ZdZd:Zd[d;Zd[d<Zd\d=Zdd>	 	 	 	 	 d]d?Z	 	 	 	 	 	 d^d@Z G dA dBe      Zd_dCZd_dDZd`dEZdadFZ	 	 	 	 dbdGZ	 	 	 	 	 	 dcdHZdddIZdedJZdfdKZdgdLZdhdMZ	 	 	 di	 	 	 	 	 	 	 	 	 djdNZ	 	 	 	 dk	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 dldOZy)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           
     ,   | j                  d      }| j                  d      }| j                  d      }|dk(  rt        | j                  dd      ||      S |dk(  r| j                  dd      xs d}i }| j                  d	      x}rt        |      |d	<   g }g }| j                  d
      x}	r)|	|d
<   |	D ]  }
	 |j                  t	        |
d             ! | j                  d      x}r||d<   t        ||||||      S |dv r+|dk(  rd|i}ni }t        | j                  dd      |||      S |dk(  r;t        | j                  dd      t        t        | j                  d            |      S |dk(  rKi }d| v r| d   |d<   t        | j                  dd      t        t        | j                  d            |||      S t        | j                  dd      ||      S # t
        $ r/}|j                  t        |
t        |                   Y d}~[d}~ww xY w)zConvert 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                _/var/www/html/eduruby.in/venv/lib/python3.12/site-packages/langchain_openai/chat_models/base.py_convert_dict_to_messager      sX    99VD99VD
))D/Cv~EIIi$<4PP		 ))Ir*0b"$!IIo66=615m1Do.
"YY|44>4.<l+!/ %%omt&TU IIg&&5&).g&/!1
 	
 
(	(;!2D 9 "IIi,/	
 	
 
	IIi,4UYYv=N3OTW
 	
 
U?(-ff%IIi,c599^#<=/
 	
 599Y#;$3OOS ! &--.}c!fE s   7G	H$$HHc           	        | r`t        | t              rOg }| D ]E  }t        |t              rd|v r|d   dv r t        |t              r&t        |      r|j	                  t        |             Vt        |t              r|j                  d      dk(  r|j                  d      x}rt        |t              r|j                  d      dk(  rC|j                  d      x}r0|j                  d      x}r|j	                  dd	d
| d| id       |j                  d      d	k(  r+|j                  d	      x}r|j	                  dd	|id       35|j	                  |       H |S | }|S )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      sv   :gt, "	0E 5$'eO&M%RRE4(-B5-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"	0L  $    c                0   dt        | j                        i}| j                  xs | j                  j	                  d      x}||d<   t        | t              r| j                  |d<   |S t        | t              rd|d<   |S t        | t              rBd|d<   | j                  s| j                  rK| j                  D cg c]  }t        |       c}| j                  D cg c]  }t        |       c}z   |d<   nd| j                  v rX| j                  d   |d<   h d}|d   D cg c]+  }|j                         D ci c]  \  }}||v s|| c}}- c}}}|d<   n"d	| j                  v r| j                  d	   |d	<   n	 d	|v sd|v r|d   xs d|d<   d
| j                  v r.| j                  d
   }d|v rd| j                  d
   d   in|}	|	|d
<   |S t        | t              r!| j                  j	                  dd      |d<   |S t        | t               rd|d<   |S t        | t"              rBd|d<   | j$                  |d<   h d}
|j                         D ci c]  \  }}||
v s|| }}}|S t'        d|        c c}w c c}w c c}}w c c}}}w c c}}w )zConvert 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*:<1"5* "44 :"=*L& W666)0)B)B<)PL&(B% ".l!;* * #,//"3V$!Qq<U7UAV*L&  9 99 -4,E,Eo,VL)l*ll.J&29&=&EL#g///  11':I 9$ w009$?@ 
 %*L!  
G]	+&88<<x 
V  
G_	-)V  
G[	)%V'.';';^$=)5););)=VAoAU1VV  +G9566]* W*F Ws6   <I;J &J>JJJJ#JJc           
        | j                  d      }t        t        | j                  d            }t        t        | j                  d      xs d      }i }| j                  d      r!t        | d         }d|v r
|d   d|d<   ||d<   g }| j                  d      x}rX||d<   	 |D 	cg c]G  }	t	        |	d   j                  d      |	d   j                  d	      |	j                  d      |	d
         I }}	|dk(  s	|t        k(  rt        ||      S |dk(  s	|t        k(  rt        ||||      S |dv s	|t        k(  r|dk(  rddi}ni }t        |||      S |dk(  s	|t        k(  rt        || d   |      S |dk(  s	|t        k(  rt        || d   |      S |s	|t        k(  rt        |||      S  |||      S c c}	w # t
        $ r Y w xY w)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,'	 *    Z,,V4Z,,[9wwt}g,	    v~*;; S99		 ?/-	
 	
 
(	(M=O,O;!2K @ "!7H
 	
 
	}0DD#G%-CPP	=,<<%*?C
 	
 
"22dsCCW55M   		s%   #F: 'AF53F: 5F: :	GGc                   t        |t              r8t        | t              s#t        dt        |       dt        |              || z   S t        |t              rqt        | t              s#t        dt        |       dt        |              |j                         D ci c]"  \  }}|t        | j                  |d      |      $ c}}S t        j                  dt        |              |S c c}}w )Nz%Got different types for token usage: z and r   z!Unexpected type for token usage: )
r   int
ValueErrorr   rx   r   _update_token_usagerw   warningswarn)overall_token_usage	new_usager   r   s       r   r   r   z  s    
 )S!-s37	?#5.A)B(CE  ...	It	$-t47	?#5.A)B(CE  ")
1 "#6#:#:1a#@!DD
 	

 	9$y/9JKL
s   'C-c                    d| j                   v rd}t        j                  |       | d| j                   v rd}t        j                  |       |  )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                      e Zd ZU ded<   y)_FunctionCallr{   rb   N__name__
__module____qualname____annotations__ r   r   r   r     s    
Ir   r   _BM)boundc                  ,    e Zd ZU ded<   ded<   ded<   y)_AllReturnTyper!   rawzOptional[_DictOrPydantic]parsedzOptional[BaseException]parsing_errorNr   r   r   r   r   r     s    	%%**r   r   c                      e Zd ZU  edd      Zded<    edd      Zded<    edd      Zded<    edd      Zded<    ed	d
      Z	ded<   	 dZ
ded<   	  ee      Zded<   	  ed edd            Zded<    edd      Zded<   	  edd      Zded<   	  e edd            Zded<    edd       Zd!ed"<   	 d#Zd$ed%<   	 dZd&ed'<   	 dZded(<   	 dZded)<   	 dZd&ed*<   	 dZd+ed,<   	 dZd&ed-<   	 dZd.ed/<   	 d#Zd$ed0<   	 dZd&ed1<   	 dZded2<   	  ed      Zd&ed3<   	 dZ ded4<   	 dZ!d5ed6<   	 dZ"ded7<   	 dZ#ded8<   	 dZ$d9ed:<   dZ%d;ed<<    edd      Z&d=ed><   	  edd      Z'd=ed?<   	  edd@      Z(dAedB<   	 dZ)dCedD<   	 d#Z*d$edE<   	  ed      Z+d5edF<   	 dZ,dGedH<   	 dZ-dedI<   	 dZ.d+edJ<   	 dZ/dedK<   	 d#Z0d$edL<   	 dZ1d+edM<   	 dNZ2dOedP<   	  e3dQ      Z4 e5dRS      e6dzdT              Z7 e5dRS      e6dzdU              Z8 e5dVS      d{dW       Z9e:d|dX       Z;d}dYZ<	 	 	 	 	 	 	 	 d~dZZ=	 	 d	 	 	 	 	 	 	 	 	 dd[Z>	 	 d	 	 	 	 	 	 	 	 	 dd\Z?	 d	 	 	 	 	 dd]Z@	 	 ddd^	 	 	 	 	 	 	 	 	 	 	 dd_ZA	 	 d	 	 	 	 	 	 	 	 	 dd`ZBddaZCddb	 	 	 	 	 	 	 ddcZD	 d	 	 	 	 	 dddZE	 	 ddd^	 	 	 	 	 	 	 	 	 	 	 ddeZF	 	 d	 	 	 	 	 	 	 	 	 ddfZGe:d|dg       ZH	 d	 	 	 	 	 d fdhZI	 d	 	 	 	 	 ddiZJe:ddj       ZKddkZLd fdlZM	 d	 	 	 	 	 d fdmZN eOdndodpq      	 d	 	 	 	 	 	 	 d fdr       ZPdddds	 	 	 	 	 	 	 	 	 	 	 d fdtZQ	 ddud#dddv	 	 	 	 	 	 	 	 	 	 	 	 	 ddwZRddxZS	 	 	 	 ddyZT xZUS )BaseChatOpenAINT)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                4    t        |       }t        ||      }|S )z>Build extra kwargs from additional params that were passed in.)rE   rK   )clsvaluesall_required_field_namess      r   build_extrazBaseChatOpenAI.build_extra  s!     $<C#@ $V-EFr   c                    |j                  d      xs |j                  d      xs d}|j                  d      r	d|vrd|d<   |j                  d      r*|j                  d      }||dk7  r|j                  dd       |S )	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_temperaturez#BaseChatOpenAI.validate_temperature  s     

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

=$/r   afterc                   | j                   | j                   dk  rt        d      | j                   &| j                   dkD  r| j                  rt        d      | j                  xs, t	        j
                  d      xs t	        j
                  d      | _        | j                  xs t	        j
                  d      | _        | j                  r| j                  j                         nd| j                  | j                  | j                  | j                  | j                  d}| j                  | j                  |d	<   | j                  rP| j                  s| j                  r8| j                  }| j                  }| j                  }t        d
|d|d|      | j                   s| j                  r7| j                  s+	 ddl}|j'                  | j                  t(              | _        d| j                  xs  t+        | j                  | j                        i}t-        j.                  di ||| _        | j0                  j2                  j4                  | _        | j6                  s| j                  r7| j                  s+	 ddl}|j9                  | j                  t(              | _        d| j                  xs  t;        | j                  | j                        i}t-        j<                  di ||| _        | j>                  j2                  j4                  | _        | S # t$        $ r}t%        d      |d}~ww xY w# t$        $ r}t%        d      |d}~ww xY w)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_environmentz#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   =L =L7 	L4#L//L47	M MMc                   i d| j                   d| j                  d| j                  d| j                  d| j                  d| j
                  d| j                  d| j                  xs d	d
| j                  d| j                  d| j                  d| j                  d| j                  d| j                  d| j                  d| j                  d| j                   | j"                  | j$                  d}| j&                  | j(                  d|j+                         D ci c]  \  }}|	|| c}}| j,                  }|S c c}}w )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   )r,  exclude_if_noner   r   paramss        r   _default_paramszBaseChatOpenAI._default_params0  s   
 5 5
!7!7
 DII
 TZZ	

 
 D--
 $//
 DII%
 $//
 $//
 
 4++
  5 5
 
 
  t||!
" D--#
$ //ZZ'
. __nn
 !0 5 5 7I11=q!tI
 	
 	 Js   (
E3Ec                
   i }d }|D ]c  }||j                  d      }|7|j                         D ]$  \  }}|	||v rt        ||   |      ||<    |||<   & |S|j                  d      }e || j                  d}|r||d<   |S )Ntoken_usagesystem_fingerprint)r8  r   )rw   r   r   r   )	r,  llm_outputsr   r9  outputr8  r   r   combineds	            r   _combine_llm_outputsz#BaseChatOpenAI._combine_llm_outputsR  s    $&!! 	FF~ **]3K&'--/ 3DAqy //1D/2A2+A. 23+A.3 ")%+ZZ0D%E"!	F" $7dooV-?H)*r   c                   |j                  d      dk(  ry |j                  d      }|j                  dg       xs" |j                  di       j                  dg       }|rt        |      nd }t        |      dk(  rt         |d|      |	      }|S |d   }|d
   y t	        |d
   |      }	|ri |ni }
|j                  d      x}rM||
d<   |j                  d      x}r||
d<   |j                  d      x}r||
d<   |j                  d      x}r||
d<   |j                  d      }|r||
d<   |rt        |	t              r||	_        t        |	|
xs d 	      }|S )Nr   zcontent.deltausagechoiceschunkr   rf   )re   usage_metadatar   generation_infodeltafinish_reasonr   r   r9  r  r   )rw   _create_usage_metadatalenr<   r   r   r    rB  )r,  rA  default_chunk_classbase_generation_infor8  r@  rB  generation_chunkchoicemessage_chunkrD  rF  r   r9  r  r   s                   r   "_convert_chunk_to_generation_chunkz1BaseChatOpenAI._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/<OO,"YYw//z/0:-%*YY/C%DD!D8J 45$yy88|82>/::j)*2OJ'jG+9M(.!?3Jd
  r   c              +    K   d|d<    | j                   |fd|i|}| j                  rX | j                  j                  j                  j
                  di |}|j                         }dt        |j                        i}n( | j                  j                  j
                  di |}i }|j                  d      }	|5 }
d}d}d}d}d}|
D ]l  }|r|ni }t        |||||	||| j                        \  }}}}|s.|r|j                  |j                  |	       d}d
|j                  j                  v rd}| n 	 d d d        y # 1 sw Y   y xY wwNTr3  r   headersresponse_formatF)schemametadatahas_reasoningr  rA  r   r   )_get_request_payloadr   r   with_raw_response	responsescreateparserx   rQ  rw   ,_convert_responses_chunk_to_generation_chunkr  on_llm_new_tokentextr   rl   r,  messagesr   run_managerkwargspayloadraw_context_managercontext_managerrQ  original_schema_objresponseis_first_chunkcurrent_indexcurrent_output_indexcurrent_sub_indexrV  rA  rU  rK  s                      r   _stream_responsesz BaseChatOpenAI._stream_responses  s      x+$++HJ4J6J(("U$"2"2"D"D"N"N"U"U ## 2779O $':'B'B"CDG?d..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7AE9	EEEc               &  K   d|d<    | j                   |fd|i|}| j                  r` | j                  j                  j                  j
                  di | d {   }|j                         }dt        |j                        i}n0 | j                  j                  j
                  di | d {   }i }|j                  d      }	|4 d {   }
d}d}d}d}d}|
2 3 d {   }|r|ni }t        |||||	||| j                        \  }}}}|s4|r%|j                  |j                  |	       d {    d}d
|j                  j                  v rd}| }7 7 7 7 7 /6 d d d       d {  7   y # 1 d {  7  sw Y   y xY wwrP  )rX  r   r   rY  rZ  r[  r\  rx   rQ  rw   r]  r  r^  r_  r   rl   r`  s                      r   _astream_responsesz!BaseChatOpenAI._astream_responses  s      x+$++HJ4J6J((Od,,>>HHOO    
 2779O $':'B'B"CDG$KD$:$:$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EAF2E!3FE#FE<!E)%E%&E))+E<"E<7E'8&E<F!F#F%E)'E<)E<*F5E86F<FFF
Fc                    ||j                  di       j                  d      | j                  j                  di       j                  d      | j                  g}|D ]  }t        |t              s|c S  | j                  S )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   )r,  r   rc  stream_usage_sourcesr   s        r   _should_stream_usagez#BaseChatOpenAI._should_stream_usage  s     JJ',00A!!"2B7;;OL	 
 + 	F&$'	    r   )r   c             +    K   d|d<    | j                   |fi |}|rd|i|d<    | j                  |fd|i|}t        }i }d|v ro| j                  rt	        j
                  d       |j                  d        | j                  j                  j                  j                  j                  di |}	|	}
nx| j                  rN | j                  j                  j                  di |}|j                         }dt!        |j"                        i}n | j                  j                  di |}|}
	 |
5 }d}|D ]  }t%        |t               s|j'                         }| j)                  |||r|ni       }|=|j*                  j,                  }|j.                  xs i j1                  d	      }|r|j3                  |j4                  ||
       d}|  	 d d d        t=        d      rJd|v rE|j?                         }| jA                  |      }|r|j3                  |j4                  |       | y y y # 1 sw Y   `xY w# t6        j8                  $ r}t;        |       Y d }~d }~ww xY wwNTr3  rr  rq  r   rR  LCannot currently include response headers when response_format is specified.rQ  r   )rA  r   Fget_final_completionrW  r   )!rt  rX  r    r   r   r   r  r   betar(  r)  r3  r   rY  r[  r\  rx   rQ  r   
model_dumprN  r   	__class__rD  rw   r^  r_  r&  BadRequestErrorr   hasattrrx  %_get_generation_chunk_from_completionr,  ra  r   rb  r   rc  rd  rI  rJ  response_streamrf  raw_responserh  ri  rA  rK  r   r   final_completions                      r   _streamzBaseChatOpenAI._stream"  s      x0t00HH(7'FF#$+$++HJ4J6J6D!',,! KK!Kd..3388DDKKVgVO-O,,Ct{{<<CCNgN'--/(148L8L3M'N$-4;;--88&O	*  +H!%% +E%eT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49Jg9U'<<>#II   ,,$))1A -  #" :V41+ +, %% 	*&q))	*sJ   D*I%-H: /BH.H: AI%.H73H: :I"II%I""I%c                   | j                   r! | j                  |f||d|}t        |      S  | j                  |fd|i|}d }d|v ro| j                  rt        j                  d       |j                  d       	  | j                  j                  j                  j                  j                  di |}no| j!                  |      r|j#                  d      }
|
r2t%        |
      r' | j                  j&                  j                  di |}n| j                  rX | j                  j(                  j&                  j*                  di |}|j                         }dt-        |j.                        i}n& | j                  j&                  j*                  di |}t1        ||
|| j2                        S | j                  rN | j4                  j(                  j*                  di |}|j                         }dt-        |j.                        i}n | j4                  j*                  di |}| j7                  |      S # t        j                  $ r}	t        |	       Y d }	~	5d }	~	ww xY w	N)r   rb  r   rR  rw  r3  rQ  )rT  rU  r  r   )r   r  r   rX  r   r   r   r  r   ry  r(  r)  r\  r&  r|  r   _use_responses_apirw   _is_pydantic_classrZ  rY  r[  rx   rQ  '_construct_lc_result_from_responses_apir  r   _create_chat_resultr,  ra  r   rb  rc  stream_iterrd  rD  rh  r   rg  r  s               r   	_generatezBaseChatOpenAI._generateh  sC    >>&$,,#@FK (44+$++HJ4J6J',,! KK!.G4++0055AAGGR'R $$W-"(**->"?"'9:M'N;4++55;;FgF00#V4#3#3#E#E#O#O#V#V $!$L  ,113H'0$|7K7K2L&MO@t//99@@K7KH:*(#22	  **?4;;88??J'JL#))+H($|/C/C*DEO)t{{))4G4H''/BB7 )) .*1--.s   <:H9 9I!II!c                    t        | j                  t              r| j                  S | j                  dk(  ry| j                  y| j
                  y| j                  y| j                  ryt        |      S )Nzresponses/v1T)	r   r  r   r  r   r   r  r  r  )r,  rd  s     r   r  z!BaseChatOpenAI._use_responses_api  sm    d,,d3)))  N2\\%^^'__(**%g..r   r   c               \   | j                  |      j                         }|||d<   i | j                  |}| j                  |      rC| j                  r)t        |      \  }}|r|n|}|r||d<   t        ||      }|S t        ||      }|S |D 	cg c]  }	t        |	       c}	|d<   |S c c}	w )Nr   previous_response_idra  )_convert_inputto_messagesr6  r  r  _get_last_messages _construct_responses_api_payloadr   )
r,  input_r   rc  ra  rd  last_messagesr  payload_to_usems
             r   rX  z#BaseChatOpenAI._get_request_payload  s     &&v.::<!F6N4T))4V4""7+,,6H6R332FH'6JG23:>7S
  ;8WM  IQ"Q1#;A#>"QGJ #Rs   B)c                p   g }t        |t              r|n|j                         }|j                  d      rt	        |j                  d            	 |d   }|t        d      |j                  d      }|D ]  }t        |d         }	|r t        |	t              rt        |      |	_        |xs i }|j                  d      |j                  d      n|j                  d      |d<   d|v r|d   |d<   t        |	|	      }
|j                  |
        ||j                  d
| j                        |j                  dd      d}d|v r|d   |d<   d|v r|d   |d<   t        |t        j                         rt#        |dd       r}|j$                  d   j&                  }	t)        |	d      r&|	j*                  |d   j&                  j,                  d<   t)        |	d      r&|	j.                  |d   j&                  j,                  d<   t1        ||      S # t
        $ r"}t        d|j                                |d }~ww xY w)Nerrorr@  z Response missing `choices` key: z0Received response with null value for `choices`.r?  r   rF  r   rC  r   r9  rf   )r8  r   r9  rc   r  r   r   refusal)generations
llm_output)r   rx   rz  rw   r   r   keysr   r   r   rG  rB  r;   ry   r   r&  rN   getattrr@  r   r}  r   rl   r  r=   )r,  rh  rD  r  response_dictr@  r   r8  resr   genr  s               r   r  z"BaseChatOpenAI._create_chat_result  sS   
  #8T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1gi7
 &&q)11Gw)EL^^A&&88Bw	*FMooA&&88CkjIIW  	2=3E3E3G2HI	s   H
 
	H5H00H5c              ~  K   d|d<    | j                   |fi |}|rd|i|d<    | j                  |fd|i|}t        }i }d|v ro| j                  rt	        j
                  d       |j                  d        | j                  j                  j                  j                  j                  di |}	|	}
n| j                  rV | j                  j                  j                  di | d {   }|j                         }dt!        |j"                        i}n$ | j                  j                  di | d {   }|}
	 |
4 d {   }d}|2 3 d {   }t%        |t               s|j'                         }| j)                  |||r|ni       }|C|j*                  j,                  }|j.                  xs i j1                  d	      }|r&|j3                  |j4                  ||
       d {    d}| 7 7 7 7 7 6 d d d       d {  7   n# 1 d {  7  sw Y   nxY wn+# t6        j8                  $ r}t;        |       Y d }~nd }~ww xY wt=        d      r]d|v rX|j?                          d {  7  }| jA                  |      }|r&|j3                  |j4                  |       d {  7   | y y y wrv  )!rt  rX  r    r   r   r   r  r   ry  r(  r)  r3  r   rY  r[  r\  rx   rQ  r   rz  rN  r   r{  rD  rw   r^  r_  r&  r|  r   r}  rx  r~  r  s                      r   _astreamzBaseChatOpenAI._astream  s      x0t00HH(7'FF#$+$++HJ4J6J6D!',,! KK!Qd4499>>JJQQ O .O,,%OT%6%6%H%H%O%O &&   (--/(148L8L3M'N$!9!2!2!9!9!DG!DD&O	*& + +(!%#+ + +%%eT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49Jg9U%-%B%B%DDD#II   !22$))1A 3    #" :V4s   C'J=)G4*AJ=5G76J==H( G9H( HG?G;G?BH'G=(H4J=7J=9H( ;G?=H?H H( HH( H$HH$ H( 'J=(I;IJ=I&J=6I978J=/J20J=c                  K   | j                   r) | j                  |f||d|}t        |       d {   S  | j                  |fd|i|}d }d|v rw| j                  rt        j                  d       |j                  d       	  | j                  j                  j                  j                  j                  di | d {   }n| j!                  |      r |j#                  d      }
|
r:t%        |
      r/ | j                  j&                  j                  di | d {   }n| j                  r` | j                  j(                  j&                  j*                  di | d {   }|j                         }dt-        |j.                        i}n. | j                  j&                  j*                  di | d {   }t1        ||
|| j2                        S | j                  rV | j4                  j(                  j*                  di | d {   }|j                         }dt-        |j.                        i}n$ | j4                  j*                  di | d {   }t7        d | j8                  |       d {   S 7 O7 # t        j                  $ r}	t        |	       Y d }	~	Id }	~	ww xY w7 7 N7 7 7 _7 Awr  )r   r  r   rX  r   r   r   r  r   ry  r(  r)  r\  r&  r|  r   r  rw   r  rZ  rY  r[  rx   rQ  r  r  r   rB   r  r  s               r   
_ageneratezBaseChatOpenAI._agenerateQ  s     >>'$--#@FK /{;;;+$++HJ4J6J',,! KK!.!S!7!7!<!<!A!A!M!M!S!S "" 
 $$W-"(**->"?"'9:M'N!G!7!7!A!A!G!G!R'!RR00Wd44FFPPWW %  !
  ,113H'0$|7K7K2L&MO%LT%;%;%E%E%L%L%Ww%WWH:*(#22	  **!K!2!2!D!D!K!K!Vg!VVL#))+H($|/C/C*DEO5T..55@@@H$$**Ho
 
 	
W < )) .*1--.
 S  X W A
s   1KJAK=J JJ AK#J3$AK(J6)AK>J9?AKJ;AKJ=K=J?>KJ J0J+&K+J00K6K9K;K=K?Kc                6    d| j                   i| j                  S )zGet the identifying parameters.r   )r   r6  r,  s    r   _identifying_paramsz"BaseChatOpenAI._identifying_params  s     dooF1E1EFFr   c                :   d| j                   it        | 	  |      | j                  |}|j	                  d      x}rUt        |t              rE|D cg c]6  }t        |t              r"|j	                  d      dk(  rd|v ri |ddin|n|8 c}|d<   |S c c}w )z,Get the parameters used to invoke the model.r   r  toolsr   r^   rQ  z**REDACTED**)r   super_get_invocation_paramsr6  rw   r   r   rx   )r,  r   rc  r5  r  rt   r{  s         r   r  z%BaseChatOpenAI._get_invocation_params  s    
 T__
g,$,7
 ""
 	
 ZZ((E(j.E
 "	  dD)dhhv.>%.G 9BT8I4D4)^4tF7O s   ;Bc           	     P    | j                   dd|i|}t        d| j                  d|j                  d| j                              }|j                  d| j
                        xs |j                  d| j
                        x}r||d<   |xs |j                  dd	      x}r||d
<   |S )z Get standard params for tracing.r   r&  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   )r,  r   rc  r5  	ls_paramsr  r  s          r   _get_ls_paramszBaseChatOpenAI._get_ls_params  s     -,,A$A&A# // !::mT5E5EF	
	 #JJ|T__E 
#T__J
 
= 
 *7Io&6fjj6676#*Ii r   c                     y)zReturn type of chat model.zopenai-chatr   r  s    r   	_llm_typezBaseChatOpenAI._llm_type  s     r   c                x   | j                   | j                   }n| j                  }	 t        j                  |      }||fS # t        $ rp d}| j                  j                  d      s6| j                  j                  d      s| j                  j                  d      rd}t        j                  |      }Y ||fS w xY w)Ncl100k_basezgpt-4ozgpt-4.1r  
o200k_base)r   r   tiktokenencoding_for_modelr   r  get_encoding)r,  r   encodingencoders       r   _get_encoding_modelz"BaseChatOpenAI._get_encoding_model  s    ##/,,EOOE
	62259H h  	6#G**84??--i8??--g6&,,W5Hh	6s   A   A3B98B9c                    | j                   | j                  |      S t        j                  d   dk  rt        |   |      S | j                         \  }}|j                  |      S )z9Get the tokens present in the text with tiktoken package.r     )custom_get_token_idssysversion_infor  get_token_idsr  encode)r,  r_  _encoding_modelr{  s       r   r  zBaseChatOpenAI.get_token_ids  sg    $$0,,T22A!#7(.. 446>$$T**r   c           
        |t        j                  d       t        j                  d   dk  rt        |   |      S | j                         \  }}|j                  d      rd}d}nG|j                  d      s"|j                  d      s|j                  d	      rd
}d}nt        d| d      d}|D cg c]  }t        |       }	}|	D ]  }
||z  }|
j                         D ]n  \  }}|dk(  r|d
z  }t        |t              r|D ]  }t        |t              s|d   dk(  r5t        |t              r|d   n|}|t        |j!                  |            z  }Q|d   dk(  r=|d   j#                  d      dk(  r|dz  }vt%        |d   d         }|s|t'        | z  }|d   dk(  rG|t        |j!                  |d   d               z  }|t        |j!                  |d   d               z  }|d   dk(  rt        j                  d       t)        d|        n*|s=|t        |j!                  t        |                  z  }|dk(  sj||z  }q  |d
z  }|S c c}w )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   rS  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   r_  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   rH  r  rw   _url_to_size_count_image_tokensr   )r,  ra  r  r   r  tokens_per_messagetokens_per_name
num_tokensr  messages_dictr   keyvaluevalr_  
image_sizer{  s                   r   r  z+BaseChatOpenAI.get_num_tokens_from_messages  s   . MMW A!#77AA224x01!" O_-((!"O%"G $LL  
>FG1!4GG$ .	2G,,J%mmo ,2
U .(!OJeT*$ %c3/3v;&3H2<S$2G3v;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,2.	2` 	a
e Hs   4Iz0.2.1z7langchain_openai.chat_models.base.ChatOpenAI.bind_toolsz1.0.0)sincealternativeremovalc                f   |D cg c]  }t        |       }}|t        |t              r|dvrd|in|}t        |t              rt	        |      dk7  rt        d      t        |t              r&|d   d   |d   k7  rt        d| d|d   d    d      i |d	|i}t        |   dd
|i|S c c}w )a  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   rH  r   r  bind)r,  r  rh   rc  fnformatted_functionsr{  s         r   bind_functionszBaseChatOpenAI.bind_functions?  s   F IRR"9"=RR$ mS1!)99 ' #	  -.37J3Kq3P   
 =$/'*62mF6KK $]O 4--@-CF-K,LAO  @??Fw|D&9DVDD- Ss   B.)tool_choicestrictparallel_tool_callsc                  |||d<   |D cg c]  }t        ||       }}g }|D ]7  }d|v r|j                  |d   d          d|v r|j                  |d          89 |rit        |t              r"||v rdd|id}nH|t        v rd|i}n;|dk(  rd}n3n2t        |t
              rd}nt        |t              rnt        d	|       ||d
<   t        	| $  dd|i|S c c}w )a`  Bind tool-like objects to this chat model.

        Assumes model is compatible with OpenAI tool-calling API.

        Args:
            tools: A list of tool definitions to bind to this chat model.
                Supports any tool definition handled by
                :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  )
r,  r  r  r  r  rc  rt   formatted_tools
tool_namesr{  s
            r   
bind_toolszBaseChatOpenAI.bind_toolsz  s;   X *,?F()DI
<@"47
 
 
# 	DT!!!$z"26":;4!!$v,/	 +s+*, *%+[$9#K !N2#);"7K !E)",KK.(K. !!,/  %0F=!w|</<V<<K
s   Cfunction_calling)methodinclude_rawr  r  c                  ||dk(  rt        d      t        |      }|dk(  r|r't        |t              rt	        j
                  d       d}| j                  rj| j                  j                  d      s*| j                  j                  d      s| j                  dk(  r%t	        j
                  d	| j                   d
       d}|dk(  r||t        d      t        |      d   d   } | j                  d(i i t        |d|||d|d      |}	 | j                  |gfi |	}
|rt        |gd      }n(t        |d      }n|dk(  rA | j                  d(i i t        ddid|i|d      |}
|rt        |      n	t!               }n|dk(  r|t        d      t#        ||      }i t        d(|||dt        |      dd|}	|r|D cg c]  }t        ||       c}|	d<    | j                  d(i |	}
|rGt%        t'        t(        t+        t,        |                  j/                  t+        t,        |            }nt!               }nt        d| d      |r^t1        j2                  t5        d       |z  d! "      }t1        j2                  d# $      }|j7                  |gd%&      }t9        |
'      |z  S |
|z  S c c}w ))a  Model wrapper that returns outputs formatted to match the given schema.

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

                - an OpenAI function/tool schema,
                - a JSON Schema,
                - a TypedDict class (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  )rc  rT  )r  r  r  ls_structured_output_formatT)r  first_tool_only)key_namer  r   json_objectr  )rR  r  )pydantic_objectr  r  )rT  )output_typez\Unrecognized method argument. Expected one of 'function_calling' or 'json_mode'. Received: ''r   c                     y Nr   r  s    r   <lambda>z7BaseChatOpenAI.with_structured_output.<locals>.<lambda>      r   )r   r   c                     y r  r   r  s    r   r  z7BaseChatOpenAI.with_structured_output.<locals>.<lambda>  r  r   )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@   )r,  rT  r  r  r  r  rc  is_pydantic_schema	tool_namebind_kwargsllmoutput_parserrR  tparser_assignparser_noneparser_with_fallbacks                    r   with_structured_outputz%BaseChatOpenAI.with_structured_output  sh   V &K"7N  07]" #z&+'F? ,**73??--h7??g-A$//AR S? ? ,''~ %  /v6zB6JI6$66 $-,1%176&J&,5	 K "$//6(:k:C!*=!($(+
 !9&! {"$)) 	)/(?'/&8&,5	 	C & %V<%' 
 }$~ %  APVWO	 $3-3v"F"8"@1 	K FK(AB*1V<(G$ $))*k*C! .:4fCUV!*dF);*<  !1 2++1(!5 
 /66!%(=8M .44NKK#0#?#?_ $@ $  3'*>>>&&5(s   Kc                    | j                   s|S i }|j                         D ]9  \  }}|| j                   v r!| j                   |   || j                   |   v r5|||<   ; |S r  )r   r   )r,  rc  filteredr   r   s        r   r  z&BaseChatOpenAI._filter_disabled_params  st    ##MLLN 	 DAqD((($$Q'/18L8LQ8O3O  	  r   c                D   | j                  |      }|j                  d   j                  }t        |t              r6|j
                  }d|j                  v r|j                  j                  d       nd}t        d|j                  |      }t        ||j                        S )zDGet chunk from completion (e.g., from final completion of a stream).r   ri   Nrf   )re   rl   rB  rC  )r  r  r   r   r   rB  rl   r  r    r<   r  )r,  
completionchat_resultchat_messagerB  r   s         r   r~  z4BaseChatOpenAI._get_generation_chunk_from_completion  s     ..z:"..q199lI.)88N|===..22<@!N *<<)

 #[-C-C
 	
r   )r  r   returnr   )r#  rS   r#  r   )r:  zlist[Optional[dict]]r#  rx   )rA  rx   rI  r   rJ  Optional[dict]r#  zOptional[ChatGenerationChunk])NN)
ra  list[BaseMessage]r   r   rb  "Optional[CallbackManagerForLLMRun]rc  r   r#  Iterator[ChatGenerationChunk])
ra  r&  r   r   rb  'Optional[AsyncCallbackManagerForLLMRun]rc  r   r#  "AsyncIterator[ChatGenerationChunk]r  )r   r   rc  r   r#  r   )ra  r&  r   r   rb  r'  r   r   rc  r   r#  r(  )
ra  r&  r   r   rb  r'  rc  r   r#  r=   rd  rx   r#  r   r  r   r   r   rc  r   r#  rx   )rh  zUnion[dict, openai.BaseModel]rD  r%  r#  r=   )ra  r&  r   r   rb  r)  r   r   rc  r   r#  r*  )
ra  r&  r   r   rb  r)  rc  r   r#  r=   )r   r   rc  r   r#  r   )r   r   rc  r   r#  r   )r#  r{   )r#  ztuple[str, tiktoken.Encoding])r_  r{   r#  z	list[int])ra  r&  r  zCOptional[Sequence[Union[dict[str, Any], type, Callable, BaseTool]]]r#  r   )r  zDSequence[Union[dict[str, Any], type[BaseModel], Callable, BaseTool]]rh   z<Optional[Union[_FunctionCall, str, Literal['auto', 'none']]]rc  r   r#  )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   rc  r   r#  r-  )rT  Optional[_DictOrPydanticClass]r  7Literal['function_calling', 'json_mode', 'json_schema']r  r   r  r   r  zOptional[list]rc  r   r#  -Runnable[LanguageModelInput, _DictOrPydantic])rc  r   r#  r   )r   zopenai.BaseModelr#  r<   )Vr   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  r0  propertyr6  r=  rN  rm  ro  rt  r  r  r  rX  r  r  r  r  r  r  r  r  r  r  r   r  r  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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=n 26K' !!% $K'.K'
	K' K' K' K' K' 
7K'Z
*
	
r   r   c                      e Zd ZU dZ edd      Zded<   	 edd       Ze	dd       Z
edd	       Ze	dd
       Zed fd       Zdd	 	 	 	 	 	 	 d fdZd fdZ	 	 	 	 	 	 d fdZ	 ddddd	 	 	 	 	 	 	 	 	 	 	 d fdZ xZS )
ChatOpenAIuc  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                
    ddiS )Nr   r   r   r  s    r   
lc_secretszChatOpenAI.lc_secrets
  s     "233r   c                
    g dS )z*Get the namespace of the langchain object.)	langchainchat_modelsr&  r   r  s    r   get_lc_namespacezChatOpenAI.get_lc_namespace
  s
     65r   c                    i }| j                   r| j                   |d<   | j                  r| j                  |d<   | j                  r| j                  |d<   |S )Nr   r   r   )r   r   r   )r,  
attributess     r   lc_attributeszChatOpenAI.lc_attributes
  sZ    %'
##040H0HJ,-,0,@,@J())-):):J~&r   c                     y)z9Return whether this model can be serialized by LangChain.Tr   r=  s    r   is_lc_serializablezChatOpenAI.is_lc_serializable
  s     r   c                L    t         |   }d|v r|j                  d      |d<   |S )r2  r   r  )r  r6  r  )r,  r5  r{  s     r   r6  zChatOpenAI._default_params  s0     (6!.4jj.FF*+r   r  c                   t        |   |fd|i|}d|v r|j                  d      |d<   | j                  rEt	        j
                  d| j                        r%|j                  dg       D ]  }|d   dk(  sd|d<    |S )	Nr   r   r  z^o\dra  ra   ro   rp   )r  rX  r  r   rematchrw   )r,  r  r   rc  rd  r   r{  s         r   rX  zChatOpenAI._get_request_payload  s     '.vKDKFK 7"/6{{</HG+, ??rxxA";;z26 26?h.&1GFO2 r   c                ~    | j                  i || j                        rt        |   |i |S t        |   |i |S )+Route to Chat Completions or Responses API.)r  r   r  rm  r  )r,  r   rc  r{  s      r   r  zChatOpenAI._stream,  sK    ""#Bf#B0A0A#BC7,d=f==7?D3F33r   c                  K   | j                  i || j                        rt        |   |i |2 3 d{   }| t        |   |i |2 3 d{   }| 7 (6 y7 6 yw)rI  N)r  r   r  ro  r  )r,  r   rc  rA  r{  s       r   r  zChatOpenAI._astream3  s      ""#Bf#B0A0A#BC$w94J6J  e$w/@@  e	J@sI   /A'A!AA!A'A%A#A%A'A!!A'#A%%A'r  Fr  r  r  c               ,    t        |   |f|||d|S )a>  Model wrapper that returns outputs formatted to match the given schema.

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

                - 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
                # }

        rK  )r  r  )r,  rT  r  r  r  rc  r{  s         r   r  z!ChatOpenAI.with_structured_output>  s/    F w-
!{6
MS
 	
r   )r#  zdict[str, str])r#  z	list[str]r$  )r#  r   r,  )r   r   rc  r   r#  r(  )r   r   rc  r   r#  r*  r  )rT  r.  r  r/  r  r   r  r   rc  r   r#  r0  )r   r   r   __doc__rP   r   r   r3  r9  r2  r>  rA  rC  r6  rX  r  r  r  r4  r5  s   @r   r7  r7    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   r7  c                <    t        | t              xr t        |       S r  )r   r   rJ   )objs    r   r  r    s    c4 ?%:3%??r   c                P    d| d   | d   t        j                  | d   d      dd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                &    d| d   | d   | d   ddS )Nrr   rc   rb   r   rR  rS  r   )invalid_tool_calls    r   r   r     s.     %%f-*62
 r   c                .   	 ddl m} t        |       r[	 dd l}|j                  |       }|j                          |j                  t        |j                              j                  \  }}||fS t        |       rU| j                  dd      \  }}t        j                   |      }|j                  t        |            j                  \  }}||fS y # t        $ r t        j	                  d       Y y w xY w# t        $ r t        j	                  d       Y y w xY w)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  )PILrY  r#  loggerinfo_is_urlr"  rw   raise_for_statusopenr	   re   size_is_b64splitr   	b64decode)	image_sourcerY  r"  rh  widthheightr  encodedr   s	            r   r  r    s	    |	 99\*!!#

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

74=166vf}3  -	
   	KK* 	s"   C C3 C0/C03DDc                n    t        | |      \  } }t        |dz        }t        | dz        }d|z  |z  dz   S )Ni      r  )_resizer   )rf  rg  hws       r   r  r    sA    E6*ME6Vc\AUS[A!GaK2r   c                    	 t        |       }t        |j                  |j                  g      S # t        $ r"}t
        j                  d|        Y d }~yd }~ww xY w)NzUnable to parse URL: 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                $    | j                  d      S )Nz
data:image)r  )rs  s    r   rb  rb    s    <<%%r   c                    | dkD  s|dkD  r| |kD  r|dz  | z  }d} n
| dz  |z  } d}| dkD  r"|dkD  r| |kD  r| dz  |z  } d}| |fS | dz  |z  }d} | |fS )Ni   i   r   )rf  rg  s     r   rk  rk    s    t|v}6>tm-FET\f,EFs{v|6>S[V+EF &= ckf,FE&=r   r  c                  t        | t              rt        |       r| S t        | t              rd| v r| j	                  d      dk(  r| }n}t        | t              rd| v r
d| v rd| d}n_|7t        | t              r%t        | j	                  d      t
              r| d   }nd}t        | |      }|j                  d	      |d<   d|d}|@||d   j	                  d      ur*t        | t              rd
| d   d    d| d}t        |      |S )Nr  r   rb   rT  )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   )rT  r  rR  rr   msgs        r   r  r  
  s*    &$$9&$A 	64 V#JJv-/ 	FD	!f&68v;M#0H>&$'Jvzz(7KT,R)-fVD%\\,7#0J 	/-8<<XFFvt$ ?m$X./ 0))/ 178 	 or   c                   | j                   j                  d      x}rt        |t              r |di |S |S | j                   j                  d      rt	        | j                   d         | j
                  ry t        d|        )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_msgrT  r   s      r   r  r  1  s     ))--h77v7fd##F##M		!	!	%	%i	0 !9!9)!DEE			++1(4
 	
r   c                      e Zd ZdZy)r{  am  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
    N)r   r   r   rM  r   r   r   r{  r{  D  s    	r   r{  c                   | j                  d      xs d}| j                  d      xs d}| j                  d      xs ||z   }| j                  d      xs i j                  d      | j                  d      xs i j                  d      d}| j                  d	      xs i j                  d      | j                  d	      xs i j                  d
      d}t        |||t        di |j                         D ci c]  \  }}|	|| c}}t	        di |j                         D ci c]  \  }}|	|| c}}      S c c}}w c c}}w )Nprompt_tokensr   completion_tokenstotal_tokens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   rG  rG  Q  sk   "&&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1q}q!tM
 0 
 4 : : <N1q!tN

 

 N Os   7
EE&
E1Ec                   | j                  dd      }| j                  dd      }| j                  d||z         }d| j                  d      xs i j                  d      i}d| j                  d	      xs i j                  d
      i}t        |||t        di |j                         D ci c]  \  }}|	|| c}}t	        di |j                         D ci c]  \  }}|	|| c}}      S c c}}w c c}}w )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"&&~|m7STLo))*ABHbMM
" 	**+ABHbMM
!
 !#!- 
 3 9 9 ;M1q}q!tM
 0 
 4 : : <N1q!tN

 

 N Os   (
C23C2
C8"C8c                    d| v xr | d   dk7  S )Nr   rr   r   )rt   s    r   _is_builtin_toolr    s    T>8d6lj88r   c                |    d| v xr t        d | d   D              }h d}t        |xs |j                  |             S )Nr  c              3  2   K   | ]  }t        |        y wr  )r  ).0rt   s     r   	<genexpr>z%_use_responses_api.<locals>.<genexpr>  s      4#'4s   >   r_  r   r   r  r  )r  r   intersection)rd  uses_builtin_toolsresponses_only_argss      r   r  r    sR     G+  4+27+;4 1 "O&9&F&Fw&OPPr   c                    t        t        |       dz
  dd      D ]F  }| |   }t        |t              s|j                  j                  d      }|r| |dz   d |fc S | dfc S  | dfS )aI  
    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  rS  rc   N)rangerH  r   r   response_metadatarw   )ra  iry  response_ids       r   r  r    s}     3x=1$b"- &qkc9%//33D9KA(+55~%& T>r   c                   dD ]  }||v s|j                  |      |d<    d|v rd|vrd|j                  d      i|d<   |j                  dd      }|j                  d      r|j                  d	d        t        |       |d
<   |j                  dd       x}rwg }|D ]k  }|d   dk(  rd|v r|j	                  ddi|d          (|d   dk(  r+d|v rt        d      |j                  d      r
d|vrd|d<   n	 |j	                  |       m ||d<   |j                  dd       x}r.t        |t              r|d   dk(  rd|v rddi|d   |d<   n||d<   |j                  dd       x}r|j                  d      r|d   }	t        d|d|	      |j                  dd       }
|j                  d      st        |      r||d<   nht        |      r|j                         }d}
n|}|ddik(  r
dddii|d<   n7t        ||
      x}r't        |t              r|d   dk(  rdddi|d   i|d<   n	 |j                  dd       }|d|vr	dddii|d<   ||d   d<   |S ) 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.r3  r  r  rR  r_  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  )ra  rd  legacy_token_paramr   r  	new_toolsrt   r  rT  r_  r  schema_dictrR  r   s                 r   r  r    s    F K(+2;;7I+JG'(K 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"%0GM" .55v5;;v6?DIXw(  Xt,{{8$);F)C%+GM"!&)$668$v}55#+fm-D"E (J#F( O   6$V,= v}W8VW# K.I '&&)9:GFO'0$Nr   c                    | j                   dd}t        | j                  t              rt	        d | j                  D              }nd| j                  d}||d<   d| j
                  v r| j
                  d   |d<   |S )Ncomputer_call_output)call_idr   c              3  L   K   | ]  }t        t        |      d    dk(  r|  yw)r   input_imageN)r   rx   )r  r   s     r   r  z:_make_computer_call_output_from_message.<locals>.<genexpr>#  s,      
D% (M9 
s   "$r  r   r;  acknowledged_safety_checks)ru   r   re   r   nextrl   )r   r  r;  s      r   '_make_computer_call_output_from_messager    s    ''&" '//4( 
 
 
 (gooF%+"#w'@'@@=D=V=V(>
9:  r   c                    d }| j                   D ]M  }t        |t              s|j                  d      dk(  s)d| j                  |j                  d      xs dd} |S  |S )Nr   custom_tool_call_outputr;  rf   )r   r  r;  )re   r   rx   rw   ru   )r   custom_tool_outputr   s      r   %_make_custom_tool_output_from_messager  3  sn     eT"uyy'8<U'U1"//))H-3"
  r   c                4   | j                         D ci c]  \  }}|dk7  s|| }}}d|v r^t        |d   t              rKg }|d   D ]<  }|j                         D ci c]  \  }}|dk7  s|| }}}|j                  |       > ||d<   |S c c}}w c c}}w )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     #(++-@$!Q1<A@I@I*Yy-A4"H"9- 	.I.7oo.?Pda1<QTPMP}-	.  +	) A Qs   BBB,Bc           	        g }| D ]  }t        |t              rt        |      }t        |      }d|v r|j	                  d       |d   dk(  r|d   }t        |      }|r|j                  |       k|j                  j                  d      dk(  r+t        t        t        |            }|j                  |       t        |t              st        |      }d||d   d	}|j                  |       |d   d
k(  rt        |j                  d      t              r|d   D ]  }t        |t              s|j                  d      x}	s(|	dv r|j                  d      }
|	dv rd|d   |j                  d      xs g d}n|	dk(  rd|d   d}|D ]:  }|j                  d      x}s||
k(  sd|vrg |d<   |d   j                           |j                  dgd
|
d       |	dv r|j                  t!        |             |	dk(  r|j                  d|d   d        n;t        |j                  d      t              r|j                  dd
d|d   dgd       |j	                  dd      x}sj|D ch c]  }|j                  d      dv r	d|v r|d     }}|D ]1  }|d   |vsd|d    d   |d    d!   |d   d"}|j                  |       3 |d   d#v rt        |d   t              rg }d$}|d   D ]  }|d   dk(  r|j                  d%|d   d       #|d   d&k(  r<d'|d&   d(   d)}|d&   j                  d*      r|d&   d*   |d*<   |j                  |       g|d   d+k(  rdd,i|d+   }|j                  |       |d   d-v r|j                  |       |d   |v r|j                  |        ||d<   |d   s|j                  |       |j                  |       |j                  |        |S c c}w ).z1Construct the input for the OpenAI Responses API.rb   ra   rt   re   r   r  function_call_outputru   )r   r;  r  rg   )r_  output_textr  rc   )r_  r  r  r_  r   )r   r_  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   r_  )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  )ra  r  lc_msgry  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 Nfi(1&9F&v.S=GGFOv;& i.K!Fv!N!01))--f59OO'Nf-($ 23!+s3",["9K2)">2($
 23[K'#''),d3 ^ 4!E!%.%))FBS4SJ4S%)KK%*YYt_F)-DD,9,1&M3899]3K3Qr-"	
 ",y!8,5/4Y/?-"	 )/ "/3xx~$=G$=7fCT'0'<:<Y$(O$:$:9$E$)" !'094=;0;.4	%&!" ( ,  #MM*B5*IJ'+BB"MM)@d T !i4!j CGGI.4 ) +-:C	N$S#T !WW\488z8 "($yy(,QQ!U* )$$  $ ", 5I .>>$3$-j$9&$A)2:)>{)K'0	) m45 [;;#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#]N` Mi$s   3#O:c                   t        | d      r| j                  S g }| j                  D ]N  }|j                  dk(  s|j                  D ]-  }|j                  dk(  s|j                  |j                         / P dj                  |      S )z1OpenAI SDK deleted response.output_text in 1.99.2r  r   rf   )r}  r  r;  r   re   ry   r_  join)rh  textsr;  re   s       r   _get_output_textr    s{    x'###E// /;;)#!>> /<<=0LL.// 775>r   c           	     D   | j                   rt        | j                         | j                  dd      j                         D ci c]  \  }}|dv r|| }}}|r|j	                  |       |j                  d      |d<   | j                  r$t        | j                  j                               }nd}g }g }	g }
i }| j                  D ]*  }|j                  dk(  r|j                  D ]  }|j                  d	k(  rmd
|j                  |j                  D cg c]  }|j                          c}|j                  d}|j                  |       t        |d      r|j                   |d<   |j                  dk(  s|j                  d|j"                  |j                  d        |j                  dk(  r|j                  |j                  dd             	 t%        j&                  |j(                  d      }d}|.d|j.                  ||j0                  d}|	j                  |       _d|j.                  ||j0                  |d}|
j                  |       |j                  dk(  r\|j                  |j                  dd             d|j.                  d|j2                  i|j0                  d}|	j                  |       |j                  dv s	|j                  |j                  dd             - t5        |       }|d|vr|r| j                  rw| j                  j                         x}r[|j                  di       x}rG|j                  d      dk(  r3	 t%        j&                  |      }|rt7        |      r	 |d i |}n|}||d<   t9        || j                  ||||	|
      }|dk(  rt;        |      }n	 t=        t?        |      g      S c c}}w c c}w # t*        $ r"}|j(                  }t-        |      }Y d}~d}~ww xY w# t$        j*                  $ r Y w xY w)!z9Construct ChatResponse from OpenAI Response API response.TrT  exclude_noner  )	
created_atrc   incomplete_detailsrU  objectstatusrd   r   r  r   r   Nr   r  r_  )r   r_  r   rc   r   r  )r   r  rc   rh   Fr  r   )r   rb   r   rc   rW  )r   rb   r   rc   r  r  __arg1)	r   r  r  r  r  r  r  r  r  r  r   r  )re   rc   rB  r  rl   ri   rm   r  r   )r  r   ) r  r   rz  r   updaterw   r?  r  r;  r   re   r_  r   rc   ry   r}  r   r  rT  loadsr   r
   r{   rb   r  r  r  r  r   rW   r=   r;   )rh  rT  rU  r  r   r   r  rB  content_blocksri   rm   rl   r;  re   
annotationr   r   r  r   r   r  text_configformat_parsed_dictr   r   s                             r   r  r    s    ~~(( ''T'GMMOAq

 	
1 $   *&7&;&;G&Dl#~~9(..:S:S:UVNJ // AU;;)#!>> <<=0 & ' /6.A.A( * '113( %iiE #))%0w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AUd #8,K--MM$MM4466[6#"55W5[[ M1	**[1K,V4.+.$*0h' ;;%++-G ,W5>'#B"CDDcL($ # ''AT ## 		s6   OO#O2P	 	P$PP	PPc           	        d/d0fd}g }	g }
i }|r|}ni }d }d }| j                   dk(  r> || j                  | j                         |	j                  d| j                  d       n| j                   dk(  rx || j                  | j                         t        | j                  t              r| j                  }n| j                  j                  dd      }|	j                  |gd	       nK| j                   d
k(  r |	j                  | j                  d       n| j                   dk(  r1| j                  j                  }| j                  j                  |d<   n| j                   dk(  rt        t        t        | j                  ||      j                  d   j                         }|j"                  j%                  d      x}r||d<   |j&                  }|j(                  j+                         D ci c]  \  }}|dk7  s|| }}}n-| j                   dk(  r8| j,                  j                   dk(  r|dk(  r| j,                  j                  }nn| j                   dk(  r| j,                  j                   dk(  r || j                         |
j                  d| j,                  j.                  | j,                  j0                  | j,                  j2                  d       |	j                  d| j,                  j.                  | j,                  j0                  | j,                  j2                  | j,                  j                  d       n| j                   dk(  r_| j,                  j                   dv rG || j                         | j,                  j                  dd      }|d<   |	j                  |       n| j                   dk(  r| j,                  j                   dk(  r || j                         | j,                  j                  dd      }|d<   |	j                  |       |
j                  d| j,                  j.                  t5        j6                  d| j,                  j8                  i      | j,                  j2                  d       n| j                   dk(  rR || j                         |
j                  d| j                  d       |	j                  d| j                  d        nI| j                   d!k(  r |	j                  d"| j:                  d#       n| j                   dk(  r_| j,                  j                   d$k(  rF || j                         | j,                  j                  dd      }|d<   |	j                  |       n| j                   d%k(  r7 || j                         |	j                  | j<                  d&d'd(gd$d)       nf| j                   d*k(  rnV| j                   d+k(  rA || j                         |	j                  | j<                  d&| j                  d(gd$d)       nd fS t?        |	|
||||,      }|dk(  rt        t>        tA        ||-            }n	 tC        |.      fS c c}}w )1Nc                J    || k7  rdz  | y| k7  s|k7  rdz  || y)a3  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_idxrj  rk  rl  s     r   _advancez>_convert_responses_chunk_to_generation_chunk.<locals>._advance  sM    H ?#z1"
  * %
28IW8T" ')r   zresponse.output_text.deltar_  )r   r_  r   z%response.output_text.annotation.addedTrT  r  )r   r   zresponse.output_text.done)rc   r   zresponse.createdrc   zresponse.completed)rT  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   r_  )r  r   r   z,response.image_generation_call.partial_imagez%response.reasoning_summary_text.delta)re   r   rB  r  rl   rc   )rV  r  r  )r  r   r  r   r#  None)"r   output_indexcontent_indexry   rE  r   r  rx   rz  r  rh  rc   r   r   r  r  r   rl   rw   rB  r  r   r  rb   r   r  rT  rU  r  r  summary_indexr    rW   r<   )rA  rj  rk  rl  rT  rU  rV  r  r  re   r   rl   r  rB  rc   r  ry  r   r   r   r  r   r   s    ```                   r   r]  r]    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:
Qa4iAqD
 
 
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   8Z Z )r|   Mapping[str, Any]r#  r!   )re   r   r#  r   )r   r!   r#  rx   )r|   r  r   ztype[BaseMessageChunk]r#  r"   )r   Union[int, dict]r   r  r#  r  )r   zopenai.BadRequestErrorr#  r  )rO  r   r#  r   )r   r,   r#  rx   )rW  r)   r#  rx   )re  r{   r#  zOptional[tuple[int, int]])rf  r   rg  r   r#  r   )rs  r{   r#  r   )rf  r   rg  r   r#  ztuple[int, int])rT  zUnion[dict[str, Any], type]r  r   r#  zUnion[dict, TypeBaseModel])r|  r   rT  z	type[_BM]r#  zOptional[PydanticBaseModel])r  rx   r#  r3   )rt   rx   r#  r   r+  )ra  Sequence[BaseMessage]r#  z+tuple[Sequence[BaseMessage], Optional[str]])ra  r  rd  rx   r#  rx   )r   r-   r#  rx   )r   r-   r#  r%  )r   rx   r#  rx   )ra  r  r#  r   )rh  rX   r#  r{   )NNr  )
rh  rX   rT  Optional[type[_BM]]rU  r%  r  r  r#  r=   )NNFr  )rA  r   rj  r   rk  r   rl  r   rT  r  rU  r%  rV  r   r  r  r#  z3tuple[int, int, int, Optional[ChatGenerationChunk]])rM  
__future__r   r   rT  loggingr  rF  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   r7  r  r   r   r  r  r^  rb  rk  r  r  rz   r{  rG  r  r  r  r  r  r  r  r  r  r  r  r]  r   r   r   <module>r#     s    "    	 	 
 
  F F      
 
 
 "    6 >     ( 
 9 P  S R  < ) 0 9 
 V U M M 0 "
 /			8	$ 0S//}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   