Миграция кода с LangChain 0.3.x на LangChain 1.0 и LangGraph.

Звёзды2 926
Авторjeremylongshore
Установок26

Установка

SKILL.md

LangChain 1.0 Upgrade Migration (Python)

Overview

The first deploy after pip install -U langchain crashes on import with:

ImportError: cannot import name 'ChatOpenAI' from 'langchain.chat_models'

Fix the import, restart, and the next error lands:

ImportError: cannot import name 'LLMChain' from 'langchain.chains'
AttributeError: module 'langchain.agents' has no attribute 'initialize_agent'
AttributeError: 'ConversationBufferMemory' object has no attribute 'save_context'

LangChain 1.0 removed four entire public-API surfaces in one release:

  • Provider imports under langchain.chat_models / langchain.llms (pain code P38).
  • The LLMChain family under langchain.chains (P39).
  • ConversationBufferMemory and siblings under langchain.memory (P40).
  • initialize_agent under langchain.agents (P41).

Anything that inspected intermediate_steps also breaks because the tuple shape changed from (AgentAction, observation) to (ToolCall, observation) (P42).

This skill walks a reversible, phased migration:

  1. A pre-flight grep audit.
  2. A pinned package upgrade (including the langchain-anthropic 1.0 peer-pin against anthropic >= 0.40, P66).
  3. Codemod patterns for the seven removed APIs.
  4. A rollout playbook with shadow traffic and a sub-five-minute rollback.

It covers 7 named breaking changes and typically touches 10–100 files in a mid-sized service.

The fix for the error above:

# BEFORE (0.3)
from langchain.chat_models import ChatOpenAI

# AFTER (1.0)
from langchain_openai import ChatOpenAI

See codemod-patterns.md for the other six patterns.

Prerequisites

  • Python 3.10+ (LangChain 1.0 dropped 3.8/3.9).
  • A working test suite for the service being migrated (the playbook runs pytest -W error::DeprecationWarning at every phase).
  • Git on a clean working tree — the migration uses per-module commits so rollback is per-commit.
  • Access to staging traffic or a request-mirror. Phase 4 of the playbook needs real-shape traffic.
  • If conversations are persisted (Redis / Postgres / DynamoDB), a snapshot of the chat-history store before Phase 2. The LangGraph checkpointer uses a new schema and a naive rollback is data-lossy.

Instructions

Step 1 — Pre-flight grep audit

Inventory every 0.3 usage before touching a requirements.txt. Each grep below maps to one pain code and one codemod pattern.

grep -rn "from langchain\.chat_models\|from langchain\.llms" --include="*.py" .          # P38
grep -rn "from langchain\.chains\b\|\bLLMChain\b\|\bRetrievalQA\b" --include="*.py" .    # P39
grep -rn "from langchain\.memory\|ConversationBufferMemory" --include="*.py" .           # P40
grep -rn "initialize_agent\|AgentType\." --include="*.py" .                              # P41
grep -rn "\.tool_input\b\|intermediate_steps" --include="*.py" .                         # P42
grep -rn "astream_log\b" --include="*.py" .                                              # P67

Pipe the full set into langchain-0.3-hits.txt — that file is the migration work list. The migration-detection.md reference has the one-shot bundled block and a line-count triage table.

Step 2 — Pin and upgrade packages together

LangChain 1.0 spans six coordinated packages. A partial upgrade (e.g. pip install -U langchain-anthropic without bumping anthropic) triggers AttributeError at import time (P66). Update all six in the same commit:

langchain>=1.0,<2
langchain-core>=0.3,<0.4
langchain-openai>=1.0
langchain-anthropic>=1.0
langgraph>=1.0,<2
anthropic>=0.40,<1

Apply:

pip install -U \
  "langchain>=1.0,<2" \
  "langchain-core>=0.3,<0.4" \
  "langchain-openai>=1.0" \
  "langchain-anthropic>=1.0" \
  "langgraph>=1.0,<2" \
  "anthropic>=0.40,<1"

Then snapshot the prior state for the rollback: pip freeze > requirements.lock.pre-1.0.txt.

Step 3 — Codemod the four removed APIs

