
    Ngz                        d dl 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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mZmZmZmZmZmZm Z m!Z!m"Z"m#Z#m$Z$m%Z%m&Z& d d	l'm(Z(m)Z)m*Z* d d
l+m,Z, d dl-m.Z.m/Z/m0Z0m1Z1 d dl2m3Z3m4Z4m5Z5 d dl6m7Z7m8Z8m9Z9 d dl:m;Z; d dl<m=Z= d dl>m?Z? d dl@mAZAmBZBmCZC d dlDmEZE  G d de          ZFde)deGfdZHde(deGfdZIdeeJef         defdZKdedefdZLdedeGfdZMdeeJef         d ee         defd!ZNdS )"    N)
itemgetter)Path)AnyCallableDictIteratorListMappingOptionalSequenceTypeUnioncast)CallbackManagerForLLMRun)LanguageModelInput)BaseChatModelgenerate_from_stream)	AIMessageAIMessageChunkBaseMessageBaseMessageChunkChatMessageChatMessageChunkFunctionMessageFunctionMessageChunkHumanMessageHumanMessageChunkSystemMessageSystemMessageChunkToolMessageToolMessageChunk)InvalidToolCallToolCallToolCallChunk)OutputParserLike)JsonOutputKeyToolsParserPydanticToolsParsermake_invalid_tool_callparse_tool_call)ChatGenerationChatGenerationChunk
ChatResult)RunnableRunnableMapRunnablePassthrough)BaseToolconvert_to_openai_tool)is_basemodel_subclass)	BaseModelFieldmodel_validator)Selfc                   ~    e Zd ZU dZdZeed<   eed<   	 dZe	e         ed<   	 dZ
e	e         ed<   	 dZeed<   	 d	Zeed
<   	 d	Zeed<   	 dZeed<   	 dZeed<   	 dZeed<   	 dZeed<   	 dZe	e         ed<   	 dZeed<   	 dZe	e         ed<   	 dZe	e         ed<   	 dZeed<   	 dZeed<   	 dZeed<   	 dZe	e         ed<   	 dZeed<   	 dZe	ee                  ed<   	 d Z eed!<   	 d"Z!eed#<   	 d$Z"eed%<   	 dZ#eed&<   	 d'Z$eed(<   	 d)Z%eed*<   	  e&e'+          Z(e)eef         ed,<   	 dZ*eed-<   	 dZ+e	e,ee-f                  ed.<   	 dZ.eed/<   	 dZ/eed0<   	  e0d12          d3e1fd4            Z2de	ee                  d3e)eef         fd5Z3d6ee4         d3ee)eef                  fd7Z5d8e'd3e6fd9Z7	 	 dId6ee4         de	ee                  d:e	e8         d;ed3e6f
d<Z9	 	 dId6ee4         de	ee                  d:e	e8         d;ed3e:e;         f
d=Z<dd>d?e=e,e)eef         e>e?         e@eAf                  d@e	e,e'eef                  d;ed3eBeCe4f         f fdAZD	 dJddBdCe	e,e)e>e?         f                  dDed;ed3eBeCe,e)e?f         f         fdEZEeFd3e)eef         fdF            ZGeFd3efdG            ZHeFd3e)eef         fdH            ZI xZJS )KChatLlamaCppzllama.cpp model.

    To use, you should have the llama-cpp-python library installed, and provide the
    path to the Llama model as a named parameter to the constructor.
    Check out: https://github.com/abetlen/llama-cpp-python

    Nclient
model_path	lora_base	lora_pathi   n_ctxn_partsseedTf16_kvF
logits_all
vocab_only	use_mlock	n_threads   n_batchn_gpu_layerssuffix   
max_tokensg?temperaturegffffff?top_plogprobsechostopg?repeat_penalty(   top_k@   last_n_tokens_sizeuse_mmapg      ?rope_freq_scaleg     @rope_freq_base)default_factorymodel_kwargs	streaminggrammar_pathgrammarverboseafter)modereturnc                 t    	 ddl m}m} n# t          $ r t          d          w xY w j        }g d} fd|D             } j        
 j        |d<   |                     j                   	  ||fi | _        n'# t          $ r}t          d| d	|           d}~ww xY w j        r+ j        r$ j        } j        }t          d
