Skip to main content
LLM은 인간처럼 텍스트를 해석하고 생성할 수 있는 강력한 AI 도구입니다. 콘텐츠 작성, 언어 번역, 요약, 질문 답변 등 각 작업에 대한 전문적인 훈련 없이도 다양한 작업을 수행할 수 있습니다. 텍스트 생성 외에도 많은 모델이 다음 기능을 지원합니다: 모델은 agent(에이전트)의 추론 엔진입니다. 어떤 도구를 호출할지, 결과를 어떻게 해석할지, 언제 최종 답변을 제공할지 결정하는 에이전트의 의사결정 프로세스를 주도합니다. 선택하는 모델의 품질과 기능은 에이전트의 신뢰성과 성능에 직접적인 영향을 미칩니다. 모델마다 뛰어난 작업이 다릅니다. 복잡한 지시사항을 따르는 데 뛰어난 모델도 있고, 구조화된 추론에 능한 모델도 있으며, 더 많은 정보를 처리하기 위해 더 큰 context window(컨텍스트 윈도우)를 지원하는 모델도 있습니다. LangChain의 표준 모델 인터페이스는 다양한 제공업체 통합에 대한 액세스를 제공하므로 모델을 쉽게 실험하고 전환하여 사용 사례에 가장 적합한 모델을 찾을 수 있습니다.
제공업체별 통합 정보 및 기능에 대해서는 해당 제공업체의 통합 페이지를 참조하세요.

기본 사용법

모델은 두 가지 방식으로 활용할 수 있습니다:
  1. 에이전트와 함께 - agent(에이전트)를 생성할 때 모델을 동적으로 지정할 수 있습니다.
  2. 독립 실행형 - 에이전트 프레임워크 없이 텍스트 생성, 분류 또는 추출과 같은 작업을 위해 모델을 직접(에이전트 루프 외부에서) 호출할 수 있습니다.
두 컨텍스트 모두에서 동일한 모델 인터페이스가 작동하므로 간단하게 시작하여 필요에 따라 더 복잡한 에이전트 기반 워크플로우로 확장할 수 있는 유연성을 제공합니다.

모델 초기화

LangChain에서 독립 실행형 모델을 시작하는 가장 쉬운 방법은 init_chat_model을 사용하여 선택한 provider(제공업체)에서 모델을 초기화하는 것입니다(아래 예시):
👉 Read the OpenAI chat model integration docs
pip install -U "langchain[openai]"
import os
from langchain.chat_models import init_chat_model

os.environ["OPENAI_API_KEY"] = "sk-..."

model = init_chat_model("openai:gpt-4.1")
response = model.invoke("Why do parrots talk?")
자세한 내용은 init_chat_model을 참조하세요. 모델 parameter(매개변수)를 전달하는 방법에 대한 정보도 포함되어 있습니다.

주요 메서드

Invoke

모델은 메시지를 입력으로 받아 완전한 응답을 생성한 후 메시지를 출력합니다.

Stream

모델을 호출하되, 실시간으로 생성되는 출력을 스트리밍합니다.

Batch

여러 요청을 일괄 처리하여 모델에 전송하여 더 효율적으로 처리합니다.
chat model(채팅 모델) 외에도 LangChain은 embedding model(임베딩 모델) 및 vector store(벡터 저장소)와 같은 인접 기술에 대한 지원을 제공합니다. 자세한 내용은 통합 페이지를 참조하세요.

Parameter(매개변수)

chat model(채팅 모델)은 동작을 구성하는 데 사용할 수 있는 매개변수를 사용합니다. 지원되는 매개변수의 전체 집합은 모델 및 제공업체에 따라 다르지만 표준 매개변수는 다음과 같습니다:
model
string
required
제공업체와 함께 사용하려는 특정 모델의 이름 또는 식별자입니다.
api_key
string
모델 제공업체의 인증에 필요한 키입니다. 일반적으로 모델에 대한 액세스 권한을 등록할 때 발급됩니다. 을 설정하여 액세스하는 경우가 많습니다.
temperature
number
모델 출력의 무작위성을 제어합니다. 높은 값은 응답을 더 창의적으로 만들고, 낮은 값은 더 결정적으로 만듭니다.
timeout
number
요청을 취소하기 전에 모델의 응답을 기다리는 최대 시간(초)입니다.
max_tokens
number
응답의 총 수를 제한하여 출력 길이를 효과적으로 제어합니다.
max_retries
number
네트워크 시간 초과 또는 rate limit(속도 제한)과 같은 문제로 인해 요청이 실패할 경우 시스템이 요청을 재전송하는 최대 시도 횟수입니다.
init_chat_model을 사용하여 이러한 매개변수를 인라인 로 전달합니다:
Initialize using model parameters
model = init_chat_model(
    "anthropic:claude-sonnet-4-5",
    # Kwargs passed to the model:
    temperature=0.7,
    timeout=30,
    max_tokens=1000,
)
각 chat model(채팅 모델) 통합에는 제공업체별 기능을 제어하는 데 사용되는 추가 매개변수가 있을 수 있습니다. 예를 들어, ChatOpenAI에는 OpenAI Responses API 또는 Completions API를 사용할지 여부를 결정하는 use_responses_api가 있습니다.특정 채팅 모델이 지원하는 모든 매개변수를 찾으려면 채팅 모델 통합 페이지로 이동하세요.

