{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "ac47bfab-0f4f-42ce-8bb6-898ef22a0338",
   "metadata": {},
   "source": [
    "# How to merge consecutive messages of the same type\n",
    "\n",
    "Certain models do not support passing in consecutive messages of the same type (a.k.a. \"runs\" of the same message type).\n",
    "\n",
    "The `merge_message_runs` utility makes it easy to merge consecutive messages of the same type.\n",
    "\n",
    "## Basic usage"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "1a215bbb-c05c-40b0-a6fd-d94884d517df",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "SystemMessage(content=\"you're a good assistant.\\nyou always respond with a joke.\")\n",
      "\n",
      "HumanMessage(content=[{'type': 'text', 'text': \"i wonder why it's called langchain\"}, 'and who is harrison chasing anyways'])\n",
      "\n",
      "AIMessage(content='Well, I guess they thought \"WordRope\" and \"SentenceString\" just didn\\'t have the same ring to it!\\nWhy, he\\'s probably chasing after the last cup of coffee in the office!')\n"
     ]
    }
   ],
   "source": [
    "from langchain_core.messages import (\n",
    "    AIMessage,\n",
    "    HumanMessage,\n",
    "    SystemMessage,\n",
    "    merge_message_runs,\n",
    ")\n",
    "\n",
    "messages = [\n",
    "    SystemMessage(\"you're a good assistant.\"),\n",
    "    SystemMessage(\"you always respond with a joke.\"),\n",
    "    HumanMessage([{\"type\": \"text\", \"text\": \"i wonder why it's called langchain\"}]),\n",
    "    HumanMessage(\"and who is harrison chasing anyways\"),\n",
    "    AIMessage(\n",
    "        'Well, I guess they thought \"WordRope\" and \"SentenceString\" just didn\\'t have the same ring to it!'\n",
    "    ),\n",
    "    AIMessage(\"Why, he's probably chasing after the last cup of coffee in the office!\"),\n",
    "]\n",
    "\n",
    "merged = merge_message_runs(messages)\n",
    "print(\"\\n\\n\".join([repr(x) for x in merged]))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "0544c811-7112-4b76-8877-cc897407c738",
   "metadata": {},
   "source": [
    "Notice that if the contents of one of the messages to merge is a list of content blocks then the merged message will have a list of content blocks. And if both messages to merge have string contents then those are concatenated with a newline character."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "1b2eee74-71c8-4168-b968-bca580c25d18",
   "metadata": {},
   "source": [
    "## Chaining\n",
    "\n",
    "`merge_message_runs` can be used in an imperatively (like above) or declaratively, making it easy to compose with other components in a chain:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "6d5a0283-11f8-435b-b27b-7b18f7693592",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "AIMessage(content=[], response_metadata={'id': 'msg_01D6R8Naum57q8qBau9vLBUX', 'model': 'claude-3-sonnet-20240229', 'stop_reason': 'end_turn', 'stop_sequence': None, 'usage': {'input_tokens': 84, 'output_tokens': 3}}, id='run-ac0c465b-b54f-4b8b-9295-e5951250d653-0', usage_metadata={'input_tokens': 84, 'output_tokens': 3, 'total_tokens': 87})"
      ]
     },
     "execution_count": 3,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# pip install -U langchain-anthropic\n",
    "from langchain_anthropic import ChatAnthropic\n",
    "\n",
    "llm = ChatAnthropic(model=\"claude-3-sonnet-20240229\", temperature=0)\n",
    "# Notice we don't pass in messages. This creates\n",
    "# a RunnableLambda that takes messages as input\n",
    "merger = merge_message_runs()\n",
    "chain = merger | llm\n",
    "chain.invoke(messages)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "72e90dce-693c-4842-9526-ce6460fe956b",
   "metadata": {},
   "source": [
    "Looking at the LangSmith trace we can see that before the messages are passed to the model they are merged: https://smith.langchain.com/public/ab558677-cac9-4c59-9066-1ecce5bcd87c/r\n",
    "\n",
    "Looking at just the merger, we can see that it's a Runnable object that can be invoked like all Runnables:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "460817a6-c327-429d-958e-181a8c46059c",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[SystemMessage(content=\"you're a good assistant.\\nyou always respond with a joke.\"),\n",
       " HumanMessage(content=[{'type': 'text', 'text': \"i wonder why it's called langchain\"}, 'and who is harrison chasing anyways']),\n",
       " AIMessage(content='Well, I guess they thought \"WordRope\" and \"SentenceString\" just didn\\'t have the same ring to it!\\nWhy, he\\'s probably chasing after the last cup of coffee in the office!')]"
      ]
     },
     "execution_count": 4,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "merger.invoke(messages)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "4548d916-ce21-4dc6-8f19-eedb8003ace6",
   "metadata": {},
   "source": [
    "## API reference\n",
    "\n",
    "For a complete description of all arguments head to the API reference: https://api.python.langchain.com/en/latest/messages/langchain_core.messages.utils.merge_message_runs.html"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "poetry-venv-2",
   "language": "python",
   "name": "poetry-venv-2"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.9.1"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
