## 1. Project Overview & Quickstart (langchain-ai/langchainjs)

## File: README.md

[](https://opensource.org/licenses/MIT) [](https://x.com/langchain_js)

LangChain is a framework for building LLM-powered applications. It helps you chain together interoperable components and third-party integrations to simplify AI application development — all while future-proofing decisions as the underlying technology evolves.

> [!TIP]
> Just getting started? Check out **[Deep Agents](http://docs.langchain.com/oss/javascript/deepagents/)** — a higher-level package built on LangChain for agents that have built-in capabilites for common usage patterns such as planning, subagents, file system usage, and more.

**Documentation**: To learn more about LangChain, check out [the docs](https://docs.langchain.com/oss/javascript/langchain/overview).

If you're looking for more advanced customization or agent orchestration, check out [LangGraph.js](https://docs.langchain.com/oss/javascript/langgraph/overview), our framework for building agents and controllable workflows.

For an equivalent Python library, check out [LangChain](https://github.com/langchain-ai/langchain).

To help you ship LangChain apps to production faster, check out [LangSmith](https://smith.langchain.com), a unified developer platform for building, testing, and monitoring LLM applications.

## ⚡️ Quick Install

You can use npm, pnpm, or yarn to install LangChain.js

`npm install -S langchain` or `pnpm install langchain` or `yarn add langchain`

## 🚀 Why use LangChain?

LangChain helps developers build applications powered by LLMs through a standard interface for agents, models, embeddings, vector stores, and more.

Use LangChain for:

- **Real-time data augmentation**. Easily connect LLMs to diverse data sources and external/internal systems, drawing from LangChain’s vast library of integrations with model providers, tools, vector stores, retrievers, and more.
- **Model interoperability**. Swap models in and out as your engineering team experiments to find the best choice for your application’s needs. As the industry frontier evolves, adapt quickly — LangChain’s abstractions keep you moving without losing momentum.
- **Rapid prototyping**. Quickly build and iterate on LLM applications with LangChain's modular, component-based architecture. Test different approaches and workflows without rebuilding from scratch, accelerating your development cycle.
- **Production-ready features**. Deploy reliable applications with built-in support for monitoring, evaluation, and debugging through integrations like LangSmith. Scale with confidence using battle-tested patterns and best practices.
- **Vibrant community and ecosystem**. Leverage a rich ecosystem of integrations, templates, and community-contributed components. Benefit from continuous improvements and stay up-to-date with the latest AI developments through an active open-source community.
- **Flexible abstraction layers**. Work at the level of abstraction that suits your needs - from high-level chains for quick starts to low-level components for fine-grained control. LangChain grows with your application's complexity.

## 📦 LangChain's ecosystem

- [Deep Agents (JS)](https://docs.langchain.com/oss/javascript/deepagents/overview) - Build agents that can plan, use subagents, and leverage file systems for complex tasks. A higher-level package built on top of LangChain.
- [LangSmith](https://www.langchain.com/langsmith) - Unified developer platform for building, testing, and monitoring LLM applications. With LangSmith, you can debug poor-performing LLM app runs, evaluate agent trajectories, gain visibility in production, and deploy agents with confidence.
- [LangSmith Deployment](https://docs.langchain.com/langsmith/deployments) — Deploy and scale agents with a purpose-built platform for long-running, stateful workflows
- [LangGraph](https://docs.langchain.com/oss/javascript/langgraph/overview) - Build agents that can reliably handle complex tasks with LangGraph, our low-level agent orchestration framework. LangGraph offers customizable architecture, long-term memory, and human-in-the-loop workflows — and is trusted in production by companies like LinkedIn, Uber, Klarna, and GitLab.
- [Integrations](https://docs.langchain.com/oss/javascript/integrations/providers/overview) — Chat & embedding models, tools & toolkits, and more

## 🌐 Supported Environments

LangChain.js is written in TypeScript and can be used in:

- Node.js (ESM and CommonJS) - 20.x, 22.x, 24.x
- Cloudflare Workers
- Vercel / Next.js (Browser, Serverless and Edge functions)
- Supabase Edge Functions
- Browser
- Deno
- Bun

## 📖 Additional Resources

- [Getting started](https://docs.langchain.com/oss/javascript/langchain/overview): Installation, setting up the environment, simple examples
- [Learn](https://docs.langchain.com/oss/javascript/learn): Learn about the core concepts of LangChain.
- [LangChain Forum](https://forum.langchain.com): Connect with the community and share all of your technical questions, ideas, and feedback.
- [Chat LangChain](https://chat.langchain.com): Ask questions & chat with our documentation.

## 💁 Contributing

As an open-source project in a rapidly developing field, we are extremely open to contributions, whether it be in the form of a new feature, improved infrastructure, or better documentation.

For detailed information on how to contribute, see [`CONTRIBUTING.md`](https://github.com/langchain-ai/langchainjs/blob/main/CONTRIBUTING.md).

Please report any security issues or concerns following our [security guidelines](https://github.com/langchain-ai/.github/blob/main/SECURITY.md).

---

## File: docs/core_docs/README.md

These docs have moved! See https://docs.langchain.com/oss/javascript/ ([Repo](https://github.com/langchain-ai/docs))

---

## File: environment_tests/test-exports-cf/README.md

# test-exports-cf

This package was generated with `wrangler init` with the purpose of testing compatibility with Cloudlfare Workers.

---

## File: environment_tests/test-exports-vercel/README.md

This is a [Next.js](https://nextjs.org/) project bootstrapped with [`create-next-app`](https://github.com/vercel/next.js/tree/canary/packages/create-next-app).

## Getting Started

First, run the development server:

```bash
npm run dev
# or
yarn dev
# or
pnpm dev
```

Open [http://localhost:3000](http://localhost:3000) with your browser to see the result.

You can start editing the page by modifying `pages/index.tsx`. The page auto-updates as you edit the file.

[API routes](https://nextjs.org/docs/api-routes/introduction) can be accessed on [http://localhost:3000/api/hello](http://localhost:3000/api/hello). This endpoint can be edited in `pages/api/hello.ts`.

The `pages/api` directory is mapped to `/api/*`. Files in this directory are treated as [API routes](https://nextjs.org/docs/api-routes/introduction) instead of React pages.

This project uses [`next/font`](https://nextjs.org/docs/basic-features/font-optimization) to automatically optimize and load Inter, a custom Google Font.

## Learn More

To learn more about Next.js, take a look at the following resources:

- [Next.js Documentation](https://nextjs.org/docs) - learn about Next.js features and API.
- [Learn Next.js](https://nextjs.org/learn) - an interactive Next.js tutorial.

You can check out [the Next.js GitHub repository](https://github.com/vercel/next.js/) - your feedback and contributions are welcome!

## Deploy on Vercel

The easiest way to deploy your Next.js app is to use the [Vercel Platform](https://vercel.com/new?utm_medium=default-template&filter=next.js&utm_source=create-next-app&utm_campaign=create-next-app-readme) from the creators of Next.js.

Check out our [Next.js deployment documentation](https://nextjs.org/docs/deployment) for more details.

---

## File: environment_tests/test-zod-compat/README.md

# Zod Compatibility Tests

Regression tests for the zod version mismatch OOM bug (TS2589).

These tests verify that `@langchain/core` and `langchain` exported types
work correctly when consumers install different zod versions than what
the packages were built with.

## Test Scenarios

| Test           | Consumer zod                                                 | What it tests                                                |
| -------------- | ------------------------------------------------------------ | ------------------------------------------------------------ |
| `zod-v3`       | `~3.25.76`                                                   | Core types + agent APIs with zod v3                          |
| `zod-v4`       | `^4`                                                         | Core types + agent APIs with zod v4                          |
| `zod-mismatch` | `~3.25.76` (top-level) + `4.3.6` (nested in @langchain/core) | OOM regression — two different zod copies in the module tree |

## What's tested

Each test simulates a real consumer app using `@langchain/core` and `langchain`:

- `tool()` with simple, nested, enum, and deeply-nested zod schemas
- `StructuredOutputParser.fromZodSchema()`
- `createMiddleware()` with `stateSchema` and `beforeAgent`/`beforeModel` hooks
- `createAgent()` — basic, with middleware, with `responseFormat`, with `stateSchema`, kitchen sink
- `toolStrategy()` and `providerStrategy()` with zod schemas

No internal type utilities are imported — only public consumer-facing APIs.
On `main` (before the fix), `zod-mismatch` will OOM. On this branch it passes.

## Running

```bash
# From monorepo root:
bash environment_tests/test-zod-compat/run.sh
```

The script:

1. Builds `langchain` (which also builds `@langchain/core`)
2. Packs both as tarballs
3. For each test: creates an isolated temp directory, installs both tarballs + zod + typescript
4. Runs `tsc --noEmit` with a 120s timeout and 512MB heap limit
5. Reports pass/fail

## How the mismatch test works

The `zod-v3` and `zod-v4` tests are straightforward: install one version
of zod at the top level and type-check against it.

The `zod-mismatch` test is different. After the normal npm install, the
run script forces a **different** zod version into a nested `node_modules`
inside `@langchain/core`:

```
node_modules/
  zod/                          <-- 3.25.76 (consumer's top-level copy)
  @langchain/core/
    node_modules/
      zod/                      <-- 4.3.6 (different copy, nested)
```

This means TypeScript resolves **two distinct copies** of zod's `.d.ts`
files. When `@langchain/core`'s internal `.d.ts` files `import` from `zod`,
TypeScript follows the Node module resolution and finds the nested v4 copy.
When the consumer's code `import`s from `zod`, it finds the top-level v3 copy.

If `@langchain/core`'s **exported** types referenced real zod types
(`z3.ZodType`, `z4.$ZodType`), TypeScript would need to check whether the
consumer's v3 zod type is assignable to core's v4 zod type (or vice versa).
Since the two copies are nominally different, TypeScript falls back to a full
structural comparison of ~3,400+ lines of mutually-recursive generics — OOM.

With the structural duck-type fix, `@langchain/core`'s exported `.d.ts`
files don't `import` from `zod` at all. The exported types are lightweight
interfaces (`ZodV3Like`, `ZodV4Like`, etc.) defined inline, so there is
nothing for TypeScript to structurally compare across the two copies.

---

## File: environment_tests/README.md

# Environment Tests

This directory contains tests that verify LangChain packages work correctly in different JavaScript/TypeScript environments.

## Overview

The environment tests create isolated Docker containers that mimic real user environments, ensuring our packages work correctly with:

- Different module systems (ESM, CJS)
- Different bundlers (esbuild, Vite, Webpack via Next.js)
- Different runtimes (Node.js, Bun, Cloudflare Workers)
- TypeScript compilation

## Architecture

### Test Runner (`scripts/test-runner.ts`)

The TypeScript test runner:

1. Creates a sandbox environment at `/app` in the Docker container
2. Copies the test package files (excluding build artifacts)
3. Sets up workspace packages by:
   - Copying available local packages to `/app/libs/`
   - Replacing `workspace:*` dependencies with published versions for unavailable packages
4. Runs `pnpm install --prod` to install dependencies
5. Executes the build and test commands

### Docker Setup

Each test environment runs in its own Docker container with:

- The test package mounted at `/package`
- Workspace packages mounted at their respective paths
- The test runner script mounted at `/scripts`
- A clean `/app` directory as the test sandbox

### Test Environments

- **test-exports-esm**: Tests ESM imports and exports
- **test-exports-cjs**: Tests CommonJS require/exports
- **test-exports-esbuild**: Tests bundling with esbuild
- **test-exports-tsc**: Tests TypeScript compilation
- **test-exports-cf**: Tests Cloudflare Workers compatibility
- **test-exports-vercel**: Tests Next.js/Vercel compatibility
- **test-exports-vite**: Tests Vite bundling
- **test-exports-bun**: Tests Bun runtime compatibility

## Running Tests

```bash
docker compose -f environment_tests/docker-compose.yml run <environment>
# e.g. for test-exports-esbuild
docker compose -f environment_tests/docker-compose.yml run test-exports-esbuild
```

## Adding New Tests

1. Create a new directory `test-exports-{name}/`
2. Add a `package.json` with:
   - Dependencies using `workspace:*` for local packages
   - A `build` script (if needed)
   - A `test` script that runs your tests
3. Add test files in `src/`
4. Add the service to `docker-compose.yml`:
   ```yaml
   test-exports-{name}:
     image: node:20
     environment:
       PUPPETEER_SKIP_DOWNLOAD: "true"
       PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD: "true"
     working_dir: /app
     volumes:
       - ../pnpm-workspace.yaml:/pnpm-workspace.yaml
       - ../turbo.json:/turbo.json
       - ../environment_tests/test-exports-{name}:/package
       - ../environment_tests/scripts:/scripts
       - ../langchain:/langchain
       - ../langchain-core:/langchain-core
       # ... other packages
     command: bash /scripts/docker-entrypoint.sh
   ```

## How It Works

1. Docker mounts the test package and workspace packages into the container
2. The entrypoint script installs `tsx` (or uses Bun directly) and runs the test runner
3. The test runner:
   - Creates a clean sandbox environment
   - Copies and prepares packages with proper dependency resolution
   - Runs the test package's build and test scripts
4. Tests verify that imports, exports, and functionality work as expected

This approach ensures we test against real package installations, not source code, providing confidence that our published packages work correctly in user environments.

---

## File: examples/src/README.md

# langchain-examples

This folder contains examples of how to use LangChain.

## Run an example

What you'll usually want to do.

First, build langchain. From the repository root, run:

```sh
pnpm install
pnpm build
```

Most examples require API keys. Run `cp .env.example .env`, then edit `.env` with your API keys.

Then from the `examples/` directory, run:

`pnpm run start `

eg.

`pnpm run start ./src/prompts/few_shot.ts`

## Run an example with the transpiled JS

You shouldn't need to do this, but if you want to run an example with the transpiled JS, you can do so with:

`pnpm run start:dist `

eg.

`pnpm run start:dist ./dist/prompts/few_shot.js`

---

## File: internal/test-helpers/README.md

# Test Helpers

This package exports a number of utilities that are helpful in testing.

## `env`

This module provides utilities for managing environment variables (`process.env`) within your tests, particularly for Jest. It ensures that environment variable changes are isolated to individual tests and automatically cleaned up afterward.

### Usage

Import the `env` helper from `@langchain/test-helpers/env`.

```typescript
import { env } from "@langchain/test-helpers/env";
```

#### `env.useVariables(variables, options)`

This is the primary function for setting multiple environment variables for your tests. You call it at the top level of your test file, and it uses `beforeEach` and `afterEach` hooks to manage the environment.

**Arguments:**

- `variables`: An object where keys are environment variable names and values are what you want to set them to.
  - `string`: Sets the variable to that string value.
  - `undefined`: Deletes the environment variable.
  - `env.passthrough`: A special symbol that tells the helper to keep the original value of the environment variable, if it exists.
- `options`: An optional configuration object.
  - `replace` (boolean, default: `false`): If `true`, all existing environment variables on `process.env` will be cleared before applying the ones you've specified. If `false`, your variables will be merged with the existing environment.

**Example: Setting specific environment variables**

```ts
// Set specific env vars while preserving others
env.useVariables({
  API_KEY: "test-key",
  DEBUG: "true",
});
```

**Example: Replacing the environment**

This is useful for creating isolated test environments. You can use `env.passthrough` to preserve specific variables from the original environment.

```ts
// Replace all env vars with just these
env.useVariables(
  {
    API_KEY: "test-key",
    // Preserve the existing value of PRESERVE_THIS
    PRESERVE_THIS: env.passthrough,
  },
  { replace: true }
);
```

#### `env.useVariable(key, value, options)`

A convenience wrapper around `useVariables` for when you only need to set a single environment variable.

**Example:**

```ts
// Set a single env var while preserving others
env.useVariable("API_KEY", "test-key");

// Replace all env vars with just this one
env.useVariable("API_KEY", "test-key", { replace: true });
```

#### `env.applyEnv(envObject)`

This is a lower-level function used internally by the helpers, but it's exported for direct use. It takes an object and applies its key-value pairs to `process.env`. If a value is `undefined`, the corresponding key is deleted from `process.env`. This function applies changes immediately and does **not** handle automatic cleanup.

```ts
env.applyEnv({
  KEY_A: "VALUE_A",
  KEY_B: undefined, // This will delete process.env.KEY_B
});
```

---

## File: internal/standard-tests/README.md

# LangChain.js Standard Tests

This package contains the base standard tests for LangChain.js. It includes unit, and integration test classes.
This package is not intended to be used outside of the LangChain.js project, and thus it is not published to npm.

At the moment, we only have support for standard tests for chat models.

## Usage

Each LangChain.js integration should contain both unit and integration standard tests.
The package should have `@langchain/standard-tests` as a dev workspace dependency like so:

`package.json`:

```json
{
  "devDependencies": {
    "@langchain/standard-tests": "workspace:*"
  }
}
```

To use the standard tests, you could create two files:

- `src/tests/chat_models.standard.test.ts` - chat model unit tests
- `src/tests/chat_models.standard.int.test.ts` - chat model integration tests

Your unit test file should look like this:

`chat_models.standard.test.ts`:

```typescript
/* oxlint-disable no-process-env */
import { test, expect } from "@jest/globals";
import { ChatModelUnitTests } from "@langchain/standard-tests";
import { AIMessageChunk } from "@langchain/core/messages";
import { MyChatModel, MyChatModelCallOptions } from "../chat_models.js";

class MyChatModelStandardUnitTests extends ChatModelUnitTests<
  MyChatModelCallOptions,
  AIMessageChunk
> {
  constructor() {
    super({
      Cls: MyChatModel,
      chatModelHasToolCalling: true, // Set to true if the model has tool calling support
      chatModelHasStructuredOutput: true, // Set to true if the model has withStructuredOutput support
      constructorArgs: {}, // Any additional constructor args
    });
    // This must be set so method like `.bindTools` or `.withStructuredOutput`
    // which we call after instantiating the model will work.
    // (constructor will throw if API key is not set)
    process.env.CHAT_MODEL_API_KEY = "test";
  }

  testChatModelInitApiKey() {
    // Unset the API key env var here so this test can properly check
    // the API key class arg.
    process.env.CHAT_MODEL_API_KEY = "";
    super.testChatModelInitApiKey();
    // Re-set the API key env var here so other tests can run properly.
    process.env.CHAT_MODEL_API_KEY = "test";
  }
}

const testClass = new MyChatModelStandardUnitTests();

test("MyChatModelStandardUnitTests", () => {
  const testResults = testClass.runTests();
  expect(testResults).toBe(true);
});
```

To use the standard tests, extend the `ChatModelUnitTests` class, passing in your chat model's call options and message chunk types. Super the constructor with your chat model class, any additional constructor args, and set the `chatModelHasToolCalling` and `chatModelHasStructuredOutput` flags if supported.

Set the model env var in the constructor directly to `process.env` for the tests to run properly. You can optionally override test methods to replace or add code before/after the test runs.

Run all tests by calling `.runTests()`, which returns `true` if all tests pass, `false` otherwise. Tests are called in `try`/`catch` blocks so that failing tests are caught and marked as failed, but the rest still run.

For integration tests, extend `ChatModelIntegrationTests` instead. Integration tests have an optional arg for all methods (except `withStructuredOutput`) to pass in "invoke" time call options. For example, in the OpenAI integration test:

```typescript
async testUsageMetadataStreaming() {
  // ChatOpenAI does not support streaming tokens by
  // default, so we must pass in a call option to
  // enable streaming tokens.
  const callOptions: ChatOpenAI["ParsedCallOptions"] = {
    stream_options: {
      include_usage: true,
    },
  };
  await super.testUsageMetadataStreaming(callOptions);
}
```

This overrides the base `testUsageMetadataStreaming` to pass a `callOptions` arg enabling streaming tokens.

---

## File: internal/model-profiles/README.md

# Model Profiles Generator

A CLI tool for automatically generating TypeScript model profile files from the [models.dev](https://models.dev) API. This tool fetches model capabilities and constraints, applies provider-level and model-specific overrides, and generates type-safe TypeScript files using the TypeScript AST API.

## Overview

The model-profiles generator simplifies the process of maintaining model capability profiles across LangChain provider packages.

### Key Features

- 🔄 **Automatic Data Fetching**: Fetches latest model data from the models.dev API
- 🎯 **Provider-Level Overrides**: Apply overrides to all models for a provider
- 🔧 **Model-Specific Overrides**: Fine-tune individual model profiles
- 📝 **TypeScript AST Generation**: Uses TypeScript compiler API for type-safe code generation
- 🎨 **Prettier Integration**: Automatically formats generated code using your project's Prettier config
- 📦 **Monorepo Friendly**: Works seamlessly with pnpm workspaces and `--filter` commands
- ✅ **Type Safety**: Generates code that matches the `ModelProfile` interface from `@langchain/core`

## Architecture

The model-profiles generator consists of:

```text
internal/model-profiles/
├── src/
│   ├── cli.ts              # Command-line interface
│   ├── config.ts            # TOML config parsing and override logic
│   ├── generator.ts         # TypeScript code generation and API integration
│   ├── api-schema.ts        # TypeScript types for models.dev API
│   └── tests/               # Test suite
│       ├── config.test.ts
│       └── generator.test.ts
├── package.json             # Tool dependencies
├── vitest.config.ts         # Test configuration
└── README.md                # This documentation
```

## Usage

### Basic Usage

Create a TOML configuration file (e.g., `profiles.toml`) in a provider package:

```toml
provider = "openai"
output = "src/chat_models/profiles.ts"
```

Then run the generator:

```bash
# From the model-profiles package
pnpm --filter @langchain/model-profiles make --config profiles.toml

# Or if running from within a provider package
pnpm --filter @langchain/model-profiles make --config profiles.toml
```

### Configuration File Format

The TOML configuration file supports the following structure:

```toml
# Required: Provider ID from models.dev
provider = "openai"

# Required: Output path for generated TypeScript file (relative to config file)
output = "src/chat_models/profiles.ts"

# Optional: Provider-level overrides (applied to all models)
[overrides]
maxInputTokens = 100000
toolCalling = true
structuredOutput = true
imageUrlInputs = true

# Optional: Model-specific overrides (override provider-level settings)
[overrides."gpt-4"]
maxOutputTokens = 8192

[overrides."gpt-3.5-turbo"]
maxInputTokens = 16385
imageUrlInputs = false
```

## 2. Official Technical Reference & Guides (langchain-ai/docs)

# LangChain Docs

🦜 **Welcome!** This repository contains the documentation build pipeline for LangChain projects.

* 🏠 [`docs.langchain.com`](https://docs.langchain.com) is our docs home, centralizing LangChain, LangGraph, LangSmith, and LangChain Labs (Deep Agents, Open SWE, Open Agent Platform). This site is hosted on [Mintlify](https://mintlify.com).
* 🛠️ [`reference.langchain.com`](https://reference.langchain.com/python/) hosts generated API reference for LangChain, LangGraph, LangSmith, and integration packages. That site is **not** built from this repository (no reference build scripts or output live here).
  * [`Python reference`](https://reference.langchain.com/python/)
  * [`JavaScript/TypeScript reference`](https://reference.langchain.com/javascript/)
* 💬 [`chat.langchain.com`](https://chat.langchain.com) is an AI-powered assistant that can answer questions about LangChain documentation.

---

**Table of contents:**

- [LangChain Docs](#langchain-docs)
  - [Contribute](#contribute)
  - [Reference](#reference)
    - [Repository structure](#repository-structure)
      - [`docs.langchain.com`](#docslangchaincom)
      - [`reference.langchain.com`](#referencelangchaincom)
    - [File formats](#file-formats)
    - [Available commands](#available-commands)
  - [Linting](#linting)
    - [Codespell](#codespell)
  - [Troubleshooting](#troubleshooting)
    - [`docs dev` not working / running](#docs-dev-not-working--running)
    - [Mintlify `.venv` parsing error](#mintlify-venv-parsing-error)
    - [Warning: page doesn't exist](#warning-page-doesnt-exist)
    - [General Mintlify errors](#general-mintlify-errors)

---

## Contribute

To run a local preview of the documentation:

```bash
git clone https://github.com/langchain-ai/docs.git
```

```bash
cd docs
```

```bash
make install
```

```bash
make dev
```

For more information on how to contribute to LangChain documentation, follow the steps outlined in the [contributing guide](https://docs.langchain.com/oss/python/contributing/overview). The contributing guide also explains our documentation types and their writing and quality standards.

For detailed information about setting up your development environment and contributing to documentation, see the [documentation contributing guide](https://docs.langchain.com/oss/python/contributing/documentation).

To report issues with **reference.langchain.com** (missing pages, broken links, or generated API content), [open a reference documentation issue](https://github.com/langchain-ai/docs/issues/new?template=04-reference-docs.yml) on this repo so maintainers can route it.

## Reference

### Repository structure

```text
# --- docs.langchain.com ----------------------------------------------
build/                    # Built docs (DO NOT EDIT)
packages.yml              # Package metadata (indexes, tables, downloads; not the API reference build)
pipeline/                 # Build pipeline source code
scripts/                  # Helper scripts
src/                      # Source documentation files (< EDIT CONTENT HERE)
    langsmith/            # LangSmith docs
    oss/                  # LangChain, LangGraph, Deep Agents, and integrations docs
    docs.json             # Mintlify site configuration and navigation
tests/                    # Test files for the pipeline
Makefile                  # Build targets
pyproject.toml            # Dependencies
```

#### `docs.langchain.com`

The Mintlify docs pipeline is structured with `.mdx` source files in `/src` and build artifacts in `/build`. Mintlify deploys from the `/build` folder, which is generated by preprocessing logic.

> [!IMPORTANT]
> Never edit `/build` directly.

The `/src/docs.json` file is used to configure the Mintlify site navigation and settings. Refer to the [Mintlify documentation](https://www.mintlify.com/docs/organize/navigation) for detailed syntax and component usage.

Documentation changes follow a PR workflow where all tests must pass before merging. See the [contributing guidelines](https://docs.langchain.com/oss/python/contributing/documentation) for more details.

#### `reference.langchain.com`

API reference is generated and deployed outside this repo. Browse [Python](https://reference.langchain.com/python/) and [JavaScript/TypeScript](https://reference.langchain.com/javascript/) reference there. If something is wrong with that site, use the [reference docs issue template](https://github.com/langchain-ai/docs/issues/new?template=04-reference-docs.yml).

### File formats

* **Markdown files** (`.md`, `.mdx`) - Standard documentation content
* **Snippets** (`src/snippets/`) - Reusable MDX content that can be imported into multiple pages. **Important:** Snippets undergo special link preprocessing. When writing links in snippets, be careful about path segments.
* **Jupyter notebooks** (`.ipynb`) - Converted to markdown during build, though **these are not recommended for new content!** Your PR will likely be rejected if you attempt to add a Jupyter notebook unless asked to by a maintainer.
* **Assets** - Images and other files are copied to the build directory

### Available commands

**Make commands:**

* `make dev` - Start development mode with file watching and live rebuild
* `make build` - Build documentation to `./build` directory
* `make broken-links` - Check for broken links in documentation
* `make broken-links-with-anchors` - Check for broken links + check links with anchors
* `make install` - Install all dependencies
* `make clean` - Remove build artifacts
* `make test` - Run the test suite
* `make lint` - Check code style and formatting
* `make format` - Auto-format code
* `make lint_md` - Lint markdown files
* `make lint_md_fix` - Lint and fix markdown files
* `make help` - Show all available commands

**`docs` CLI tool:**

The `docs` command (installed as `uv run docs`) provides additional functionality:

* **`docs migrate `** - Convert MkDocs markdown/notebook files to Mintlify format
  * `--dry-run` - Preview changes without writing files
  * `--output ` - Specify output location (default: in-place)
  * Supports `.md`, `.markdown`, `.ipynb` files

* **`docs migrate-docusaurus `** - Convert Docusaurus markdown/notebook files to Mintlify format
  * `--dry-run` - Preview changes without writing files
  * `--output ` - Specify output location (default: in-place)
  * Supports `.md`, `.markdown`, `.mdx`, `.ipynb` files
  * Converts Docusaurus-specific syntax (admonitions, tabs, imports, etc.)

* **`docs mv <old_path> <new_path>`** - Move files and update cross-references
  * `--dry-run` - Preview changes without moving files

These can be used directly using the `Makefile` or via the `docs` CLI tool:

* **`docs dev`** - Start development mode with file watching and hot reload
  * Automatically rebuilds changed files from `src/` to `build/`
  * Launches Mintlify dev server at <http://localhost:3000>
  * Provides automatic browser refresh when files change
  * `--skip-build` - Skip initial build and use existing build directory

* **`docs build`** - Build documentation files
  * `--watch` - Watch for file changes after building

## Linting

After running `make install`, you can use `make lint_prose` to ensure your writing meets our style guide rules.

### Codespell

`make lint` runs `uv run codespell src` to check source documentation for common spelling errors.

Codespell is configured in `pyproject.toml` under `[tool.codespell]`:

* Add custom accepted words to `src/.codespellignore`. This file is referenced by `ignore-words = "src/.codespellignore"`.
* Exclude generated files, vendor content, or other paths that should not be spell checked by adding glob patterns to the `skip` setting.
* Keep skip patterns scoped. Prefer adding accepted words to `src/.codespellignore` when the word is valid documentation content, and use `skip` when the file or directory should not be checked at all.

You can also follow these steps to enable `vale` with VS Code or Cursor:

1. Install the [Vale extension](https://marketplace.visualstudio.com/items?itemName=chrischinchilla.vale-vscode) (Vale by Chris Chinchilla)
2. Install Vale CLI: `brew install vale` (macOS) or see [Vale installation](https://vale.sh/docs/vale-cli/installation/) for other platforms
3. Navigate to the Vale extension settings:
   - Set `Vale CLI: Config` to the absolute path to `.vale.ini` (in the root of this repo)
   - Set `Vale CLI: Min Alert Level` to `suggestion` (many rules are coded as suggestions)

If you cannot use the VS Code UI to configure Vale, add these settings to your `settings.json`:

```json
    "vale.valeCLI.config": "/path/to/docs/.vale.ini",
    "vale.valeCLI.minAlertLevel": "suggestion"
```

**Note:** The extension requires Vale on your `PATH`. If annotations don't appear (e.g., when Cursor is launched from the Dock), launch Cursor from a terminal so it inherits your PATH, or ensure Homebrew is in your shell profile.

## Troubleshooting

### General Mintlify errors

In some cases, we use new features that are only available in the latest Mintlify CLI. If you encounter errors, ensure you have the latest version installed:

```bash
mint update

# or

npm install mint
```

### `docs dev` not working / running

Re-do the [steps to set up your dev environment](https://docs.langchain.com/oss/python/contributing/documentation#set-up-local-environment), ensuring you have activated the virtual environment and installed all dependencies.

> [!IMPORTANT]
> Most of the time, `mint update` solves any `docs dev` / `make dev` issues!

### Mintlify `.venv` parsing error

**Problem**: Running `mint broken-links` or other Mintlify commands from the project root causes parsing errors like:

```txt
Unable to parse .venv/lib/python3.13/site-packages/soupsieve-2.7.dist-info/licenses/LICENSE.md
- 3:48: Unexpected character '@' (U+0040) in name
```

**Root Cause**: Mintlify tries to parse all files in the directory, including Python virtual environment files that contain invalid MDX syntax.

**Solutions** (in order of preference):

1. **Use the safe Make commands** (recommended):

   ```bash
   make broken-links-with-anchors      # Builds docs first, then checks internal links
   ```

2. **Run Mintlify commands from the build directory**:

   ```bash
   cd build               # Change to build directory where final docs are
   mint broken-links      # Now safe to run
   ```

**Why this works**: The solution ensures Mintlify commands run from the `build/` directory where the final documentation is generated, which is the correct place to check for broken links. This avoids scanning the Python virtual environment in the project root.

**Prevention**: Always use the provided Make commands instead of running raw `mint` commands from the project root.

### Warning: page doesn't exist

If adding a new group, ensure the root `index.mdx` is included in the `pages` array like:

```json
{
  "group": "New group",
  "pages": ["new-group/index", "new-group/other-page"]
}
```

If the trailing `/index` (no extension included) is omitted, the Mintlify parser will raise a warning even though the site will still build.