
    h6_                    :   d dl mZ d dlmZmZmZmZmZmZm	Z	m
Z
 d dlmZmZ d dlmZ d dlmZ d dlmZ d dlmZmZ d dlmZ d d	lmZ d d
lmZmZmZ d dlm Z  erd dl!Z!d dl"m#Z# d dl$m%Z& ddZ'ddZ(ddZ)	 	 	 	 ddZ*	 	 	 	 ddZ+ e        G d de             Z,y)    )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                     	 ddl }  | j                  ddi      S # t        $ r}t        d      |d}~wt        $ r}t        d      |d}~ww xY w)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     n/var/www/html/eduruby.in/venv/lib/python3.12/site-packages/langchain_community/agents/openai_assistant/base.py_get_openai_clientr)      se    v}}m_-MNN P
	  =
 	    	A0AAAc                     	 ddl }  | j                  ddi      S # t        $ r}t        d      |d}~wt        $ r}t        d      |d}~ww xY w)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   sg    !v!!=/2RSS P
	  =
 	r*   c                L    g }| D ]  }|j                  |ddiddigd        |S )a  Convert 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   sI     K 
!=1F<N3OP	

     c                D    d}t        | t              xr d| v xr | d   |v S )aM  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                2    t        |       r| S t        |       S )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                  \   e Zd ZU dZ ee      Zded<   	 dZded<   	 ded<   	 d	Z	d
ed<   	 dZ
ded<   	  ed      dd       Zei dddd	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 dd       Z	 d	 	 	 	 	 	 	 ddZeddd	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 d d       Z	 d	 	 	 	 	 	 	 ddZd!dZd"dZd!dZd"dZy)#OpenAIAssistantV2Runnablea  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                    | j                   2ddl}| j                  j                  } |j                  |      | _         | S )z?Validate that the async client is set, otherwise initialize it.Nr   )api_key)rG   r"   rF   rQ   r,   )selfr"   rQ   s      r(   validate_async_clientz/OpenAIAssistantV2Runnable.validate_async_client   s<     $kk))G 2 2 27 CDr9   )model_kwargsrF   tool_resources
extra_bodyc                   |xs
 t               }|ddlm}
 |
} |j                  j                  j
                  d|||D cg c]  }t        |       c}|||d|} | d|j                  |d|	S c c}w )a  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   rU   modelrV   )rI   rF    )r)   openai._typesrY   r   
assistantscreaterB   r7   )clsrZ   r[   r3   r\   rT   rF   rU   rV   kwargsrY   r>   	assistants                r(   create_assistantz*OpenAIAssistantV2Runnable.create_assistant   s    D /-/!/&N1FKK**11 
%:?@$'-@)!
 
	 F	VFvFF As    A2c           	     j   t        |      }t        j                  |j                  d      |j                  d      |j                  d            }|j	                  t        |       ||j                  d      xs | j                               }t        |j                  dg             }|j                  dg       |z   }	 | j                  r`|j                  d	      rO| j                  |d	         } | j                  j                  j                  j                  j                  di |}	nd
|vr?d|d   ||j                  d      dg|j                  d      d}
| j                  ||
      }	nd|vre| j                  j                  j                  j                   j#                  |d
   |d   d||j                  d            }| j%                  |      }	n: | j                  j                  j                  j                  j                  di |}	| j'                  |	j(                  |	j*                        }		 | j1                  |	      }|j3                  |       |S # t,        $ r}|j/                  |       |d}~ww xY w# t,        $ r(}|j/                  ||	j5                                |d}~ww xY w)a(  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rZ   r5   r6   intermediate_steps	thread_idusercontentmessage_metadatarolerr   r6   rh   thread_metadatamessagesrh   run_idrr   ru   r6   rh   Nrh   r]   )r   r   	configuregeton_chain_startr   get_namer8   rM   _parse_intermediate_stepsrF   r   threadsrunssubmit_tool_outputs_create_thread_and_runrx   r`   _create_run_wait_for_runr7   rp   BaseExceptionon_chain_error_get_responseon_chain_endr=   rR   inputconfigrb   callback_managerrun_managerfilesr6   tool_outputsrunthread_r'   responses                 r(   invokez OpenAIAssistantV2Runnable.invoke+  s   B v&*44"(**["9#ZZ/!'J!7

 '55$KVZZ
%;%Nt}} 6 
 36::j"3MNjj3e;&	}}+?!@#==./  Hdkk&&..33GGW,WE) %+',Y'7+6(-		2D(E	! !&		*; <
 11%@&KK$$,,55<<+&!), +"YY'9: =  &&u- Hdkk&&..33GGP%P$$SVVS]];C	))#.H
 $$X.O  	&&q)G	
  	&&q388:&>G	s1    E8I 9J 	I>&I99I>	J2
#J--J2)rG   rU   c                 K   |xs
 t               }|ddlm} |}|D 	cg c]  }	t        |	       }
}	|j                  j
                  j                  |||