Invocation(호출)

chat model(채팅 모델)은 출력을 생성하기 위해 호출되어야 합니다. 각각 다른 사용 사례에 적합한 세 가지 주요 호출 메서드가 있습니다.

Invoke

모델을 호출하는 가장 간단한 방법은 단일 메시지 또는 메시지 목록과 함께 invoke()를 사용하는 것입니다.
Single message
response = model.invoke("Why do parrots have colorful feathers?")
print(response)
대화 기록을 나타내기 위해 모델에 메시지 목록을 제공할 수 있습니다. 각 메시지에는 모델이 대화에서 메시지를 보낸 사람을 나타내는 데 사용하는 role(역할)이 있습니다. role, type 및 content에 대한 자세한 내용은 message(메시지) 가이드를 참조하세요.
Dictionary format
from langchain.messages import HumanMessage, AIMessage, SystemMessage

conversation = [
    {"role": "system", "content": "You are a helpful assistant that translates English to French."},
    {"role": "user", "content": "Translate: I love programming."},
    {"role": "assistant", "content": "J'adore la programmation."},
    {"role": "user", "content": "Translate: I love building applications."}
]

response = model.invoke(conversation)
print(response)  # AIMessage("J'adore créer des applications.")
Message objects
from langchain_core.messages import HumanMessage, AIMessage, SystemMessage

conversation = [
    SystemMessage("You are a helpful assistant that translates English to French."),
    HumanMessage("Translate: I love programming."),
    AIMessage("J'adore la programmation."),
    HumanMessage("Translate: I love building applications.")
]

response = model.invoke(conversation)
print(response)  # AIMessage("J'adore créer des applications.")

Stream

대부분의 모델은 생성되는 동안 출력 콘텐츠를 스트리밍할 수 있습니다. 출력을 점진적으로 표시함으로써 스트리밍은 특히 긴 응답의 경우 사용자 경험을 크게 향상시킵니다. stream()을 호출하면 생성되는 출력 청크를 생성하는 를 반환합니다. 루프를 사용하여 각 청크를 실시간으로 처리할 수 있습니다:
for chunk in model.stream("Why do parrots have colorful feathers?"):
    print(chunk.text, end="|", flush=True)
모델이 전체 응답을 생성한 후 단일 AIMessage를 반환하는 invoke()와 달리, stream()은 각각 출력 텍스트의 일부를 포함하는 여러 AIMessageChunk 객체를 반환합니다. 중요한 점은 스트림의 각 청크가 합산을 통해 전체 메시지로 수집되도록 설계되었다는 것입니다:
Construct an AIMessage
full = None  # None | AIMessageChunk
for chunk in model.stream("What color is the sky?"):
    full = chunk if full is None else full + chunk
    print(full.text)

# The
# The sky
# The sky is
# The sky is typically
# The sky is typically blue
# ...

print(full.content_blocks)
# [{"type": "text", "text": "The sky is typically blue..."}]
결과 메시지는 invoke()로 생성된 메시지와 동일하게 처리할 수 있습니다. 예를 들어 메시지 기록에 집계하여 대화 컨텍스트로 모델에 다시 전달할 수 있습니다.
스트리밍은 프로그램의 모든 단계가 청크 스트림을 처리하는 방법을 알고 있는 경우에만 작동합니다. 예를 들어, 스트리밍이 불가능한 애플리케이션은 처리하기 전에 전체 출력을 메모리에 저장해야 하는 애플리케이션입니다.
LangChain은 스트리밍 메서드를 명시적으로 호출하지 않더라도 특정 경우에 스트리밍 모드를 자동으로 활성화하여 chat model(채팅 모델)에서 스트리밍을 단순화합니다. 이는 비스트리밍 invoke 메서드를 사용하지만 여전히 채팅 모델의 중간 결과를 포함하여 전체 애플리케이션을 스트리밍하려는 경우 특히 유용합니다.예를 들어, LangGraph agent(에이전트)에서 노드 내에서 model.invoke()를 호출할 수 있지만, LangChain은 스트리밍 모드에서 실행 중인 경우 자동으로 스트리밍으로 위임합니다.

작동 방식

