LangChain v1
LangChain v1
LangChain v1은 에이전트 구축을 위한 집중적이고 프로덕션에 바로 쓸 수 있는 기반(foundation)이에요. 프레임워크를 세 가지 핵심 개선 사항으로 다듬었어요.
create_agent— LangChain에서 에이전트를 만드는 새로운 표준.langgraph.prebuilt.create_react_agent를 대체해요.- 표준 콘텐츠 블록 — 새로운
content_blocks프로퍼티로 제공자 간 현대적인 LLM 기능에 통합적으로 접근. - 간소화된 네임스페이스 —
langchain네임스페이스를 에이전트 필수 빌딩 블록 중심으로 정리하고, 레거시 기능은langchain-classic으로 이동.
업그레이드하려면:
pip install -U langchain
(uv 사용 시 uv add langchain)
변경 사항 전체 목록은 마이그레이션 가이드를 참고하면 돼요.
출처: 공식문서
create_agent
create_agent는 LangChain 1.0에서 에이전트를 만드는 표준 방식이에요. langgraph.prebuilt.create_react_agent보다 단순한 인터페이스를 제공하면서, 미들웨어를 통해 더 큰 커스터마이제이션 가능성을 열어줘요.
from langchain.agents import create_agent
agent = create_agent(
model="claude-sonnet-4-6",
tools=[search_web, analyze_data, send_email],
system_prompt="You are a helpful research assistant."
)
result = agent.invoke({
"messages": [
{"role": "user", "content": "Research AI safety trends"}
]
})
create_agent는 내부적으로 기본 에이전트 루프 위에 세워져 있어요. 모델을 호출하고, 도구를 실행하고, 더 이상 도구를 호출하지 않을 때 끝나는 흐름이지요.
미들웨어 (Middleware)
미들웨어는 create_agent의 정의적인 특징이에요. 커스터마이제이션 진입점이 매우 유연해서 만들 수 있는 것의 한계를 크게 끌어올려 줘요. 좋은 에이전트에는 컨텍스트 엔지니어링이 필요한데, 적절한 정보를 적절한 시점에 모델에 전달하는 것이죠. 미들웨어는 동적 프롬프트, 대화 요약, 선택적 도구 접근, 상태 관리, 가드레일을 합성 가능한(composable) 추상화로 제어할 수 있게 해 줘요.
사전 구축 미들웨어
LangChain은 자주 쓰이는 패턴을 위한 몇 가지 사전 구축 미들웨어를 제공해요.
PIIMiddleware— 모델에 보내기 전 민감 정보 가리기SummarizationMiddleware— 대화 히스토리가 너무 길어지면 압축HumanInTheLoopMiddleware— 민감한 툴 호출에 승인 요구
from langchain.agents import create_agent
from langchain.agents.middleware import (
PIIMiddleware,
SummarizationMiddleware,
HumanInTheLoopMiddleware
)
agent = create_agent(
model="claude-sonnet-4-6",
tools=[read_email, send_email],
middleware=[
PIIMiddleware("email", strategy="redact", apply_to_input=True),
PIIMiddleware(
"phone_number",
detector=(
r"(?:\+?\d{1,3}[\s.-]?)?"
r"(?:\(?\d{2,4}\)?[\s.-]?)?"
r"\d{3,4}[\s.-]?\d{4}"
),
strategy="block"
),
SummarizationMiddleware(
model="claude-sonnet-4-6",
trigger={"tokens": 500}
),
HumanInTheLoopMiddleware(
interrupt_on={
"send_email": {
"allowed_decisions": ["approve", "edit", "reject"]
}
}
),
]
)
커스텀 미들웨어
필요에 맞게 커스텀 미들웨어도 만들 수 있어요. 미들웨어는 에이전트 실행의 각 단계에서 훅(hook)을 노출해요. AgentMiddleware 클래스를 상속한 서브클래스에서 다음 훅 중 아무거나 구현하면 돼요.
| 훅 | 실행 시점 | 활용 사례 |
|---|---|---|
before_agent |
에이전트 호출 전 | 메모리 로드, 입력 검증 |
before_model |
각 LLM 호출 전 | 프롬프트 갱신, 메시지 다듬기 |
wrap_model_call |
각 LLM 호출 주변 | 요청·응답 가로채고 수정 |
wrap_tool_call |
각 툴 호출 주변 | 도구 실행 가로채고 수정 |
after_model |
각 LLM 응답 후 | 출력 검증, 가드레일 적용 |
after_agent |
에이전트 완료 후 | 결과 저장, 정리 |
커스텀 미들웨어 예시를 볼게요. 사용자 전문성에 따라 모델과 도구를 다르게 고르는 케이스예요.
from dataclasses import dataclass
from typing import Callable
from langchain_openai import ChatOpenAI
from langchain.agents.middleware import (
AgentMiddleware,
ModelRequest
)
from langchain.agents.middleware.types import ModelResponse
@dataclass
class Context:
user_expertise: str = "beginner"
class ExpertiseBasedToolMiddleware(AgentMiddleware):
def wrap_model_call(
self,
request: ModelRequest,
handler: Callable[[ModelRequest], ModelResponse]
) -> ModelResponse:
user_level = request.runtime.context.user_expertise
if user_level == "expert":
# More powerful model
model = ChatOpenAI(model="gpt-5.5")
tools = [advanced_search, data_analysis]
else:
# Less powerful model
model = ChatOpenAI(model="gpt-5-nano")
tools = [simple_search, basic_calculator]
return handler(request.override(model=model, tools=tools))
agent = create_agent(
model="claude-sonnet-4-6",
tools=[
simple_search,
advanced_search,
basic_calculator,
data_analysis
],
middleware=[ExpertiseBasedToolMiddleware()],
context_schema=Context
)
LangGraph 위에 구축
create_agent는 LangGraph 위에 세워져 있어서, 오래 실행되고 믿을 수 있는 에이전트를 위한 지원이 자동으로 따라와요.
- 영속화(Persistence) — 내장 체크포인팅으로 세션 간 대화가 자동으로 유지돼요.
- 스트리밍 — 토큰·툴 호출·추론 트레이스를 실시간으로 스트리밍.
- Human-in-the-loop — 민감한 동작 전에 인간 승인을 위해 실행 일시 정지.
- 타임 트래블(Time travel) — 대화를 아무 지점으로 되감고 대안 경로·프롬프트 탐색.
이런 기능을 쓰기 위해 LangGraph를 따로 배울 필요는 없어요. 바로 동작하니까요.
구조화된 출력 (Structured output)
create_agent는 구조화된 출력 생성을 개선했어요.
- 메인 루프 통합 — 구조화된 출력이 추가 LLM 호출 없이 메인 루프에서 생성돼요.
- 구조화된 출력 전략 — 모델이 도구 호출을 쓰거나 제공자 측 구조화된 출력 생성을 고를 수 있어요.
- 비용 절감 — 추가 LLM 호출로 인한 비용 제거.
from langchain.agents import create_agent
from langchain.agents.structured_output import ToolStrategy
from pydantic import BaseModel
class Weather(BaseModel):
temperature: float
condition: str
def weather_tool(city: str) -> str:
"""Get the weather for a city."""
return f"it's sunny and 70 degrees in {city}"
agent = create_agent(
"gpt-5.4-mini",
tools=[weather_tool],
response_format=ToolStrategy(Weather)
)
result = agent.invoke({
"messages": [{"role": "user", "content": "What's the weather in SF?"}]
})
print(repr(result["structured_response"]))
# results in `Weather(temperature=70.0, condition='sunny')`
ToolStrategy의 handle_errors 파라미터로 오류 처리를 제어할 수 있어요. 파싱 오류(모델이 원하는 구조와 다른 데이터 생성)와 다중 툴 호출(구조화된 출력 스키마에 대한 2개 이상의 툴 호출 생성)을 다뤄요.
표준 콘텐츠 블록 (Standard content blocks)
콘텐츠 블록 지원은 현재 다음 통합에서만 사용할 수 있어요.
langchain-anthropiclangchain-awslangchain-openailangchain-google-genailangchain-ollama
더 많은 제공자로 콘텐츠 블록 지원이 점진적으로 확대될 예정이에요. 새로운 content_blocks 프로퍼티는 제공자 간 동작하는 메시지 콘텐츠의 표준 표현을 도입해요.
from langchain_anthropic import ChatAnthropic
model = ChatAnthropic(model="claude-sonnet-4-6")
response = model.invoke("What's the capital of France?")
# Unified access to content blocks
for block in response.content_blocks:
if block["type"] == "reasoning":
print(f"Model reasoning: {block['reasoning']}")
elif block["type"] == "text":
print(f"Response: {block['text']}")
elif block["type"] == "tool_call":
print(f"Tool call: {block['name']}({block['args']})")
이점
- 제공자 무관(Provider agnostic) — 추론 트레이스, 인용, 내장 도구(웹 검색·코드 인터프리터 등) 등을 제공자와 무관하게 같은 API로 접근
- 타입 세이프 — 모든 콘텐츠 블록 타입에 대한 완전한 타입 힌트
- 하위 호환 — 표준 콘텐츠를 지연 로드할 수 있어 파괴적인 변경 없음
간소화된 패키지
LangChain v1은 langchain 패키지 네임스페이스를 에이전트 필수 빌딩 블록 중심으로 다듬었어요. 가장 유용하고 관련성 높은 기능을 노출하지요.
| 모듈 | 제공 내용 | 비고 |
|---|---|---|
langchain.agents |
create_agent, AgentState |
에이전트 생성 핵심 기능 |
langchain.messages |
메시지 타입, 콘텐츠 블록, trim_messages |
langchain-core에서 재수출 |
langchain.tools |
@tool, BaseTool, 주입 헬퍼 |
langchain-core에서 재수출 |
langchain.chat_models |
init_chat_model, BaseChatModel |
통합 모델 초기화 |
langchain.embeddings |
Embeddings, init_embeddings |
임베딩 모델 |
대부분 langchain-core에서 편의를 위해 재수출된 것들이라, 에이전트 구축에 집중된 API 표면을 제공해요.
# Agent building
from langchain.agents import create_agent
# Messages and content
from langchain.messages import AIMessage, HumanMessage
# Tools
from langchain.tools import tool
# Model initialization
from langchain.chat_models import init_chat_model
from langchain.embeddings import init_embeddings
langchain-classic
레거시 기능은 코어 패키지를 가볍고 집중적으로 유지하기 위해 langchain-classic으로 이동했어요. 여기에 들어 있는 것들:
- 레거시 체인과 체인 구현
- 검색기(retrievers, 예:
MultiQueryRetriever또는 기존langchain.retrievers모듈의 것들) - indexing API
hub모듈(프롬프트를 프로그래매틱하게 관리)langchain-communityexport- 그 외 폐기된 기능
이 기능들을 쓴다면 langchain-classic을 설치하고:
pip install langchain-classic
(uv 사용 시 uv add langchain-classic)
import를 갱신해요:
from langchain import ...
from langchain_classic import ...
from langchain.chains import ...
from langchain_classic.chains import ...
from langchain.retrievers import ...
from langchain_classic.retrievers import ...
from langchain import hub
from langchain_classic import hub
마이그레이션과 이슈
코드를 LangChain v1로 갱신할 때는 마이그레이션 가이드를 참고하세요. 1.0에서 발견한 이슈는 GitHub에서 v1 라벨을 붙여 보고해 주세요.
더 알아보기 (Learn more)
- LangChain 1.0 발표 문서와 미들웨어 가이드
- Agents 문서와 Message Content(새 콘텐츠 블록 API)
- 버저닝과 릴리스 정책 문서