
    A'h)              
       >   d dl Z 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 d dlmZmZmZmZmZmZmZ d dlmZ d dlmZ eee   ef   ZdZd	e	d
e	eegef   fdZedddededee
d      d
efd       Z G d de      Z G d de      Z dee   d
ee   fdZ!y)    N)Sequence)partial)	AnnotatedAnyCallableLiteralOptionalUnioncast)
AnyMessageBaseMessageBaseMessageChunkMessageLikeRepresentationRemoveMessageconvert_to_messagesmessage_chunk_to_message)	TypedDict)
StateGraph__remove_all__funcreturnc                     	 ddt         t           dt         t           dt        dt        t        t        t        t        gt        f   f   f fd} j
                  |_        t        t        t        t        gt        f   |      S )Nleftrightkwargsr   c                 j    | |
 | |fi |S | |d| rdnd d}t        |      t        fi |S )NzMMust specify non-null arguments for both 'left' and 'right'. Only received: 'r   r   z'.)
ValueErrorr   )r   r   r   msgr   s       ^/home/kushmeetdev/Regenta/Chatbot/venv/lib/python3.12/site-packages/langgraph/graph/message.py_add_messagesz,_add_messages_wrapper.<locals>._add_messages"   sd      1e.v..!2(,f':">  S/!4*6**    )NN)r	   Messagesr   r
   r   __doc__r   )r   r    s   ` r   _add_messages_wrapperr$   !   sx    EI+x +080B+UX+	x8X"6"@AA	B+ !LLM(H-x78-HHr!   )formatr   r   r%   langchain-openaic          	         d}t        | t              s| g} t        |t              s|g}t        |       D cg c]  }t        t	        t
        |             } }t        |      D cg c]  }t        t	        t
        |             }}| D ]1  }|j                  t        t        j                               |_        3 t        |      D ]Z  \  }}|j                  "t        t        j                               |_        t        |t              sE|j                  t        k(  sY|}\ |||dz   d S | j                         }t        |      D ci c]  \  }}|j                  | }}}t               }	|D ]  }|j                  |j                        x}
Mt        |t              r|	j!                  |j                         L|	j#                  |j                         |||
<   mt        |t              rt%        d|j                   d      t'        |      ||j                  <   |j)                  |        |D cg c]  }|j                  |	vs| }}|dk(  rt+        |      }|S |rd|d}t%        |      	 |S c c}w c c}w c c}}w c c}w )a>  Merges two lists of messages, updating existing messages by ID.

    By default, this ensures the state is "append-only", unless the
    new message has the same ID as an existing message.

    Args:
        left: The base list of messages.
        right: The list of messages (or single message) to merge
            into the base list.
        format: The format to return messages in. If None then messages will be
            returned as is. If 'langchain-openai' then messages will be returned as
            BaseMessage objects with their contents formatted to match OpenAI message
            format, meaning contents can be string, 'text' blocks, or 'image_url' blocks
            and tool responses are returned as their own ToolMessages.

            !!! important "Requirement"

                Must have ``langchain-core>=0.3.11`` installed to use this feature.

    Returns:
        A new list of messages with the messages from `right` merged into `left`.
        If a message in `right` has the same ID as a message in `left`, the
        message from `right` will replace the message from `left`.

    Example:
        ```python title="Basic usage"
        from langchain_core.messages import AIMessage, HumanMessage
        msgs1 = [HumanMessage(content="Hello", id="1")]
        msgs2 = [AIMessage(content="Hi there!", id="2")]
        add_messages(msgs1, msgs2)
        # [HumanMessage(content='Hello', id='1'), AIMessage(content='Hi there!', id='2')]
        ```

        ```python title="Overwrite existing message"
        msgs1 = [HumanMessage(content="Hello", id="1")]
        msgs2 = [HumanMessage(content="Hello again", id="1")]
        add_messages(msgs1, msgs2)
        # [HumanMessage(content='Hello again', id='1')]
        ```

        ```python title="Use in a StateGraph"
        from typing import Annotated
        from typing_extensions import TypedDict
        from langgraph.graph import StateGraph

        class State(TypedDict):
            messages: Annotated[list, add_messages]

        builder = StateGraph(State)
        builder.add_node("chatbot", lambda state: {"messages": [("assistant", "Hello")]})
        builder.set_entry_point("chatbot")
        builder.set_finish_point("chatbot")
        graph = builder.compile()
        graph.invoke({})
        # {'messages': [AIMessage(content='Hello', id=...)]}
        ```

        ```python title="Use OpenAI message format"
        from typing import Annotated
        from typing_extensions import TypedDict
        from langgraph.graph import StateGraph, add_messages

        class State(TypedDict):
            messages: Annotated[list, add_messages(format='langchain-openai')]

        def chatbot_node(state: State) -> list:
            return {"messages": [
                {
                    "role": "user",
                    "content": [
                        {
                            "type": "text",
                            "text": "Here's an image:",
                            "cache_control": {"type": "ephemeral"},
                        },
                        {
                            "type": "image",
                            "source": {
                                "type": "base64",
                                "media_type": "image/jpeg",
                                "data": "1234",
                            },
                        },
                    ]
                },
            ]}

        builder = StateGraph(State)
        builder.add_node("chatbot", chatbot_node)
        builder.set_entry_point("chatbot")
        builder.set_finish_point("chatbot")
        graph = builder.compile()
        graph.invoke({"messages": []})
        # {
        #     'messages': [
        #         HumanMessage(
        #             content=[
        #                 {"type": "text", "text": "Here's an image:"},
        #                 {
        #                     "type": "image_url",
        #                     "image_url": {"url": "data:image/jpeg;base64,1234"},
        #                 },
        #             ],
        #         ),
        #     ]
        # }
        ```

    N   z?Attempting to delete a message with an ID that doesn't exist ('z')r&   zUnrecognized format=z+. Expected one of 'langchain-openai', None.)
isinstancelistr   r   r   r   idstruuiduuid4	enumerater   REMOVE_ALL_MESSAGEScopysetgetadddiscardr   lenappend_format_messages)r   r   r%   remove_all_idxmidxmergedimerged_by_idids_to_removeexisting_idxr   s               r   add_messagesrA   4   s   h NdD!veT" %T* 	!&6!:;D  %U+ 	!&6!:;E 
  %44<tzz|$AD% E" !Q44<tzz|$ADa'ADD4G,G N	! !^a')** YY[F(1&(9:1ADD!G:L:EM (,,QTT22L?!]+!!!$$'%%add+'(|$!]+ UVWVZVZU[[]^  "%VLMM!  =A144}#<a=F=##!&) M 
%fY&QRoMe& ;" >s    I:% I?J8J
J
c                   $     e Zd ZdZd fdZ xZS )MessageGrapha  A StateGraph where every node receives a list of messages as input and returns one or more messages as output.

    MessageGraph is a subclass of StateGraph whose entire state is a single, append-only* list of messages.
    Each node in a MessageGraph takes a list of messages as input and returns zero or more
    messages as output. The `add_messages` function is used to merge the output messages from each node
    into the existing list of messages in the graph's state.

    Examples:
        ```pycon
        >>> from langgraph.graph.message import MessageGraph
        ...
        >>> builder = MessageGraph()
        >>> builder.add_node("chatbot", lambda state: [("assistant", "Hello!")])
        >>> builder.set_entry_point("chatbot")
        >>> builder.set_finish_point("chatbot")
        >>> builder.compile().invoke([("user", "Hi there.")])
        [HumanMessage(content="Hi there.", id='...'), AIMessage(content="Hello!", id='...')]
        ```

        ```pycon
        >>> from langchain_core.messages import AIMessage, HumanMessage, ToolMessage
        >>> from langgraph.graph.message import MessageGraph
        ...
        >>> builder = MessageGraph()
        >>> builder.add_node(
        ...     "chatbot",
        ...     lambda state: [
        ...         AIMessage(
        ...             content="Hello!",
        ...             tool_calls=[{"name": "search", "id": "123", "args": {"query": "X"}}],
        ...         )
        ...     ],
        ... )
        >>> builder.add_node(
        ...     "search", lambda state: [ToolMessage(content="Searching...", tool_call_id="123")]
        ... )
        >>> builder.set_entry_point("chatbot")
        >>> builder.add_edge("chatbot", "search")
        >>> builder.set_finish_point("search")
        >>> builder.compile().invoke([HumanMessage(content="Hi there. Can you search for X?")])
        {'messages': [HumanMessage(content="Hi there. Can you search for X?", id='b8b7d8f4-7f4d-4f4d-9c1d-f8b8d8f4d9c1'),
                     AIMessage(content="Hello!", id='f4d9c1d8-8d8f-4d9c-b8b7-d8f4f4d9c1d8'),
                     ToolMessage(content="Searching...", id='d8f4f4d9-c1d8-4f4d-b8b7-d8f4f4d9c1d8', tool_call_id="123")]}
        ```
    c                 T    t         |   t        t        t           t
        f          y )N)super__init__r   r*   r   rA   )self	__class__s    r   rF   zMessageGraph.__init__  s    4
#3\#ABCr!   )r   N)__name__
__module____qualname__r#   rF   __classcell__)rH   s   @r   rC   rC      s    ,\D Dr!   rC   c                   (    e Zd ZU eee   ef   ed<   y)MessagesStatemessagesN)rI   rJ   rK   r   r*   r   rA   __annotations__ r!   r   rN   rN     s    Z(,677r!   rN   rO   c                     	 ddl m} t         ||             S # t        $ r% d}t	        j
                  |       t        |       cY S w xY w)Nr   )convert_to_openai_messageszMust have langchain-core>=0.3.11 installed to use automatic message formatting (format='langchain-openai'). Please update your langchain-core version or remove the 'format' flag. Returning un-formatted messages.)langchain_core.messagesrS   r   ImportErrorwarningswarnr*   )rO   rS   r   s      r   r8   r8     sQ    IF ##=h#GHH   	 	cH~s    +AA)"r-   rV   collections.abcr   	functoolsr   typingr   r   r   r   r	   r
   r   rT   r   r   r   r   r   r   r   typing_extensionsr   langgraph.graph.stater   r*   r"   r0   r$   rA   rC   rN   r8   rQ   r!   r   <module>r]      s     $      ( ,/02KKL& I IXx6JH6T-U I& 
 59	l
ll W/01	l
 l l^0D: 0Df8I 8Ix4 Ik9J Ir!   