chat model(채팅 모델)을 invoke()할 때, LangChain은 전체 애플리케이션을 스트리밍하려는 것을 감지하면 자동으로 내부 스트리밍 모드로 전환합니다. invoke를 사용하는 코드에 관한 한 호출 결과는 동일하지만, 채팅 모델이 스트리밍되는 동안 LangChain은 LangChain의 callback system(콜백 시스템)에서 on_llm_new_token 이벤트를 호출합니다.Callback event(콜백 이벤트)를 통해 LangGraph stream()astream_events()가 실시간으로 채팅 모델의 출력을 표시할 수 있습니다.
LangChain chat model(채팅 모델)은 astream_events()를 사용하여 semantic event(의미론적 이벤트)를 스트리밍할 수도 있습니다.이는 이벤트 유형 및 기타 메타데이터를 기반으로 필터링을 단순화하고 백그라운드에서 전체 메시지를 집계합니다. 아래 예제를 참조하세요.
async for event in model.astream_events("Hello"):

    if event["event"] == "on_chat_model_start":
        print(f"Input: {event['data']['input']}")

    elif event["event"] == "on_chat_model_stream":
        print(f"Token: {event['data']['chunk'].text}")

    elif event["event"] == "on_chat_model_end":
        print(f"Full message: {event['data']['output'].text}")

    else:
        pass
Input: Hello
Token: Hi
Token:  there
Token: !
Token:  How
Token:  can
Token:  I
...
Full message: Hi there! How can I help today?
이벤트 유형 및 기타 세부 정보는 astream_events() 참조를 확인하세요.

Batch

독립적인 요청 컬렉션을 모델에 일괄 처리하면 처리를 병렬로 수행할 수 있으므로 성능을 크게 향상시키고 비용을 절감할 수 있습니다:
Batch
responses = model.batch([
    "Why do parrots have colorful feathers?",
    "How do airplanes fly?",
    "What is quantum computing?"
])
for response in responses:
    print(response)
이 섹션에서는 클라이언트 측에서 모델 호출을 병렬화하는 chat model(채팅 모델) 메서드 batch()에 대해 설명합니다.이는 OpenAI 또는 Anthropic과 같은 추론 제공업체가 지원하는 batch API(일괄 처리 API)와는 구별됩니다.
기본적으로 batch()는 전체 배치에 대한 최종 출력만 반환합니다. 각 개별 입력이 생성을 완료할 때 출력을 받으려면 batch_as_completed()로 결과를 스트리밍할 수 있습니다:
Yield batch responses upon completion
for response in model.batch_as_completed([
    "Why do parrots have colorful feathers?",
    "How do airplanes fly?",
    "What is quantum computing?"
]):
    print(response)
batch_as_completed()를 사용할 때 결과가 순서 없이 도착할 수 있습니다. 각각에는 필요에 따라 원래 순서를 재구성하기 위해 일치시키는 입력 인덱스가 포함됩니다.
batch() 또는 batch_as_completed()를 사용하여 많은 수의 입력을 처리할 때 최대 병렬 호출 수를 제어할 수 있습니다. 이는 RunnableConfig 딕셔너리에서 max_concurrency 속성을 설정하여 수행할 수 있습니다.
Batch with max concurrency
model.batch(
    list_of_inputs,
    config={
        'max_concurrency': 5,  # Limit to 5 parallel calls
    }
)
지원되는 속성의 전체 목록은 RunnableConfig 참조를 확인하세요.
일괄 처리에 대한 자세한 내용은 reference를 참조하세요.

Tool calling(도구 호출)

모델은 데이터베이스에서 데이터 가져오기, 웹 검색 또는 코드 실행과 같은 작업을 수행하는 도구를 호출하도록 요청할 수 있습니다. Tool(도구)은 다음으로 구성됩니다:
  1. 도구 이름, 설명 및/또는 인수 정의(종종 JSON schema(스키마))를 포함하는 schema(스키마)
  2. 실행할 function(함수) 또는
“function calling(함수 호출)“이라는 용어를 들을 수 있습니다. 우리는 이를 “tool calling(도구 호출)“과 같은 의미로 사용합니다.
정의한 도구를 모델에서 사용할 수 있도록 하려면 bind_tools()를 사용하여 바인딩해야 합니다. 후속 호출에서 모델은 필요에 따라 바인딩된 도구 중 하나를 호출하도록 선택할 수 있습니다. 일부 모델 제공업체는 모델 또는 호출 매개변수를 통해 활성화할 수 있는 기본 제공 도구를 제공합니다(예: ChatOpenAI, ChatAnthropic). 자세한 내용은 해당 provider reference(제공업체 참조)를 확인하세요.
도구 생성에 대한 세부 정보 및 기타 옵션은 도구 가이드를 참조하세요.
Binding user tools
from langchain.tools import tool

@tool
def get_weather(location: str) -> str:
    """Get the weather at a location."""
    return f"It's sunny in {location}."


model_with_tools = model.bind_tools([get_weather])  

response = model_with_tools.invoke("What's the weather like in Boston?")
for tool_call in response.tool_calls:
    # View tool calls made by the model
    print(f"Tool: {tool_call['name']}")
    print(f"Args: {tool_call['args']}")
