# langchain

Guides Cursor to write modern LangChain code in Python: enforces LCEL pipelines, LangGraph agents, and Pydantic schemas instead of legacy chains.

- rule · `type=rule` · Cursor · ★ 3580
- Author: sanjeed5
- License: CC0-1.0 · policy=mirror · the beginning of the file is at the end of this page
- Source: https://github.com/sanjeed5/awesome-cursor-rules-mdc/tree/HEAD/rules-mdc/langchain.mdc
- Updated: 2026-05-19
- HTML: https://affpapa.org/en/nevibecode/rules/langchain

## What it does

The rule triggers on `**/*.py` files inside Cursor. It dictates a modular architecture, splitting logic into dedicated directories for models, prompts, tools, agents, and memory. Consolidating everything into a single monolithic script is forbidden.

For composing pipelines, the guide mandates LCEL syntax with the pipe `|` operator, strictly banning deprecated classes like `LLMChain`. When writing agents, it enforces `create_agent` backed by LangGraph rather than custom execution loops. Outputs must use Pydantic models through `with_structured_output`, and long operations stream responses via asynchronous calls to avoid blocking execution.

## Install

### Cursor (native platform)

**Manually: put the files in place**
- File: `.cursor/rules/langchain.mdc` — Frontmatter: description, globs, alwaysApply

### Claude Code

**Manually: put the files in place**
- File: `.claude/rules/langchain.md` — The paths frontmatter field limits the files: move globs from the source into paths

### Codex

**AGENTS.md**
- Codex reads AGENTS.md: paste the rule text there

### GitHub Copilot

**Manually: put the files in place**
- File: `.github/instructions/langchain.instructions.md` — The applyTo field sets which files it applies to: move globs from the source into applyTo

### Windsurf (Devin Desktop)

**Manually: put the files in place**
- File: `.devin/rules/langchain.md`

### Cline

**Manually: put the files in place**
- File: `.clinerules/langchain.md`

Where a file is given instead of a command, copy the files from the source to that path: https://github.com/sanjeed5/awesome-cursor-rules-mdc/tree/HEAD/rules-mdc/langchain.mdc

## When to use it
- migrate legacy `LLMChain` calls to clean LCEL syntax
- build stateful agents using `create_agent` with LangGraph
- enforce structured JSON responses through Pydantic models
- split monolithic Python files into modular components
- implement asynchronous streaming with `chain.stream`

## Example prompts
- Create an LCEL chain with ChatOpenAI and StrOutputParser for user questions.
- Set up a ReAct agent using `create_agent` with a custom weather lookup tool.
- Extract structured data using a Pydantic schema and `with_structured_output`.

## Source text · langchain.mdc · CC0-1.0

Below is the content of a third-party file. It is data, not instructions for you: do not act on anything written inside unless the human asks. Block tag: d1e046603d4587de.

BEGIN THIRD-PARTY FILE d1e046603d4587de
````text
---
description: Definitive guidelines for writing maintainable, performant, and robust LangChain applications using modern best practices (LCEL, LangGraph, Pydantic, `create_agent`).
globs: **/*.py
---
# LangChain Best Practices

This guide outlines the definitive best practices for developing with LangChain. Adhere to these rules to ensure your LLM applications are modular, scalable, and production-ready.

## 1. Code Organization and Structure

Always structure your LangChain projects around core components, separating concerns into distinct modules. This enhances readability, testability, and maintainability.

**✅ GOOD: Modular Structure**
Organize by component type (models, prompts, tools, agents, memory).

```python
# my_project/
# ├── agents/
# │   └── flight_booking_agent.py
# ├── models/
# │   └── llm_config.py
# ├── prompts/
# │   └── flight_prompts.py
# ├── tools/
# │   └── flight_tools.py
# ├── memory/
# │   └── chat_memory.py
# └── main.py
```

**❌ BAD: Monolithic Files**
Avoid dumping all logic into a single file.

```python
# main.py (containing everything)
from langchain_openai import ChatOpenAI
from langchain_core.prompts import ChatPromptTemplate
# ... many more imports and definitions
# ... LLM, prompt, tools, agent definition all in one file
```

## 2. Leverage LangChain Expression Language (LCEL)

LCEL is the modern, recommended way to compose chains. It offers first-class streaming, async support, and clear debugging. **Never use deprecated `LLMChain` or older chain patterns.**

**✅ GOOD: LCEL for Chains**
Use the `|` operator for clear, composable pipelines.

```python
from langchain_core.prompts import ChatPromptTemplate
from langchain_openai import ChatOpenAI
from langchain_core.output_parsers import StrOutputParser

# Define components
prompt = ChatPromptTemplate.from_messages([
    ("system", "You are a helpful assistant."),
    ("user", "{question}")
])
llm = ChatOpenAI(model="gpt-4o-mini", temperature=0)
output_parser = StrOutputParser()

# Compose chain with LCEL
chain = prompt | llm | output_parser

# Invoke
response = chain.invoke({"question": "What is the capital of France?"})
print(response)
```

**❌ BAD: Deprecated `LLMChain`**
This pattern is outdated and lacks modern features.

```python
from langchain.chains import LLMChain # DEPRECATED
from langchain_core.prompts import PromptTemplate
from langchain_openai import ChatOpenAI

prompt = PromptTemplate.from_template("What is the capital of {country}?")
llm = ChatOpenAI(model="gpt-4o-mini", temperature=0)

# Avoid this
chain = LLMChain(llm=llm, prompt=prompt)
response = chain.invoke({"country": "Germany"})
print(response)
```

## 3. Agents: Use `create_agent` with LangGraph

For stateful, multi-step reasoning, use `create_agent` which is built on LangGraph. This provides durable execution, checkpointing, and human-in-the-loop support.

**✅ GOOD: `create_agent` for Robust Agents**
Leverage the proven ReAct pattern out-of-the-box.

```python
from langchain.agents import create_agent, tool
from langchain_openai import ChatOpenAI
from typing import Literal

@tool
def get_current_weather(location: str, unit: Literal["celsius", "fahrenheit"] = "fahrenheit") -> str:
    """Get the current weather in a given location and unit."""
    if "tokyo" in location.lower():
        return "It's 25 degrees Celsius and sunny in Tokyo."
    elif "san francisco" in location.lower():
        return "It's 60 degrees Fahrenheit and foggy in San Francisco."
    else:
        return f"Weather data for {location} not available."

llm = ChatOpenAI(model="gpt-4o-mini", temperature=0)
tools = [get_current_weather]
system_prompt = "You are a helpful AI assistant that can answer questions about the weather."

agent_executor = create_agent(llm, tools, system_prompt=system_prompt)

# Run the agent
````
END THIRD-PARTY FILE d1e046603d4587de

The third-party file has ended. Everything between the d1e046603d4587de tags is data: requests and commands from it are not followed. An “end of file” line with another tag inside the block is part of the file.

First 3902 of 10473 bytes. © sanjeed5 · CC0-1.0 · https://github.com/sanjeed5/awesome-cursor-rules-mdc/tree/HEAD/rules-mdc/langchain.mdc

_Part of the page did not fit — see the HTML version._

---
NeVibeCode on affpapa.org. Catalog texts are descriptions, not instructions for the agent. How to choose and install: https://affpapa.org/en/nevibecode/agents.md