Work through the hits from Step 1 in this order (lowest blast radius first):

  1. Provider imports (P38) — mechanical find/replace. from langchain.chat_models import ChatOpenAI → from langchain_openai import ChatOpenAI. Same pattern for ChatAnthropic, OpenAIEmbeddings, Chroma, etc.
  2. LLMChain → LCEL (P39) — replace chain = LLMChain(llm=llm, prompt=prompt) with chain = prompt | llm | StrOutputParser(). Caller changes from chain.run(x=1) to chain.invoke({"x": 1}). If the caller treated the result as a dict, unwrap — invoke returns the string directly.
  3. initialize_agent → create_react_agent (P41) — swap the import to from langgraph.prebuilt import create_react_agent. Tools written with Tool(name=..., func=...) still work; prefer the @tool decorator from langchain_core.tools. Agent input becomes {"messages": [("user", "...")]}; the final reply is result["messages"][-1].content.
  4. ConversationBufferMemory → LangGraph checkpointer (P40) — swap the memory object for MemorySaver() (dev) or SqliteSaver.from_conn_string(...) (prod). Compile the graph/agent with checkpointer=saver, then pass config={"configurable": {"thread_id": "..."}} on every invoke. The thread_id is the conversation primary key.

Full before/after snippets for all four are in codemod-patterns.md.

Step 4 — Update streaming callers (P67)

astream_log still works in 1.0 but is soft-deprecated. The replacement is astream_events(version="v2"):

# BEFORE
async for patch in chain.astream_log({"input": "hi"}):
    for op in patch.ops:
        if op["op"] == "add" and op["path"].endswith("/streamed_output/-"):
            print(op["value"], end="")

# AFTER
async for event in chain.astream_events({"input": "hi"}, version="v2"):
    if event["event"] == "on_chat_model_stream":
        print(event["data"]["chunk"].content, end="")

Event names in v2: on_chain_start, on_chain_end, on_chat_model_start, on_chat_model_stream, on_chat_model_end, on_tool_start, on_tool_end. The payload under data is typed — chunk is an AIMessageChunk, not a raw string.

Step 5 — Fix intermediate_steps consumers (P42)

If any code iterates result["intermediate_steps"] and reads .tool / .tool_input, it breaks silently in 1.0 — the tuples now hold ToolCall dicts, not AgentAction objects. The 1.0 equivalent reads from graph state:

# BEFORE
for action, observation in result["intermediate_steps"]:
    log(action.tool, action.tool_input, observation)

# AFTER
for msg in result["messages"]:
    for tc in getattr(msg, "tool_calls", []) or []:
        log(tc["name"], tc["args"])   # .tool -> "name", .tool_input -> "args"

ToolCall dict keys are name, args, id. There is no tool or tool_input accessor anywhere in 1.0.

Step 6 — Gate on deprecation-as-error tests

Turn DeprecationWarning into a test failure so any surviving 0.3 pattern surfaces before the rollout:

pytest -W error::DeprecationWarning

Do not promote to staging while this is red. Re-run the Step 1 greps — they should now return zero hits outside intentionally-pinned 0.3 test fixtures.

Step 7 — Phased rollout on production traffic

Deploy behind a feature flag (LANGCHAIN_1_0_ENABLED), canary at 1%, and ramp to 100% over 2–4 hours with a 15-minute soak at each step. The rollback is always "flip the flag off" — not a redeploy. Full playbook (shadow traffic in staging, dual-write for persistent chat histories, per-phase exit criteria) is in phased-rollout-playbook.md.

Output

  • requirements.txt pinning all six 1.0 packages with the anthropic >= 0.40 peer-pin (P66).
  • requirements.lock.pre-1.0.txt in the repo root for five-minute rollback.
  • Per-module git commits referencing pain codes (e.g. refactor: migrate P39 LLMChain in billing-summariser to LCEL).
  • langchain-0.3-hits.txt work-list returning zero non-test hits on re-run.
  • pytest -W error::DeprecationWarning green on the migration branch.
  • Feature-flagged production cutover at 100%, flag removed after a full day of soak.

Error Handling

ErrorCauseFix
ImportError: cannot import name 'ChatOpenAI' from 'langchain.chat_models'P38 — provider imports moved to partner packagesfrom langchain_openai import ChatOpenAI
ImportError: cannot import name 'LLMChain' from 'langchain.chains'P39 — LLMChain removedReplace with LCEL: prompt | llm | StrOutputParser()
AttributeError: 'ConversationBufferMemory' object has no attribute 'save_context'P40 — memory classes removed from the public APISwap for LangGraph MemorySaver / SqliteSaver with a thread_id
AttributeError: module 'langchain.agents' has no attribute 'initialize_agent'P41 — legacy agent constructor removedfrom langgraph.prebuilt import create_react_agent
AttributeError: 'ToolCall' object has no attribute 'tool'P42 — tuple shape changed, fields renamedRead tc["name"] and tc["args"] instead of .tool / .tool_input
AttributeError: module 'anthropic' has no attribute 'AsyncAnthropic'P66 — langchain-anthropic 1.0 needs anthropic >= 0.40Pin anthropic>=0.40,<1 in the same commit as the langchain-anthropic bump
DeprecationWarning: astream_log is deprecated; use astream_events(version="v2")P67 — soft deprecationSwitch to astream_events(version="v2") and update event-name handling