사용자 정의 도구를 바인딩할 때 모델의 응답에는 도구 실행에 대한 요청이 포함됩니다. agent(에이전트)와 별도로 모델을 사용하는 경우, 요청된 작업을 수행하고 후속 추론에 사용할 수 있도록 결과를 모델에 반환하는 것은 사용자의 책임입니다. agent(에이전트)를 사용하는 경우 에이전트 루프가 도구 실행 루프를 처리합니다. 아래에서는 tool calling(도구 호출)을 사용할 수 있는 몇 가지 일반적인 방법을 보여줍니다.
모델이 tool call(도구 호출)을 반환하면 도구를 실행하고 결과를 모델에 다시 전달해야 합니다. 이렇게 하면 모델이 도구 결과를 사용하여 최종 응답을 생성할 수 있는 대화 루프가 생성됩니다. LangChain에는 이러한 오케스트레이션을 처리하는 agent(에이전트) 추상화가 포함되어 있습니다.다음은 간단한 예입니다:
Tool execution loop
# Bind (potentially multiple) tools to the model
model_with_tools = model.bind_tools([get_weather])

# Step 1: Model generates tool calls
messages = [{"role": "user", "content": "What's the weather in Boston?"}]
ai_msg = model_with_tools.invoke(messages)
messages.append(ai_msg)

# Step 2: Execute tools and collect results
for tool_call in ai_msg.tool_calls:
    # Execute the tool with the generated arguments
    tool_result = get_weather.invoke(tool_call)
    messages.append(tool_result)

# Step 3: Pass results back to model for final response
final_response = model_with_tools.invoke(messages)
print(final_response.text)
# "The current weather in Boston is 72°F and sunny."
도구가 반환한 각 ToolMessage에는 원래 도구 호출과 일치하는 tool_call_id가 포함되어 있어 모델이 결과를 요청과 연관시키는 데 도움이 됩니다.
기본적으로 모델은 사용자 입력을 기반으로 사용할 바인딩된 도구를 자유롭게 선택할 수 있습니다. 그러나 모델이 특정 도구 또는 주어진 목록의 모든 도구 중 하나를 사용하도록 도구 선택을 강제할 수 있습니다:
model_with_tools = model.bind_tools([tool_1], tool_choice="any")
많은 모델이 적절한 경우 여러 도구를 병렬로 호출하는 것을 지원합니다. 이를 통해 모델이 동시에 다른 소스에서 정보를 수집할 수 있습니다.
Parallel tool calls
model_with_tools = model.bind_tools([get_weather])

response = model_with_tools.invoke(
    "What's the weather in Boston and Tokyo?"
)


# The model may generate multiple tool calls
print(response.tool_calls)
# [
#   {'name': 'get_weather', 'args': {'location': 'Boston'}, 'id': 'call_1'},
#   {'name': 'get_weather', 'args': {'location': 'Tokyo'}, 'id': 'call_2'},
# ]


# Execute all tools (can be done in parallel with async)
results = []
for tool_call in response.tool_calls:
    if tool_call['name'] == 'get_weather':
        result = get_weather.invoke(tool_call)
    ...
    results.append(result)
모델은 요청된 작업의 독립성을 기반으로 병렬 실행이 적절한 시기를 지능적으로 결정합니다.
tool calling(도구 호출)을 지원하는 대부분의 모델은 기본적으로 parallel tool call(병렬 도구 호출)을 활성화합니다. 일부(OpenAIAnthropic 포함)는 이 기능을 비활성화할 수 있습니다. 이렇게 하려면 parallel_tool_calls=False를 설정하세요:
model.bind_tools([get_weather], parallel_tool_calls=False)
응답을 스트리밍할 때 도구 호출은 ToolCallChunk를 통해 점진적으로 구축됩니다. 이를 통해 완전한 응답을 기다리지 않고 도구 호출이 생성될 때 확인할 수 있습니다.
Streaming tool calls
for chunk in model_with_tools.stream(
    "What's the weather in Boston and Tokyo?"
):
    # Tool call chunks arrive progressively
    for tool_chunk in chunk.tool_call_chunks:
        if name := tool_chunk.get("name"):
            print(f"Tool: {name}")
        if id_ := tool_chunk.get("id"):
            print(f"ID: {id_}")
        if args := tool_chunk.get("args"):
            print(f"Args: {args}")

# Output:
# Tool: get_weather
# ID: call_SvMlU1TVIZugrFLckFE2ceRE
# Args: {"lo
# Args: catio
# Args: n": "B
# Args: osto
# Args: n"}
# Tool: get_weather
# ID: call_QMZdy6qInx13oWKE7KhuhOLR
# Args: {"lo
# Args: catio
# Args: n": "T
# Args: okyo
# Args: "}
청크를 누적하여 완전한 도구 호출을 구축할 수 있습니다:
Accumulate tool calls
gathered = None
for chunk in model_with_tools.stream("What's the weather in Boston?"):
    gathered = chunk if gathered is None else gathered + chunk
    print(gathered.tool_calls)

Structured output(구조화된 출력)

모델은 주어진 schema(스키마)와 일치하는 형식으로 응답을 제공하도록 요청할 수 있습니다. 이는 출력을 쉽게 구문 분석하고 후속 처리에 사용할 수 있도록 하는 데 유용합니다. LangChain은 구조화된 출력을 적용하기 위한 여러 스키마 유형과 메서드를 지원합니다.
Pydantic model(모델)은 필드 유효성 검사, 설명 및 중첩된 구조를 갖춘 가장 풍부한 기능 세트를 제공합니다.
from pydantic import BaseModel, Field

