
    dh6_                    N   S SK Jr  S SKJrJrJrJrJrJrJ	r	J
r
  S SKJrJr  S SKJr  S SKJr  S SKJr  S SKJrJr  S SKJr  S S	KJr  S S
KJrJrJr  S SKJ r   \(       a  S SK!r!S SK"J#r#  S SK$J%r&  SS jr'SS jr(SS jr)    SS jr*    SS jr+\" 5        " S S\5      5       r,g)    )annotations)TYPE_CHECKINGAnyCallableDictOptionalSequenceTypeUnion)OpenAIAssistantRunnable
OutputType)beta)CallbackManager)dumpd)RunnableConfigensure_config)BaseTool)convert_to_openai_tool)	BaseModelFieldmodel_validator)SelfN)NotGiven)ToolResourcesc                      SSK n U R                  " SS0S9$ ! [         a  n[        S5      UeSnAf[         a  n[        S5      UeSnAff = f)zGet the OpenAI client.

Returns:
    openai.OpenAI: OpenAI client

Raises:
    ImportError: If `openai` is not installed.
    AttributeError: If the installed `openai` version is not compatible.
r   NOpenAI-Betaassistants=v2default_headersBUnable to import openai, please install with `pip install openai`.wPlease make sure you are using a v1.23-compatible version of openai. You can install with `pip install "openai>=1.23"`.)openaiOpenAIImportErrorAttributeErrorr"   es     h/var/www/html/shao/venv/lib/python3.13/site-packages/langchain_community/agents/openai_assistant/base.py_get_openai_clientr)      sc    }}m_-MNN P
	  =
 	    
A.AAAc                      SSK n U R                  " SS0S9$ ! [         a  n[        S5      UeSnAf[         a  n[        S5      UeSnAff = f)zGet the async OpenAI client.

Returns:
    openai.AsyncOpenAI: Async OpenAI client

Raises:
    ImportError: If `openai` is not installed.
    AttributeError: If the installed `openai` version is not compatible.
r   Nr   r   r   r    r!   )r"   AsyncOpenAIr$   r%   r&   s     r(   _get_openai_async_clientr-   7   se    !!=/2RSS P
	  =
 	r*   c                P    / nU  H  nUR                  USS0SS0/S.5        M     U$ )zConvert file_ids into attachments
File search and Code interpreter will be turned on by default.

Args:
    file_ids (list): List of file_ids that need to be converted into attachments.

Returns:
    list: List of attachments converted from file_ids.