|d|d          t           j        t                    r |                     j                   _        n( j        r |                     j                   _        n	  S )z4Validate that llama-cpp-python library is installed.r   )LlamaLlamaGrammarzCould not import llama-cpp-python library. Please install the llama-cpp-python library to use this embedding model: pip install llama-cpp-python)rX   rY   r=   r<   r>   r@   rA   rB   rC   rD   rE   rF   rH   rW   rV   r_   c                 2    i | ]}|t          |          S  )getattr).0kselfs     d/var/www/html/ai-engine/env/lib/python3.11/site-packages/langchain_community/chat_models/llamacpp.py
<dictcomp>z5ChatLlamaCpp.validate_environment.<locals>.<dictcomp>   s%    GGG74++GGG    NrI   z&Could not load Llama model from path: z. Received error zCCan only pass in one of grammar and grammar_path. Received grammar=z and grammar_path=.)	llama_cpprd   re   ImportErrorr;   rI   updater[   r:   	Exception
ValueErrorr^   r]   
isinstancestrfrom_string	from_file)	rk   rd   re   r;   model_param_namesmodel_paramser^   r]   s	   `        rl   validate_environmentz!ChatLlamaCpp.validate_environment   s   	555555555 	 	 	I  	 _

 
 
$ HGGG5FGGG(+/+<L(D-...	%
;;l;;DKK 	 	 	& & &"#& &  	 < 	D- 	lG,L33 3".3 3 3   c** 	'33DLAADLL 	'11$2CDDDLLs     &.A= =
B!BB!c                 ^    | j         }|                    d          }|p
|p| j        pg |d<   |S )z
        Performs sanity check, preparing parameters in format needed by llama_cpp.

        Returns:
            Dictionary containing the combined parameters.
        stop_sequencesrQ   )_default_paramspoprQ   )rk   rQ   paramsr~   s       rl   _get_parameterszChatLlamaCpp._get_parameters   sA     %  $455 BB49Bvrn   messagesc                     d |D             }|S )Nc                 ,    g | ]}t          |          S rg   )_convert_message_to_dict)ri   ms     rl   
<listcomp>z6ChatLlamaCpp._create_message_dicts.<locals>.<listcomp>  s!    GGG1!44GGGrn   rg   )rk   r   message_dictss      rl   _create_message_dictsz"ChatLlamaCpp._create_message_dicts   s     HGhGGGrn   responsec                 L   g }|d         D ]o}t          |d                   }t          |                    d                    }d|v r|d         |d<   t          ||          }|                    |           p|                    di           }d|i}t          ||	          S )
Nchoicesmessagefinish_reason)r   rO   r   generation_infousagetoken_usage)generations
llm_output)_convert_dict_to_messagedictgetr*   appendr,   )	rk   r   r   resr   r   genr   r   s	            rl   _create_chat_resultz ChatLlamaCpp._create_chat_result  s    I& 	$ 	$C.s9~>>G"1I1IJJJOS  .1*o
+ /RRRCs####ll7B//;

 kjIIIIrn   run_managerkwargsc                 &   i |                      |          |}| j        r4|                    d          s | j        |fd|i|}t	          |          S |                     |          } | j        j        dd|i|}|                     |          S )Ntool_choicer   r   rg   )	r   r\   r   _streamr   r   r:   create_chat_completionr   )	rk   r   rQ   r   r   r   stream_iterr   r   s	            rl   	_generatezChatLlamaCpp._generate  s     :D((..9&9 > 	5&**]";"; 	5&$,xSS[SFSSK'444228<<54;5WW}WPVWW''111rn   c              +     K   i |                      |          |}|                     |          } | j        j        d|dd|}t          }d}	|D ]}
|	dz  }	t          |
t                    s|
                                }
t          |
d                   dk    rJ|
d         d         }|d         at          |d         |          }
i }|
                    d          x}r||d<   |
                    d          }|r||d<   |
j        }t          |
|pd 	          }
|r|                    |
j        |
|
           |
V  d S )NT)r   streamr      r   deltar   rO   r   )chunkrO   rg   )r   r   r:   r   r   ru   r   
model_dumplen_convert_delta_to_message_chunkr   	__class__r+   on_llm_new_tokentext)rk   r   rQ   r   r   r   r   resultdefault_chunk_classcountr   choicer   r   rO   s                  rl   r   zChatLlamaCpp._stream+  s      :D((..9&9228<<33 
"4
 
39
 
 - 	 	EQJEeT** +((**5#$$))9%a(Fg&3w!4 E !O &

? ; ;;} A3@0zz*--H 7.6
+"'/'/F$  E  Y,,UZux,XXXKKKK1	 	rn   r   toolsr   c                ^   d |D             }d |D             }rt          t                    r2t          fd|D                       st          dd| d          nt          t                    r'fd|D             }|st          dd| d          nct          t
                    r<t          |          dk    r t          d	t          |           d
          |d         nt          d           |d<   d |D             } t                      j        dd|i|S )a  Bind tool-like objects to this chat model

        tool_choice: does not currently support "any", "auto" choices like OpenAI
            tool-calling API. should be a dict of the form to force this tool
            {"type": "function", "function": {"name": <<tool_name>>}}.
        c                 ,    g | ]}t          |          S rg   r1   ri   tools     rl   r   z+ChatLlamaCpp.bind_tools.<locals>.<listcomp>b  !    JJJD1$77JJJrn   c                 *    g | ]}|d          d         S functionnamerg   )ri   fts     rl   r   z+ChatLlamaCpp.bind_tools.<locals>.<listcomp>c  s!    GGGbnV,GGGrn   c              3   <   K   | ]}d          d         |k    V  dS )r   r   Nrg   )ri   r   r   s     rl   	<genexpr>z*ChatLlamaCpp.bind_tools.<locals>.<genexpr>f  sC        @DK
+F3t;     rn   zTool choice tool_choice=z1 was specified, but the only provided tools were ro   c                 8    g | ]}|d          d         k    |S r   rg   )ri   fr   s     rl   r   z+ChatLlamaCpp.bind_tools.<locals>.<listcomp>n  s3       !J-2G;2V2VA2V2V2Vrn   r   zQtool_choice=True can only be specified when a single tool is passed in. Received z tools.r   zUnrecognized tool_choice type. Expected dict having format like 
                    this {"type": "function", "function": {"name": <<tool_name>>}}Received: r   c                 ,    g | ]}t          |          S rg   r1   r   s     rl   r   z+ChatLlamaCpp.bind_tools.<locals>.<listcomp>  r   rn   r   rg   )	ru   r   anyrt   rv   boolr   superbind)rk   r   r   r   formatted_tools
tool_nameschosenr   s     `    rl   
bind_toolszChatLlamaCpp.bind_toolsU  s    KJEJJJGGGGG
 	+t,,     HR      %={ = =/9= = =   K--    .    $={ = =/9= = =  
 K.. ''!++$C/25zzC C C   .a0 /!,/ /   !,}JJEJJJuww|<</<V<<<rn   )include_rawschemar   c                X   |rt          d|           t          |t                    ot          |          }|t          d          t	          |          d         d         }dd|id}|                     |g|          }|r&t          t          t          |          gd	          }nt          |d
          }|rht          j        t          d          |z  d           }	t          j        d           }
