개요

LangChain의 create_agent는 내부적으로 LangGraph의 runtime에서 실행됩니다. LangGraph는 다음 정보를 포함하는 Runtime 객체를 제공합니다:
  1. Context: 사용자 ID, 데이터베이스 연결 또는 에이전트 호출을 위한 기타 종속성과 같은 정적 정보
  2. Store: 장기 메모리에 사용되는 BaseStore 인스턴스
  3. Stream writer: "custom" stream mode를 통해 정보를 스트리밍하는 데 사용되는 객체
도구미들웨어 내에서 runtime 정보에 액세스할 수 있습니다.

액세스

create_agent로 에이전트를 생성할 때, context_schema를 지정하여 에이전트 Runtime에 저장된 context의 구조를 정의할 수 있습니다. 에이전트를 호출할 때, 실행에 필요한 구성과 함께 context 인수를 전달합니다:
from dataclasses import dataclass

from langchain.agents import create_agent


@dataclass
class Context:
    user_name: str

agent = create_agent(
    model="openai:gpt-5-nano",
    tools=[...],
    context_schema=Context  
)

agent.invoke(
    {"messages": [{"role": "user", "content": "What's my name?"}]},
    context=Context(user_name="John Smith")  
)

도구 내부

도구 내부에서 runtime 정보에 액세스하여 다음을 수행할 수 있습니다:
  • context에 액세스
  • 장기 메모리 읽기 또는 쓰기
  • custom stream에 쓰기 (예: 도구 진행 상황 / 업데이트)
ToolRuntime 매개변수를 사용하여 도구 내부에서 Runtime 객체에 액세스합니다.
from dataclasses import dataclass
from langchain.tools import tool, ToolRuntime  

@dataclass
class Context:
    user_id: str

@tool
def fetch_user_email_preferences(runtime: ToolRuntime[Context]) -> str:  
    """Fetch the user's email preferences from the store."""
    user_id = runtime.context.user_id  

    preferences: str = "The user prefers you to write a brief and polite email."
    if runtime.store:  
        if memory := runtime.store.get(("users",), user_id):  
            preferences = memory.value["preferences"]

    return preferences

미들웨어 내부

미들웨어에서 runtime 정보에 액세스하여 동적 프롬프트를 생성하거나, 메시지를 수정하거나, 사용자 context를 기반으로 에이전트 동작을 제어할 수 있습니다. request.runtime을 사용하여 미들웨어 데코레이터 내부에서 Runtime 객체에 액세스합니다. runtime 객체는 미들웨어 함수에 전달되는 ModelRequest 매개변수에서 사용할 수 있습니다.
from dataclasses import dataclass

from langchain.messages import AnyMessage
from langchain.agents import create_agent, AgentState
from langchain.agents.middleware import dynamic_prompt, ModelRequest, before_model, after_model
from langgraph.runtime import Runtime


@dataclass
class Context:
    user_name: str

# Dynamic prompts
@dynamic_prompt
def dynamic_system_prompt(request: ModelRequest) -> str:
    user_name = request.runtime.context.user_name  
    system_prompt = f"You are a helpful assistant. Address the user as {user_name}."
    return system_prompt

# Before model hook
@before_model
def log_before_model(state: AgentState, runtime: Runtime[Context]) -> dict | None:  
    print(f"Processing request for user: {runtime.context.user_name}")  
    return None

# After model hook
@after_model
def log_after_model(state: AgentState, runtime: Runtime[Context]) -> dict | None:  
    print(f"Completed request for user: {runtime.context.user_name}")  
    return None

agent = create_agent(
    model="openai:gpt-5-nano",
    tools=[...],
    middleware=[dynamic_system_prompt, log_before_model, log_after_model],  
    context_schema=Context
)

agent.invoke(
    {"messages": [{"role": "user", "content": "What's my name?"}]},
    context=Context(user_name="John Smith")
)

Connect these docs programmatically to Claude, VSCode, and more via MCP for real-time answers.
I