langchain / / 2025. 11. 8. 21:14

[LangChain v1.0] Runtime

Overview

LangChain의 create_agent는 내부적으로 LangGraph의 runtime 위에서 실행됩니다.

LangGraph는 다음 정보를 포함하는 Runtime 객체를 제공합니다:

  • Context: 사용자 ID, 데이터베이스 연결 또는 에이전트 호출을 위한 기타 종속성과 같은 정적 정보
  • Store: 장기 메모리에 사용되는 BaseStore 인스턴스
  • Stream writer: "custom" 스트림 모드를 통해 정보를 스트리밍하는 데 사용되는 객체

도구미들웨어 내에서 runtime 정보에 접근할 수 있습니다.

Access

create_agent로 에이전트를 생성할 때, 에이전트 Runtime에 저장된 context의 구조를 정의하기 위해 context_schema를 지정할 수 있습니다.

에이전트를 호출할 때, 실행에 대한 관련 설정과 함께 context 인수를 전달합니다:

from dataclasses import dataclass

from langchain.agents import create_agent


@dataclass
class Context:
    user_name: str

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

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

Inside tools

도구 내에서 runtime 정보에 접근하여 다음을 수행할 수 있습니다:

  • context 접근
  • 장기 메모리 읽기 또는 쓰기
  • custom stream에 쓰기 (예: 도구 진행 상황 / 업데이트)

도구 내에서 Runtime 객체에 접근하려면 ToolRuntime 매개변수를 사용합니다.

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

Inside middleware

미들웨어에서 runtime 정보에 접근하여 동적 프롬프트를 생성하거나, 메시지를 수정하거나, 사용자 컨텍스트를 기반으로 에이전트 동작을 제어할 수 있습니다.

미들웨어 데코레이터 내에서 Runtime 객체에 접근하려면 request.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="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")
)

출처: https://docs.langchain.com/oss/python/langchain/runtime


Langchain v1.0

반응형
  • 네이버 블로그 공유
  • 네이버 밴드 공유
  • 페이스북 공유
  • 카카오스토리 공유