|	                    |
gd          }t          |          |z  S ||z  S )at  Model wrapper that returns outputs formatted to match the given schema.

        Args:
            schema: The output schema as a dict or a Pydantic class. If a Pydantic class
                then the model output will be an object of that class. If a dict then
                the model output will be a dict. With a Pydantic class the returned
                attributes will be validated, whereas with a dict they will not be. If
                `method` is "function_calling" and `schema` is a dict, then the dict
                must match the OpenAI function-calling spec or be a valid JSON schema
                with top level 'title' and 'description' keys specified.
            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".
            kwargs: Any other args to bind to model, ``self.bind(..., **kwargs)``.

        Returns:
            A Runnable that takes any ChatModel input and returns as output:

                If include_raw is True then a dict with keys:
                    raw: BaseMessage
                    parsed: Optional[_DictOrPydantic]
                    parsing_error: Optional[BaseException]

                If include_raw is False then just _DictOrPydantic is returned,
                where _DictOrPydantic depends on the schema:

                If schema is a Pydantic class then _DictOrPydantic is the Pydantic
                    class.

                If schema is a dict then _DictOrPydantic is a dict.

        Example: Pydantic schema (include_raw=False):
            .. code-block:: python

                from langchain_community.chat_models import ChatLlamaCpp
                from pydantic import BaseModel

                class AnswerWithJustification(BaseModel):
                    '''An answer to the user question along with justification for the answer.'''
                    answer: str
                    justification: str

                llm = ChatLlamaCpp(
                    temperature=0.,
                    model_path="./SanctumAI-meta-llama-3-8b-instruct.Q8_0.gguf",
                    n_ctx=10000,
                    n_gpu_layers=4,
                    n_batch=200,
                    max_tokens=512,
                    n_threads=multiprocessing.cpu_count() - 1,
                    repeat_penalty=1.5,
                    top_p=0.5,
                    stop=["<|end_of_text|>", "<|eot_id|>"],
                )
                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.'
                # )

        Example: Pydantic schema (include_raw=True):
            .. code-block:: python

                from langchain_community.chat_models import ChatLlamaCpp
                from pydantic import BaseModel

                class AnswerWithJustification(BaseModel):
                    '''An answer to the user question along with justification for the answer.'''
                    answer: str
                    justification: str

                llm = ChatLlamaCpp(
                    temperature=0.,
                    model_path="./SanctumAI-meta-llama-3-8b-instruct.Q8_0.gguf",
                    n_ctx=10000,
                    n_gpu_layers=4,
                    n_batch=200,
                    max_tokens=512,
                    n_threads=multiprocessing.cpu_count() - 1,
                    repeat_penalty=1.5,
                    top_p=0.5,
                    stop=["<|end_of_text|>", "<|eot_id|>"],
                )
                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
                # }

        Example: dict schema (include_raw=False):
            .. code-block:: python

                from langchain_community.chat_models import ChatLlamaCpp
                from pydantic import BaseModel
                from langchain_core.utils.function_calling import convert_to_openai_tool

                class AnswerWithJustification(BaseModel):
                    '''An answer to the user question along with justification for the answer.'''
                    answer: str
                    justification: str

                dict_schema = convert_to_openai_tool(AnswerWithJustification)
                llm = ChatLlamaCpp(
                    temperature=0.,
                    model_path="./SanctumAI-meta-llama-3-8b-instruct.Q8_0.gguf",
                    n_ctx=10000,
                    n_gpu_layers=4,
                    n_batch=200,
                    max_tokens=512,
                    n_threads=multiprocessing.cpu_count() - 1,
                    repeat_penalty=1.5,
                    top_p=0.5,
                    stop=["<|end_of_text|>", "<|eot_id|>"],
                )
                structured_llm = llm.with_structured_output(dict_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.'
                # }

        zReceived unsupported arguments NzJschema must be specified when method is 'function_calling'. Received None.r   r   )typer   r   T)r   first_tool_only)key_namer   rawc                     d S Nrg   _s    rl   <lambda>z5ChatLlamaCpp.with_structured_output.<locals>.<lambda>*  s    RV rn   )parsedparsing_errorc                     d S r   rg   r   s    rl   r   z5ChatLlamaCpp.with_structured_output.<locals>.<lambda>,  s    d rn   )r   r   )exception_key)r   )rt   ru   r   r3   r2   r   r'   r   r   r&   r/   assignr   with_fallbacksr.   )rk   r   r   r   is_pydantic_schema	tool_namer   llmoutput_parserparser_assignparser_noneparser_with_fallbacks               rl   with_structured_outputz#ChatLlamaCpp.with_structured_output  s   X  	IGvGGHHH'55W:OPV:W:W>!   +622:>vF	)	7JKKoovhKo@@ 	.AD&))*D/ / /MM 5"D  M  
	'/6!%((=8  M .4NNKKKK#0#?#?_ $@ $ $  3'''*>>>&&rn   c                 &    i d| j         i| j        S )zReturn a dictionary of identifying parameters.

        This information is used by the LangChain callback system, which
        is used for tracing purposes make it possible to monitor LLMs.
        r;   )r;   r   rk   s    rl   _identifying_paramsz ChatLlamaCpp._identifying_params4  s*    

 T_-
 "
 	