||       d{   } | d|j                  |d|S c c}	w 7 w)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   rX   )rZ   r[   r3   rU   r\   )rI   rG   r]   )r-   r^   rY   rB   r   r_   r`   r7   )ra   rZ   r[   r3   r\   rG   rU   rb   rY   r>   openai_toolsrc   s               r(   acreate_assistantz+OpenAIAssistantV2Runnable.acreate_assistant  s     < $A'?'A!/&N?DEt,T2EE&++66==%) > 
 
	 R	<R6RR F
s   BA:/B A?!Bc           	       K   |xs i }t        j                  |j                  d      |j                  d      |j                  d            }|j                  t	        |       ||j                  d      xs | j                               }t        |j                  dg             }|j                  dg       |z   }	 | j                  ri|j                  d	      rX| j                  |d	         } | j                  j                  j                  j                  j                  di | d
{   }	nd|vrGd|d   ||j                  d      dg|j                  d      d}
| j                  ||
       d
{   }	nd|vru| j                  j                  j                  j                  j!                  |d   |d   d||j                  d             d
{   }| j#                  |       d
{   }	nB | j                  j                  j                  j                  j                  di | d
{   }	| j%                  |	j&                  |	j(                         d
{   }		 | j/                  |	      }|j1                  |       |S 7 `7 7 7 7 a7 5# t*        $ r}|j-                  |       |d
}~ww xY w# t*        $ r(}|j-                  ||	j3                                |d
}~ww xY ww)a*  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.
        rf   rg   rh   ri   rm   rn   r5   r6   ro   Nrp   rq   rr   rs   rt   rv   rw   ry   rz   r{   r]   )r   r|   r}   r~   r   r   r8   rM   r   rG   r   r   r   r   _acreate_thread_and_runrx   r`   _acreate_run_await_for_runr7   rp   r   r   r   r   r=   r   s                 r(   ainvokez!OpenAIAssistantV2Runnable.ainvoke  s    B 2*44"(**["9#ZZ/!'J!7

 '55$KVZZ
%;%Nt}} 6 
 36::j"3MNjj3e;*	}}+?!@#==./  TD--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 TD--22::??SS   ++CFFCMMBBC	))#.H
 $$X.OY  H 5 C 	&&q)G	
  	&&q388:&>G	s   B:K1=A.J +J,AJ 7J8AJ JJ 0J1AJ 3J4-J !J"J 'J= 8K1J J J J J J 	J:"J55J::K1=	K.#K))K..K1c                    d}|j                         D ci c]  \  }}||v s|| }}} | j                  j                  j                  j                  j
                  |d   fd| j                  i|S c c}}w )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   rU   run_metadatatruncation_strategymax_prompt_tokensrp   rI   )itemsrF   r   r   r   r`   rI   )rR   r   allowed_assistant_paramskvparamss         r(   r   z%OpenAIAssistantV2Runnable._create_run  s    $
  $);;=R41aA9Q4Q!Q$RR3t{{'',,33+
**
 
 	
 Ss
   A5A5c                
   |j                         D ci c]  \  }}|dv r|| }}}|j                  d      x}r||d<    | j                  j                  j                  j
                  d| j                  |d|}|S c c}}w )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   rU   rI   r   r]   )r   r}   rF   r   r   create_and_runrI   rR   r   r   r   r   r   rU   r   s           r(   r   z0OpenAIAssistantV2Runnable._create_thread_and_run2  s     
1FF qD
 

 #YY'788>8'5F#$5dkk&&55 
**
 

 

s   A?c                  K   |j                         D ci c]  \  }}|dv r|| }}} | j                  j                  j                  j                  j
                  |d   fd| j                  i| d{   S c c}}w 7 
w)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   rU   r   rp   rI   N)r   rG   r   r   r   r`   rI   )rR   r   r   r   r   s        r(   r   z&OpenAIAssistantV2Runnable._acreate_runJ  s      
1XX qD
 

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


s   BA<AB7B8Bc                &  K   |j                         D ci c]  \  }}|dv r|| }}}|j                  d      x}r||d<    | j                  j                  j                  j
                  d| j                  |d| d{   }|S c c}}w 7 w)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   rU   r   Nr]   )r   r}   rG   r   r   r   rI   r   s           r(   r   z1OpenAIAssistantV2Runnable._acreate_thread_and_run^  s      
1FF qD
 

 #YY'788>8'5F#$AD%%**22AA 
**
 
 

 


s   BB	ABBB)returnr   )rZ   rH   r[   rH   r3   Sequence[Union[BaseTool, dict]]r\   rH   rT   zdict[str, float]rF   z2Optional[Union[openai.OpenAI, openai.AzureOpenAI]]rU   7Optional[Union[AssistantToolResources, dict, NotGiven]]rV   zOptional[object]rb   r   r   r   )N)r   r=   r   zOptional[RunnableConfig]rb   r   r   r   )rZ   rH   r[   rH   r3   r   r\   rH   rG   z<Optional[Union[openai.AsyncOpenAI, openai.AsyncAzureOpenAI]]rU   r   rb   r   r   r   )r   r=   r   r   )r   r=   r   r=   r   r   )__name__
__module____qualname____doc__r   r)   rF   __annotations__rG   rK   rM   r   rS   classmethodrd   r   r   r   r   r   r   r   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   rL   )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   