In a recent project, I needed LangChain to use the output of one chain as the input for another chain. I wanted to achieve this in the JavaScript version of LangChain.
Here's an example:
const country = executeChain(
`Which country has the highest population in Latin America?`
)
const fact = executeSecondChain(
`Tell me the {someFact} about {country}`
)
The idea was to pass the output from the first chain to the second chain along with another parameter.

While trying to Google my way out of this situation, I discovered some Python solutions but nothing JavaScript-related.
It turns out that to nest multiple chains in LangChain.js, you use the RunnableSequence.
Below is the full code:
import { ChatOpenAI } from "@langchain/openai"
import { StringOutputParser } from "@langchain/core/output_parsers"
import { PromptTemplate } from "@langchain/core/prompts"
import { RunnableSequence } from "@langchain/core/runnables"
import * as dotenv from "dotenv"
dotenv.config()
const model = new ChatOpenAI()
const prompt1 = PromptTemplate.fromTemplate(
`Which country has the highest population in Latin America?
Respond only with the name of the country.`
)
const chain1 = prompt1
.pipe(model)
.pipe(new StringOutputParser())
const prompt2 = PromptTemplate.fromTemplate(
`Tell me the {word} of {country}?`
)
const chain2 = prompt2
.pipe(model)
.pipe(new StringOutputParser())
const completeChain = RunnableSequence.from([
{
country: chain1,
word: input => input.word
},
chain2
])
const response = await completeChain.invoke({word: 'currency'})
console.log(response)
It will output something like this:
The currency of Brazil is the Brazilian Real, symbolized as BRL.
If you want to give it a test you can pull down the Node.js example for this article from my GitHub.
š Build a full trivia game app with LangChain
Learn by doing with this FREE ebook! This 35-page guide walks you through every step of building your first fully functional AI-powered app using JavaScript and LangChain.js
š Build a full trivia game app with LangChain
Learn by doing with this FREE ebook! This 35-page guide walks you through every step of building your first fully functional AI-powered app using JavaScript and LangChain.js