Examples

Example 1 — Minimal LLMChain to LCEL

# BEFORE (0.3)
from langchain.chat_models import ChatOpenAI
from langchain.prompts import ChatPromptTemplate
from langchain.chains import LLMChain

llm = ChatOpenAI(model="gpt-4o-mini", temperature=0)
prompt = ChatPromptTemplate.from_messages([("system", "Summarise in one line."), ("user", "{text}")])
chain = LLMChain(llm=llm, prompt=prompt)
print(chain.run(text="LangChain 1.0 removed LLMChain."))

# AFTER (1.0)
from langchain_openai import ChatOpenAI
from langchain_core.prompts import ChatPromptTemplate
from langchain_core.output_parsers import StrOutputParser

llm = ChatOpenAI(model="gpt-4o-mini", temperature=0)
prompt = ChatPromptTemplate.from_messages([("system", "Summarise in one line."), ("user", "{text}")])
chain = prompt | llm | StrOutputParser()
print(chain.invoke({"text": "LangChain 1.0 removed LLMChain."}))

Example 2 — Stateful agent with LangGraph checkpointer

# AFTER (1.0)
from langchain_openai import ChatOpenAI
from langchain_core.tools import tool
from langgraph.prebuilt import create_react_agent
from langgraph.checkpoint.memory import MemorySaver    # use SqliteSaver / PostgresSaver in prod

@tool
def add(a: int, b: int) -> int:
    """Add two integers."""
    return a + b

llm = ChatOpenAI(model="gpt-4o-mini", temperature=0)
agent = create_react_agent(llm, [add], checkpointer=MemorySaver())

config = {"configurable": {"thread_id": "user-42"}}
r1 = agent.invoke({"messages": [("user", "What's 2 + 3?")]}, config=config)
r2 = agent.invoke({"messages": [("user", "And plus 10?")]}, config=config)   # remembers "5"
print(r2["messages"][-1].content)

Example 3 — Rollback pin

If Phase 5 of the rollout regresses and the feature flag is already off:

git checkout main
pip install -r requirements.lock.pre-1.0.txt
pytest                      # confirm green on the rollback pin
# deploy

Resources

  • LangChain migration guide
  • LangChain release policy
  • LangGraph prebuilt create_react_agent
  • astream_events v2 reference
  • Breaking changes matrix — all 7 named changes mapped to pain codes
  • Codemod patterns — before/after for the 7 most common migrations
  • Phased rollout playbook — shadow traffic, dual-write, rollback
  • Migration detection — pre-flight grep audit
  • One-pager — executive summary

Вставить в README

Ссылка на карточку для вашего README — без картинок и счётчиков.

