o
    Jjguc                     @   s  d dl 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 d dlmZmZmZmZ d dl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mZ d d
lm Z  d dl!m"Z" eddddd	d9ddddee	ee#ef ee" ef  dedee de$dee	eef  dedefddZ%eddddd	d9ddddd d!e	ee#ef ee" f dedee dee	eef  d"e$d#e$d$ed% d&edefd'd(Z&d)e	ee#ef ee" ef dedee dee	eef  d*e$d+e$defd,d-Z'd.d/d)e	ee#ef ee" ef d+e$de	eef fd0d1Z(dee	ee#ef ee" ef  de	eef fd2d3Z)	d9dd4d!e	ee#ef ee" f dedee dee	eef  def
d5d6Z*	d9dd4d!e	ee#ef ee" f dedee dee	eef  dedefd7d8Z+dS ):    N)AnyCallableDictLiteralOptionalSequenceTypeUnion)
deprecated)BaseGenerationOutputParserBaseOutputParserJsonOutputParserPydanticOutputParser)JsonOutputFunctionsParser!PydanticAttrOutputFunctionsParserPydanticOutputFunctionsParser)JsonOutputKeyToolsParserPydanticToolsParser)BasePromptTemplate)Runnable)convert_to_openai_functionconvert_to_openai_tool)is_basemodel_subclass)	BaseModelz0.1.14a  LangChain has introduced a method called `with_structured_output` that is available on ChatModels capable of tool calling. You can read more about the method here: <https://python.langchain.com/docs/modules/model_io/chat/structured_output/>. Please follow our extraction use case documentation for more guidelines on how to do information extraction with LLMs. <https://python.langchain.com/docs/use_cases/extraction/>. If you notice other issues, please provide feedback here: <https://github.com/langchain-ai/langchain/discussions/18154>z1.0a4  
            from pydantic import BaseModel, Field
            from langchain_anthropic import ChatAnthropic
    
            class Joke(BaseModel):
                setup: str = Field(description="The setup of the joke")
                punchline: str = Field(description="The punchline to the joke") 
    
            # Or any other chat model that supports tools.
            # Please reference to to the documentation of structured_output
            # to see an up to date list of which models support 
            # with_structured_output.
            model = ChatAnthropic(model="claude-3-opus-20240229", temperature=0)
            structured_llm = model.with_structured_output(Joke)
            structured_llm.invoke("Tell me a joke about cats. 
                Make sure to call the Joke function.")
            )sincemessageremovalalternativeT)enforce_single_function_usageoutput_parser	functionsllmpromptr   r   
llm_kwargsreturnc                K   s   | st ddd | D }d|i|}t|dkr%|r%d|d d i|d< |p*t| }|r9||jd
i |B |B S |jd
i ||B S )a!  Create a runnable sequence that uses OpenAI functions.

    Args:
        functions: A sequence of either dictionaries, pydantic.BaseModels classes, or
            Python functions. If dictionaries are passed in, they are assumed to
            already be a valid OpenAI functions. If only a single
            function is passed in, then it will be enforced that the model use that
            function. pydantic.BaseModels and Python functions should have docstrings
            describing what the function does. For best results, pydantic.BaseModels
            should have descriptions of the parameters and Python functions should have
            Google Python style args descriptions in the docstring. Additionally,
            Python functions should only use primitive types (str, int, float, bool) or
            pydantic.BaseModels for arguments.
        llm: Language model to use, assumed to support the OpenAI function-calling API.
        prompt: BasePromptTemplate to pass to the model.
        enforce_single_function_usage: only used if a single function is passed in. If
            True, then the model will be forced to use the given function. If False,
            then the model will be given the option to use the given function or not.
        output_parser: BaseLLMOutputParser to use for parsing model outputs. By default
            will be inferred from the function types. If pydantic.BaseModels are passed
            in, then the OutputParser will try to parse outputs using those. Otherwise
            model outputs will simply be parsed as JSON. If multiple functions are
            passed in and they are not pydantic.BaseModels, the chain output will
            include both the name of the function that was returned and the arguments
            to pass to the function.
        **llm_kwargs: Additional named arguments to pass to the language model.

    Returns:
        A runnable sequence that will pass in the given functions to the model when run.

    Example:
        .. code-block:: python

                from typing import Optional

                from langchain.chains.structured_output import create_openai_fn_runnable
                from langchain_openai import ChatOpenAI
                from pydantic import BaseModel, Field


                class RecordPerson(BaseModel):
                    '''Record some identifying information about a person.'''

                    name: str = Field(..., description="The person's name")
                    age: int = Field(..., description="The person's age")
                    fav_food: Optional[str] = Field(None, description="The person's favorite food")


                class RecordDog(BaseModel):
                    '''Record some identifying information about a dog.'''

                    name: str = Field(..., description="The dog's name")
                    color: str = Field(..., description="The dog's color")
                    fav_food: Optional[str] = Field(None, description="The dog's favorite food")


                llm = ChatOpenAI(model="gpt-4", temperature=0)
                structured_llm = create_openai_fn_runnable([RecordPerson, RecordDog], llm)
                structured_llm.invoke("Harry was a chubby brown beagle who loved chicken)
                # -> RecordDog(name="Harry", color="brown", fav_food="chicken")
    z5Need to pass in at least one function. Received zero.c                 S   s   g | ]}t |qS  r   ).0fr%   r%   _/var/www/html/zoom/venv/lib/python3.10/site-packages/langchain/chains/structured_output/base.py
