a
    ”˜ëj|1  ã                   @   s¼  d Z ddlZddlmZmZmZmZ ddlmZ ddl	m
Z
mZ ddlmZmZmZ ddlmZmZmZ ddlmZmZ G d	d
„ d
ƒZG dd„ deeƒZG dd„ deeƒZG dd„ deƒZeeeef ee edœdd„ZG dd„ deƒZdddddœee ee ee ee edœdd„Z G dd„ deƒZ!dddddœee ee ee ee e!dœdd„Z"e#e e$e#e e#e! f d œd!d"„Z%e#e e#e d œd#d$„Z&ed% ed% ed% d&œd'd(„Z'dS ))zMessages for tools.é    N)ÚAnyÚLiteralÚOptionalÚUnion)ÚUUID)ÚFieldÚmodel_validator)ÚNotRequiredÚ	TypedDictÚoverride)ÚBaseMessageÚBaseMessageChunkÚmerge_content)Úmerge_dictsÚ	merge_objc                   @   s   e Zd ZdZdS )ÚToolOutputMixina  Mixin for objects that tools can return directly.

    If a custom BaseTool is invoked with a ``ToolCall`` and the output of custom code is
    not an instance of ``ToolOutputMixin``, the output will automatically be coerced to
    a string and wrapped in a ``ToolMessage``.

    N)Ú__name__Ú
__module__Ú__qualname__Ú__doc__© r   r   ú[/mnt/bigstor/www/usecases/.venv/lib/python3.9/site-packages/langchain_core/messages/tool.pyr      s   r   c                       sº   e Zd ZU dZeed< dZed ed< dZe	ed< dZ
ed ed	< eed
d�Zeed< eed
d�Zeed< edd�eeedœdd„ƒƒZeeeeeef  f e	ddœ‡ fdd„Z‡  ZS )ÚToolMessagea„  Message for passing the result of executing a tool back to a model.

    ``ToolMessage``s contain the result of a tool invocation. Typically, the result
    is encoded inside the ``content`` field.

    Example: A ``ToolMessage`` representing a result of ``42`` from a tool call with id

        .. code-block:: python

            from langchain_core.messages import ToolMessage

            ToolMessage(content="42", tool_call_id="call_Jja7J89XsjrOLA5r!MEOW!SL")


    Example: A ``ToolMessage`` where only part of the tool output is sent to the model
        and the full output is passed in to artifact.

        .. versionadded:: 0.2.17

        .. code-block:: python

            from langchain_core.messages import ToolMessage

            tool_output = {
                "stdout": "From the graph we can see that the correlation between "
                "x and y is ...",
                "stderr": None,
                "artifacts": {"type": "image", "base64_data": "/9j/4gIcSU..."},
            }

            ToolMessage(
                content=tool_output["stdout"],
                artifact=tool_output,
                tool_call_id="call_Jja7J89XsjrOLA5r!MEOW!SL",
            )

    The ``tool_call_id`` field is used to associate the tool call request with the
    tool call response. This is useful in situations where a chat model is able
    to request multiple tool calls in parallel.

    Útool_call_idZtoolÚtypeNÚartifactÚsuccess©r   ÚerrorÚstatusF)Údefault_factoryÚreprÚadditional_kwargsÚresponse_metadataÚbefore)Úmode)ÚvaluesÚreturnc                 C   s<  |d }t |tƒrt|ƒ}t |ttfƒsvzt|ƒ|d< W n: tyr } z"d|›d�}t|ƒ|‚W Y d}~n
d}~0 0 nœt |tƒ�rg |d< t|ƒD ]~\}}t |ttfƒ�sz|d  t|ƒ¡ W n> tyþ } z&d|› d|› �}t|ƒ|‚W Y d}~n
d}~0 0 q’|d  |¡ q’|d }t |tt	t
fƒ�r8t|ƒ|d< |S )zrCoerce the model arguments to the correct types.

        Args:
            values: The model arguments.

        ÚcontentzUToolMessage content should be a string or a list of string/dicts. Received:

content=z,

 which could not be coerced into a string.NzrToolMessage content should be a string or a list of string/dicts. Received a list but element ToolMessage.content[z8] is not a dict and could not be coerced to a string.:

r   )Ú
isinstanceÚtupleÚlistÚstrÚ
ValueErrorÚ	enumerateÚdictÚappendr   ÚintÚfloat)Úclsr&   r(   ÚeÚmsgÚiÚxr   r   r   r   Úcoerce_argsd   s>    	
ÿÿ"þýÿ"zToolMessage.coerce_args)r(   Úkwargsr'   c                    s   t ƒ jf d|i|¤Ž dS )z•Initialize ``ToolMessage``.

        Args:
            content: The string contents of the message.
            **kwargs: Additional fields.
        r(   N)ÚsuperÚ__init__)Úselfr(   r9   ©Ú	__class__r   r   r;   ‘   s    zToolMessage.__init__)r   r   r   r   r,   Ú__annotations__r   r   r   r   r   r   r/   r"   r#   r   Úclassmethodr8   r   r+   r;   Ú__classcell__r   r   r=   r   r      s   
*-ür   c                       s>   e Zd ZU dZd Zed  ed< eee	dœ‡ fdd„ƒZ
‡  ZS )ÚToolMessageChunkzTool Message chunk.r   )Úotherr'   c              
      s|   t |tƒrp| j|jkr"d}t|ƒ‚| j| jt| j|jƒt| j|jƒt	| j