class Movie(BaseModel):
    """A movie with details."""
    title: str = Field(..., description="The title of the movie")
    year: int = Field(..., description="The year the movie was released")
    director: str = Field(..., description="The director of the movie")
    rating: float = Field(..., description="The movie's rating out of 10")

model_with_structure = model.with_structured_output(Movie)
response = model_with_structure.invoke("Provide details about the movie Inception")
print(response)  # Movie(title="Inception", year=2010, director="Christopher Nolan", rating=8.8)
구조화된 출력에 대한 주요 고려 사항:
  • Method parameter(메서드 매개변수): 일부 제공업체는 다양한 메서드('json_schema', 'function_calling', 'json_mode')를 지원합니다
    • 'json_schema'는 일반적으로 제공업체가 제공하는 전용 구조화된 출력 기능을 나타냅니다
    • 'function_calling'은 주어진 스키마를 따르는 tool call(도구 호출)을 강제하여 구조화된 출력을 파생합니다
    • 'json_mode'는 일부 제공업체가 제공하는 'json_schema'의 전신입니다. 유효한 json을 생성하지만 스키마는 prompt(프롬프트)에 설명되어야 합니다
  • Include raw: include_raw=True를 사용하여 구문 분석된 출력과 원시 AI 메시지를 모두 얻습니다
  • Validation(유효성 검사): Pydantic 모델은 자동 유효성 검사를 제공하는 반면 TypedDict 및 JSON Schema는 수동 유효성 검사가 필요합니다
원시 AIMessage 객체를 구문 분석된 표현과 함께 반환하여 token count(토큰 수)와 같은 응답 메타데이터에 액세스하는 것이 유용할 수 있습니다. 이렇게 하려면 with_structured_output을 호출할 때 include_raw=True를 설정하세요:
from pydantic import BaseModel, Field

class Movie(BaseModel):
    """A movie with details."""
    title: str = Field(..., description="The title of the movie")
    year: int = Field(..., description="The year the movie was released")
    director: str = Field(..., description="The director of the movie")
    rating: float = Field(..., description="The movie's rating out of 10")

model_with_structure = model.with_structured_output(Movie, include_raw=True)  
response = model_with_structure.invoke("Provide details about the movie Inception")
response
# {
#     "raw": AIMessage(...),
#     "parsed": Movie(title=..., year=..., ...),
#     "parsing_error": None,
# }
스키마는 중첩될 수 있습니다:
from pydantic import BaseModel, Field

class Actor(BaseModel):
    name: str
    role: str

class MovieDetails(BaseModel):
    title: str
    year: int
    cast: list[Actor]
    genres: list[str]
    budget: float | None = Field(None, description="Budget in millions USD")

model_with_structure = model.with_structured_output(MovieDetails)

Supported models(지원되는 모델)

LangChain은 OpenAI, Anthropic, Google, Azure, AWS Bedrock 등을 포함한 모든 주요 모델 제공업체를 지원합니다. 각 제공업체는 다양한 기능을 가진 다양한 모델을 제공합니다. LangChain에서 지원되는 모델의 전체 목록은 통합 페이지를 참조하세요.

고급 주제

Multimodal(멀티모달)

특정 모델은 이미지, 오디오 및 비디오와 같은 비텍스트 데이터를 처리하고 반환할 수 있습니다. content block(콘텐츠 블록)을 제공하여 모델에 비텍스트 데이터를 전달할 수 있습니다.
기본 multimodal(멀티모달) 기능이 있는 모든 LangChain chat model(채팅 모델)은 다음을 지원합니다:
  1. cross-provider(교차 제공업체) 표준 형식의 데이터(메시지 가이드 참조)
  2. OpenAI chat completions(채팅 완료) 형식
  3. 특정 제공업체에 고유한 형식(예: Anthropic 모델은 Anthropic 고유 형식을 허용)
자세한 내용은 메시지 가이드의 multimodal section(멀티모달 섹션)을 참조하세요. 은 응답의 일부로 멀티모달 데이터를 반환할 수 있습니다. 그렇게 호출된 경우 결과 AIMessage에는 멀티모달 유형의 content block(콘텐츠 블록)이 포함됩니다.
Multimodal output
response = model.invoke("Create a picture of a cat")
print(response.content_blocks)
# [
#     {"type": "text", "text": "Here's a picture of a cat"},
#     {"type": "image", "base64": "...", "mime_type": "image/jpeg"},
# ]
특정 제공업체에 대한 자세한 내용은 통합 페이지를 참조하세요.

Reasoning(추론)

