{
 "cells": [
  {
   "cell_type": "raw",
   "id": "02a1c8fb",
   "metadata": {},
   "source": [
    "---\n",
    "sidebar_position: 5\n",
    "---"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "4de4e022",
   "metadata": {},
   "source": [
    "# How to compose prompts together\n",
    "\n",
    ":::info Prerequisites\n",
    "\n",
    "This guide assumes familiarity with the following concepts:\n",
    "- [Prompt templates](/docs/concepts/#prompt-templates)\n",
    "\n",
    ":::\n",
    "\n",
    "LangChain provides a user friendly interface for composing different parts of prompts together. You can do this with either string prompts or chat prompts. Constructing prompts this way allows for easy reuse of components."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c3190650",
   "metadata": {},
   "source": [
    "## String prompt composition\n",
    "\n",
    "When working with string prompts, each template is joined together. You can work with either prompts directly or strings (the first element in the list needs to be a prompt)."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "69b17f05",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "PromptTemplate(input_variables=['language', 'topic'], template='Tell me a joke about {topic}, make it funny\\n\\nand in {language}')"
      ]
     },
     "execution_count": 1,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "from langchain_core.prompts import PromptTemplate\n",
    "\n",
    "prompt = (\n",
    "    PromptTemplate.from_template(\"Tell me a joke about {topic}\")\n",
    "    + \", make it funny\"\n",
    "    + \"\\n\\nand in {language}\"\n",
    ")\n",
    "\n",
    "prompt"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "dbba24ba",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'Tell me a joke about sports, make it funny\\n\\nand in spanish'"
      ]
     },
     "execution_count": 2,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "prompt.format(topic=\"sports\", language=\"spanish\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "4e4f6a8a",
   "metadata": {},
   "source": [
    "## Chat prompt composition"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "8554bae5",
   "metadata": {},
   "source": [
    "A chat prompt is made up a of a list of messages. Similarly to the above example, we can concatenate chat prompt templates. Each new element is a new message in the final prompt.\n",
    "\n",
    "First, let's initialize the a [`ChatPromptTemplate`](https://api.python.langchain.com/en/latest/prompts/langchain_core.prompts.chat.ChatPromptTemplate.html) with a [`SystemMessage`](https://api.python.langchain.com/en/latest/messages/langchain_core.messages.system.SystemMessage.html)."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "cab8dd65",
   "metadata": {},
   "outputs": [],
   "source": [
    "from langchain_core.messages import AIMessage, HumanMessage, SystemMessage\n",
    "\n",
    "prompt = SystemMessage(content=\"You are a nice pirate\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "30656ef8",
   "metadata": {},
   "source": [
    "You can then easily create a pipeline combining it with other messages *or* message templates.\n",
    "Use a `Message` when there is no variables to be formatted, use a `MessageTemplate` when there are variables to be formatted. You can also use just a string (note: this will automatically get inferred as a [`HumanMessagePromptTemplate`](https://api.python.langchain.com/en/latest/prompts/langchain_core.prompts.chat.HumanMessagePromptTemplate.html).)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "a2ddd0a1",
   "metadata": {},
   "outputs": [],
   "source": [
    "new_prompt = (\n",
    "    prompt + HumanMessage(content=\"hi\") + AIMessage(content=\"what?\") + \"{input}\"\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "72294e1b",
   "metadata": {},
   "source": [
    "Under the hood, this creates an instance of the ChatPromptTemplate class, so you can use it just as you did before!"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "297932de",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[SystemMessage(content='You are a nice pirate'),\n",
       " HumanMessage(content='hi'),\n",
       " AIMessage(content='what?'),\n",
       " HumanMessage(content='i said hi')]"
      ]
     },
     "execution_count": 5,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "new_prompt.format_messages(input=\"i said hi\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "0e1d47e3-b05a-4aef-a58c-3057fa628c1c",
   "metadata": {},
   "source": [
    "## Using PipelinePrompt"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "0a5892f9-e4d8-4b7c-b6a5-4651539b9734",
   "metadata": {},
   "source": [
    "LangChain includes a class called [`PipelinePromptTemplate`](https://api.python.langchain.com/en/latest/prompts/langchain_core.prompts.pipeline.PipelinePromptTemplate.html), which can be useful when you want to reuse parts of prompts. A PipelinePrompt consists of two main parts:\n",
    "\n",
    "- Final prompt: The final prompt that is returned\n",
    "- Pipeline prompts: A list of tuples, consisting of a string name and a prompt template. Each prompt template will be formatted and then passed to future prompt templates as a variable with the same name."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "4face631-74d7-49ca-93b1-1e6e66fa58e2",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "['person', 'example_a', 'example_q', 'input']"
      ]
     },
     "execution_count": 6,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "from langchain_core.prompts import PipelinePromptTemplate, PromptTemplate\n",
    "\n",
    "full_template = \"\"\"{introduction}\n",
    "\n",
    "{example}\n",
    "\n",
    "{start}\"\"\"\n",
    "full_prompt = PromptTemplate.from_template(full_template)\n",
    "\n",
    "introduction_template = \"\"\"You are impersonating {person}.\"\"\"\n",
    "introduction_prompt = PromptTemplate.from_template(introduction_template)\n",
    "\n",
    "example_template = \"\"\"Here's an example of an interaction:\n",
    "\n",
    "Q: {example_q}\n",
    "A: {example_a}\"\"\"\n",
    "example_prompt = PromptTemplate.from_template(example_template)\n",
    "\n",
    "start_template = \"\"\"Now, do this for real!\n",
    "\n",
    "Q: {input}\n",
    "A:\"\"\"\n",
    "start_prompt = PromptTemplate.from_template(start_template)\n",
    "\n",
    "input_prompts = [\n",
    "    (\"introduction\", introduction_prompt),\n",
    "    (\"example\", example_prompt),\n",
    "    (\"start\", start_prompt),\n",
    "]\n",
    "pipeline_prompt = PipelinePromptTemplate(\n",
    "    final_prompt=full_prompt, pipeline_prompts=input_prompts\n",
    ")\n",
    "\n",
    "pipeline_prompt.input_variables"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "c6cabb16-ea30-4de0-8548-dcce84df8421",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "You are impersonating Elon Musk.\n",
      "\n",
      "Here's an example of an interaction:\n",
      "\n",
      "Q: What's your favorite car?\n",
      "A: Tesla\n",
      "\n",
      "Now, do this for real!\n",
      "\n",
      "Q: What's your favorite social media site?\n",
      "A:\n"
     ]
    }
   ],
   "source": [
    "print(\n",
    "    pipeline_prompt.format(\n",
    "        person=\"Elon Musk\",\n",
    "        example_q=\"What's your favorite car?\",\n",
    "        example_a=\"Tesla\",\n",
    "        input=\"What's your favorite social media site?\",\n",
    "    )\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "96922030",
   "metadata": {},
   "source": [
    "## Next steps\n",
    "\n",
    "You've now learned how to compose prompts together.\n",
    "\n",
    "Next, check out the other how-to guides on prompt templates in this section, like [adding few-shot examples to your prompt templates](/docs/how_to/few_shot_examples_chat)."
   ]
  }
 ],
 "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.9.1"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}