<listcomp>   s    z-create_openai_fn_runnable.<locals>.<listcomp>r       namer   function_callNr%   )
ValueErrorlenget_openai_output_parserbind)r    r!   r"   r   r   r#   openai_functionsllm_kwargs_r%   r%   r)   create_openai_fn_runnable   s   ir4   z0.1.17a  LangChain has introduced a method called `with_structured_output` that is available on ChatModels capable of tool calling. You can read more about the method here: <https://python.langchain.com/docs/modules/model_io/chat/structured_output/>.Please follow our extraction use case documentation for more guidelines on how to do information extraction with LLMs. <https://python.langchain.com/docs/use_cases/extraction/>. If you notice other issues, please provide feedback here: <https://github.com/langchain-ai/langchain/discussions/18154>a,  
            from pydantic import BaseModel, Field
            from langchain_anthropic import ChatAnthropic

            class Joke(BaseModel):
                setup: str = Field(description="The setup of the joke")
                punchline: str = Field(description="The punchline to the joke") 

            # Or any other chat model that supports tools.
            # Please reference to to the documentation of structured_output
            # to see an up to date list of which models support 
            # with_structured_output.
            model = ChatAnthropic(model="claude-3-opus-20240229", temperature=0)
            structured_llm = model.with_structured_output(Joke)
            structured_llm.invoke("Tell me a joke about cats. 
                Make sure to call the Joke function.")
            openai-functions)r   enforce_function_usagereturn_singlemodeoutput_schemar6   r7   r8   )r5   openai-toolsopenai-jsonkwargsc                K   s   | d|}|dkr)t| }	|	dh }
|
rtd|
 dt| |||||dS |dkr:t| |f|||d|S |dkrP|rDtd	t| |f||d
