Mastering RunnableAssign in LangChain.js
Aug 8,2026

Introduction

In the previous article, we learned about RunnablePassthrough.

RunnablePassthrough is useful when we want to preserve the original input while passing it through a LangChain workflow.

For example:

Input
  ↓
RunnablePassthrough
  ↓
Same Input

We also learned about:

RunnablePassthrough.assign()

which can preserve an existing object and add new fields to it.

That brings us to today's topic:

RunnableAssign

At first, RunnableAssign might look very similar to RunnablePassthrough.assign().

And that's a reasonable observation.

The important idea is that RunnableAssign is the explicit Runnable class for merging the original input object with the output of a mapping of Runnables. It accepts dictionary-like input and adds new key-value pairs produced by its mapper.

In this article, we'll understand:

  • What RunnableAssign is

  • Why we need it

  • How it works internally

  • RunnableAssign with RunnableParallel

  • RunnableAssign with RunnableLambda

  • Adding calculated fields

  • Adding AI-generated fields

  • OpenAI examples

  • Gemini examples

  • RunnableAssign vs RunnablePassthrough.assign()

  • RunnableAssign vs RunnableParallel

  • Real-world examples

  • Best practices

  • Common mistakes

Let's get started.


What is RunnableAssign?

RunnableAssign is a Runnable that takes an existing object and adds new fields to it.

Conceptually:

Existing Object
      ↓
Process New Fields
      ↓
Merge
      ↓
Original Object + New Fields

For example, suppose we have:

{
  name: "John",
  age: 25
}

We want to calculate:

{
  isAdult: true
}

RunnableAssign can produce:

{
  name: "John",
  age: 25,
  isAdult: true
}

The original fields are preserved.

The new fields are added.


Why Do We Need RunnableAssign?

Imagine your application already has an object:

{
  title: "Node.js Streams",
  content: "..."
}

Now you want AI to generate:

  • Summary

  • Keywords

  • Difficulty

You don't want to lose the original article.

You want:

{
  title: "Node.js Streams",
  content: "...",
  summary: "...",
  keywords: [...],
  difficulty: "beginner"
}

This is exactly the kind of data-enrichment workflow that RunnableAssign is designed for.


RunnableAssign Architecture

Think of the workflow like this:

                  ┌──→ New Field A
                  │
Original Input ───┼──→ New Field B
                  │
                  └──→ New Field C
                         │
                         ▼
                       Merge
                         │
                         ▼
              Original + New Fields

The important point is:

RunnableAssign preserves the original object and merges the results generated by its mapper.

The current LangChain.js reference describes RunnableAssign as a Runnable that assigns key-value pairs to inputs of type Record<string, unknown>.


Project Setup

Create a new project:

mkdir runnable-assign
cd runnable-assign
npm init -y

Install the required packages:

npm install @langchain/core @langchain/openai @langchain/google-genai dotenv

Project Structure

runnable-assign/
│
├── index.js
├── .env
└── package.json

Configure API Keys

Create a .env file:

OPENAI_API_KEY=your_openai_api_key
GOOGLE_API_KEY=your_google_api_key

Never commit your .env file to Git.

Add it to .gitignore:

node_modules/
.env

Import RunnableAssign

import {
  RunnableAssign,
  RunnableLambda,
  RunnableParallel,
} from "@langchain/core/runnables";

We'll use:

  • RunnableAssign to merge data.

  • RunnableLambda for custom JavaScript logic.

  • RunnableParallel to calculate multiple fields independently.


Your First RunnableAssign

Let's start with a simple example.

Suppose we have:

const input = {
  name: "John",
  age: 25,
};

We want to add:

isAdult: true

First, create a Runnable that calculates the new field.

const mapper =
  RunnableParallel.from({
    isAdult: RunnableLambda.from(
      (data) => ({
        isAdult: data.age >= 18,
      })
    ),
  });

Now create RunnableAssign:

const assign =
  new RunnableAssign({
    mapper,
  });

Invoke it:

const result =
  await assign.invoke({
    name: "John",
    age: 25,
  });

console.log(result);

The result is conceptually:

{
  name: "John",
  age: 25,
  isAdult: {
    isAdult: true
  }
}

Notice something important.

The mapper branch itself returns:

{
  isAdult: true
}

and because the branch is named isAdult, the merged result contains:

{
  isAdult: {
    isAdult: true
  }
}

If you want the new field itself to be isAdult: true, return the boolean directly:

const mapper =
  RunnableParallel.from({
    isAdult: RunnableLambda.from(
      (data) => data.age >= 18
    ),
  });