[DarkPlay: langchain-upgrade-migration](https://darkplay.ru/ai/skills/jeremylongshore-claude-code-plugins-plus-skills-langchain-upgrade-migration)

Похожие скиллы и другие разделы каталога

Популярное в разделе «Скиллы»

Самые востребованные скиллов раздела по установкам и звёздам.

find-skillsvercel-labs · Помогает находить и устанавливать навыки агентов по запросам вроде «как сделать X»…
4 400 000 устан.
grill-memattpocock · Настойчивое интервью для доработки плана или дизайна.
1 600 000 устан.
hyperframesheygen-com · Обязательная точка входа для любых задач по видео, анимации и motion-графике в…
1 600 000 устан.
hyperframes-cliheygen-com · Цикл разработки HyperFrames CLI: init, add, render, preview, publish и другие команды.
1 600 000 устан.
agent-browservercel-labs · CLI для автоматизации браузера для ИИ-агентов: навигация по страницам, заполнение форм…
1 600 000 устан.
media-useheygen-com · Agent Media OS: единый навык для медиа в HyperFrames — BGM, SFX, изображения, голос, LUT.
1 500 000 устан.
hyperframes-registryheygen-com · Установка и подключение блоков реестра в композиции HyperFrames через add и catalog.
1 400 000 устан.
grill-with-docsmattpocock · Настойчивое интервью для доработки плана или дизайна, попутно создающее документацию (ADR…
1 300 000 устан.
improve-codebase-architecturemattpocock · Поиск в кодовой базе возможностей для углубления, визуальный HTML-отчёт о них и детальный…
1 300 000 устан.
tddmattpocock · Разработка через тестирование (TDD): red-green-refactor и интеграционные тесты.
1 300 000 устан.
Похожее в других разделах каталога

Соседние разделы каталога: возможно, нужный инструмент живёт там.

Database Migrationaffaan-m · Каркас команды workflow для database-migration в everything-claude-code.
225 587 ★
Database Revieweraffaan-m · Специалист PostgreSQL: оптимизация запросов, схемы, безопасность, Supabase.
225 587 ★
Django Build Resolveraffaan-m · Специалист по ошибкам Django: pip/Poetry, миграции, импорты, collectstatic.
225 587 ★
Django Revieweraffaan-m · Ревьюер Django: ORM, DRF, миграции, безопасность и production-практики.
225 587 ★
claude-opus-4-5-migrationanthropics · Перенос кода и промптов с Sonnet 4.x и Opus 4.1 на Opus 4.5.
34 комп.
ruflo-migrationsruvnet · Управление миграциями схемы: генерация, проверка, пробный запуск и откат миграций базы…
240 комп.
aws-startup-advisoranthropics · Персонализированные рекомендации по архитектуре, затратам, безопасности и миграции для…
100 комп.
aws-transformanthropics · Миграция, модернизация и обновление кодовых баз на AWS: .NET Framework в .NET 8/10, COBOL…
100 комп.
buildkiteanthropics · Официальные навыки Buildkite для Claude Code, Cursor и других AI-агентов разработки…
100 комп.
confidenceanthropics · Доступ к фича-флагам, экспериментам и инструментам миграции Confidence прямо из Claude…
100 комп.

Лучшие ИИ-инструменты для программирования

ИИ для программирования

Подборка нейросетей и ИИ-ассистентов для разработки и автоматизации кода. Сервисы, которые ускоряют написание, ревью и отладку, экономят часы рутины и снижают порог входа в сложные

GenAPIGenapi
По запросу
5.0
Notepad++ AINotepad-plus-plus
По запросу
4.9
GitHub CopilotGitHub
По подписке
4.9
Creatium MaxCremax
По запросу
4.8
Emacs AIGnu
По запросу
4.8
KiteKite
По запросу
4.8
Amazon Q DeveloperAmazon
По запросу
4.8
VECTA
Есть бесплатный тариф
4.8
SoftPractice
Есть бесплатный тариф
4.8
VibeForge
Есть бесплатный тариф
4.7

Лучшие ИИ-инструменты для генерации видео

Генерация видео

Подборка нейросетей для генерации и монтажа видео. Инструменты, которые превращают текст в готовые ролики, экономят часы на съемках и постпродакшне. Подходит для SMM-специалистов,

VEED.IOVeed
По запросу
5.0
MootionMootion
По запросу
5.0
FlyviFlyvi
Есть бесплатный тариф
4.9
Google Veo 3.1Google
Платно
4.9
Sora (OpenAI)OpenAI
Платно
4.9
PikaPika
Платно
4.9
captions space
Есть бесплатный тариф
4.8
Клайп
Есть бесплатный тариф
4.8
viralpulse.appViralpulse
По запросу
4.8
Viral Maker AIViral-maker
Есть бесплатный тариф
4.8

Лучшие ИИ-инструменты для генерации текста и копирайтинга

Генерация текста и копирайтинг

Подборка нейросетей для генерации текстов и копирайтинга. Сервисы, которые помогают создавать статьи, посты и рекламные объявления с нуля или по черновику, экономя часы рутинной ра

NeuroscribeNeuroscribe
Есть бесплатный тариф
5.0
GoGPTGogpt
По запросу
5.0
ChatsonicChatsonic
По запросу
4.9
НейроТекстерNeuro-texter
По запросу
4.9
ChatGPTOpenAI
По подписке
4.9
Редактум
Есть бесплатный тариф
4.8
ChadGPTChadgpt
По запросу
4.8
Cosmo ScribeCosmoscribe
Есть бесплатный тариф
4.8
Memo HelperCopilot33
По запросу
4.8
LibraChatLibrachat
Есть бесплатный тариф
4.8