{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "b5ee5b75-6876-4d62-9ade-5a7a808ae5a2",
   "metadata": {},
   "source": [
    "# How to trim messages\n",
    "\n",
    ":::info Prerequisites\n",
    "\n",
    "This guide assumes familiarity with the following concepts:\n",
    "\n",
    "- [Messages](/docs/concepts/#messages)\n",
    "- [Chat models](/docs/concepts/#chat-models)\n",
    "- [Chaining](/docs/how_to/sequence/)\n",
    "- [Chat history](/docs/concepts/#chat-history)\n",
    "\n",
    "The methods in this guide also require `langchain-core>=0.2.9`.\n",
    "\n",
    ":::\n",
    "\n",
    "All models have finite context windows, meaning there's a limit to how many tokens they can take as input. If you have very long messages or a chain/agent that accumulates a long message is history, you'll need to manage the length of the messages you're passing in to the model.\n",
    "\n",
    "The `trim_messages` util provides some basic strategies for trimming a list of messages to be of a certain token length.\n",
    "\n",
    "## Getting the last `max_tokens` tokens\n",
    "\n",
    "To get the last `max_tokens` in the list of Messages we can set `strategy=\"last\"`. Notice that for our `token_counter` we can pass in a function (more on that below) or a language model (since language models have a message token counting method). It makes sense to pass in a model when you're trimming your messages to fit into the context window of that specific model:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "c974633b-3bd0-4844-8a8f-85e3e25f13fe",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[AIMessage(content=\"Hmmm let me think.\\n\\nWhy, he's probably chasing after the last cup of coffee in the office!\"),\n",
       " HumanMessage(content='what do you call a speechless parrot')]"
      ]
     },
     "execution_count": 1,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# pip install -U langchain-openai\n",
    "from langchain_core.messages import (\n",
    "    AIMessage,\n",
    "    HumanMessage,\n",
    "    SystemMessage,\n",
    "    trim_messages,\n",
    ")\n",
    "from langchain_openai import ChatOpenAI\n",
    "\n",
    "messages = [\n",
    "    SystemMessage(\"you're a good assistant, you always respond with a joke.\"),\n",
    "    HumanMessage(\"i wonder why it's called langchain\"),\n",
    "    AIMessage(\n",
    "        'Well, I guess they thought \"WordRope\" and \"SentenceString\" just didn\\'t have the same ring to it!'\n",
    "    ),\n",
    "    HumanMessage(\"and who is harrison chasing anyways\"),\n",
    "    AIMessage(\n",
    "        \"Hmmm let me think.\\n\\nWhy, he's probably chasing after the last cup of coffee in the office!\"\n",
    "    ),\n",
    "    HumanMessage(\"what do you call a speechless parrot\"),\n",
    "]\n",
    "\n",
    "trim_messages(\n",
    "    messages,\n",
    "    max_tokens=45,\n",
    "    strategy=\"last\",\n",
    "    token_counter=ChatOpenAI(model=\"gpt-4o\"),\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "d3f46654-c4b2-4136-b995-91c3febe5bf9",
   "metadata": {},
   "source": [
    "If we want to always keep the initial system message we can specify `include_system=True`:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "589b0223-3a73-44ec-8315-2dba3ee6117d",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[SystemMessage(content=\"you're a good assistant, you always respond with a joke.\"),\n",
       " HumanMessage(content='what do you call a speechless parrot')]"
      ]
     },
     "execution_count": 2,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "trim_messages(\n",
    "    messages,\n",
    "    max_tokens=45,\n",
    "    strategy=\"last\",\n",
    "    token_counter=ChatOpenAI(model=\"gpt-4o\"),\n",
    "    include_system=True,\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "8a8b542c-04d1-4515-8d82-b999ea4fac4f",
   "metadata": {},
   "source": [
    "If we want to allow splitting up the contents of a message we can specify `allow_partial=True`:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "8c46a209-dddd-4d01-81f6-f6ae55d3225c",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[SystemMessage(content=\"you're a good assistant, you always respond with a joke.\"),\n",
       " AIMessage(content=\"\\nWhy, he's probably chasing after the last cup of coffee in the office!\"),\n",
       " HumanMessage(content='what do you call a speechless parrot')]"
      ]
     },
     "execution_count": 3,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "trim_messages(\n",
    "    messages,\n",
    "    max_tokens=56,\n",
    "    strategy=\"last\",\n",
    "    token_counter=ChatOpenAI(model=\"gpt-4o\"),\n",
    "    include_system=True,\n",
    "    allow_partial=True,\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "306adf9c-41cd-495c-b4dc-e4f43dd7f8f8",
   "metadata": {},
   "source": [
    "If we need to make sure that our first message (excluding the system message) is always of a specific type, we can specify `start_on`:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "878a730b-fe44-4e9d-ab65-7b8f7b069de8",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[SystemMessage(content=\"you're a good assistant, you always respond with a joke.\"),\n",
       " HumanMessage(content='what do you call a speechless parrot')]"
      ]
     },
     "execution_count": 4,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "trim_messages(\n",
    "    messages,\n",
    "    max_tokens=60,\n",
    "    strategy=\"last\",\n",
    "    token_counter=ChatOpenAI(model=\"gpt-4o\"),\n",
    "    include_system=True,\n",
    "    start_on=\"human\",\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "7f5d391d-235b-4091-b2de-c22866b478f3",
   "metadata": {},
   "source": [
    "## Getting the first `max_tokens` tokens\n",
    "\n",
    "We can perform the flipped operation of getting the *first* `max_tokens` by specifying `strategy=\"first\"`:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "5f56ae54-1a39-4019-9351-3b494c003d5b",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[SystemMessage(content=\"you're a good assistant, you always respond with a joke.\"),\n",
       " HumanMessage(content=\"i wonder why it's called langchain\")]"
      ]
     },
     "execution_count": 5,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "trim_messages(\n",
    "    messages,\n",
    "    max_tokens=45,\n",
    "    strategy=\"first\",\n",
    "    token_counter=ChatOpenAI(model=\"gpt-4o\"),\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ab70bf70-1e5a-4d51-b9b8-a823bf2cf532",
   "metadata": {},
   "source": [
    "## Writing a custom token counter\n",
    "\n",
    "We can write a custom token counter function that takes in a list of messages and returns an int."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "1c1c3b1e-2ece-49e7-a3b6-e69877c1633b",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[AIMessage(content=\"Hmmm let me think.\\n\\nWhy, he's probably chasing after the last cup of coffee in the office!\"),\n",
       " HumanMessage(content='what do you call a speechless parrot')]"
      ]
     },
     "execution_count": 6,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "from typing import List\n",
    "\n",
    "# pip install tiktoken\n",
    "import tiktoken\n",
    "from langchain_core.messages import BaseMessage, ToolMessage\n",
    "\n",
    "\n",
    "def str_token_counter(text: str) -> int:\n",
    "    enc = tiktoken.get_encoding(\"o200k_base\")\n",
    "    return len(enc.encode(text))\n",
    "\n",
    "\n",
    "def tiktoken_counter(messages: List[BaseMessage]) -> int:\n",
    "    \"\"\"Approximately reproduce https://github.com/openai/openai-cookbook/blob/main/examples/How_to_count_tokens_with_tiktoken.ipynb\n",
    "\n",
    "    For simplicity only supports str Message.contents.\n",
    "    \"\"\"\n",
    "    num_tokens = 3  # every reply is primed with 
assistant
\n",
    "    tokens_per_message = 3\n",
    "    tokens_per_name = 1\n",
    "    for msg in messages:\n",
    "        if isinstance(msg, HumanMessage):\n",
    "            role = \"user\"\n",
    "        elif isinstance(msg, AIMessage):\n",
    "            role = \"assistant\"\n",
    "        elif isinstance(msg, ToolMessage):\n",
    "            role = \"tool\"\n",
    "        elif isinstance(msg, SystemMessage):\n",
    "            role = \"system\"\n",
    "        else:\n",
    "            raise ValueError(f\"Unsupported messages type {msg.__class__}\")\n",
    "        num_tokens += (\n",
    "            tokens_per_message\n",
    "            + str_token_counter(role)\n",
    "            + str_token_counter(msg.content)\n",
    "        )\n",
    "        if msg.name:\n",
    "            num_tokens += tokens_per_name + str_token_counter(msg.name)\n",
    "    return num_tokens\n",
    "\n",
    "\n",
    "trim_messages(\n",
    "    messages,\n",
    "    max_tokens=45,\n",
    "    strategy=\"last\",\n",
    "    token_counter=tiktoken_counter,\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "4b2a672b-c007-47c5-9105-617944dc0a6a",
   "metadata": {},
   "source": [
    "## Chaining\n",
    "\n",
    "`trim_messages` 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": 7,
   "id": "96aa29b2-01e0-437c-a1ab-02fb0141cb57",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "AIMessage(content='A: A \"Polly-gone\"!', response_metadata={'token_usage': {'completion_tokens': 9, 'prompt_tokens': 32, 'total_tokens': 41}, 'model_name': 'gpt-4o-2024-05-13', 'system_fingerprint': 'fp_66b29dffce', 'finish_reason': 'stop', 'logprobs': None}, id='run-83e96ddf-bcaa-4f63-824c-98b0f8a0d474-0', usage_metadata={'input_tokens': 32, 'output_tokens': 9, 'total_tokens': 41})"
      ]
     },
     "execution_count": 7,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "llm = ChatOpenAI(model=\"gpt-4o\")\n",
    "\n",
    "# Notice we don't pass in messages. This creates\n",
    "# a RunnableLambda that takes messages as input\n",
    "trimmer = trim_messages(\n",
    "    max_tokens=45,\n",
    "    strategy=\"last\",\n",
    "    token_counter=llm,\n",
    "    include_system=True,\n",
    ")\n",
    "\n",
    "chain = trimmer | llm\n",
    "chain.invoke(messages)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "4d91d390-e7f7-467b-ad87-d100411d7a21",
   "metadata": {},
   "source": [
    "Looking at the LangSmith trace we can see that before the messages are passed to the model they are first trimmed: https://smith.langchain.com/public/65af12c4-c24d-4824-90f0-6547566e59bb/r\n",
    "\n",
    "Looking at just the trimmer, we can see that it's a Runnable object that can be invoked like all Runnables:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "id": "1ff02d0a-353d-4fac-a77c-7c2c5262abd9",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[SystemMessage(content=\"you're a good assistant, you always respond with a joke.\"),\n",
       " HumanMessage(content='what do you call a speechless parrot')]"
      ]
     },
     "execution_count": 8,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "trimmer.invoke(messages)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "dc4720c8-4062-4ebc-9385-58411202ce6e",
   "metadata": {},
   "source": [
    "## Using with ChatMessageHistory\n",
    "\n",
    "Trimming messages is especially useful when [working with chat histories](/docs/how_to/message_history/), which can get arbitrarily long:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "id": "a9517858-fc2f-4dc3-898d-bf98a0e905a0",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "AIMessage(content='A \"polly-no-wanna-cracker\"!', response_metadata={'token_usage': {'completion_tokens': 10, 'prompt_tokens': 32, 'total_tokens': 42}, 'model_name': 'gpt-4o-2024-05-13', 'system_fingerprint': 'fp_5bf7397cd3', 'finish_reason': 'stop', 'logprobs': None}, id='run-054dd309-3497-4e7b-b22a-c1859f11d32e-0', usage_metadata={'input_tokens': 32, 'output_tokens': 10, 'total_tokens': 42})"
      ]
     },
     "execution_count": 9,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "from langchain_core.chat_history import InMemoryChatMessageHistory\n",
    "from langchain_core.runnables.history import RunnableWithMessageHistory\n",
    "\n",
    "chat_history = InMemoryChatMessageHistory(messages=messages[:-1])\n",
    "\n",
    "\n",
    "def dummy_get_session_history(session_id):\n",
    "    if session_id != \"1\":\n",
    "        return InMemoryChatMessageHistory()\n",
    "    return chat_history\n",
    "\n",
    "\n",
    "llm = ChatOpenAI(model=\"gpt-4o\")\n",
    "\n",
    "trimmer = trim_messages(\n",
    "    max_tokens=45,\n",
    "    strategy=\"last\",\n",
    "    token_counter=llm,\n",
    "    include_system=True,\n",
    ")\n",
    "\n",
    "chain = trimmer | llm\n",
    "chain_with_history = RunnableWithMessageHistory(chain, dummy_get_session_history)\n",
    "chain_with_history.invoke(\n",
    "    [HumanMessage(\"what do you call a speechless parrot\")],\n",
    "    config={\"configurable\": {\"session_id\": \"1\"}},\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "556b7b4c-43cb-41de-94fc-1a41f4ec4d2e",
   "metadata": {},
   "source": [
    "Looking at the LangSmith trace we can see that we retrieve all of our messages but before the messages are passed to the model they are trimmed to be just the system message and last human message: https://smith.langchain.com/public/17dd700b-9994-44ca-930c-116e00997315/r"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "75dc7b84-b92f-44e7-8beb-ba22398e4efb",
   "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.trim_messages.html"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "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.10.4"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}