Multiple chains
Runnables can be used to combine multiple Chains together:
Interactive tutorial
The screencast below interactively walks through an example. You can update and run the code as it's being written in the video!
- npm
- Yarn
- pnpm
npm install @langchain/anthropic
yarn add @langchain/anthropic
pnpm add @langchain/anthropic
import { PromptTemplate } from "@langchain/core/prompts";
import { RunnableSequence } from "@langchain/core/runnables";
import { StringOutputParser } from "@langchain/core/output_parsers";
import { ChatAnthropic } from "@langchain/anthropic";
const prompt1 = PromptTemplate.fromTemplate(
`What is the city {person} is from? Only respond with the name of the city.`
);
const prompt2 = PromptTemplate.fromTemplate(
`What country is the city {city} in? Respond in {language}.`
);
const model = new ChatAnthropic({});
const chain = prompt1.pipe(model).pipe(new StringOutputParser());
const combinedChain = RunnableSequence.from([
{
city: chain,
language: (input) => input.language,
},
prompt2,
model,
new StringOutputParser(),
]);
const result = await combinedChain.invoke({
person: "Obama",
language: "German",
});
console.log(result);
/*
Chicago befindet sich in den Vereinigten Staaten.
*/
API Reference:
- PromptTemplate from
@langchain/core/prompts
- RunnableSequence from
@langchain/core/runnables
- StringOutputParser from
@langchain/core/output_parsers
- ChatAnthropic from
@langchain/anthropic
The RunnableSequence
above coerces the object into a RunnableMap
.
Each property in the map receives the same parameters. The runnable or function set as the value of that property
is invoked with those parameters, and the return value populates an object which is then passed onto the next runnable in the sequence.
Passthroughs
In the example above, we use a passthrough in a runnable map to pass along original input variables to future steps in the chain.
In general, how exactly you do this depends on what exactly the input is:
- If the original input was a string, then you likely just want to pass along the string. This can be done with
RunnablePassthrough
. For an example of this, see the retrieval chain in the RAG section of this cookbook. - If the original input was an object, then you likely want to pass along specific keys. For this, you can use an arrow function that takes the object as input and extracts the desired key, as shown above.