rn   c                     dS )z7Get the type of language model used by this chat model.zllama-cpp-pythonrg   r   s    rl   	_llm_typezChatLlamaCpp._llm_typeD  s
     "!rn   c                     | j         | j        | j        | j        | j        | j        | j        d}| j        r
| j        |d<   |S )z>Get the default parameters for calling create_chat_completion.)rL   rM   rN   rT   rO   r~   rR   r^   )rL   rM   rN   rT   rO   rQ   rR   r^   )rk   r   s     rl   r   zChatLlamaCpp._default_paramsI  sR     /+ZZ"i"1
 
 < 	- $F9rn   )NNr   )K__name__
__module____qualname____doc__r:   r   __annotations__rv   r<   r   r=   r>   intr@   rA   rB   r   rC   rD   rE   rF   rH   rI   rJ   rL   rM   floatrN   rO   rP   rQ   r	   rR   rT   rV   rW   rX   rY   r5   r   r[   r   r\   r]   r   r   r^   r_   r6   r7   r|   r   r   r   r,   r   r   r   r   r+   r   r   r   r4   r   r0   r-   r   r   r   propertyr   r   r   __classcell__)r   s   @rl   r9   r9   =   s          FCOOO+#Ix}###0#Ix}###AE3GS? D#NNN-FD1J@J/It,#Ix}###C GS/ #'L(3-&&&F FHSM   SJ3K.E5."Hhsm"""ND$% $D(49
$$$@NE2E3OOO.    MHd1 OU   )#NE###+#(5#>#>#>L$sCx.>>>?It8/3L(5d+,333 GS GT)_'""":d : : : #":xHT#Y$7 DcN    $[)	d38n	   JD JZ J J J J& %):>	2 2{#2 tCy!2 67	2
 2 