typefile_searchcode_interpreter)file_idtools)append)file_idsattachmentsids      r(   "_convert_file_ids_into_attachmentsr8   P   sD     K!=1F<N3OP	
      c                \    Sn[        U [        5      =(       a    SU ;   =(       a    U S   U;   $ )a1  Determine if tool corresponds to OpenAI Assistants built-in.

Args:
    tool (Union[Dict[str, Any], Type[BaseModel], Callable, BaseTool]):
        Tool that needs to be determined.

Returns:
    A boolean response of true or false indicating if the tool corresponds to
        OpenAI Assistants built-in.
)r1   	retrievalr0   r/   )
isinstancedict)toolassistants_builtin_toolss     r(   _is_assistants_builtin_toolr@   e   s8      P4 	7t^	7&\55r9   c                <    [        U 5      (       a  U $ [        U 5      $ )a  Convert a raw function/class to an OpenAI tool.

Note that OpenAI assistants supports several built-in tools,
such as "code_interpreter" and "retrieval."

Args:
    tool (Union[Dict[str, Any], Type[BaseModel], Callable, BaseTool]):
        Tools or functions that need to be converted to OpenAI tools.

Returns:
    Dict[str, Any]: A dictionary of tools that are converted into OpenAI tools.
)r@   r   )r>   s    r(   _get_assistants_toolrB   z   s     #4((%d++r9   c                  r   \ rS rSr% Sr\" \S9rS\S'    Sr	S\S'    S\S	'    S
r
S\S'    SrS\S'    \" SS9SS j5       r\0 SSSS.                   SS jj5       r S        S!S jjr\SSS.               S"S jj5       r S        S!S jjrS#S jrS$S jrS#S jrS$S jrSrg)%OpenAIAssistantV2Runnable   a  Run an OpenAI Assistant.

Attributes:
    client (Any): OpenAI or AzureOpenAI client.
    async_client (Any): Async OpenAI or AzureOpenAI client.
    assistant_id (str): OpenAI assistant ID.
    check_every_ms (float): Frequency to check progress in milliseconds.
    as_agent (bool): Whether to use the assistant as a LangChain agent.

Example using OpenAI tools:
    .. code-block:: python

        from langchain.agents.openai_assistant import OpenAIAssistantV2Runnable

        assistant = OpenAIAssistantV2Runnable.create_assistant(
            name="math assistant",
            instructions="You are a personal math tutor. Write and run code to answer math questions.",
            tools=[{"type": "code_interpreter"}],
            model="gpt-4-1106-preview"
        )
        output = assistant.invoke({"content": "What's 10 - 4 raised to the 2.7"})

Example using custom tools and AgentExecutor:
    .. code-block:: python

        from langchain.agents.openai_assistant import OpenAIAssistantV2Runnable
        from langchain.agents import AgentExecutor
        from langchain.tools import E2BDataAnalysisTool


        tools = [E2BDataAnalysisTool(api_key="...")]
        agent = OpenAIAssistantV2Runnable.create_assistant(
            name="langchain assistant e2b tool",
            instructions="You are a personal math tutor. Write and run code to answer math questions.",
            tools=tools,
            model="gpt-4-1106-preview",
            as_agent=True
        )

        agent_executor = AgentExecutor(agent=agent, tools=tools)
        agent_executor.invoke({"content": "Analyze the data..."})

Example using custom tools and custom execution:
    .. code-block:: python

        from langchain.agents.openai_assistant import OpenAIAssistantV2Runnable
        from langchain.agents import AgentExecutor
        from langchain_core.agents import AgentFinish
        from langchain.tools import E2BDataAnalysisTool


        tools = [E2BDataAnalysisTool(api_key="...")]
        agent = OpenAIAssistantV2Runnable.create_assistant(
            name="langchain assistant e2b tool",
            instructions="You are a personal math tutor. Write and run code to answer math questions.",
            tools=tools,
            model="gpt-4-1106-preview",
            as_agent=True
        )

        def execute_agent(agent, tools, input):
            tool_map = {tool.name: tool for tool in tools}
            response = agent.invoke(input)
            while not isinstance(response, AgentFinish):
                tool_outputs = []
                for action in response:
                    tool_output = tool_map[action.tool].invoke(action.tool_input)
                    tool_outputs.append({"output": tool_output, "tool_call_id": action.tool_call_id})
                response = agent.invoke(
                    {
                        "tool_outputs": tool_outputs,
                        "run_id": action.run_id,
                        "thread_id": action.thread_id
                    }
                )

            return response

        response = execute_agent(agent, tools, {"content": "What's 10 - 4 raised to the 2.7"})
        next_response = execute_agent(agent, tools, {"content": "now add 17.241", "thread_id": response.thread_id})

)default_factoryr   clientNasync_clientstrassistant_idg     @@floatcheck_every_msFboolas_agentafter)modec                ~    U R                   c/  SSKnU R                  R                  nUR                  " US9U l         U $ )z?Validate that the async client is set, otherwise initialize it.Nr   )api_key)rH   r"   rG   rR   r,   )selfr"   rR   s      r(   validate_async_client/OpenAIAssistantV2Runnable.validate_async_client   s:     $kk))G & 2 27 CDr9   )model_kwargsrG   tool_resources
extra_bodyc                   U=(       d
    [        5       nUc  SSKJn
  U
nUR                  R                  R
                  " SUUU Vs/ sH  n[        U5      PM     snUUUS.UD6nU " SUR                  US.U	D6$ s  snf )ap  Create an OpenAI Assistant and instantiate the Runnable.

Args:
    name (str): Assistant name.
    instructions (str): Assistant instructions.
    tools (Sequence[Union[BaseTool, dict]]): Assistant tools. Can be passed
        in OpenAI format or as BaseTools.
    tool_resources (Optional[Union[AssistantToolResources, dict, NotGiven]]):
        Assistant tool resources. Can be passed in OpenAI format.
    model (str): Assistant model to use.
    client (Optional[Union[openai.OpenAI, openai.AzureOpenAI]]): OpenAI or
        AzureOpenAI client. Will create default OpenAI client (Assistant v2)
        if not specified.
    model_kwargs: Additional model arguments. Only available for temperature
        and top_p parameters.
    extra_body: Additional body parameters to be passed to the assistant.

Returns:
    OpenAIAssistantRunnable: The configured assistant runnable.
r   	NOT_GIVEN)nameinstructionsr3   rW   modelrX   )rJ   rG    )r)   openai._typesr[   r   
assistantscreaterB   r7   )clsr\   r]   r3   r^   rV   rG   rW   rX   kwargsr[   r>   	assistants                r(   create_assistant*OpenAIAssistantV2Runnable.create_assistant   s    D /-/!/&NKK**11 
%:?@%$'-%@)!
 
	 F	VFvFF As   A:c           	     x   [        U5      n[        R                  " UR                  S5      UR                  S5      UR                  S5      S9nUR	                  [        U 5      XR                  S5      =(       d    U R                  5       S9n[        UR                  S/ 5      5      nUR                  S/ 5      U-   n U R                  (       ae  UR                  S	5      (       aO  U R                  US	   5      nU R                  R                  R                  R                  R                  " S0 UD6n	OS
U;  a>  SUS   UUR                  S5      S./UR                  S5      S.n
U R                  X5      n	OSU;  ab  U R                  R                  R                  R                   R#                  US
   US   SUUR                  S5      S9nU R%                  U5      n	O:U R                  R                  R                  R                  R                  " S0 UD6n	U R'                  U	R(                  U	R*                  5      n	 U R1                  U	5      nUR3                  U5        U$ ! [,         a  nUR/                  U5        UeSnAff = f! [,         a$  nUR/                  XR5                  5       S9  UeSnAff = f)aX  Invoke the assistant.

Args:
    input (dict): Runnable input dict that can have:
        content: User message when starting a new run.
        thread_id: Existing thread to use.
        run_id: Existing run to use. Should only be supplied when providing
            the tool output for a required action after an initial invocation.
        file_ids: (deprecated) File ids to include in new run. Use
            'attachments' instead
        attachments: Assistant files to include in new run. (v2 API).
        message_metadata: Metadata to associate with new message.
        thread_metadata: Metadata to associate with new thread. Only relevant
            when new thread being created.
        instructions: Additional run instructions.
        model: Override Assistant model for this run.
        tools: Override Assistant tools for this run.
        tool_resources: Override Assistant tool resources for this run (v2 API).
        run_metadata: Metadata to associate with new run.
    config (Optional[RunnableConfig]): Configuration for the run.

Returns:
    OutputType: If self.as_agent, will return
        Union[List[OpenAIAssistantAction], OpenAIAssistantFinish]. Otherwise,
        will return OpenAI types
        Union[List[ThreadMessage], List[RequiredActionFunctionToolCall]].

Raises:
    BaseException: If an error occurs during the invocation.
	callbackstagsmetadatainheritable_callbacksinheritable_tagsinheritable_metadatarun_namer\   r5   r6   intermediate_steps	thread_idusercontentmessage_metadataroleru   r6   rk   thread_metadatamessagesrk   run_idru   rx   r6   rk   Nrk   r_   )r   r   	configuregeton_chain_startr   get_namer8   rN   _parse_intermediate_stepsrG   r   threadsrunssubmit_tool_outputs_create_thread_and_runr{   rb   _create_run_wait_for_runr7   rs   BaseExceptionon_chain_error_get_responseon_chain_endr=   rS   inputconfigrd   callback_managerrun_managerfilesr6   tool_outputsrunthread_r'   responses                 r(   invoke OpenAIAssistantV2Runnable.invoke+  s   B v&*44"(**["9#ZZ/!'J!7

 '55$KZZ
%;%Nt}} 6 
 36::j"3MNjj3e;&	}}+?!@!@#==./  kk&&..33GGW,WE) %+',Y'7+6(-		2D(E	! !&		*; <
 11%@&KK$$,,55<<+&!), +"YY'9: =  &&u- kk&&..33GGP%P$$SVVS]];C	))#.H
 $$X.O  	&&q)G	
  	&&q88:&>G	s1   ?FI& J &
