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!
import { PromptTemplate } from "langchain/prompts";
import { RunnableSequence } from "langchain/schema/runnable";
import { StringOutputParser } from "langchain/schema/output_parser";
import { ChatAnthropic } from "langchain/chat_models/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/prompts
- RunnableSequence from
langchain/schema/runnable
- StringOutputParser from
langchain/schema/output_parser
- ChatAnthropic from
langchain/chat_models/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.