2 2 2 20 %):>	( ({#( tCy!( 67	(
 ( 
%	&( ( ( (\ 9=	1= 1= 1=d38nd9oxQRS1= eD$O45	1=
 1= 
$k1	21= 1= 1= 1= 1= 1=j :>j' "	j' j' j'tT)_456j' 	j'
 j' 
$eD)O&<<	=j' j' j' j'X 
T#s(^ 
 
 
 X
 "3 " " " X" c3h    X    rn   r9   	tool_callrb   c                 \    d| d         | d         t          j        | d                   ddS Nr   idr   args)r   	arguments)r   r   r   )jsondumps)r   s    rl   !_lc_tool_call_to_openai_tool_callr   Z  s?    of%If$566
 
  rn   invalid_tool_callc                 8    d| d         | d         | d         ddS r   rg   )r   s    rl   )_lc_invalid_tool_call_to_openai_tool_callr  e  s8     %%f-*62
 
  rn   _dictc           	         |                      d          }|                      d          }|                      d          }|dk    r&t          |                      dd          ||          S |dk    r|                      dd          pd}i }|                      d	          x}rt          |          |d	<   g }g }|                      d
          x}	r}|	|d
<   |	D ]u}
	 t          |
d          }|s|                    |           -# t
          $ r<}t          |