J0JJ
J9J44J9)rH   rW   c                 #    U=(       d
    [        5       nUc  SSKJn  UnU V	s/ sH  n	[        U	5      PM     n
n	UR                  R
                  R                  UUU
UUS9I Sh  vN nU " SUR                  US.UD6$ s  sn	f  N7f)a  Create an AsyncOpenAI Assistant and instantiate the Runnable.

Args:
    name (str): Assistant name.
    instructions (str): Assistant instructions.
    tools (Sequence[Union[BaseTool, dict]]): Assistant tools. Can be passed
        in OpenAI format or as BaseTools.
    tool_resources (Optional[Union[AssistantToolResources, dict, NotGiven]]):
        Assistant tool resources. Can be passed in OpenAI format.
    model (str): Assistant model to use.
    async_client (Optional[Union[openai.OpenAI, openai.AzureOpenAI]]): OpenAI or
    AzureOpenAI async client. Will create default async_client if not specified.

Returns:
    AsyncOpenAIAssistantRunnable: The configured assistant runnable.
Nr   rZ   )r\   r]   r3   rW   r^   )rJ   rH   r_   )r-   r`   r[   rB   r   ra   rb   r7   )rc   r\   r]   r3   r^   rH   rW   rd   r[   r>   openai_toolsre   s               r(   acreate_assistant+OpenAIAssistantV2Runnable.acreate_assistant  s     < $A'?'A!/&N?DEut,T2uE&++66==%) > 
 
	 R	<R6RR F
s   #BA?,B%B&Bc           	       #    U=(       d    0 n[         R                  " UR                  S5      UR                  S5      UR                  S5      S9nUR                  [	        U 5      XR                  S5      =(       d    U R                  5       S9n[        UR                  S/ 5      5      nUR                  S/ 5      U-   n U R                  (       an  UR                  S	5      (       aX  U R                  US	   5      nU R                  R                  R                  R                  R                  " S0 UD6I S
h  vN n	GOSU;  aF  SUS   UUR                  S5      S./UR                  S5      S.n
U R                  X5      I S
h  vN n	OSU;  ar  U R                  R                  R                  R                  R!                  US   US   SUUR                  S5      S9I S
h  vN nU R#                  U5      I S
h  vN n	OBU R                  R                  R                  R                  R                  " S0 UD6I S
h  vN n	U R%                  U	R&                  U	R(                  5      I S
h  vN n	 U R/                  U	5      nUR1                  U5        U$  GN` GN N N Na N5! [*         a  nUR-                  U5        UeS
nAff = f! [*         a$  nUR-                  XR3                  5       S9  UeS
nAff = f7f)aZ  Async invoke assistant.

Args:
    input (dict): Runnable input dict that can have:
        content: User message when starting a new run.
        thread_id: Existing thread to use.
        run_id: Existing run to use. Should only be supplied when providing
            the tool output for a required action after an initial invocation.
        file_ids: (deprecated) File ids to include in new run. Use
            'attachments' instead
        attachments: Assistant files to include in new run. (v2 API).
        message_metadata: Metadata to associate with new message.
        thread_metadata: Metadata to associate with new thread. Only relevant
            when new thread being created.
        instructions: Additional run instructions.
        model: Override Assistant model for this run.
        tools: Override Assistant tools for this run.
        tool_resources: Override Assistant tool resources for this run (v2 API).
        run_metadata: Metadata to associate with new run.
    config (Optional[RunnableConfig]): Configuration for the run.

Returns:
    OutputType: If self.as_agent, will return
        Union[List[OpenAIAssistantAction], OpenAIAssistantFinish]. Otherwise,
        will return OpenAI types
        Union[List[ThreadMessage], List[RequiredActionFunctionToolCall]].

Raises:
    BaseException: If an error occurs during the invocation.
ri   rj   rk   rl   rp   rq   r5   r6   rr   Nrs   rt   ru   rv   rw   ry   rz   r|   r}   r~   r_   )r   r   r   r   r   r   r8   rN   r   rH   r   r   r   r   _acreate_thread_and_runr{   rb   _acreate_run_await_for_runr7   rs   r   r   r   r   r=   r   s                 r(   ainvoke!OpenAIAssistantV2Runnable.ainvoke  s    B 2*44"(**["9#ZZ/!'J!7

 '55$KZZ
%;%Nt}} 6 
 36::j"3MNjj3e;*	}}+?!@!@#==./  !--22::??SS "  E) %+',Y'7+6(-		2D(E	! !&		*; <
 !88GG&++0088AAHH+&!), +"YY'9: I   !--e44 !--22::??SS   ++CFFCMMBBC	))#.H
 $$X.OY  H 5 C 	&&q)G	
  	&&q88:&>G	s   B>K=A8J' 9J:AJ' JAJ' %J&J' >J!?AJ' J#-J' /J%0J' 5K K=J' J' J' !J' #J' %J' '