Now:

const assign =
  new RunnableAssign({
    mapper,
  });

Invoke:

const result =
  await assign.invoke({
    name: "John",
    age: 25,
  });

console.log(result);

Output:

{
  name: "John",
  age: 25,
  isAdult: true
}

This is the pattern we want.


Understanding the Mapper

The mapper is very important.

RunnableAssign uses a mapping of Runnables to calculate the new fields. The official JavaScript reference shows RunnableAssign being constructed with a RunnableParallel mapper.

Think of it like:

Input Object
     │
     ▼
RunnableParallel
     │
     ├──→ Field A
     ├──→ Field B
     └──→ Field C
     │
     ▼
RunnableAssign
     │
     ▼
Original + A + B + C

So RunnableAssign and RunnableParallel often work together.


Adding Multiple Fields

Let's add multiple calculated fields.

Input:

{
  name: "John",
  age: 25,
  salary: 50000
}

We want to calculate:

  • isAdult

  • isHighEarner

  • category

Create the mapper:

const mapper =
  RunnableParallel.from({

    isAdult:
      RunnableLambda.from(
        (data) => data.age >= 18
      ),

    isHighEarner:
      RunnableLambda.from(
        (data) => data.salary >= 50000
      ),

    category:
      RunnableLambda.from(
        (data) =>
          data.age < 30
            ? "Young Professional"
            : "Experienced Professional"
      ),
  });

Create the assignment:

const assign =
  new RunnableAssign({
    mapper,
  });

Invoke:

const result =
  await assign.invoke({
    name: "John",
    age: 25,
    salary: 50000,
  });

console.log(result);

Output:

{
  name: "John",
  age: 25,
  salary: 50000,
  isAdult: true,
  isHighEarner: true,
  category: "Young Professional"
}

The original object remains intact.


RunnableAssign with RunnableLambda

RunnableLambda is useful when the new field requires custom JavaScript logic.

For example:

const createFullName =
  RunnableLambda.from(
    (data) =>
      `${data.firstName} ${data.lastName}`
  );

Create the mapper:

const mapper =
  RunnableParallel.from({
    fullName: createFullName,
  });

Then:

const assign =
  new RunnableAssign({
    mapper,
  });

Invoke:

const result =
  await assign.invoke({
    firstName: "John",
    lastName: "Doe",
  });

console.log(result);

Output:

{
  firstName: "John",
  lastName: "Doe",
  fullName: "John Doe"
}

RunnableAssign with OpenAI

Now let's use AI-generated data.

Suppose we have an article:

const article = {
  title: "Understanding Node.js Streams",
  content: `
    Node.js streams allow applications
    to process data efficiently...
  `,
};

We want AI to generate a summary.


Initialize OpenAI

import { ChatOpenAI } from "@langchain/openai";

const model =
  new ChatOpenAI({
    model: "gpt-4.1-mini",
  });

Create the prompt:

import {
  PromptTemplate,
} from "@langchain/core/prompts";

const summaryPrompt =
  PromptTemplate.fromTemplate(`
Summarize the following article
in 2-3 sentences.

Title:
{title}

Content:
{content}
`);

Add a parser:

import {
  StringOutputParser,
} from "@langchain/core/output_parsers";

const parser =
  new StringOutputParser();

Create the summary chain:

const summaryChain =
  summaryPrompt
    .pipe(model)
    .pipe(parser);

Now create the mapper:

const mapper =
  RunnableParallel.from({
    summary: summaryChain,
  });

Create RunnableAssign:

const assign =
  new RunnableAssign({
    mapper,
  });

Invoke:

const result =
  await assign.invoke(article);

console.log(result);

The final object looks like:

{
  title: "Understanding Node.js Streams",

  content: "...",

  summary:
    "Node.js streams provide..."
}

The original article is preserved.

The AI-generated summary is added.


Adding Multiple AI Fields

Now let's make the example more realistic.

We want:

  • Summary

  • Keywords

  • Difficulty

Create three prompts:

const summaryPrompt =
  PromptTemplate.fromTemplate(`
Summarize this article in 2-3 sentences.

{content}
`);

const keywordPrompt =
  PromptTemplate.fromTemplate(`
Extract 5 important keywords
from this article.

{content}
`);

const difficultyPrompt =
  PromptTemplate.fromTemplate(`
Determine the technical difficulty
of this article.

Return only one of:
beginner, intermediate, advanced.

Article:
{content}
`);

Create chains:

const summaryChain =
  summaryPrompt
    .pipe(model)
    .pipe(parser);