t          |                    }|                    |           Y d}~nd}~ww xY wt          ||||||          S |dk    r&t          |                      dd          ||          S |dk    rLt          |                      dd          t          t          |                      d                    |          S |dk    r_i }d| v r| d         |d<   t          |                      dd          t          t          |                      d                    |||          S t          |                      dd          t          t          |          |          S )zConvert a dictionary to a LangChain message.

    Args:
        _dict: The dictionary.

    Returns:
        The LangChain message.
    roler   r   usercontent )r  r   r   	assistantfunction_call
tool_callsT)	return_idN)r  additional_kwargsr   r   r
  invalid_tool_callssystemr  r   r   r   r   tool_call_id)r  r  r  r   r   r  r  r   )r   r   r   r)   r   rs   r(   rv   r   r   r   r   r    r   )r  r  r   id_r  r  r	  r
  r  raw_tool_callsraw_tool_calltcr{   
invalid_tcs                 rl   r   r   r  s    99VD99VD
))D//Cv~~EIIi$<$<4PPPP			 ))Ir**0b"$!IIo666= 	E15m1D1Do.
"YY|444> 	..<l+!/ 
. 
.	.($GGGB
  . "))"---- ! : : :!7s1vv!N!NJ&--j99999999: /!1
 
 
 	
 
		UYYy"%=%=DSQQQQ			IIi,,4UYYv=N=N3O3OTW
 
 
 	
 
U??(-ff%IIi,,c599^#<#<==/
 
 
 	
 IIi,,4T??s
 
 
 	
s   D
E
2EE
r  c                     | rXt          | t                    rCg }| D ]=}t          |t                    rd|v r|d         dk    r(|                    |           >n| }|S )zFormat message content.r   tool_use)ru   listr   r   )r  formatted_contentblocks      rl   _format_message_contentr    s     $:gt,, $ 	0 	0E5$''0eOO&MZ//!((////	0 $rn   r   c                    dt          | j                  i}| j        p| j                            d          x}||d<   t          | t                    r| j        |d<   nat          | t                    rd|d<   nEt          | t                    rd|d<   d| j        v r| j        d         |d<   | j
        s| j        r'd | j
        D             d	 | j        D             z   |d
<   n6d
| j        v r,| j        d
         |d
<   h dfd|d
         D             |d