|j
ƒt	| j|jƒ| jt| j|jƒd�S tƒ  |¡S )Nz:Cannot concatenate ToolMessageChunks with different names.)r   r(   r   r"   r#   Úidr   )r)   rB   r   r-   r>   r   r(   r   r   r   r"   r#   rD   Ú_merge_statusr   r:   Ú__add__)r<   rC   r5   r=   r   r   rF   §   s$    
ÿÿõzToolMessageChunk.__add__)r   r   r   r   r   r   r?   r   r   r   rF   rA   r   r   r=   r   rB   Ÿ   s   
rB   c                   @   sF   e Zd ZU dZeed< eeef ed< ee ed< e	e
d  ed< dS )ÚToolCalla  Represents a request to call a tool.

    Example:

        .. code-block:: python

            {"name": "foo", "args": {"a": 1}, "id": "123"}

        This represents a request to call the tool named ``'foo'`` with arguments
        ``{"a": 1}`` and an identifier of ``'123'``.

    ÚnameÚargsrD   Ú	tool_callr   N)r   r   r   r   r,   r?   r/   r   r   r	   r   r   r   r   r   rG   ¿   s
   
rG   )rH   rI   rD   r'   c                 C   s   t | ||dd�S )zèCreate a tool call.

    Args:
        name: The name of the tool to be called.
        args: The arguments to the tool call.
        id: An identifier associated with the tool call.

    Returns:
        The created tool call.
    rJ   )rH   rI   rD   r   )rG   ©rH   rI   rD   r   r   r   rJ   Û   s    rJ   c                   @   sR   e Zd ZU dZee ed< ee ed< ee ed< ee ed< ee	d  ed< dS )	ÚToolCallChunka§  A chunk of a tool call (e.g., as part of a stream).

    When merging ``ToolCallChunk``s (e.g., via ``AIMessageChunk.__add__``),
    all string attributes are concatenated. Chunks are only merged if their
    values of ``index`` are equal and not None.

    Example:

    .. code-block:: python

        left_chunks = [ToolCallChunk(name="foo", args='{"a":', index=0)]
        right_chunks = [ToolCallChunk(name=None, args="1}", index=0)]

        (
            AIMessageChunk(content="", tool_call_chunks=left_chunks)
            + AIMessageChunk(content="", tool_call_chunks=right_chunks)
        ).tool_call_chunks == [ToolCallChunk(name="foo", args='{"a":1}', index=0)]

    rH   rI   rD   ÚindexÚtool_call_chunkr   N)
r   r   r   r   r   r,   r?   r1   r	   r   r   r   r   r   rL   î   s   
rL   ©rH   rI   rD   rM   )rH   rI   rD   rM   r'   c                 C   s   t | |||dd�S )a-  Create a tool call chunk.

    Args:
        name: The name of the tool to be called.
        args: The arguments to the tool call.
        id: An identifier associated with the tool call.
        index: The index of the tool call in a sequence.

    Returns:
        The created tool call chunk.
    rN   )rH   rI   rD   rM   r   )rL   rO   r   r   r   rN     s    
ÿrN   c                   @   sR   e Zd ZU dZee ed< ee ed< ee ed< ee ed< eed  ed< dS )	ÚInvalidToolCallz•Allowance for errors made by LLM.

    Here we add an ``error`` key to surface errors made during generation
    (e.g., invalid JSON arguments.)
    rH   rI   rD   r   Úinvalid_tool_callr   N)	r   r   r   r   r   r,   r?   r	   r   r   r   r   r   rP   %  s   
rP   ©rH   rI   rD   r   )rH   rI   rD   r   r'   c                 C   s   t | |||dd�S )a8  Create an invalid tool call.

    Args:
        name: The name of the tool to be called.
        args: The arguments to the tool call.
        id: An identifier associated with the tool call.
        error: An error message associated with the tool call.

    Returns:
        The created invalid tool call.
    rQ   )rH   rI   rD   r   r   )rP   rR   r   r   r   rQ   7  s    
ÿrQ   )Úraw_tool_callsr'   c                 C   s¦   g }g }| D ]�}d|vrq|d d }z<t  |d d ¡}t|pBd|pHi | d¡d�}| |¡ W q t jyš   | t||d d | d¡dd�¡ Y q0 q||fS )	z®Best-effort parsing of tools.

    Args:
        raw_tool_calls: List of raw tool call dicts to parse.

    Returns:
        A list of tool calls and invalid tool calls.
    ÚfunctionrH   Ú	argumentsÚ rD   rK   NrR   )ÚjsonÚloadsrJ   Úgetr0   ÚJSONDecodeErrorrQ   )rS   Z
tool_callsZinvalid_tool_callsZraw_tool_callÚfunction_nameÚfunction_argsÚparsedr   r   r   Údefault_tool_parserN  s0    ý
üÿr^   c                 C   sb   g }| D ]T}d|vrd}d}n|d d }|d d }t ||| d¡| d¡d�}| |¡ q|S )z­Best-effort parsing of tool chunks.

    Args:
        raw_tool_calls: List of raw tool call dicts to parse.

    Returns:
        List of parsed ToolCallChunk objects.
    rT   NrU   rH   rD   rM   rO   )rN   rY   r0   )rS   Ztool_call_chunksrJ   r\   r[   r]   r   r   r   Údefault_tool_chunk_parsers  s    	ür_   r   )ÚleftÚrightr'   c                 C   s   d| |hv rdS dS )Nr   r   r   )r`   ra   r   r   r   rE   Ž  s    rE   )(r   rW   Útypingr   r   r   r   Úuuidr   Zpydanticr   r   Ztyping_extensionsr	   r
   r   Zlangchain_core.messages.baser   r   r   Zlangchain_core.utils._merger   r   r   r   rB   rG   r,   r/   rJ   rL   r1   rN   rP   rQ   r+   r*   r^   r_   rE   r   r   r   r   Ú<module>   s`   
  
û"ûúûúþ%þ