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

기본 사용법

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

모델 초기화

LangChain에서 독립 실행형 모델을 시작하는 가장 쉬운 방법은 initChatModel을 사용하여 선택한 provider(제공업체)에서 모델을 초기화하는 것입니다(아래 예시):
👉 Read the OpenAI chat model integration docs
npm install @langchain/openai
import { initChatModel } from "langchain";

process.env.OPENAI_API_KEY = "your-api-key";

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

주요 메서드

Invoke

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

Stream

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

Batch

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

Parameter(매개변수)

chat model(채팅 모델)은 동작을 구성하는 데 사용할 수 있는 매개변수를 사용합니다. 지원되는 매개변수의 전체 집합은 모델 및 제공업체에 따라 다르지만 표준 매개변수는 다음과 같습니다:
model
string
required
제공업체와 함께 사용하려는 특정 모델의 이름 또는 식별자입니다.
apiKey
string
모델 제공업체의 인증에 필요한 키입니다. 일반적으로 모델에 대한 액세스 권한을 등록할 때 발급됩니다. 을 설정하여 액세스하는 경우가 많습니다.
temperature
number
모델 출력의 무작위성을 제어합니다. 높은 값은 응답을 더 창의적으로 만들고, 낮은 값은 더 결정적으로 만듭니다.
timeout
number
요청을 취소하기 전에 모델의 응답을 기다리는 최대 시간(초)입니다.
maxTokens
number
응답의 총 수를 제한하여 출력 길이를 효과적으로 제어합니다.
maxRetries
number
네트워크 시간 초과 또는 rate limit(속도 제한)과 같은 문제로 인해 요청이 실패할 경우 시스템이 요청을 재전송하는 최대 시도 횟수입니다.
initChatModel을 사용하여 이러한 매개변수를 인라인 매개변수로 전달합니다:
Initialize using model parameters
const model = await initChatModel(
    "anthropic:claude-sonnet-4-5",
    { 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
const response = await model.invoke("Why do parrots have colorful feathers?");
console.log(response);
대화 기록을 나타내기 위해 모델에 메시지 목록을 제공할 수 있습니다. 각 메시지에는 모델이 대화에서 메시지를 보낸 사람을 나타내는 데 사용하는 role(역할)이 있습니다. role, type 및 content에 대한 자세한 내용은 message(메시지) 가이드를 참조하세요.
Object format
const 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." },
];

const response = await model.invoke(conversation);
console.log(response);  // AIMessage("J'adore créer des applications.")
Message objects
import { HumanMessage, AIMessage, SystemMessage } from "langchain";

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

const response = await model.invoke(conversation);
console.log(response);  // AIMessage("J'adore créer des applications.")

Stream

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

// The
// The sky
// The sky is
// The sky is typically
// The sky is typically blue
// ...

console.log(full.contentBlocks);
// [{"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()streamEvents()가 실시간으로 채팅 모델의 출력을 표시할 수 있습니다.
LangChain chat model(채팅 모델)은 [streamEvents()][BaseChatModel.streamEvents]를 사용하여 semantic event(의미론적 이벤트)를 스트리밍할 수도 있습니다.이는 이벤트 유형 및 기타 메타데이터를 기반으로 필터링을 단순화하고 백그라운드에서 전체 메시지를 집계합니다. 아래 예제를 참조하세요.
const stream = await model.streamEvents("Hello");
for await (const event of stream) {
    if (event.event === "on_chat_model_start") {
        console.log(`Input: ${event.data.input}`);
    }
    if (event.event === "on_chat_model_stream") {
        console.log(`Token: ${event.data.chunk.text}`);
    }
    if (event.event === "on_chat_model_end") {
        console.log(`Full message: ${event.data.output.text}`);
    }
}
Input: Hello
Token: Hi
Token:  there
Token: !
Token:  How
Token:  can
Token:  I
...
Full message: Hi there! How can I help today?
이벤트 유형 및 기타 세부 정보는 streamEvents() 참조를 확인하세요.

Batch

독립적인 요청 컬렉션을 모델에 일괄 처리하면 처리를 병렬로 수행할 수 있으므로 성능을 크게 향상시키고 비용을 절감할 수 있습니다:
Batch
const responses = await model.batch([
  "Why do parrots have colorful feathers?",
  "How do airplanes fly?",
  "What is quantum computing?",
  "Why do parrots have colorful feathers?",
  "How do airplanes fly?",
  "What is quantum computing?",
]);
for (const response of responses) {
  console.log(response);
}
batch()를 사용하여 많은 수의 입력을 처리할 때 최대 병렬 호출 수를 제어할 수 있습니다. 이는 RunnableConfig 딕셔너리에서 maxConcurrency 속성을 설정하여 수행할 수 있습니다.
Batch with max concurrency
model.batch(
  listOfInputs,
  {
    maxConcurrency: 5,  // Limit to 5 parallel calls
  }
)
지원되는 속성의 전체 목록은 RunnableConfig 참조를 확인하세요.
일괄 처리에 대한 자세한 내용은 reference를 참조하세요.

Tool calling(도구 호출)

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

const getWeather = tool(
  (input) => `It's sunny in ${input.location}.`,
  {
    name: "get_weather",
    description: "Get the weather at a location.",
    schema: z.object({
      location: z.string().describe("The location to get the weather for"),
    }),
  },
);

const model = new ChatOpenAI({ model: "gpt-4o" });
const modelWithTools = model.bindTools([getWeather]);  

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

// Step 1: Model generates tool calls
const messages = [{"role": "user", "content": "What's the weather in Boston?"}]
const ai_msg = await modelWithTools.invoke(messages)
messages.push(ai_msg)

// Step 2: Execute tools and collect results
for (const tool_call of ai_msg.tool_calls) {
    // Execute the tool with the generated arguments
    const tool_result = await get_weather.invoke(tool_call)
    messages.push(tool_result)
}

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

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


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


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

// Output:
// Tool: get_weather
// Args:
// Tool:
// Args: {"loc
// Tool:
// Args: ation": "BOS"}
// Tool: get_time
// Args:
// Tool:
// Args: {"timezone": "Tokyo"}
청크를 누적하여 완전한 도구 호출을 구축할 수 있습니다:
Accumulate tool calls
let full: AIMessageChunk | null = null
const stream = await modelWithTools.stream("What's the weather in Boston?")
for await (const chunk of stream) {
    full = full ? full.concat(chunk) : chunk
    console.log(full.contentBlocks)
}

Structured output(구조화된 출력)

모델은 주어진 schema(스키마)와 일치하는 형식으로 응답을 제공하도록 요청할 수 있습니다. 이는 출력을 쉽게 구문 분석하고 후속 처리에 사용할 수 있도록 하는 데 유용합니다. LangChain은 구조화된 출력을 적용하기 위한 여러 스키마 유형과 메서드를 지원합니다.
zod schema(스키마)는 출력 스키마를 정의하는 데 선호되는 방법입니다. zod 스키마가 제공되면 모델 출력도 zod의 parse 메서드를 사용하여 스키마에 대해 유효성이 검사됩니다.
import * as z from "zod";

const Movie = z.object({
  title: z.string().describe("The title of the movie"),
  year: z.number().describe("The year the movie was released"),
  director: z.string().describe("The director of the movie"),
  rating: z.number().describe("The movie's rating out of 10"),
});

const modelWithStructure = model.withStructuredOutput(Movie);

const response = await modelWithStructure.invoke("Provide details about the movie Inception");
console.log(response);
// {
//   title: "Inception",
//   year: 2010,
//   director: "Christopher Nolan",
//   rating: 8.8,
// }
구조화된 출력에 대한 주요 고려 사항:
  • Method parameter(메서드 매개변수): 일부 제공업체는 다양한 메서드('jsonSchema', 'functionCalling', 'jsonMode')를 지원합니다
  • Include raw: @[includeRaw: true][BaseChatModel.with_structured_output(include_raw)]를 사용하여 구문 분석된 출력과 원시 AIMessage를 모두 얻습니다
  • Validation(유효성 검사): Zod 모델은 자동 유효성 검사를 제공하는 반면 JSON Schema는 수동 유효성 검사가 필요합니다
원시 AIMessage 객체를 구문 분석된 표현과 함께 반환하여 token count(토큰 수)와 같은 응답 메타데이터에 액세스하는 것이 유용할 수 있습니다. 이렇게 하려면 @[with_structured_output][BaseChatModel.with_structured_output]을 호출할 때 @[include_raw=True][BaseChatModel.with_structured_output(include_raw)]를 설정하세요:
import * as z from "zod";

const Movie = z.object({
  title: z.string().describe("The title of the movie"),
  year: z.number().describe("The year the movie was released"),
  director: z.string().describe("The director of the movie"),
  rating: z.number().describe("The movie's rating out of 10"),
  title: z.string().describe("The title of the movie"),
  year: z.number().describe("The year the movie was released"),
  director: z.string().describe("The director of the movie"),  
  rating: z.number().describe("The movie's rating out of 10"),
});

const modelWithStructure = model.withStructuredOutput(Movie, { includeRaw: true });

const response = await modelWithStructure.invoke("Provide details about the movie Inception");
console.log(response);
// {
//   raw: AIMessage { ... },
//   parsed: { title: "Inception", ... }
// }
스키마는 중첩될 수 있습니다:
import * as z from "zod";

const Actor = z.object({
  name: str
  role: z.string(),
});

const MovieDetails = z.object({
  title: z.string(),
  year: z.number(),
  cast: z.array(Actor),
  genres: z.array(z.string()),
  budget: z.number().nullable().describe("Budget in millions USD"),
});

const modelWithStructure = model.withStructuredOutput(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
const response = await model.invoke("Create a picture of a cat");
console.log(response.contentBlocks);
// [
//   { type: "text", text: "Here's a picture of a cat" },
//   { type: "image", data: "...", mimeType: "image/jpeg" },
// ]
특정 제공업체에 대한 자세한 내용은 통합 페이지를 참조하세요.

Reasoning(추론)

최신 모델은 결론에 도달하기 위해 다단계 추론을 수행할 수 있습니다. 여기에는 복잡한 문제를 더 작고 관리하기 쉬운 단계로 나누는 작업이 포함됩니다. 기본 모델이 지원하는 경우 이 추론 프로세스를 표시하여 모델이 최종 답변에 어떻게 도달했는지 더 잘 이해할 수 있습니다.
const stream = model.stream("Why do parrots have colorful feathers?");
for await (const chunk of stream) {
    const reasoningSteps = chunk.contentBlocks.filter(b => b.type === "reasoning");
    console.log(reasoningSteps.length > 0 ? reasoningSteps : 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(콘텐츠 블록)에 액세스하면 제공업체에 구애받지 않는 형식으로 서버 측 도구 호출 및 결과가 반환됩니다:
import { initChatModel } from "langchain";

const model = await initChatModel("openai:gpt-4.1-mini");
const modelWithTools = model.bindTools([{ type: "web_search" }])

const message = await modelWithTools.invoke("What was a positive news story from today?");
console.log(message.contentBlocks);
이는 단일 대화 턴을 나타냅니다. 클라이언트 측 tool-calling(도구 호출)에서처럼 전달해야 하는 관련 ToolMessage 객체가 없습니다. 사용 가능한 도구 및 사용 세부 정보는 해당 제공업체의 통합 페이지를 참조하세요.

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

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

Log probabilities(로그 확률)

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

const responseMessage = await model.invoke("Why do parrots talk?");

responseMessage.response_metadata.logprobs.content.slice(0, 5);

Token usage(토큰 사용량)

많은 모델 제공업체가 호출 응답의 일부로 token usage(토큰 사용량) 정보를 반환합니다. 사용 가능한 경우 이 정보는 해당 모델에서 생성한 AIMessage 객체에 포함됩니다. 자세한 내용은 message(메시지) 가이드를 참조하세요.
OpenAI 및 Azure OpenAI chat completion(채팅 완료)를 포함한 일부 제공업체 API는 사용자가 스트리밍 컨텍스트에서 token usage data(토큰 사용량 데이터)를 수신하도록 선택해야 합니다. 자세한 내용은 통합 가이드의 streaming usage metadata(스트리밍 사용 메타데이터) 섹션을 참조하세요.

Invocation config(호출 구성)

모델을 호출할 때 RunnableConfig 객체를 사용하여 config 매개변수를 통해 추가 구성을 전달할 수 있습니다. 이는 실행 동작, callback(콜백) 및 metadata tracking(메타데이터 추적)에 대한 런타임 제어를 제공합니다. 일반적인 구성 옵션은 다음과 같습니다:
Invocation with config
const response = await model.invoke(
    "Tell me a joke",
    {
        runName: "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 추적으로 디버깅
  • 사용자 정의 로깅 또는 모니터링 구현
  • 프로덕션에서 리소스 사용 제어
  • 복잡한 파이프라인 전체에서 호출 추적
runName
string
로그 및 추적에서 이 특정 호출을 식별합니다. 하위 호출에 의해 상속되지 않습니다.
tags
string[]
디버깅 도구에서 필터링 및 구성을 위해 모든 하위 호출에 의해 상속되는 레이블입니다.
metadata
object
추가 컨텍스트를 추적하기 위한 사용자 정의 키-값 쌍으로, 모든 하위 호출에 의해 상속됩니다.
maxConcurrency
number
batch()를 사용할 때 최대 병렬 호출 수를 제어합니다.
callbacks
CallbackHandler[]
실행 중 이벤트를 모니터링하고 응답하기 위한 핸들러입니다.
recursion_limit
number
복잡한 파이프라인에서 무한 루프를 방지하기 위한 chain(체인)의 최대 재귀 깊이입니다.
지원되는 모든 속성은 전체 RunnableConfig 참조를 확인하세요.

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