const keywordChain =
  keywordPrompt
    .pipe(model)
    .pipe(parser);

const difficultyChain =
  difficultyPrompt
    .pipe(model)
    .pipe(parser);

Now create the mapper:

const mapper =
  RunnableParallel.from({
    summary: summaryChain,
    keywords: keywordChain,
    difficulty: difficultyChain,
  });

Create RunnableAssign:

const assign =
  new RunnableAssign({
    mapper,
  });

Invoke:

const result =
  await assign.invoke({
    title: "Understanding Node.js Streams",

    content:
      "Node.js streams allow..."
  });

console.log(result);

The result can look like:

{
  title: "Understanding Node.js Streams",

  content: "Node.js streams allow...",

  summary:
    "Streams allow applications to process data...",

  keywords:
    "Node.js, streams, readable, writable, buffers",

  difficulty:
    "intermediate"
}

Why Use RunnableAssign Here?

We could simply return:

{
  summary,
  keywords,
  difficulty
}

But then we'd lose the original article data.

With RunnableAssign, we get:

Original Article
       +
AI Generated Data
       ↓
Enriched Article

That's the key advantage.


Gemini Example

The same workflow can be used with Gemini.

Initialize Gemini:

import {
  ChatGoogleGenerativeAI,
} from "@langchain/google-genai";

const geminiModel =
  new ChatGoogleGenerativeAI({
    model: "gemini-2.5-flash",
  });

Create the chain:

const summaryChain =
  summaryPrompt
    .pipe(geminiModel)
    .pipe(parser);

Then:

const mapper =
  RunnableParallel.from({
    summary: summaryChain,
  });

const assign =
  new RunnableAssign({
    mapper,
  });

Invoke:

const result =
  await assign.invoke(article);

console.log(result);

The resulting object has the same shape.

The model provider changes, but the Runnable architecture doesn't.


OpenAI + Gemini Together

We can even use both models in the same assignment.

For example:

Article
   │
   ├──→ OpenAI → Summary
   │
   └──→ Gemini → Keywords

Create two chains:

const summaryChain =
  summaryPrompt
    .pipe(openAIModel)
    .pipe(parser);

const keywordChain =
  keywordPrompt
    .pipe(geminiModel)
    .pipe(parser);

Create the mapper:

const mapper =
  RunnableParallel.from({
    summary: summaryChain,
    keywords: keywordChain,
  });

Create the assignment:

const assign =
  new RunnableAssign({
    mapper,
  });

Invoke:

const result =
  await assign.invoke(article);

console.log(result);

Output:

{
  title: "...",
  content: "...",
  summary: "...",
  keywords: "..."
}

This is a good example of how LangChain keeps workflows provider-independent.


RunnableAssign vs RunnablePassthrough.assign()

This is an important question.

In previous articles, we used:

RunnablePassthrough.assign()

Now we're learning:

new RunnableAssign(...)

They are closely related.

The current LangChain.js Runnable API includes an assign() method that returns a new Runnable for assigning fields to dictionary-like output. RunnableAssign is the explicit class that performs the underlying merge behavior.

You can think about it like this:

RunnablePassthrough.assign()
          ↓
Convenient API
          ↓
RunnableAssign
          ↓
Explicit Runnable

For most application code, the convenience method can be easier to read.

But understanding RunnableAssign is useful because it exposes the underlying Runnable abstraction directly.


RunnableAssign vs RunnableParallel

These two are also easy to confuse.

RunnableParallel

RunnableParallel runs multiple branches and returns their results.

Input
 │
 ├──→ Branch A
 │
 ├──→ Branch B
 │
 └──→ Branch C
 │
 ▼
{
  a: resultA,
  b: resultB,
  c: resultC
}

The output contains the results of the branches.


RunnableAssign

RunnableAssign takes those generated fields and merges them with the original input.

Original Input
      +
Parallel Results
      ↓
Enriched Object

For example:

{
  name: "John"
}

plus:

{
  age: 25,
  role: "Developer"
}

becomes:

{
  name: "John",
  age: 25,
  role: "Developer"
}

The easiest way to remember:

RunnableParallel calculates. RunnableAssign merges.


RunnableAssign vs RunnableLambda

RunnableLambda executes custom JavaScript logic.

Input
 ↓
Function
 ↓
Transformed Output

RunnableAssign combines new values with the original object.

Original Object
      +
New Values
      ↓
Enriched Object

They solve different problems.


RunnableAssign with pipe()

Because RunnableAssign is a Runnable, it can participate in a larger chain.

For example:

Input
 ↓
Prompt
 ↓
Model
 ↓
Parser
 ↓
RunnableAssign
 ↓
Enriched Object

You could build:

const chain =
  firstChain.pipe(assign);

The output of firstChain becomes the input object for RunnableAssign.


RunnableAssign Inside RunnableSequence

You can also explicitly create a sequence:

import {
  RunnableSequence,
} from "@langchain/core/runnables";

const chain =
  RunnableSequence.from([
    prepareInput,
    prompt,
    model,
    parser,
    assign,
  ]);

This works because RunnableAssign is itself a Runnable.


Real-World Example: Resume Analyzer

Suppose your application already has:

{
  name: "John Doe",
  resumeText: "..."
}

You want AI to add:

  • Skills

  • Experience

  • Job Role

  • Summary

The workflow:

Resume
  │
  ├──→ Skills
  │
  ├──→ Experience
  │
  ├──→ Job Role
  │
  └──→ Summary
  │
  ▼
RunnableAssign
  │
  ▼
Enriched Resume

Final object:

{
  name: "John Doe",
  resumeText: "...",
  skills: ["React", "Node.js"],
  experience: 5,
  jobRole: "Frontend Developer",
  summary: "..."
}

This is a very natural use case for RunnableAssign.


Real-World Example: Product Analyzer

Suppose your backend already provides:

{
  id: 101,
  name: "Laptop",
  description: "..."
}

You want AI to add:

  • Category

  • Sentiment

  • Target Audience

  • Short Description

The result:

{
  id: 101,
  name: "Laptop",
  description: "...",
  category: "Electronics",
  sentiment: "Positive",
  targetAudience: "Developers",
  shortDescription: "..."
}

Again:

Existing Product
       ↓
RunnableAssign
       ↓
Enriched Product

Real-World Example: Blog Metadata Generator

This is especially useful for a blog platform.

Existing data:

{
  title: "Understanding Node.js Streams",
  content: "..."
}

AI generates:

{
  summary: "...",
  tags: [...],
  category: "Node.js",
  difficulty: "Intermediate"
}

Final object:

{
  title: "...",
  content: "...",
  summary: "...",
  tags: [...],
  category: "...",
  difficulty: "..."
}

Your application can then store the entire enriched object in a database.


Important: RunnableAssign Works With Objects

RunnableAssign expects dictionary-like input.

In JavaScript, this generally means an object such as:

{
  name: "John",
  age: 25
}

It isn't intended to enrich a primitive value like:

"John"

If your workflow starts with a string, first transform it into an object.

For example:

const prepareInput =
  RunnableLambda.from(
    (name) => ({
      name,
    })
  );

Then pass that object to RunnableAssign.


Error Handling

Since the mapper may contain models, APIs, or custom functions, errors are possible.

Use normal error handling around the workflow:

try {
  const result =
    await assign.invoke(input);

  console.log(result);
} catch (error) {
  console.error(
    "Assignment failed:",
    error
  );
}

If one of the mapped Runnables fails, the overall operation may fail.

For more advanced failure handling, LangChain provides withFallbacks() and retry functionality, which we'll cover later.


A Complete Example

Let's put everything together.

import "dotenv/config";

import {
  ChatOpenAI,
} from "@langchain/openai";

import {
  PromptTemplate,
} from "@langchain/core/prompts";

import {
  StringOutputParser,
} from "@langchain/core/output_parsers";

import {
  RunnableAssign,
  RunnableParallel,
} from "@langchain/core/runnables";

const model =
  new ChatOpenAI({
    model: "gpt-4.1-mini",
  });

const parser =
  new StringOutputParser();

const summaryPrompt =
  PromptTemplate.fromTemplate(`
Summarize this article in 2 sentences:

{content}
`);

const difficultyPrompt =
  PromptTemplate.fromTemplate(`
Classify this article as:

beginner
intermediate
advanced

Return only the classification.

Article:
{content}
`);

const summaryChain =
  summaryPrompt
    .pipe(model)
    .pipe(parser);

const difficultyChain =
  difficultyPrompt
    .pipe(model)
    .pipe(parser);

const mapper =
  RunnableParallel.from({
    summary: summaryChain,
    difficulty: difficultyChain,
  });

const assign =
  new RunnableAssign({
    mapper,
  });

const result =
  await assign.invoke({
    title:
      "Understanding Node.js Streams",

    content:
      "Node.js streams allow applications to process data efficiently without loading everything into memory at once.",
  });

console.log(result);

The final result will have the structure:

