{"owner":"langchain-ai","repo":"langchainjs","hasSkills":true,"hasMcp":false,"mcpConfig":null,"found":["AGENTS.md"],"files":{"AGENTS.md":"# AGENTS.md - AI Agent Guidelines for LangChain.js\n\nThis document provides guidance for AI coding agents working with the LangChain.js codebase.\n\n## Project Overview\n\nLangChain.js is a TypeScript framework for building LLM-powered applications. It provides standard interfaces for agents, models, embeddings, vector stores, and more, enabling developers to chain together interoperable components and third-party integrations.\n\n### Supported Environments\n\n- Node.js (ESM and CommonJS) - 20.x, 22.x, 24.x\n- Cloudflare Workers\n- Vercel / Next.js (Browser, Serverless and Edge functions)\n- Supabase Edge Functions\n- Browser\n- Deno\n- Bun\n\n## Repository Structure\n\nThis is a **monorepo** managed with [pnpm workspaces](https://pnpm.io/) (v10.14.0) and [Turborepo](https://turbo.build/).\n\n### Key Packages\n\n| Package                    | Path                                  | Description                                                      |\n| -------------------------- | ------------------------------------- | ---------------------------------------------------------------- |\n| `langchain`                | `libs/langchain/`                     | Main LangChain package with agents, prompts, and orchestration   |\n| `@langchain/core`          | `libs/langchain-core/`                | Core abstractions and interfaces (base classes, runnables, etc.) |\n| `@langchain/textsplitters` | `libs/langchain-textsplitters/`       | Text splitting utilities                                         |\n| `@langchain/openai`        | `libs/providers/langchain-openai/`    | OpenAI integration                                               |\n| `@langchain/anthropic`     | `libs/providers/langchain-anthropic/` | Anthropic integration                                            |\n| Other providers            | `libs/providers/langchain-*/`         | First-party provider integrations                                |\n\n### Internal Packages\n\n| Package                     | Path                             | Description                          |\n| --------------------------- | -------------------------------- | ------------------------------------ |\n| `@langchain/build`          | `internal/build/`                | Build utilities                      |\n| `@langchain/tsconfig`       | `internal/tsconfig/`             | Shared TypeScript configuration      |\n| `@langchain/standard-tests` | `libs/langchain-standard-tests/` | Standard test suite for integrations |\n\n## Development Setup\n\n### Prerequisites\n\n- **Node.js v24.x** (check with `node -v`)\n- **pnpm v10.14.0** (package manager)\n\n### Initial Setup\n\n```bash\n# Install dependencies from root\npnpm install\n\n# Build the core package first (required before other packages)\npnpm --filter @langchain/core build\n```\n\n## Common Commands\n\nAll commands can be run from the project root using `pnpm --filter <package>` to target specific workspaces.\n\n### Package Filters\n\n- `--filter langchain` - the main `langchain` package\n- `--filter @langchain/core` - the core package\n- `--filter @langchain/openai` - OpenAI integration (and similarly for other providers)\n\n### Building\n\n```bash\npnpm --filter langchain build\npnpm --filter @langchain/core build\n```\n\n### Linting\n\n```bash\npnpm lint\n```\n\n### Formatting\n\n```bash\npnpm format        # Fix formatting\npnpm format:check  # Check only\n```\n\n### Testing\n\n```bash\n# Unit tests\npnpm --filter langchain test\npnpm --filter @langchain/core test\n\n# Integration tests (requires API keys)\npnpm --filter langchain test:integration\n\n# Single test file\npnpm --filter <package> test:single <path-to-test>\n```\n\n## Coding Standards\n\n### TypeScript Configuration\n\nThe project uses a shared TypeScript configuration from `internal/tsconfig/base.json`:\n\n- Target: ES2022\n- Module: ESNext with bundler resolution\n- Strict mode enabled\n- Source maps and declaration maps enabled\n\n### Lint Rules\n\nLint rules are defined in `.oxlintrc.json`. Key rules to follow:\n\n1. **No `process.env`** - Except in test files (`node/no-process-env: error`)\n2. **No explicit `any`** - Use proper types (`typescript/no-explicit-any: error`)\n3. **Prefer template literals** - Over string concatenation (`prefer-template: error`)\n4. **File extensions required** - In imports (`import/extensions: error`)\n\n### Import Conventions\n\n```typescript\n// Always include .js extension for local imports (ESM)\nimport { Something } from \"./something.js\";\n\n// Use named exports, not default exports\nexport { MyClass, myFunction };\n```\n\n### Zod Schema Support\n\nThe codebase supports both Zod v3 and v4:\n\n```typescript\nimport { z } from \"zod/v3\";\nimport { z as z4 } from \"zod/v4\";\n```\n\n## File Naming Conventions\n\n### Source Files\n\n- Regular modules: `my_module.ts` (snake_case)\n- Index files: `index.ts`\n- Type definitions: `types.ts`\n\n### Test Files\n\n- **Unit tests**: `*.test.ts` - Tests that don't require external APIs\n- **Integration tests**: `*.int.test.ts` - Tests that call external APIs\n- **Type tests**: `*.test-d.ts` - TypeScript type checking tests\n- **Standard tests**: `*.standard.test.ts` / `*.standard.int.test.ts` - Standard test suite\n\nTests should be placed in a `tests/` folder alongside the module being tested.\n\n## Core Abstractions\n\n### Runnables\n\nThe `Runnable` interface (`@langchain/core/runnables`) is the foundation of LangChain. All major components extend `Runnable`:\n\n```typescript\nimport {\n  Runnable,\n  RunnableConfig,\n  RunnableLike,\n} from \"@langchain/core/runnables\";\n```\n\nKey methods:\n\n- `invoke(input, config?)` - Single invocation\n- `stream(input, config?)` - Streaming invocation\n- `batch(inputs, config?)` - Batch invocation\n\n### Messages\n\nMessages are in `@langchain/core/messages`:\n\n```typescript\nimport {\n  HumanMessage,\n  AIMessage,\n  SystemMessage,\n  ToolMessage,\n  BaseMessage,\n} from \"@langchain/core/messages\";\n```\n\n### Tools\n\nTools extend `StructuredTool` from `@langchain/core/tools`:\n\n```typescript\nimport { StructuredTool, DynamicTool, tool } from \"@langchain/core/tools\";\n```\n\n### Chat Models\n\nChat models extend `BaseChatModel` from `@langchain/core/language_models/chat_models`:\n\n```typescript\nimport {\n  BaseChatModel,\n  BaseChatModelParams,\n} from \"@langchain/core/language_models/chat_models\";\n```\n\n## Writing Tests\n\n### Unit Tests\n\n```typescript\nimport { test, expect, describe } from \"vitest\";\nimport { FakeChatModel } from \"@langchain/core/utils/testing\";\n\ntest(\"should do something\", async () => {\n  const model = new FakeChatModel({});\n  const result = await model.invoke([[\"human\", \"Hello!\"]]);\n  expect(result.content).toBe(\"Hello!\");\n});\n```\n\n### Integration Tests\n\nIntegration tests require actual API credentials:\n\n```typescript\nimport { describe, test, expect } from \"vitest\";\nimport { ChatOpenAI } from \"../index.js\";\nimport { HumanMessage } from \"@langchain/core/messages\";\n\ntest(\"Test ChatOpenAI Generate\", async () => {\n  const chat = new ChatOpenAI({\n    model: \"gpt-4o-mini\",\n    maxTokens: 10,\n  });\n  const message = new HumanMessage(\"Hello!\");\n  const result = await chat.invoke([message]);\n  expect(typeof result.content).toBe(\"string\");\n});\n```\n\n### Type Tests\n\nUse `expectTypeOf` from vitest for type assertions:\n\n```typescript\nimport { expectTypeOf } from \"vitest\";\n\nexpectTypeOf(someFunction).returns.toMatchTypeOf<ExpectedType>();\n```\n\n### Standard Tests\n\nFor provider integrations, extend the standard test classes:\n\n```typescript\nimport { ChatModelUnitTests } from \"@langchain/standard-tests\";\n\nclass MyChatModelStandardUnitTests extends ChatModelUnitTests<\n  MyChatModelCallOptions,\n  AIMessageChunk\n> {\n  constructor() {\n    super({\n      Cls: MyChatModel,\n      chatModelHasToolCalling: true,\n      chatModelHasStructuredOutput: true,\n      constructorArgs: {},\n    });\n  }\n}\n```\n\n## Creating New Integrations\n\n### Provider Package Structure\n\nNew provider packages should follow this structure:\n\n```txt\nlibs/providers/langchain-{provider}/\n├── package.json\n├── tsconfig.json\n├── tsdown.config.ts\n├── vitest.config.ts\n├── turbo.json\n├── README.md\n├── LICENSE\n└── src/\n    ├── index.ts\n    ├── chat_models/\n    │   ├── index.ts\n    │   └── tests/\n    │       ├── index.test.ts\n    │       ├── index.int.test.ts\n    │       ├── index.standard.test.ts\n    │       └── index.standard.int.test.ts\n    └── embeddings.ts (if applicable)\n```\n\n### Package.json Requirements\n\n```json\n{\n  \"name\": \"@langchain/provider-name\",\n  \"type\": \"module\",\n  \"engines\": { \"node\": \">=20\" },\n  \"peerDependencies\": {\n    \"@langchain/core\": \"^1.0.0\"\n  },\n  \"devDependencies\": {\n    \"@langchain/core\": \"workspace:^\",\n    \"@langchain/standard-tests\": \"workspace:*\",\n    \"@langchain/tsconfig\": \"workspace:*\"\n  }\n}\n```\n\n### Scaffolding\n\nUse the CLI tool to create new integration packages:\n\n```bash\nnpx create-langchain-integration\n```\n\n## Best Practices\n\n### 1. Use Existing Abstractions\n\nBefore creating new classes, check if `@langchain/core` already provides what you need:\n\n- `Runnable` and its variants\n- `StructuredTool` for tools\n- `BaseChatModel` for chat models\n- `Embeddings` for embedding models\n- `BaseRetriever` for retrievers\n- `VectorStore` for vector stores\n\n### 2. Support Streaming\n\nAll LLM-related components should support streaming when possible:\n\n```typescript\nasync *_streamResponseChunks(\n  messages: BaseMessage[],\n  options: this[\"ParsedCallOptions\"],\n  runManager?: CallbackManagerForLLMRun\n): AsyncGenerator<ChatGenerationChunk> {\n  // Yield chunks as they arrive\n}\n```\n\n### 3. Handle Callbacks Properly\n\nUse the callback manager for tracing and observability:\n\n```typescript\nawait runManager?.handleLLMNewToken(token);\n```\n\n### 4. Environment Variables\n\nAccess environment variables using the utility:\n\n```typescript\nimport { getEnvironmentVariable } from \"@langchain/core/utils/env\";\n\nconst apiKey = getEnvironmentVariable(\"MY_API_KEY\");\n```\n\n### 5. Error Handling\n\nUse typed errors with proper error codes:\n\n```typescript\nthrow new Error(\"Model authentication failed\", {\n  cause: { lc_error_code: \"MODEL_AUTHENTICATION\" },\n});\n```\n\n### 6. Third-Party Dependencies\n\n- Add them as regular `dependencies` in standalone provider packages\n- Always use caret (`^`) for version ranges\n- Ensure dependencies are MIT or permissively licensed\n\n## Pull Request Checklist\n\nBefore submitting a PR:\n\n1. [ ] Run `pnpm lint` and fix any issues\n2. [ ] Run `pnpm format` to format code\n3. [ ] Add/update unit tests (`*.test.ts`)\n4. [ ] Add/update integration tests if applicable (`*.int.test.ts`)\n5. [ ] Add/update type tests if changing public APIs (`*.test-d.ts`)\n6. [ ] Update documentation if changing public APIs\n7. [ ] Keep changes focused - one feature/fix per PR\n8. [ ] Ensure no circular dependencies (checked by `lint:dpdm`)\n\n## Debugging Tips\n\n### Running Specific Tests\n\n```bash\n# Run a single test file\npnpm --filter @langchain/core test src/messages/tests/utils.test.ts\n\n# Run tests matching a pattern\npnpm --filter @langchain/core test --grep \"should handle\"\n\n# Watch mode\npnpm --filter @langchain/core test:watch\n```\n\n### Building in Watch Mode\n\n```bash\npnpm watch\n```\n\n### Checking for Circular Dependencies\n\n```bash\npnpm --filter @langchain/core lint:dpdm\n```\n\n## Resources\n\n- [Documentation](https://docs.langchain.com/oss/javascript/langchain/overview)\n- [API Reference](https://api.js.langchain.com)\n- [GitHub Issues](https://github.com/langchain-ai/langchainjs/issues)\n- [LangChain Forum](https://forum.langchain.com)\n- [Contributing Guide](./CONTRIBUTING.md)\n- [Integration Guide](./.github/contributing/INTEGRATIONS.md)\n"}}