# LangChain (≥ 1.0) ## Что это в одном абзаце LangChain — это Python-фреймворк для сборки LLM-приложений и агентов. С версии 1.0 (релиз 22 октября 2025) он позиционируется как «самый быстрый способ собрать агента с любым провайдером моделей», построенный поверх LangGraph-рантайма. До 1.0 фреймворк был известен как «монолит с LCEL» — теперь же фокус сместился на единый `create_agent` и middleware-систему; вся устаревшая функциональность (LLMChain, RetrievalQA, ConversationalRetrievalQA, legacy AgentExecutor) переехала в отдельный пакет `langchain-classic`. **Метаданные на дату snapshot 2026-06-22:** - GitHub stars: ~140k - Latest stable (Python): `langchain` 1.3.10 / `langchain-core` 1.4.8 (от 18.06.2026) - License: MIT - JS-аналог: `langchain` (npm `@langchain/langchain`) **Источники:** - README `github.com/langchain-ai/langchain` - https://changelog.langchain.com/announcements/langchain-1-0-now-generally-available - https://docs.langchain.com/oss/python/releases/langchain-v1 --- ## Ключевые API (≥ 1.0) ### Импорты верхнего уровня ```python from langchain.chat_models import init_chat_model from langchain.agents import create_agent from langchain.agents.middleware import ( HumanInTheLoopMiddleware, SummarizationMiddleware, PIIRedactionMiddleware, ) from langchain.tools import tool ``` ### Создание модели ```python # Универсальный инициализатор — один интерфейс для всех провайдеров model = init_chat_model("openai:gpt-4.1") model = init_chat_model("anthropic:claude-3-7-sonnet-latest") model = init_chat_model("google_vertexai:gemini-2.0-flash") ``` ### Создание агента (новый create_agent) ```python from langchain.agents import create_agent agent = create_agent( model="openai:gpt-4.1", tools=[get_weather], system_prompt="You are a helpful assistant.", ) result = agent.invoke({"messages": [{"role": "user", "content": "weather in NYC?"}]}) ``` ### Structured output ```python from pydantic import BaseModel class Weather(BaseModel): city: str temperature_c: float model_with_struct = model.with_structured_output(Weather) ``` ### Инструменты ```python from langchain.tools import tool @tool def get_weather(city: str) -> str: """Get the weather for a given city.""" return f"Sunny, 22°C in {city}" ``` ### Middleware (новая система v1.0) ```python from langchain.agents.middleware import HumanInTheLoopMiddleware, PIIRedactionMiddleware agent = create_agent( model=model, tools=[read_file, write_file], middleware=[ HumanInTheLoopMiddleware(interrupt_on={"write_file": True}), PIIRedactionMiddleware(redact_emails=True), ], ) ``` ### Messages (стандартизированные content blocks) ```python from langchain.messages import HumanMessage, AIMessage, SystemMessage msg = HumanMessage(content="Hello") response = model.invoke([msg]) # response.content может содержать reasoning traces, citations, tool_call блоки ``` --- ## Что нового в 1.0 1. **create_agent abstraction** — единая точка входа для всех агентов. Заменил многообразие legacy `create_react_agent`, `create_openai_functions_agent`, `create_structured_chat_agent`. Построен на LangGraph-runtime. 2. **Middleware system** — hooks до/после model call, до/после tool call. Built-in: HumanInTheLoop, Summarization, PIIRedaction. Custom middleware — first-class. 3. **Improved structured output** — интегрирован в основной цикл, без extra LLM-вызовов. Поддержка tool calling и provider-native. 4. **Standard content blocks** — провайдер-агностичный формат для reasoning traces, citations, server-side tool calls. 5. **Reduced surface area** — `langchain-classic` забрал все chains/agentsExecutor-legacy, оставив минимальное API. 6. **Stability promise** — semver-обязательство: до 2.0 не будет breaking changes. 7. **init_chat_model универсальный** — один инициализатор для всех провайдеров (был `ChatOpenAI`, `ChatAnthropic`, `ChatGoogleGenerativeAI` отдельно). --- ## Что нужно раскрыть в презентации - **LCEL (LangChain Expression Language)** — хотя 1.0 сместил фокус, LCEL остаётся основой для неагентных цепочек (`prompt | model | parser`). - **create_agent vs LCEL** — когда что: agent для циклов с инструментами, LCEL для линейных pipeline-ов. - **Middleware-система** — триггерит HITL, summarization, PII-regex; где их подключать. - **Standard content blocks** — почему важно для multi-provider совместимости. - **Миграция с 0.x** — что ушло в `langchain-classic`, что переименовано (`LLMChain` → `langchain-classic`). - **init_chat_model** — единая фабрика моделей. - **Интеграции** — `langchain-openai`, `langchain-anthropic`, `langchain-google`, `langchain-tavily`, etc. ~700+ community пакетов. --- ## 7 рабочих примеров кода Python (≥ 1.0) ### 1. Hello world (init_chat_model) ```python from langchain.chat_models import init_chat_model model = init_chat_model("openai:gpt-4.1-mini") result = model.invoke("Say hello in one sentence") print(result.content) ``` ### 2. LCEL-цепочка (промпт → модель → парсер) ```python from langchain.chat_models import init_chat_model from langchain_core.prompts import ChatPromptTemplate from langchain_core.output_parsers import StrOutputParser model = init_chat_model("openai:gpt-4.1-mini") prompt = ChatPromptTemplate.from_messages([ ("system", "Translate to French."), ("human", "{text}"), ]) chain = prompt | model | StrOutputParser() print(chain.invoke({"text": "Hello world"})) ``` ### 3. create_agent с одним инструментом ```python from langchain.agents import create_agent from langchain.tools import tool @tool def get_weather(city: str) -> str: """Get weather for a city.""" return f"Sunny, 22°C in {city}" agent = create_agent( model="openai:gpt-4.1", tools=[get_weather], system_prompt="You are a weather assistant.", ) result = agent.invoke({"messages": [{"role": "user", "content": "weather in Paris?"}]}) print(result["messages"][-1].content) ``` ### 4. Structured output ```python from langchain.chat_models import init_chat_model from pydantic import BaseModel class MovieReview(BaseModel): title: str rating: int # 1..10 summary: str model = init_chat_model("openai:gpt-4.1-mini") reviewer = model.with_structured_output(MovieReview) result = reviewer.invoke("Review the movie Inception in one sentence.") print(result.title, result.rating, result.summary) ``` ### 5. Middleware: HITL ```python from langchain.agents import create_agent from langchain.agents.middleware import HumanInTheLoopMiddleware from langchain.tools import tool @tool def send_email(to: str, body: str) -> str: """Send an email.""" return f"sent to {to}" agent = create_agent( model="openai:gpt-4.1", tools=[send_email], middleware=[HumanInTheLoopMiddleware(interrupt_on={"send_email": True})], ) result = agent.invoke({"messages": [{"role": "user", "content": "email alice@x.com"}]}) ``` ### 6. Middleware: PII-редакция ```python from langchain.agents import create_agent from langchain.agents.middleware import PIIRedactionMiddleware from langchain.tools import tool @tool def echo(text: str) -> str: """Echo back the text.""" return text agent = create_agent( model="openai:gpt-4.1-mini", tools=[echo], middleware=[PIIRedactionMiddleware(redact_emails=True, redact_phones=True)], ) result = agent.invoke({"messages": [{"role": "user", "content": "ping me at john@example.com"}]}) ``` ### 7. Streaming ```python from langchain.chat_models import init_chat_model model = init_chat_model("openai:gpt-4.1-mini") for chunk in model.stream("Write a haiku about Python"): print(chunk.content, end="", flush=True) ``` --- ## TypeScript-аналог Все примеры выше имеют прямой аналог в `@langchain/langchain` (npm): ```typescript import { initChatModel } from "langchain/chat_models/universal"; import { createAgent } from "langchain/agents"; import { tool } from "@langchain/core/tools"; import { z } from "zod"; const getWeather = tool( async ({ city }) => `Sunny, 22°C in ${city}`, { name: "get_weather", description: "Get weather", schema: z.object({ city: z.string() }) } ); const model = await initChatModel("openai:gpt-4.1"); const agent = createAgent({ model, tools: [getWeather] }); const result = await agent.invoke({ messages: [{ role: "user", content: "weather in Paris?" }] }); ``` **Где нет аналога:** legacy chains (`langchain-classic`) в JS пока имеет меньше покрытия, чем Python. На практике миграция на `create_agent` рекомендована в обоих языках. --- ## Плюсы и минусы текущей версии (1.x) ### Плюсы - **Семантическая стабильность** — обязательство не ломать API до 2.0. - **Единая точка входа** — `create_agent` вместо зоопарка agent-типов. - **Middleware-система** — clean separation cross-cutting concerns (HITL, PII, summarization). - **init_chat_model** — переключение провайдера без рефакторинга. - **LangGraph-runtime под капотом** — durable execution, checkpointing бесплатно. - **~700+ интеграций** — community-пакеты `langchain-*`. ### Минусы - **Кривая обучения для middleware** — концепция `before_model / after_model` hooks требует привычки. - **Часть экосистемы в `langchain-classic`** — много Stack Overflow-ответов по старому API, миграционная боль. - **Абстракция скрывает LangGraph** — если нужен fine-grained контроль, приходится «проваливаться» в LangGraph. - **Раздутые community-пакеты** — `langchain-community` исторически критиковали за bloated dependencies (но в 1.0 core остался lean). - **Bundled-version зависимости** — `langchain-openai` / `langchain-anthropic` / etc. имеют свои минорные циклы, нужно явно указывать версии. --- ## Заметки для презентации - В 1.0 главный фокус: **agents, not chains**. Если нужно объяснить разницу — показать, как `LLMChain` + `AgentExecutor` объединились в `create_agent`. - Подчеркнуть, что **middleware** — это новая killer-фича v1.0 (в 0.x приходилось писать custom callbacks). - Чётко сказать: **до 2.0 breaking changes не будет** — это продакшен-ready commitment. - Если рассказывать про миграцию — упомянуть `langchain-classic` как «battery-included обратная совместимость».