!function(){function t(t){document.documentElement.setAttribute("data-theme",t)}var e=function(){var t=null;try{t=new URLSearchParams(window.location.search).get("docusaurus-theme")}catch(t){}return t}()||function(){var t=null;try{t=localStorage.getItem("theme")}catch(t){}return t}();t(null!==e?e:"light")}(),document.documentElement.setAttribute("data-announcement-bar-initially-dismissed",function(){try{return"true"===localStorage.getItem("docusaurus.announcement.dismiss")}catch(t){}return!1}())

[Skip to main content](#__docusaurus_skipToContent_fallback)

LangChain v0.2 is coming soon! Preview the new docs [here](/v0.2/docs/introduction/).

[

![🦜️🔗 Langchain](/v0.1/img/brand/wordmark.png)![🦜️🔗 Langchain](/v0.1/img/brand/wordmark-dark.png)

](/v0.1/)[Docs](/v0.1/docs/get_started/introduction/)[Use cases](/v0.1/docs/use_cases/)[Integrations](/v0.1/docs/integrations/platforms/)[API Reference](https://api.js.langchain.com)

[More](#)

*   [People](/v0.1/docs/people/)
*   [Community](/v0.1/docs/community/)
*   [Tutorials](/v0.1/docs/additional_resources/tutorials/)
*   [Contributing](/v0.1/docs/contributing/)

[v0.1](#)

*   [v0.2](https://js.langchain.com/v0.2/docs/introduction)
*   [v0.1](/v0.1/docs/get_started/introduction/)

[🦜🔗](#)

*   [LangSmith](https://smith.langchain.com)
*   [LangSmith Docs](https://docs.smith.langchain.com)
*   [LangChain Hub](https://smith.langchain.com/hub)
*   [LangServe](https://github.com/langchain-ai/langserve)
*   [Python Docs](https://python.langchain.com/)

[Chat](https://chatjs.langchain.com)[](https://github.com/langchain-ai/langchainjs)

Search

*   [Get started](/v0.1/docs/get_started/)
    
    *   [Introduction](/v0.1/docs/get_started/introduction/)
    *   [Installation](/v0.1/docs/get_started/installation/)
    *   [Quickstart](/v0.1/docs/get_started/quickstart/)
*   [LangChain Expression Language](/v0.1/docs/expression_language/)
    
    *   [Get started](/v0.1/docs/expression_language/get_started/)
    *   [Why use LCEL?](/v0.1/docs/expression_language/why/)
    *   [Interface](/v0.1/docs/expression_language/interface/)
    *   [Streaming](/v0.1/docs/expression_language/streaming/)
    *   [How to](/v0.1/docs/expression_language/how_to/routing/)
        
        *   [Route between multiple runnables](/v0.1/docs/expression_language/how_to/routing/)
        *   [Cancelling requests](/v0.1/docs/expression_language/how_to/cancellation/)
        *   [Use RunnableMaps](/v0.1/docs/expression_language/how_to/map/)
        *   [Add message history (memory)](/v0.1/docs/expression_language/how_to/message_history/)
        *   [Add message history (memory)](/v0.1/docs/expression_language/how_to/with_history/)
    *   [Cookbook](/v0.1/docs/expression_language/cookbook/)
        
    *   [LangChain Expression Language (LCEL)](/v0.1/docs/expression_language/)
*   [Modules](/v0.1/docs/modules/)
    
    *   [Model I/O](/v0.1/docs/modules/model_io/)
        
    *   [Retrieval](/v0.1/docs/modules/data_connection/)
        
    *   [Chains](/v0.1/docs/modules/chains/)
    *   [Agents](/v0.1/docs/modules/agents/)
        
    *   [More](/v0.1/docs/modules/memory/)
        
*   [Security](/v0.1/docs/security/)
*   [Guides](/v0.1/docs/guides/)
    
*   [Ecosystem](/v0.1/docs/ecosystem/)
    
*   [LangGraph](/v0.1/docs/langgraph/)
*   * * *
    

*   [](/v0.1/)
*   [LangChain Expression Language](/v0.1/docs/expression_language/)
*   How to
*   Route between multiple runnables

On this page

Route between multiple Runnables
================================

This notebook covers how to do routing in the LangChain Expression Language.

Routing allows you to create non-deterministic chains where the output of a previous step defines the next step. Routing helps provide structure and consistency around interactions with LLMs.

There are two ways to perform routing:

1.  Using a RunnableBranch.
2.  Writing custom factory function that takes the input of a previous step and returns a runnable. Importantly, this should return a runnable and NOT actually execute.

We'll illustrate both methods using a two step sequence where the first step classifies an input question as being about LangChain, Anthropic, or Other, then routes to a corresponding prompt chain.

Using a RunnableBranch[​](#using-a-runnablebranch "Direct link to Using a RunnableBranch")
------------------------------------------------------------------------------------------

A RunnableBranch is initialized with a list of (condition, runnable) pairs and a default runnable. It selects which branch by passing each condition the input it's invoked with. It selects the first condition to evaluate to True, and runs the corresponding runnable to that condition with the input.

If no provided conditions match, it runs the default runnable.

Here's an example of what it looks like in action:

tip

See [this section for general instructions on installing integration packages](/v0.1/docs/get_started/installation/#installing-integration-packages).

*   npm
*   Yarn
*   pnpm

    npm install @langchain/anthropic

    yarn add @langchain/anthropic

    pnpm add @langchain/anthropic

    import { PromptTemplate } from "@langchain/core/prompts";import { StringOutputParser } from "@langchain/core/output_parsers";import { RunnableBranch, RunnableSequence } from "@langchain/core/runnables";import { ChatAnthropic } from "@langchain/anthropic";const promptTemplate =  PromptTemplate.fromTemplate(`Given the user question below, classify it as either being about \`LangChain\`, \`Anthropic\`, or \`Other\`.                                     Do not respond with more than one word.<question>{question}</question>Classification:`);const model = new ChatAnthropic({  model: "claude-3-sonnet-20240229",});const classificationChain = RunnableSequence.from([  promptTemplate,  model,  new StringOutputParser(),]);const classificationChainResult = await classificationChain.invoke({  question: "how do I call Anthropic?",});console.log(classificationChainResult);/*  Anthropic*/const langChainChain = PromptTemplate.fromTemplate(  `You are an expert in langchain.Always answer questions starting with "As Harrison Chase told me".Respond to the following question:Question: {question}Answer:`).pipe(model);const anthropicChain = PromptTemplate.fromTemplate(  `You are an expert in anthropic. \Always answer questions starting with "As Dario Amodei told me". \Respond to the following question:Question: {question}Answer:`).pipe(model);const generalChain = PromptTemplate.fromTemplate(  `Respond to the following question:Question: {question}Answer:`).pipe(model);const branch = RunnableBranch.from([  [    (x: { topic: string; question: string }) =>      x.topic.toLowerCase().includes("anthropic"),    anthropicChain,  ],  [    (x: { topic: string; question: string }) =>      x.topic.toLowerCase().includes("langchain"),    langChainChain,  ],  generalChain,]);const fullChain = RunnableSequence.from([  {    topic: classificationChain,    question: (input: { question: string }) => input.question,  },  branch,]);const result1 = await fullChain.invoke({  question: "how do I use Anthropic?",});console.log(result1);/*  AIMessage {    content: ' As Dario Amodei told me, here are some tips for how to use Anthropic:\n' +      '\n' +      "First, sign up for an account on Anthropic's website. This will give you access to their conversational AI assistant named Claude. \n" +      '\n' +      "Once you've created an account, you can have conversations with Claude through their web interface. Talk to Claude like you would talk to a person, asking questions, giving instructions, etc. Claude is trained to have natural conversations and be helpful.\n" +      '\n' +      "You can also integrate Claude into your own applications using Anthropic's API. This allows you to build Claude's conversational abilities into chatbots, virtual assistants, and other AI systems you develop.\n" +      '\n' +      'Anthropic is constantly working on improving Claude, so its capabilities are always expanding. Make sure to check their blog and documentation to stay up to date on the latest features.\n' +      '\n' +      'The key is to interact with Claude regularly so it can learn from you. The more you chat with it, the better it will become at understanding you and having personalized conversations. Over time, Claude will feel more human-like as it accumulates more conversational experience.',    additional_kwargs: {}  }*/const result2 = await fullChain.invoke({  question: "how do I use LangChain?",});console.log(result2);/*  AIMessage {    content: ' As Harrison Chase told me, here is how you use LangChain:\n' +      '\n' +      'First, think carefully about what you want to ask or have the AI do. Frame your request clearly and specifically. Avoid vague or overly broad prompts that could lead to unhelpful or concerning responses. \n' +      '\n' +      'Next, type your question or request into the chat window and send it. Be patient as the AI processes your input and generates a response. The AI will do its best to provide a helpful answer or follow your instructions, but its capabilities are limited.\n' +      '\n' +      'Keep your requests simple at first. Ask basic questions or have the AI summarize content or generate basic text. As you get more comfortable, you can try having the AI perform more complex tasks like answering tricky questions, generating stories, or having a conversation.\n' +      '\n' +      "Pay attention to the AI's responses. If they seem off topic, nonsensical, or concerning, rephrase your prompt to steer the AI in a better direction. You may need to provide additional clarification or context to get useful results.\n" +      '\n' +      'Be polite and respectful towards the AI system. Remember, it is a tool designed to be helpful, harmless, and honest. Do not try to trick, confuse, or exploit it. \n' +      '\n' +      'I hope these tips help you have a safe, fun and productive experience using LangChain! Let me know if you have any other questions.',    additional_kwargs: {}  }*/const result3 = await fullChain.invoke({  question: "what is 2 + 2?",});console.log(result3);/*  AIMessage {    content: ' 4',    additional_kwargs: {}  }*/

#### API Reference:

*   [PromptTemplate](https://api.js.langchain.com/classes/langchain_core_prompts.PromptTemplate.html) from `@langchain/core/prompts`
*   [StringOutputParser](https://api.js.langchain.com/classes/langchain_core_output_parsers.StringOutputParser.html) from `@langchain/core/output_parsers`
*   [RunnableBranch](https://api.js.langchain.com/classes/langchain_core_runnables.RunnableBranch.html) from `@langchain/core/runnables`
*   [RunnableSequence](https://api.js.langchain.com/classes/langchain_core_runnables.RunnableSequence.html) from `@langchain/core/runnables`
*   [ChatAnthropic](https://api.js.langchain.com/classes/langchain_anthropic.ChatAnthropic.html) from `@langchain/anthropic`

Using a custom function[​](#using-a-custom-function "Direct link to Using a custom function")
---------------------------------------------------------------------------------------------

You can also use a custom function to route between different outputs. Here's an example:

    import { PromptTemplate } from "@langchain/core/prompts";import { StringOutputParser } from "@langchain/core/output_parsers";import { RunnableSequence } from "@langchain/core/runnables";import { ChatAnthropic } from "@langchain/anthropic";const promptTemplate =  PromptTemplate.fromTemplate(`Given the user question below, classify it as either being about \`LangChain\`, \`Anthropic\`, or \`Other\`.                                     Do not respond with more than one word.<question>{question}</question>Classification:`);const model = new ChatAnthropic({  model: "claude-3-sonnet-20240229",});const classificationChain = RunnableSequence.from([  promptTemplate,  model,  new StringOutputParser(),]);const classificationChainResult = await classificationChain.invoke({  question: "how do I call Anthropic?",});console.log(classificationChainResult);/*  Anthropic*/const langChainChain = PromptTemplate.fromTemplate(  `You are an expert in langchain.Always answer questions starting with "As Harrison Chase told me".Respond to the following question:Question: {question}Answer:`).pipe(model);const anthropicChain = PromptTemplate.fromTemplate(  `You are an expert in anthropic. \Always answer questions starting with "As Dario Amodei told me". \Respond to the following question:Question: {question}Answer:`).pipe(model);const generalChain = PromptTemplate.fromTemplate(  `Respond to the following question:Question: {question}Answer:`).pipe(model);const route = ({ topic }: { input: string; topic: string }) => {  if (topic.toLowerCase().includes("anthropic")) {    return anthropicChain;  } else if (topic.toLowerCase().includes("langchain")) {    return langChainChain;  } else {    return generalChain;  }};const fullChain = RunnableSequence.from([  {    topic: classificationChain,    question: (input: { question: string }) => input.question,  },  route,]);const result1 = await fullChain.invoke({  question: "how do I use Anthropic?",});console.log(result1);/*  AIMessage {    content: ' As Dario Amodei told me, here are some tips for how to use Anthropic:\n' +      '\n' +      "First, sign up for an account on Anthropic's website. This will give you access to their conversational AI assistant named Claude. \n" +      '\n' +      "Once you've created an account, you can have conversations with Claude through their web interface. Talk to Claude like you would talk to a person, asking questions, giving instructions, etc. Claude is trained to have natural conversations and be helpful.\n" +      '\n' +      "You can also integrate Claude into your own applications using Anthropic's API. This allows you to build Claude's conversational abilities into chatbots, virtual assistants, and other AI systems you develop.\n" +      '\n' +      'Anthropic is constantly working on improving Claude, so its capabilities are always expanding. Make sure to check their blog and documentation to stay up to date on the latest features.\n' +      '\n' +      'The key is to interact with Claude regularly so it can learn from you. The more you chat with it, the better it will become at understanding you and having personalized conversations. Over time, Claude will feel more human-like as it accumulates more conversational experience.',    additional_kwargs: {}  }*/const result2 = await fullChain.invoke({  question: "how do I use LangChain?",});console.log(result2);/*  AIMessage {    content: ' As Harrison Chase told me, here is how you use LangChain:\n' +      '\n' +      'First, think carefully about what you want to ask or have the AI do. Frame your request clearly and specifically. Avoid vague or overly broad prompts that could lead to unhelpful or concerning responses. \n' +      '\n' +      'Next, type your question or request into the chat window and send it. Be patient as the AI processes your input and generates a response. The AI will do its best to provide a helpful answer or follow your instructions, but its capabilities are limited.\n' +      '\n' +      'Keep your requests simple at first. Ask basic questions or have the AI summarize content or generate basic text. As you get more comfortable, you can try having the AI perform more complex tasks like answering tricky questions, generating stories, or having a conversation.\n' +      '\n' +      "Pay attention to the AI's responses. If they seem off topic, nonsensical, or concerning, rephrase your prompt to steer the AI in a better direction. You may need to provide additional clarification or context to get useful results.\n" +      '\n' +      'Be polite and respectful towards the AI system. Remember, it is a tool designed to be helpful, harmless, and honest. Do not try to trick, confuse, or exploit it. \n' +      '\n' +      'I hope these tips help you have a safe, fun and productive experience using LangChain! Let me know if you have any other questions.',    additional_kwargs: {}  }*/const result3 = await fullChain.invoke({  question: "what is 2 + 2?",});console.log(result3);/*  AIMessage {    content: ' 4',    additional_kwargs: {}  }*/

#### API Reference:

*   [PromptTemplate](https://api.js.langchain.com/classes/langchain_core_prompts.PromptTemplate.html) from `@langchain/core/prompts`
*   [StringOutputParser](https://api.js.langchain.com/classes/langchain_core_output_parsers.StringOutputParser.html) from `@langchain/core/output_parsers`
*   [RunnableSequence](https://api.js.langchain.com/classes/langchain_core_runnables.RunnableSequence.html) from `@langchain/core/runnables`
*   [ChatAnthropic](https://api.js.langchain.com/classes/langchain_anthropic.ChatAnthropic.html) from `@langchain/anthropic`

* * *

#### Help us out by providing feedback on this documentation page:

[

Previous

Streaming

](/v0.1/docs/expression_language/streaming/)[

Next

Cancelling requests

](/v0.1/docs/expression_language/how_to/cancellation/)

*   [Using a RunnableBranch](#using-a-runnablebranch)
*   [Using a custom function](#using-a-custom-function)

Community

*   [Discord](https://discord.gg/cU2adEyC7w)
*   [Twitter](https://twitter.com/LangChainAI)

GitHub

*   [Python](https://github.com/langchain-ai/langchain)
*   [JS/TS](https://github.com/langchain-ai/langchainjs)

More

*   [Homepage](https://langchain.com)
*   [Blog](https://blog.langchain.dev)

Copyright © 2024 LangChain, Inc.