{
  title: "Understanding Node.js Streams",

  content: "...",

  summary: "...",

  difficulty: "beginner"
}

The exact AI-generated values will depend on the model response.


The Complete Mental Model

At this point, we have several Runnable concepts.

RunnableSequence

Use when steps depend on each other.

A
↓
B
↓
C

RunnableParallel

Use when independent tasks can run concurrently.

    ┌→ A
Input
    ├→ B
    └→ C

RunnableLambda

Use when you need custom JavaScript logic.

Input
 ↓
Function
 ↓
Output

RunnablePassthrough

Use when you need to preserve the original input.

Input
 ↓
Same Input

RunnableAssign

Use when you need to enrich an existing object with new fields.

Original Object
      +
New Fields
      ↓
Enriched Object

This gives us a very useful mental model for building LangChain workflows.


Best Practices

1. Use RunnableAssign for data enrichment

If you already have an object and want to add calculated or AI-generated fields, RunnableAssign is a natural fit.


2. Keep mapper branches focused

Each branch should ideally calculate one field.

RunnableParallel.from({
  summary: summaryChain,
  keywords: keywordChain,
  category: categoryChain,
});

This is easier to understand than one huge branch.


3. Use meaningful field names

Prefer:

{
  summary: summaryChain,
  keywords: keywordChain,
}

instead of:

{
  a: summaryChain,
  b: keywordChain,
}

4. Keep the original object useful

Don't preserve dozens of unnecessary fields.

Pass only the information your workflow actually needs.


5. Watch for key collisions

Suppose your input already contains:

{
  summary: "Existing summary"
}

and your assignment also produces:

{
  summary: "New summary"
}

The new assigned value can replace the existing value for that key.

Be deliberate about field names and overwrites.


Common Beginner Mistakes

Mistake 1: Confusing RunnableAssign with RunnableParallel

RunnableParallel produces multiple branch results.

RunnableAssign merges those results with the original input.


Mistake 2: Passing a string directly

RunnableAssign is designed for object/dictionary-like inputs.

If you have:

"Node.js"

first transform it into:

{
  topic: "Node.js"
}

Mistake 3: Returning nested objects unintentionally

If your mapper is:

RunnableParallel.from({
  summary: RunnableLambda.from(
    () => ({
      summary: "..."
    })
  )
})

your result can become:

{
  summary: {
    summary: "..."
  }
}

If you want:

{
  summary: "..."
}

return the value directly:

RunnableParallel.from({
  summary: RunnableLambda.from(
    () => "..."
  )
})

Mistake 4: Using RunnableAssign when you don't need the original data

If you only need the outputs of independent branches, RunnableParallel may be enough.

Use RunnableAssign when preserving and enriching the original object is part of the workflow.


What's Next?

We've now learned how to:

  • Run steps sequentially with RunnableSequence

  • Run independent tasks concurrently with RunnableParallel

  • Add custom JavaScript logic with RunnableLambda

  • Preserve inputs with RunnablePassthrough

  • Enrich existing objects with RunnableAssign

But our workflows are still mostly linear or parallel.

Real applications often need conditional routing.

For example:

User Input
     ↓
Check Input
     ↓
┌───────────────┐
│ Is it about   │
│ JavaScript?   │
└───────────────┘
     │
 ┌───┴────┐
 Yes      No
  ↓        ↓
JS Chain  General Chain

We don't want every input to go through the same workflow.

We want to choose a workflow based on the input.

That's where RunnableBranch comes in.

In the next article, we'll learn:

Mastering RunnableBranch in LangChain.js: Build Conditional AI Workflows (OpenAI + Gemini)


Final Thoughts

RunnableAssign is a useful component when your application needs to enrich existing data.

The core idea is simple:

Existing Object
       ↓
Calculate New Fields
       ↓
Merge
       ↓
Enriched Object

For example:

{
  title: "Node.js Streams",
  content: "...",
  summary: "...",
  keywords: [...],
  difficulty: "intermediate"
}

The original data remains available, while new information is added.

The most important distinction to remember is:

RunnableParallel
        ↓
Generate multiple results

while:

RunnableAssign
        ↓
Merge new results with original input

And because RunnableAssign is itself a Runnable, it can be combined with everything we've learned so far:

RunnableSequence
       ↓
RunnableParallel
       ↓
RunnableAssign
       ↓
RunnableLambda

This composability is what makes the Runnable architecture so powerful.

Once you become comfortable with these building blocks, you'll be able to construct much more sophisticated workflows for RAG systems, document processing, AI content generation, and production AI applications.

Happy Coding! 🚀