<   n	 d|v sd
|v r|d         pd|d<   nt          | t                    rd|d<   nvt          | t                    rd|d<   n[t          | t                    r4d|d<   | j        |d<   h dfd|                                D             }nt#          d|            |S )zConvert a LangChain message to a dictionary.

    Args:
        message: The LangChain message.

    Returns:
        The dictionary.
    r  r   Nr  r  r  r	  c                 ,    g | ]}t          |          S rg   )r   ri   r  s     rl   r   z,_convert_message_to_dict.<locals>.<listcomp>  s.     * * *:<1"55* * *rn   c                 ,    g | ]}t          |          S rg   )r  r  s     rl   r   z,_convert_message_to_dict.<locals>.<listcomp>  s0        :"==  rn   r
  >   r   r   r   c                 P    g | ]"}fd |                                 D             #S )c                 $    i | ]\  }}|v 	||S rg   rg   )ri   rj   vtool_call_supported_propss      rl   rm   z7_convert_message_to_dict.<locals>.<listcomp>.<dictcomp>  s*    VVV$!Qq<U7U7UA7U7U7Urn   )items)ri   r   r$  s     rl   r   z,_convert_message_to_dict.<locals>.<listcomp>  sH     * * * WVVV)//"3"3VVV* * *rn   r  r   r   r  >   r  r  r  c                 $    i | ]\  }}|v 	||S rg   rg   )ri   rj   r#  supported_propss      rl   rm   z,_convert_message_to_dict.<locals>.<dictcomp>  s)    VVVAoAUAU1AUAUAUrn   zGot unknown type )r  r  r   r  r   ru   r   r  r   r   r
  r  r   r   r    r  r%  	TypeError)r   message_dictr   r'  r$  s      @@rl   r   r     st    	*7?;;$L E 9 = =f E EER#V ';'' &7&|V	G\	*	* $7%V	GY	'	' "7*Vg777,3,Eo,VL) 	!; 	* *@G@R* * * !4  *L&& W666)0)B<)PL&(B(B(B%* * * *!-l!;* * *L&&
 l**ll.J.J&29&=&EL#	G]	+	+ 7'V	G_	-	- 	7)V	G[	)	) 7%V'.';^$===VVVV););)=)=VVV5G55666rn   default_classc                 n   |                      d          }t          t          |                      d                    }t          t          |                      d          pd          }i }|                      d          r+t          | d                   }d|v r|d         d|d<   ||d<   g }|                      d          x}r||d<   |D ]}		 t	          |	d                              d          |	d                              d	          |	                     d          |	d
                   }
|                    |
           w# t          $ r Y w xY w|dk    s|t          k    rt          ||          S |dk    s|t          k    rt          ||||          S |dk    s|t          k    r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 )Nr   r  r  r  r	  r   r
  r   r   index)r   r   r   r,  r  )r  r   r  )r  r  r   tool_call_chunksr  r  r   r  )r  r  r   r  )r   r   rv   r   r$   r   KeyErrorr   r   r   r   r!   r   )r  r*  r  r  r  r  r	  r-  r  rtcr   s              rl   r   r     s    ))D//CUYYv&&''D3		),,233G yy!! ;U?344]""}V'<'D$&M&!-:/*<000~ *8,'! 
	 
	C	)Z,,V44Z,,[99wwt}}g,	  	 !''	2222    v~~*;;; S9999			 ? ?/-	
 
 
 	
 
		].@@@!'c::::			}0DDD#G%-CPPPP	=,<<<%*?C
 
 
 	
 
 6"222dsCCCC}W5555s   A3E
EE)Or   operatorr   pathlibr   typingr   r   r   r   r	   r
   r   r   r   r   r   langchain_core.callbacksr   langchain_core.language_modelsr   *langchain_core.language_models.chat_modelsr   r   langchain_core.messagesr   r   r   r   r   r   r   r   r   r   r   r   r    r!   langchain_core.messages.toolr"   r#   r$   "langchain_core.output_parsers.baser%   *langchain_core.output_parsers.openai_toolsr&   r'   r(   r)   langchain_core.outputsr*   r+   r,   langchain_core.runnablesr-   r.   r/   langchain_core.toolsr0   %langchain_core.utils.function_callingr2   langchain_core.utils.pydanticr3   pydanticr4   r5   r6   typing_extensionsr7   r9   r   r   r  rv   r   r  r   r   rg   rn   rl   <module>rA     s                                         > = = = = = = = = = = =                                        R Q Q Q Q Q Q Q Q Q ? ? ? ? ? ?            S R R R R R R R R R O O O O O O O O O O ) ) ) ) ) ) H H H H H H ? ? ? ? ? ?         
 # " " " " "Z Z Z Z Z= Z Z Zz d    
&
	
 
 
 
@
GCH$5 @
+ @
 @
 @
 @
FS S    (7k 7d 7 7 7 7t/638/6-12B-C/6/6 /6 /6 /6 /6 /6rn   