최신 모델은 결론에 도달하기 위해 다단계 추론을 수행할 수 있습니다. 여기에는 복잡한 문제를 더 작고 관리하기 쉬운 단계로 나누는 작업이 포함됩니다. 기본 모델이 지원하는 경우 이 추론 프로세스를 표시하여 모델이 최종 답변에 어떻게 도달했는지 더 잘 이해할 수 있습니다.
for chunk in model.stream("Why do parrots have colorful feathers?"):
    reasoning_steps = [r for r in chunk.content_blocks if r["type"] == "reasoning"]
    print(reasoning_steps if reasoning_steps else chunk.text)
모델에 따라 추론에 투입해야 하는 노력 수준을 지정할 수 있는 경우가 있습니다. 마찬가지로 모델이 추론을 완전히 끄도록 요청할 수 있습니다. 이는 추론의 범주형 “tier(계층)“(예: 'low' 또는 'high') 또는 정수 token budget(토큰 예산) 형태를 취할 수 있습니다. 자세한 내용은 해당 채팅 모델의 통합 페이지 또는 reference(참조)를 참조하세요.

Local models(로컬 모델)

LangChain은 자체 하드웨어에서 로컬로 모델을 실행하는 것을 지원합니다. 이는 데이터 프라이버시가 중요하거나, 사용자 정의 모델을 호출하거나, 클라우드 기반 모델을 사용할 때 발생하는 비용을 피하려는 시나리오에 유용합니다. Ollama는 로컬로 모델을 실행하는 가장 쉬운 방법 중 하나입니다. 로컬 통합의 전체 목록은 통합 페이지를 참조하세요.

Prompt caching(프롬프트 캐싱)

많은 제공업체는 동일한 token(토큰)의 반복 처리에 대한 latency(지연 시간)와 비용을 줄이기 위해 prompt caching(프롬프트 캐싱) 기능을 제공합니다. 이러한 기능은 implicit(암시적) 또는 **explicit(명시적)**일 수 있습니다:
  • Implicit prompt caching(암시적 프롬프트 캐싱): 요청이 cache(캐시)에 도달하면 제공업체가 자동으로 비용 절감을 전달합니다. 예: OpenAIGemini (Gemini 2.5 이상).
  • Explicit caching(명시적 캐싱): 제공업체를 통해 더 큰 제어를 위해 또는 비용 절감을 보장하기 위해 cache point(캐시 포인트)를 수동으로 표시할 수 있습니다. 예: ChatOpenAI (prompt_cache_key를 통해), Anthropic의 AnthropicPromptCachingMiddlewarecache_control 옵션, AWS Bedrock, Gemini.
프롬프트 캐싱은 최소 입력 token(토큰) 임계값을 초과하는 경우에만 작동하는 경우가 많습니다. 자세한 내용은 제공업체 페이지를 참조하세요.
캐시 사용은 모델 응답의 usage metadata(사용 메타데이터)에 반영됩니다.

Server-side tool use(서버 측 도구 사용)

일부 제공업체는 서버 측 tool-calling(도구 호출) 루프를 지원합니다. 모델은 web search(웹 검색), code interpreter(코드 인터프리터) 및 기타 도구와 상호 작용하고 단일 대화 턴에서 결과를 분석할 수 있습니다. 모델이 서버 측에서 도구를 호출하면 응답 메시지의 content(콘텐츠)에는 도구의 호출 및 결과를 나타내는 콘텐츠가 포함됩니다. 응답의 content block(콘텐츠 블록)에 액세스하면 제공업체에 구애받지 않는 형식으로 서버 측 도구 호출 및 결과가 반환됩니다:
Invoke with server-side tool use
from langchain.chat_models import init_chat_model

model = init_chat_model("openai:gpt-4.1-mini")

tool = {"type": "web_search"}
model_with_tools = model.bind_tools([tool])

response = model_with_tools.invoke("What was a positive news story from today?")
response.content_blocks
Result
[
    {
        "type": "server_tool_call",
        "name": "web_search",
        "args": {
            "query": "positive news stories today",
            "type": "search"
        },
        "id": "ws_abc123"
    },
    {
        "type": "server_tool_result",
        "tool_call_id": "ws_abc123",
        "status": "success"
    },
    {
        "type": "text",
        "text": "Here are some positive news stories from today...",
        "annotations": [
            {
                "end_index": 410,
                "start_index": 337,
                "title": "article title",
                "type": "citation",
                "url": "..."
            }
        ]
    }
]
이는 단일 대화 턴을 나타냅니다. 클라이언트 측 tool-calling(도구 호출)에서처럼 전달해야 하는 관련 ToolMessage 객체가 없습니다. 사용 가능한 도구 및 사용 세부 정보는 해당 제공업체의 통합 페이지를 참조하세요.

Rate limiting(속도 제한)

