1# Global development guidelines for the LangChain monorepo23This document provides context to understand the LangChain Python project and assist with development.45## Project architecture and context67### Monorepo structure89This is a Python monorepo with multiple independently versioned packages that use `uv`.1011```txt12langchain/13├── libs/14│ ├── core/ # `langchain-core` primitives and base abstractions15│ ├── langchain/ # `langchain-classic` (legacy, no new features)16│ ├── langchain_v1/ # Actively maintained `langchain` package17│ ├── partners/ # Third-party integrations18│ │ ├── openai/ # OpenAI models and embeddings19│ │ ├── anthropic/ # Anthropic (Claude) integration20│ │ ├── ollama/ # Local model support21│ │ └── ... (other integrations maintained by the LangChain team)22│ ├── text-splitters/ # Document chunking utilities23│ ├── standard-tests/ # Shared test suite for integrations24│ ├── model-profiles/ # Model configuration profiles25├── .github/ # CI/CD workflows and templates26├── .vscode/ # VSCode IDE standard settings and recommended extensions27└── README.md # Information about LangChain28```2930- **Core layer** (`langchain-core`): Base abstractions, interfaces, and protocols. Users should not need to know about this layer directly.31- **Implementation layer** (`langchain`): Concrete implementations and high-level public utilities32- **Integration layer** (`partners/`): Third-party service integrations. Note that this monorepo is not exhaustive of all LangChain integrations; some are maintained in separate repos, such as `langchain-ai/langchain-google` and `langchain-ai/langchain-aws`. Usually these repos are cloned at the same level as this monorepo, so if needed, you can refer to their code directly by navigating to `../langchain-google/` from this monorepo.33- **Testing layer** (`standard-tests/`): Standardized integration tests for partner integrations3435### Development tools & commands3637- `uv` – Fast Python package installer and resolver (replaces pip/poetry)38- `make` – Task runner for common development commands. Feel free to look at the `Makefile` for available commands and usage patterns.39- `ruff` – Fast Python linter and formatter40- `mypy` – Static type checking41- `pytest` – Testing framework4243This monorepo uses `uv` for dependency management. Local development uses editable installs: `[tool.uv.sources]`4445Each package in `libs/` has its own `pyproject.toml` and `uv.lock`.4647Before running your tests, set up all packages by running:4849```bash50# For all groups51uv sync --all-groups5253# or, to install a specific group only:54uv sync --group test55```5657```bash58# Run unit tests (no network)59make test6061# Run specific test file62uv run --group test pytest tests/unit_tests/test_specific.py63```6465```bash66# Lint code67make lint6869# Format code70make format7172# Type checking73uv run --group lint mypy .74```7576#### Environment and dependency management7778Use `uv` for all environment and dependency operations in this monorepo. Do not invoke `pip`, `poetry`, or `conda` directly.7980- Let `uv` manage the interpreter and virtual environments — `uv sync` and `uv run` operate without manual `source .venv/bin/activate`. Do not create ad-hoc virtual environments outside the package directory.81- Each package targets its own supported Python range via its `pyproject.toml`; do not pin a global Python version. If you need an interpreter explicitly, defer to the package's `requires-python` rather than assuming system Python.82- Install dependencies explicitly through `uv sync` (optionally `--group <name>` / `--all-groups`); never let them install implicitly.83- Don't mix environments within a session, and don't add new dependencies unless strictly required — when you do, justify them (recent releases/commits, adoption).8485#### Key config files8687- pyproject.toml: Main workspace configuration with dependency groups88- uv.lock: Locked dependencies for reproducible builds89- Makefile: Development tasks9091#### PR and commit titles9293Follow Conventional Commits. See `.github/workflows/pr_lint.yml` for allowed types and scopes. All titles must include a scope with no exceptions — even for the main `langchain` package.9495- Start the text after `type(scope):` with a lowercase letter, unless the first word is a proper noun (e.g. `Azure`, `GitHub`, `OpenAI`) or a named entity (class, function, method, parameter, or variable name).96- Wrap named entities in backticks so they render as code. Proper nouns are left unadorned.97- Keep titles short and descriptive — save detail for the body.9899Examples:100101```txt102feat(langchain): add new chat completion feature103fix(core): resolve type hinting issue in vector store104chore(anthropic): update infrastructure dependencies105feat(langchain): `ls_agent_type` tag on `create_agent` calls106fix(openai): infer Azure chat profiles from model name107```108109#### Branch naming110111Branches should be prefixed `<github-username>/<scope>/<short-description>`:112113- `<github-username>` — the author's GitHub login (e.g. `mdrxy`).114- `<scope>` — the same scope used in the Conventional Commit title (`core`, `langchain`, partner name, `infra`, `docs`, etc.).115- `<short-description>` — kebab-case, brief, no trailing slash.116117Examples:118119```txt120mdrxy/anthropic/normalize-tool-call-ids121mdrxy/core/vector-store-type-hints122mdrxy/infra/agents-md-branch123```124125#### PR descriptions126127The description *is* the summary — do not add a `# Summary` header.128129- When the PR closes an issue, lead with the closing keyword on its own line at the very top, followed by a horizontal rule and then the body:130131 ```txt132 Closes #123133134 ---135136 <rest of description>137 ```138139 Only `Closes`, `Fixes`, and `Resolves` auto-close the referenced issue on merge. `Related:` or similar labels are informational and do not close anything.140141- Explain the *why*: the motivation and why this solution is the right one. Limit prose.142- Write for readers who may be unfamiliar with this area of the codebase. Avoid insider shorthand and prefer language that is friendly to public viewers — this aids interpretability.143- Do **not** cite line numbers; they go stale as soon as the file changes.144- Rarely include full file paths or filenames. Reference the affected symbol, class, or subsystem by name instead.145- Wrap class, function, method, parameter, and variable names in backticks.146- Skip dedicated "Test plan" or "Testing" sections in most cases. Mention tests only when coverage is non-obvious, risky, or otherwise notable.147- Call out areas of the change that require careful review.148- Add a brief disclaimer noting AI-agent involvement in the contribution.149150## Core development principles151152### Maintain stable public interfaces153154CRITICAL: Always attempt to preserve function signatures, argument positions, and names for exported/public methods. Do not make breaking changes.155You should warn the developer for any function signature changes, regardless of whether they look breaking or not.156157**Before making ANY changes to public APIs:**158159- Check if the function/class is exported in `__init__.py`160- Look for existing usage patterns in tests and examples161- Use keyword-only arguments for new parameters: `*, new_param: str = "default"`162- Mark experimental features clearly with docstring warnings (using MkDocs Material admonitions, like `!!! warning`)163164Ask: "Would this change break someone's code if they used it last week?"165166### Code quality standards167168All Python code MUST include type hints and return types.169170```python title="Example"171def filter_unknown_users(users: list[str], known_users: set[str]) -> list[str]:172 """Single line description of the function.173174 Any additional context about the function can go here.175176 Args:177 users: List of user identifiers to filter.178 known_users: Set of known/valid user identifiers.179180 Returns:181 List of users that are not in the `known_users` set.182 """183```184185- Use descriptive, self-explanatory variable names.186- Follow existing patterns in the codebase you're modifying187- Attempt to break up complex functions (>20 lines) into smaller, focused functions where it makes sense188189### Testing requirements190191Every new feature or bugfix MUST be covered by unit tests.192193- Unit tests: `tests/unit_tests/` (no network calls allowed)194- Integration tests: `tests/integration_tests/` (network calls permitted)195- We use `pytest` as the testing framework; if in doubt, check other existing tests for examples.196- The testing file structure should mirror the source code structure.197198**Checklist:**199200- [ ] Tests fail when your new logic is broken201- [ ] Happy path is covered202- [ ] Edge cases and error conditions are tested203- [ ] Use fixtures/mocks for external dependencies204- [ ] Tests are deterministic (no flaky tests)205- [ ] Does the test suite fail if your new logic is broken?206207### Security and risk assessment208209- No `eval()`, `exec()`, or `pickle` on user-controlled input210- Proper exception handling (no bare `except:`) and use a `msg` variable for error messages211- Remove unreachable/commented code before committing212- Race conditions or resource leaks (file handles, sockets, threads).213- Ensure proper resource cleanup (file handles, connections)214215### Documentation standards216217Use Google-style docstrings with Args section for all public functions.218219```python title="Example"220def send_email(to: str, msg: str, *, priority: str = "normal") -> bool:221 """Send an email to a recipient with specified priority.222223 Any additional context about the function can go here.224225 Args:226 to: The email address of the recipient.227 msg: The message body to send.228 priority: Email priority level.229230 Returns:231 `True` if email was sent successfully, `False` otherwise.232233 Raises:234 InvalidEmailError: If the email address format is invalid.235 SMTPConnectionError: If unable to connect to email server.236 """237```238239- Types go in function signatures, NOT in docstrings240 - If a default is present, DO NOT repeat it in the docstring unless there is post-processing or it is set conditionally.241- Focus on "why" rather than "what" in descriptions242- Document all parameters, return values, and exceptions243- Keep descriptions concise but clear244- Ensure American English spelling (e.g., "behavior", not "behaviour")245- Do NOT use Sphinx-style double backtick formatting (` ``code`` `). Use single backticks (`` `code` ``) for inline code references in docstrings and comments.246247#### Model references in docs and examples248249Always use the latest generally available (GA) models when referencing LLMs in docstrings and illustrative code snippets. Avoid preview or beta identifiers unless the model has no GA equivalent. Outdated model names signal stale code and confuse users.250251Before writing or updating model references, verify current model IDs against the provider's official docs. Do not rely on memorized or cached model names — they go stale quickly.252253Changing **shipped default parameter values** in code (e.g., a `model=` kwarg default in a class constructor) may constitute a breaking change — see "Maintain stable public interfaces" above. This guidance applies to documentation and examples, not code defaults.254255For model *profile data* (capability flags, context windows), use the `langchain-profiles` CLI described below.256257## Model profiles258259Model profiles are generated using the `langchain-profiles` CLI in `libs/model-profiles`. The `--data-dir` must point to the directory containing `profile_augmentations.toml`, not the top-level package directory.260261```bash262# Run from libs/model-profiles263cd libs/model-profiles264265# Refresh profiles for a partner in this repo266uv run langchain-profiles refresh --provider openai --data-dir ../partners/openai/langchain_openai/data267268# Refresh profiles for a partner in an external repo (requires echo y to confirm)269echo y | uv run langchain-profiles refresh --provider google --data-dir /path/to/langchain-google/libs/genai/langchain_google_genai/data270```271272Example partners with profiles in this repo:273274- `libs/partners/openai/langchain_openai/data/` (provider: `openai`)275- `libs/partners/anthropic/langchain_anthropic/data/` (provider: `anthropic`)276- `libs/partners/perplexity/langchain_perplexity/data/` (provider: `perplexity`)277278The `echo y |` pipe is required when `--data-dir` is outside the `libs/model-profiles` working directory.279280## CI/CD infrastructure281282### Release process283284Releases are triggered manually via `.github/workflows/_release.yml` with `working-directory` and `release-version` inputs.285286### PR labeling and linting287288**Title linting** (`.github/workflows/pr_lint.yml`)289290**Auto-labeling:**291292- `.github/workflows/pr_labeler.yml` – Unified PR labeler (size, file, title, external/internal, contributor tier)293- `.github/workflows/pr_labeler_backfill.yml` – Manual backfill of PR labels on open PRs294- `.github/workflows/auto-label-by-package.yml` – Issue labeling by package295- `.github/workflows/tag-external-issues.yml` – Issue external/internal classification296297### Adding a new partner to CI298299When adding a new partner package, update these files:300301- `.github/ISSUE_TEMPLATE/*.yml` – Add to package dropdown302- `.github/dependabot.yml` – Add dependency update entry303- `.github/scripts/pr-labeler-config.json` – Add file rule and scope-to-label mapping304- `.github/workflows/_release.yml` – Add API key secrets if needed305- `.github/workflows/auto-label-by-package.yml` – Add package label306- `.github/workflows/check_diffs.yml` – Add to change detection307- `.github/workflows/integration_tests.yml` – Add integration test config308- `.github/workflows/pr_lint.yml` – Add to allowed scopes309310## GitHub Actions & Workflows311312This repository require actions to be pinned to a full-length commit SHA. Attempting to use a tag will fail. Use the `gh` cli to query. Verify tags are not annotated tag objects (which would need dereferencing).313314## Additional resources315316- **Documentation:** https://docs.langchain.com/oss/python/langchain/overview and source at https://github.com/langchain-ai/docs or `../docs/`. Prefer the local install and use file search tools for best results. If needed, use the docs MCP server as defined in `.mcp.json` for programmatic access.317- **Contributing Guide:** [Contributing Guide](https://docs.langchain.com/oss/python/contributing/overview)
Findings
✓ No findings reported for this file.