|S td| d)aW&  Create a runnable for extracting structured outputs.

    Args:
        output_schema: Either a dictionary or pydantic.BaseModel class. If a dictionary
            is passed in, it's assumed to already be a valid JsonSchema.
            For best results, pydantic.BaseModels should have docstrings describing what
            the schema represents and descriptions for the parameters.
        llm: Language model to use. Assumed to support the OpenAI function-calling API 
            if mode is 'openai-function'. Assumed to support OpenAI response_format 
            parameter if mode is 'openai-json'.
        prompt: BasePromptTemplate to pass to the model. If mode is 'openai-json' and 
            prompt has input variable 'output_schema' then the given output_schema 
            will be converted to a JsonSchema and inserted in the prompt.
        output_parser: Output parser to use for parsing model outputs. By default
            will be inferred from the function types. If pydantic.BaseModel is passed
            in, then the OutputParser will try to parse outputs using the pydantic 
            class. Otherwise model outputs will be parsed as JSON.
        mode: How structured outputs are extracted from the model. If 'openai-functions' 
            then OpenAI function calling is used with the deprecated 'functions', 
            'function_call' schema. If 'openai-tools' then OpenAI function 
            calling with the latest 'tools', 'tool_choice' schema is used. This is 
            recommended over 'openai-functions'. If 'openai-json' then OpenAI model 
            with response_format set to JSON is used.
        enforce_function_usage: Only applies when mode is 'openai-tools' or 
            'openai-functions'. If True, then the model will be forced to use the given 
            output schema. If False, then the model can elect whether to use the output 
            schema.
        return_single: Only applies when mode is 'openai-tools'. Whether to a list of 
            structured outputs or a single one. If True and model does not return any 
            structured outputs then chain output is None. If False and model does not 
            return any structured outputs then chain output is an empty list.
        kwargs: Additional named arguments.

    Returns:
        A runnable sequence that will return a structured output(s) matching the given 
            output_schema.
    
    OpenAI tools example with Pydantic schema (mode='openai-tools'):
        .. code-block:: python
        
                from typing import Optional

                from langchain.chains import create_structured_output_runnable
                from langchain_openai import ChatOpenAI
                from pydantic import BaseModel, Field


                class RecordDog(BaseModel):
                    '''Record some identifying information about a dog.'''

                    name: str = Field(..., description="The dog's name")
                    color: str = Field(..., description="The dog's color")
                    fav_food: Optional[str] = Field(None, description="The dog's favorite food")

                llm = ChatOpenAI(model="gpt-3.5-turbo-0125", temperature=0)
                prompt = ChatPromptTemplate.from_messages(
                    [
                        ("system", "You are an extraction algorithm. Please extract every possible instance"), 
                        ('human', '{input}')
                    ]
                )
                structured_llm = create_structured_output_runnable(
                    RecordDog, 
                    llm, 
                    mode="openai-tools", 
                    enforce_function_usage=True, 
                    return_single=True
                )
                structured_llm.invoke({"input": "Harry was a chubby brown beagle who loved chicken"})
                # -> RecordDog(name="Harry", color="brown", fav_food="chicken")
                
    OpenAI tools example with dict schema (mode="openai-tools"):
        .. code-block:: python
        
                from typing import Optional

                from langchain.chains import create_structured_output_runnable
                from langchain_openai import ChatOpenAI


                dog_schema = {
                    "type": "function",
                    "function": {
                        "name": "record_dog",
                        "description": "Record some identifying information about a dog.",
                        "parameters": {
                            "type": "object",
                            "properties": {
                                "name": {
                                    "description": "The dog's name",
                                    "type": "string"
                                },
                                "color": {
                                    "description": "The dog's color",
                                    "type": "string"
                                },
                                "fav_food": {
                                    "description": "The dog's favorite food",
                                    "type": "string"
                                }
                            },
                            "required": ["name", "color"]
                        }
                    }
                }


                llm = ChatOpenAI(model="gpt-3.5-turbo-0125", temperature=0)
                structured_llm = create_structured_output_runnable(
                    dog_schema, 
                    llm, 
                    mode="openai-tools", 
                    enforce_function_usage=True, 
                    return_single=True
                )
                structured_llm.invoke("Harry was a chubby brown beagle who loved chicken")
                # -> {'name': 'Harry', 'color': 'brown', 'fav_food': 'chicken'}
    
    OpenAI functions example (mode="openai-functions"):
        .. code-block:: python

                from typing import Optional

                from langchain.chains import create_structured_output_runnable
                from langchain_openai import ChatOpenAI
                from pydantic import BaseModel, Field

                class Dog(BaseModel):
                    '''Identifying information about a dog.'''

                    name: str = Field(..., description="The dog's name")
                    color: str = Field(..., description="The dog's color")
                    fav_food: Optional[str] = Field(None, description="The dog's favorite food")

                llm = ChatOpenAI(model="gpt-3.5-turbo-0125", temperature=0)
                structured_llm = create_structured_output_runnable(Dog, llm, mode="openai-functions")
                structured_llm.invoke("Harry was a chubby brown beagle who loved chicken")
                # -> Dog(name="Harry", color="brown", fav_food="chicken")
                
    OpenAI functions with prompt example:
        .. code-block:: python

                from typing import Optional

                from langchain.chains import create_structured_output_runnable
                from langchain_openai import ChatOpenAI
                from langchain_core.prompts import ChatPromptTemplate
                from pydantic import BaseModel, Field

                class Dog(BaseModel):
                    '''Identifying information about a dog.'''

                    name: str = Field(..., description="The dog's name")
                    color: str = Field(..., description="The dog's color")
                    fav_food: Optional[str] = Field(None, description="The dog's favorite food")

                llm = ChatOpenAI(model="gpt-3.5-turbo-0125", temperature=0)
                structured_llm = create_structured_output_runnable(Dog, llm, mode="openai-functions")
                system = '''Extract information about any dogs mentioned in the user input.'''
                prompt = ChatPromptTemplate.from_messages(
                    [("system", system), ("human", "{input}"),]
                )
                chain = prompt | structured_llm
                chain.invoke({"input": "Harry was a chubby brown beagle who loved chicken"})
                # -> Dog(name="Harry", color="brown", fav_food="chicken")
    OpenAI json response format example (mode="openai-json"):
        .. code-block:: python
        
                from typing import Optional

                from langchain.chains import create_structured_output_runnable
                from langchain_openai import ChatOpenAI
                from langchain_core.prompts import ChatPromptTemplate
                from pydantic import BaseModel, Field

                class Dog(BaseModel):
                    '''Identifying information about a dog.'''

                    name: str = Field(..., description="The dog's name")
                    color: str = Field(..., description="The dog's color")
                    fav_food: Optional[str] = Field(None, description="The dog's favorite food")

                llm = ChatOpenAI(model="gpt-3.5-turbo-0125", temperature=0)
                structured_llm = create_structured_output_runnable(Dog, llm, mode="openai-json")
                system = '''You are a world class assistant for extracting information in structured JSON formats.                 
                Extract a valid JSON blob from the user input that matches the following JSON Schema:
                
                {output_schema}'''
                prompt = ChatPromptTemplate.from_messages(
                    [("system", system), ("human", "{input}"),]
                )
                chain = prompt | structured_llm
                chain.invoke({"input": "Harry was a chubby brown beagle who loved chicken"})
    r   r:   z'Got an unexpected keyword argument(s): .)r"   r   enforce_tool_usagefirst_tool_onlyr5   )r"   r   r   r;   zFenforce_single_function_usage is not supported for mode='openai-json'.r"   r   zInvalid mode zD. Expected one of 'openai-tools', 'openai-functions', 'openai-json'.)getsetkeys	TypeError_create_openai_tools_runnable3_create_openai_functions_structured_output_runnabler.   _create_openai_json_runnable)r9   r!   r"   r   r6   r7   r8   r<   force_function_usagekeys_in_kwargsunrecognized_keysr%   r%   r)   !create_structured_output_runnable   sZ    u

	