많은 chat model(채팅 모델) 제공업체는 주어진 기간 동안 수행할 수 있는 호출 수에 제한을 부과합니다. rate limit(속도 제한)에 도달하면 일반적으로 제공업체로부터 rate limit error(속도 제한 오류) 응답을 받게 되며 더 많은 요청을 하기 전에 기다려야 합니다. rate limit(속도 제한)을 관리하는 데 도움이 되도록 chat model(채팅 모델) 통합은 초기화 중에 제공할 수 있는 rate_limiter 매개변수를 허용하여 요청이 이루어지는 속도를 제어합니다.
LangChain에는 (선택 사항) 기본 제공 InMemoryRateLimiter가 함께 제공됩니다. 이 제한기는 thread-safe(스레드 안전)하며 동일한 프로세스의 여러 스레드에서 공유할 수 있습니다.
Define a rate limiter
from langchain_core.rate_limiters import InMemoryRateLimiter

rate_limiter = InMemoryRateLimiter(
    requests_per_second=0.1,  # 1 request every 10s
    check_every_n_seconds=0.1,  # Check every 100ms whether allowed to make a request
    max_bucket_size=10,  # Controls the maximum burst size.
)

model = init_chat_model(
    model="gpt-5",
    model_provider="openai",
    rate_limiter=rate_limiter  
)
제공된 rate limiter(속도 제한기)는 단위 시간당 요청 수만 제한할 수 있습니다. 요청 크기를 기반으로 제한해야 하는 경우에는 도움이 되지 않습니다.

Base URL or proxy(기본 URL 또는 프록시)

많은 chat model(채팅 모델) 통합의 경우 API 요청에 대한 base URL(기본 URL)을 구성할 수 있으므로 OpenAI 호환 API가 있는 모델 제공업체를 사용하거나 proxy server(프록시 서버)를 사용할 수 있습니다.
많은 모델 제공업체가 OpenAI 호환 API(예: Together AI, vLLM)를 제공합니다. 적절한 base_url 매개변수를 지정하여 이러한 제공업체와 함께 init_chat_model을 사용할 수 있습니다:
model = init_chat_model(
    model="MODEL_NAME",
    model_provider="openai",
    base_url="BASE_URL",
    api_key="YOUR_API_KEY",
)
직접 chat model(채팅 모델) 클래스 인스턴스화를 사용하는 경우 매개변수 이름은 제공업체에 따라 다를 수 있습니다. 자세한 내용은 해당 reference(참조)를 확인하세요.
HTTP 프록시가 필요한 배포의 경우 일부 모델 통합이 프록시 구성을 지원합니다:
from langchain_openai import ChatOpenAI

model = ChatOpenAI(
    model="gpt-4o",
    openai_proxy="http://proxy.example.com:8080"
)
프록시 지원은 통합에 따라 다릅니다. 프록시 구성 옵션은 특정 모델 제공업체의 reference(참조)를 확인하세요.

Log probabilities(로그 확률)

특정 모델은 모델을 초기화할 때 logprobs 매개변수를 설정하여 주어진 token(토큰)의 가능성을 나타내는 token-level log probability(토큰 수준 로그 확률)를 반환하도록 구성할 수 있습니다:
model = init_chat_model(
    model="gpt-4o",
    model_provider="openai"
).bind(logprobs=True)

response = model.invoke("Why do parrots talk?")
print(response.response_metadata["logprobs"])

Token usage(토큰 사용량)

많은 모델 제공업체가 호출 응답의 일부로 token usage(토큰 사용량) 정보를 반환합니다. 사용 가능한 경우 이 정보는 해당 모델에서 생성한 AIMessage 객체에 포함됩니다. 자세한 내용은 message(메시지) 가이드를 참조하세요.
OpenAI 및 Azure OpenAI chat completion(채팅 완료)를 포함한 일부 제공업체 API는 사용자가 스트리밍 컨텍스트에서 token usage data(토큰 사용량 데이터)를 수신하도록 선택해야 합니다. 자세한 내용은 통합 가이드의 streaming usage metadata(스트리밍 사용 메타데이터) 섹션을 참조하세요.
아래와 같이 callback(콜백) 또는 context manager(컨텍스트 관리자)를 사용하여 애플리케이션의 모델 전체에서 집계 token count(토큰 수)를 추적할 수 있습니다:
from langchain.chat_models import init_chat_model
from langchain_core.callbacks import UsageMetadataCallbackHandler

model_1 = init_chat_model(model="openai:gpt-4o-mini")
model_2 = init_chat_model(model="anthropic:claude-3-5-haiku-latest")

callback = UsageMetadataCallbackHandler()
result_1 = model_1.invoke("Hello", config={"callbacks": [callback]})
result_2 = model_2.invoke("Hello", config={"callbacks": [callback]})
callback.usage_metadata
{
    'gpt-4o-mini-2024-07-18': {
        'input_tokens': 8,
        'output_tokens': 10,
        'total_tokens': 18,
        'input_token_details': {'audio': 0, 'cache_read': 0},
        'output_token_details': {'audio': 0, 'reasoning': 0}
    },
    'claude-3-5-haiku-20241022': {
        'input_tokens': 8,
        'output_tokens': 21,
        'total_tokens': 29,
        'input_token_details': {'cache_read': 0, 'cache_creation': 0}
    }
}

Invocation config(호출 구성)