K	1KK		K=
K:K55K::K=c                    SnUR                  5        VVs0 sH  u  p4X2;   d  M  X4_M     nnnU R                  R                  R                  R                  R
                  " US   4SU R                  0UD6$ s  snnf )zCreate a new run within an existing thread.

Args:
    input (dict): The input data for the new run.

Returns:
    Any: The created run object.
)r]   r^   r3   rW   run_metadatatruncation_strategymax_prompt_tokensrs   rJ   )itemsrG   r   r   r   rb   rJ   )rS   r   allowed_assistant_paramskvparamss         r(   r   %OpenAIAssistantV2Runnable._create_run  s    $
  $);;=R=41A4Q$!$=R{{'',,33+
**
 
 	
 Ss
   
A7A7c                   UR                  5        VVs0 sH  u  p4US;   d  M  X4_M     nnnUR                  S5      =n(       a  XbS'   U R                  R                  R                  R
                  " SU R                  US.UD6nU$ s  snnf )zCreate a new thread and run.

Args:
    input (dict): The input data for the run.
    thread (dict): The thread data to create.

Returns:
    Any: The created thread and run.
r]   r^   r3   r   rW   rJ   r   r_   )r   r   rG   r   r   create_and_runrJ   rS   r   r   r   r   r   rW   r   s           r(   r   0OpenAIAssistantV2Runnable._create_thread_and_run2  s     
%FF AD% 	 

 #YY'788>8'5#$kk&&55 
**
 

 

s
   BBc                  #    UR                  5        VVs0 sH  u  p#US;   d  M  X#_M     nnnU R                  R                  R                  R                  R
                  " US   4SU R                  0UD6I Sh  vN $ s  snnf  N
7f)zAsynchronously create a new run within an existing thread.

Args:
    input (dict): The input data for the new run.

Returns:
    Any: The created run object.
)r]   r^   r3   rW   r   rs   rJ   N)r   rH   r   r   r   rb   rJ   )rS   r   r   r   r   s        r(   r   &OpenAIAssistantV2Runnable._acreate_runJ  s      
%XX AD% 	 

 &&++3388??+
**
 
 
 	



s!   BB B AB;B<Bc                6  #    UR                  5        VVs0 sH  u  p4US;   d  M  X4_M     nnnUR                  S5      =n(       a  XbS'   U R                  R                  R                  R
                  " SU R                  US.UD6I Sh  vN nU$ s  snnf  N7f)zAsynchronously create a new thread and run simultaneously.

Args:
    input (dict): The input data for the run.
    thread (dict): The thread data to create.

Returns:
    Any: The created thread and run.
r   rW   r   Nr_   )r   r   rH   r   r   r   rJ   r   s           r(   r   1OpenAIAssistantV2Runnable._acreate_thread_and_run^  s      
%FF AD% 	 

 #YY'788>8'5#$%%**22AA 
**
 
 

 


s!   BBBAB
BB)rH   )returnr   )r\   rI   r]   rI   r3   Sequence[Union[BaseTool, dict]]r^   rI   rV   zdict[str, float]rG   z2Optional[Union[openai.OpenAI, openai.AzureOpenAI]]rW   7Optional[Union[AssistantToolResources, dict, NotGiven]]rX   zOptional[object]rd   r   r   r   )N)r   r=   r   zOptional[RunnableConfig]rd   r   r   r   )r\   rI   r]   rI   r3   r   r^   rI   rH   z<Optional[Union[openai.AsyncOpenAI, openai.AsyncAzureOpenAI]]rW   r   rd   r   r   r   )r   r=   r   r   )r   r=   r   r=   r   r   )__name__
__module____qualname____firstlineno____doc__r   r)   rG   __annotations__rH   rL   rN   r   rT   classmethodrf   r   r   r   r   r   r   r   __static_attributes__r_   r9   r(   rD   rD      s   Qf (:;FC;'L#-#NE#EHdF'" #  *,EIRV'+/G/G /G /	/G
 /G '/G C/G P/G %/G /G 
!/G /Gd ?C\\#;\NQ\	\|  RV+S+S +S /	+S
 +S
+S P+S +S 
!+S +S\ ?C``#;`NQ`	`D
20
(r9   rD   )r   zopenai.OpenAI)r   zopenai.AsyncOpenAI)r5   listr   r   )r>   :Union[Dict[str, Any], Type[BaseModel], Callable, BaseTool]r   rM   )r>   r   r   zDict[str, Any])-
__future__r   typingr   r   r   r   r   r	   r
   r   &langchain.agents.openai_assistant.baser   r   langchain_core._apir   langchain_core.callbacksr   langchain_core.loadr   langchain_core.runnablesr   r   langchain_core.toolsr   %langchain_core.utils.function_callingr   pydanticr   r   r   typing_extensionsr   r"   r`   r   openai.types.beta.assistantr   AssistantToolResourcesr)   r-   r8   r@   rB   rD   r_   r9   r(   <module>r      s    "	 	 	 W $ 4 % B ) H 6 6 "&S22*
D	*,
D,,* d 7 d dr9   