rK   toolr>   r?   c                C   sp   t | }d|gi}|rdd|d d id|d< |pt| |d}|r.||jdi |B |B S |jdi ||B S )Ntoolsfunctionr,   )typerN   tool_choicer?   r%   )r   _get_openai_tool_output_parserr1   )rL   r!   r"   r   r>   r?   oai_toolr#   r%   r%   r)   rE     s   	

rE   FrQ   c                C   sD   t | trt| rt| g|d}|S t| d d }t||d}|S )N)rM   r?   rN   r,   )r?   key_name)
isinstancerO   r   r   r   r   )rL   r?   r   rT   r%   r%   r)   rR     s   rR   c                 C   sb   t | d tr&t| d r&t| dkrdd | D }n| d }t|d}|S tt| dkd}|S )av  Get the appropriate function output parser given the user functions.

    Args:
        functions: Sequence where element is a dictionary, a pydantic.BaseModel class,
            or a Python function. If a dictionary is passed in, it is assumed to
            already be a valid OpenAI function.

    Returns:
        A PydanticOutputFunctionsParser if functions are Pydantic classes, otherwise
            a JsonOutputFunctionsParser. If there's only one function and it is
            not a Pydantic class, then the output parser will automatically extract
            only the function arguments and not the function name.
    r   r+   c                 S   s   i | ]	}t |d  |qS )r,   r&   )r'   fnr%   r%   r)   
<dictcomp>  s    z,get_openai_output_parser.<locals>.<dictcomp>)pydantic_schema)	args_only)rU   rO   r   r/   r   r   )r    rX   r   r%   r%   r)   r0     s   r0   )r   c                C   s   t | trt| r|pt| d}t| d }n|pt }| }|jddid}|r>d|jv r8|jt	j
|ddd	}||B |B S ||B S )
 )pydantic_object
parametersrO   json_object)response_formatr9      )indentr9   )rU   rO   r   r   r   r   r1   input_variablespartialjsondumps)r9   r!   r"   r   schema_as_dictr%   r%   r)   rG      s   

rG   c                   sZ   t  trdd d}nG  fdddt}|}|pt|dd}t|g|f||d|S )	Noutput_formatterLOutput formatter. Should always be used to format your response to the user.)r,   descriptionr\   c                       s   e Zd ZU dZ ed< dS )zM_create_openai_functions_structured_output_runnable.<locals>._OutputFormatterrh   outputN)__name__
__module____qualname____doc____annotations__r%   ra   r%   r)   _OutputFormatter.  s   
 rp   rj   )rX   	attr_namer@   )rU   dictr   r   r4   )r9   r!   r"   r   r#   rN   rp   r%   ra   r)   rF     s&   

rF   )N),rd   typingr   r   r   r   r   r   r   r	   langchain_core._apir
   langchain_core.output_parsersr   r   r   r   .langchain_core.output_parsers.openai_functionsr   r   r   *langchain_core.output_parsers.openai_toolsr   r   langchain_core.promptsr   langchain_core.runnablesr   %langchain_core.utils.function_callingr   r   langchain_core.utils.pydanticr   pydanticr   strboolr4   rK   rE   rR   r0   rG   rF   r%   r%   r%   r)   <module>   s   (&S&  




"