모델을 호출할 때 RunnableConfig 딕셔너리를 사용하여 config 매개변수를 통해 추가 구성을 전달할 수 있습니다. 이는 실행 동작, callback(콜백) 및 metadata tracking(메타데이터 추적)에 대한 런타임 제어를 제공합니다. 일반적인 구성 옵션은 다음과 같습니다:
Invocation with config
response = model.invoke(
    "Tell me a joke",
    config={
        "run_name": "joke_generation",      # Custom name for this run
        "tags": ["humor", "demo"],          # Tags for categorization
        "metadata": {"user_id": "123"},     # Custom metadata
        "callbacks": [my_callback_handler], # Callback handlers
    }
)
이러한 구성 값은 다음과 같은 경우에 특히 유용합니다:
  • LangSmith 추적으로 디버깅
  • 사용자 정의 로깅 또는 모니터링 구현
  • 프로덕션에서 리소스 사용 제어
  • 복잡한 파이프라인 전체에서 호출 추적
run_name
string
로그 및 추적에서 이 특정 호출을 식별합니다. 하위 호출에 의해 상속되지 않습니다.
tags
string[]
디버깅 도구에서 필터링 및 구성을 위해 모든 하위 호출에 의해 상속되는 레이블입니다.
metadata
object
추가 컨텍스트를 추적하기 위한 사용자 정의 키-값 쌍으로, 모든 하위 호출에 의해 상속됩니다.
max_concurrency
number
batch() 또는 batch_as_completed()를 사용할 때 최대 병렬 호출 수를 제어합니다.
callbacks
array
실행 중 이벤트를 모니터링하고 응답하기 위한 핸들러입니다.
recursion_limit
number
복잡한 파이프라인에서 무한 루프를 방지하기 위한 chain(체인)의 최대 재귀 깊이입니다.
지원되는 모든 속성은 전체 RunnableConfig 참조를 확인하세요.

Configurable models(구성 가능한 모델)

configurable_fields를 지정하여 런타임 구성 가능한 모델을 만들 수도 있습니다. 모델 값을 지정하지 않으면 기본적으로 'model''model_provider'를 구성할 수 있습니다.
from langchain.chat_models import init_chat_model

configurable_model = init_chat_model(temperature=0)

configurable_model.invoke(
    "what's your name",
    config={"configurable": {"model": "gpt-5-nano"}},  # Run with GPT-5-Nano
)
configurable_model.invoke(
    "what's your name",
    config={"configurable": {"model": "claude-sonnet-4-5"}},  # Run with Claude
)
기본 모델 값으로 구성 가능한 모델을 만들고 구성 가능한 매개변수를 지정하고 구성 가능한 매개변수에 접두사를 추가할 수 있습니다:
first_model = init_chat_model(
        model="gpt-4.1-mini",
        temperature=0,
        configurable_fields=("model", "model_provider", "temperature", "max_tokens"),
        config_prefix="first",  # Useful when you have a chain with multiple models
)

first_model.invoke("what's your name")
first_model.invoke(
    "what's your name",
    config={
        "configurable": {
            "first_model": "claude-sonnet-4-5",
            "first_temperature": 0.5,
            "first_max_tokens": 100,
        }
    },
)
구성 가능한 모델에서 bind_tools, with_structured_output, with_configurable 등과 같은 선언적 작업을 호출하고 정기적으로 인스턴스화된 chat model(채팅 모델) 객체와 동일한 방식으로 구성 가능한 모델을 연결할 수 있습니다.
from pydantic import BaseModel, Field


class GetWeather(BaseModel):
    """Get the current weather in a given location"""

        location: str = Field(..., description="The city and state, e.g. San Francisco, CA")


class GetPopulation(BaseModel):
    """Get the current population in a given location"""

        location: str = Field(..., description="The city and state, e.g. San Francisco, CA")


model = init_chat_model(temperature=0)
model_with_tools = model.bind_tools([GetWeather, GetPopulation])

model_with_tools.invoke(
    "what's bigger in 2024 LA or NYC", config={"configurable": {"model": "gpt-4.1-mini"}}
).tool_calls
[
    {
        'name': 'GetPopulation',
        'args': {'location': 'Los Angeles, CA'},
        'id': 'call_Ga9m8FAArIyEjItHmztPYA22',
        'type': 'tool_call'
    },
    {
        'name': 'GetPopulation',
        'args': {'location': 'New York, NY'},
        'id': 'call_jh2dEvBaAHRaw5JUDthOs7rt',
        'type': 'tool_call'
    }
]
model_with_tools.invoke(
    "what's bigger in 2024 LA or NYC",
        config={"configurable": {"model": "claude-sonnet-4-5"}},
).tool_calls
[
    {
        'name': 'GetPopulation',
        'args': {'location': 'Los Angeles, CA'},
        'id': 'toolu_01JMufPf4F4t2zLj7miFeqXp',
        'type': 'tool_call'
    },
    {
        'name': 'GetPopulation',
        'args': {'location': 'New York City, NY'},
        'id': 'toolu_01RQBHcE8kEEbYTuuS8WqY1u',
        'type': 'tool_call'
    }
]

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