Skip to main content
Message는 LangChain에서 모델의 컨텍스트를 구성하는 기본 단위입니다. LLM과 상호작용할 때 대화의 상태를 나타내는 데 필요한 콘텐츠와 메타데이터를 모두 포함하여 모델의 입력과 출력을 나타냅니다. Message는 다음을 포함하는 객체입니다:
  • Role - 메시지 유형을 식별합니다 (예: system, user)
  • Content - 메시지의 실제 콘텐츠를 나타냅니다 (텍스트, 이미지, 오디오, 문서 등)
  • Metadata - 응답 정보, 메시지 ID, 토큰 사용량과 같은 선택적 필드
LangChain은 모든 모델 제공자에서 작동하는 표준 메시지 타입을 제공하여 호출되는 모델에 관계없이 일관된 동작을 보장합니다.

기본 사용법

메시지를 사용하는 가장 간단한 방법은 메시지 객체를 생성하고 호출할 때 모델에 전달하는 것입니다.
import { initChatModel, HumanMessage, SystemMessage } from "langchain";

const model = await initChatModel("openai:gpt-5-nano");

const systemMsg = new SystemMessage("You are a helpful assistant.");
const humanMsg = new HumanMessage("Hello, how are you?");

const messages = [systemMsg, humanMsg];
const response = await model.invoke(messages);  // AIMessage 반환

텍스트 프롬프트

텍스트 프롬프트는 문자열로, 대화 기록을 유지할 필요가 없는 간단한 생성 작업에 이상적입니다.
const response = await model.invoke("Write a haiku about spring");
텍스트 프롬프트를 사용하는 경우:
  • 단일의 독립적인 요청이 있을 때
  • 대화 기록이 필요하지 않을 때
  • 코드 복잡성을 최소화하고 싶을 때

메시지 프롬프트

또는 메시지 객체 목록을 제공하여 모델에 메시지 목록을 전달할 수 있습니다.
import { SystemMessage, HumanMessage, AIMessage } from "langchain";

const messages = [
  new SystemMessage("You are a poetry expert"),
  new HumanMessage("Write a haiku about spring"),
  new AIMessage("Cherry blossoms bloom..."),
];
const response = await model.invoke(messages);
메시지 프롬프트를 사용하는 경우:
  • 다중 턴 대화를 관리할 때
  • 멀티모달 콘텐츠(이미지, 오디오, 파일)로 작업할 때
  • 시스템 지침을 포함할 때

딕셔너리 형식

OpenAI 채팅 완성 형식으로 직접 메시지를 지정할 수도 있습니다.
const messages = [
  { role: "system", content: "You are a poetry expert" },
  { role: "user", content: "Write a haiku about spring" },
  { role: "assistant", content: "Cherry blossoms bloom..." },
];
const response = await model.invoke(messages);

메시지 타입

  • System message - 모델의 동작 방식을 지시하고 상호작용에 대한 컨텍스트를 제공합니다
  • Human message - 사용자 입력 및 모델과의 상호작용을 나타냅니다
  • AI message - 텍스트 콘텐츠, 도구 호출, 메타데이터를 포함하여 모델이 생성한 응답입니다
  • Tool message - 도구 호출의 출력을 나타냅니다

System Message

@[SystemMessage]는 모델의 동작을 설정하는 초기 지침 세트를 나타냅니다. 시스템 메시지를 사용하여 톤을 설정하고, 모델의 역할을 정의하며, 응답에 대한 가이드라인을 수립할 수 있습니다.
Basic instructions
import { SystemMessage, HumanMessage, AIMessage } from "langchain";

const systemMsg = new SystemMessage("You are a helpful coding assistant.");

const messages = [
  systemMsg,
  new HumanMessage("How do I create a REST API?"),
];
const response = await model.invoke(messages);
Detailed persona
import { SystemMessage, HumanMessage } from "langchain";

const systemMsg = new SystemMessage(`
You are a senior TypeScript developer with expertise in web frameworks.
Always provide code examples and explain your reasoning.
Be concise but thorough in your explanations.
`);

const messages = [
  systemMsg,
  new HumanMessage("How do I create a REST API?"),
];
const response = await model.invoke(messages);

Human Message

@[HumanMessage]는 사용자 입력과 상호작용을 나타냅니다. 텍스트, 이미지, 오디오, 파일 및 기타 멀티모달 콘텐츠를 포함할 수 있습니다.

텍스트 콘텐츠

Message object
const response = await model.invoke([
  new HumanMessage("What is machine learning?"),
]);
String shortcut
const response = await model.invoke("What is machine learning?");

메시지 메타데이터

Add metadata
const humanMsg = new HumanMessage({
  content: "Hello!",
  name: "alice",
  id: "msg_123",
});
name 필드의 동작은 제공자에 따라 다릅니다. 일부는 사용자 식별에 사용하고 다른 일부는 무시합니다. 확인하려면 모델 제공자의 참조 문서를 참조하세요.

AI Message

AIMessage는 모델 호출의 출력을 나타냅니다. 멀티모달 데이터, 도구 호출 및 나중에 액세스할 수 있는 제공자별 메타데이터를 포함할 수 있습니다.
const response = await model.invoke("Explain AI");
console.log(typeof response);  // AIMessage
AIMessage 객체는 모델을 호출할 때 반환되며, 응답에서 연결된 모든 메타데이터를 포함합니다. 그러나 이것이 생성/수정될 수 있는 유일한 곳은 아닙니다. 제공자는 메시지 타입에 따라 다르게 가중치를 부여하고 컨텍스트화하므로, 때로는 새로운 AIMessage 객체를 생성하여 마치 모델에서 나온 것처럼 메시지 기록에 삽입하는 것이 유용합니다.
import { AIMessage, SystemMessage, HumanMessage } from "langchain";

const aiMsg = new AIMessage("I'd be happy to help you with that question!");

const messages = [
  new SystemMessage("You are a helpful assistant"),
  new HumanMessage("Can you help me?"),
  aiMsg,  // 모델에서 나온 것처럼 삽입
  new HumanMessage("Great! What's 2+2?")
]

const response = await model.invoke(messages);
text
string
메시지의 텍스트 콘텐츠입니다.
content
string | ContentBlock[]
메시지의 원본 콘텐츠입니다.
content_blocks
ContentBlock.Standard[]
메시지의 표준화된 콘텐츠 블록입니다. (콘텐츠 참조)
tool_calls
ToolCall[] | None
모델이 수행한 도구 호출입니다. 도구가 호출되지 않으면 비어 있습니다.
id
string
메시지의 고유 식별자입니다 (LangChain에서 자동으로 생성되거나 제공자 응답에서 반환됨)
usage_metadata
UsageMetadata | None
사용 가능한 경우 토큰 수를 포함할 수 있는 메시지의 사용 메타데이터입니다.
response_metadata
ResponseMetadata | None
메시지의 응답 메타데이터입니다.

도구 호출

모델이 도구 호출을 수행하면 AIMessage에 포함됩니다:
const modelWithTools = model.bindTools([getWeather]);
const response = await modelWithTools.invoke("What's the weather in Paris?");

for (const toolCall of response.tool_calls) {
  console.log(`Tool: ${toolCall.name}`);
  console.log(`Args: ${toolCall.args}`);
  console.log(`ID: ${toolCall.id}`);
}
추론이나 인용과 같은 다른 구조화된 데이터도 메시지 콘텐츠에 나타날 수 있습니다.

토큰 사용량

AIMessageusage_metadata 필드에 토큰 수 및 기타 사용 메타데이터를 보유할 수 있습니다:
import { initChatModel } from "langchain";

const model = await initChatModel("openai:gpt-5-nano");

const response = await model.invoke("Hello!");
console.log(response.usage_metadata);
{
  "output_tokens": 304,
  "input_tokens": 8,
  "total_tokens": 312,
  "input_token_details": {
    "cache_read": 0
  },
  "output_token_details": {
    "reasoning": 256
  }
}
자세한 내용은 UsageMetadata를 참조하세요.

스트리밍 및 청크

스트리밍 중에는 전체 메시지로 결합할 수 있는 AIMessageChunk 객체를 받게 됩니다:
import { AIMessageChunk } from "langchain";

let finalChunk: AIMessageChunk | undefined;
for (const chunk of chunks) {
  finalChunk = finalChunk ? finalChunk.concat(chunk) : chunk;
}

Tool Message

도구 호출을 지원하는 모델의 경우 AI 메시지에 도구 호출이 포함될 수 있습니다. 도구 메시지는 단일 도구 실행 결과를 모델에 다시 전달하는 데 사용됩니다. 도구는 @[ToolMessage] 객체를 직접 생성할 수 있습니다. 아래에 간단한 예제를 보여드립니다. 자세한 내용은 도구 가이드를 참조하세요.
import { AIMessage, ToolMessage } from "langchain";

const aiMessage = new AIMessage({
  content: [],
  tool_calls: [{
    name: "get_weather",
    args: { location: "San Francisco" },
    id: "call_123"
  }]
});

const toolMessage = new ToolMessage({
  content: "Sunny, 72°F",
  tool_call_id: "call_123"
});

const messages = [
  new HumanMessage("What's the weather in San Francisco?"),
  aiMessage,  // 모델의 도구 호출
  toolMessage,  // 도구 실행 결과
];

const response = await model.invoke(messages);  // 모델이 결과를 처리
content
string
required
도구 호출의 문자열화된 출력입니다.
tool_call_id
string
required
이 메시지가 응답하는 도구 호출의 ID입니다. (AIMessage의 도구 호출 ID와 일치해야 함)
name
string
required
호출된 도구의 이름입니다.
artifact
dict
모델에 전송되지 않지만 프로그래밍 방식으로 액세스할 수 있는 추가 데이터입니다.
artifact 필드는 모델에 전송되지 않지만 프로그래밍 방식으로 액세스할 수 있는 보조 데이터를 저장합니다. 이는 모델의 컨텍스트를 어지럽히지 않고 원시 결과, 디버깅 정보 또는 다운스트림 처리를 위한 데이터를 저장하는 데 유용합니다.
예를 들어, 검색 도구는 모델이 참조할 문서에서 구절을 검색할 수 있습니다. 메시지 content에 모델이 참조할 텍스트가 포함되어 있는 경우, artifact에는 애플리케이션이 사용할 수 있는 문서 식별자 또는 기타 메타데이터가 포함될 수 있습니다(예: 페이지 렌더링). 아래 예제를 참조하세요:
import { ToolMessage } from "langchain";

// 다운스트림에서 사용 가능한 아티팩트
const artifact = { document_id: "doc_123", page: 0 };

const toolMessage = new ToolMessage({
  content: "It was the best of times, it was the worst of times.",
  tool_call_id: "call_123",
  name: "search_books",
  artifact
});
LangChain으로 검색 에이전트를 구축하는 엔드투엔드 예제는 RAG 튜토리얼을 참조하세요.

콘텐츠

메시지의 콘텐츠는 모델로 전송되는 데이터의 페이로드로 생각할 수 있습니다. 메시지에는 문자열과 타입이 지정되지 않은 객체 목록(예: 딕셔너리)을 지원하는 느슨하게 타입이 지정된 content 속성이 있습니다. 이를 통해 멀티모달 콘텐츠 및 기타 데이터와 같은 제공자 네이티브 구조를 LangChain 채팅 모델에서 직접 지원할 수 있습니다. 별도로 LangChain은 텍스트, 추론, 인용, 멀티모달 데이터, 서버 측 도구 호출 및 기타 메시지 콘텐츠에 대한 전용 콘텐츠 타입을 제공합니다. 아래 콘텐츠 블록을 참조하세요. LangChain 채팅 모델은 content 속성에서 메시지 콘텐츠를 수락하며 다음을 포함할 수 있습니다:
  1. 문자열
  2. 제공자 네이티브 형식의 콘텐츠 블록 목록
  3. LangChain의 표준 콘텐츠 블록 목록
멀티모달 입력을 사용하는 예제는 아래를 참조하세요:
import { HumanMessage } from "langchain";

// 문자열 콘텐츠
const humanMessage = new HumanMessage("Hello, how are you?");

// 제공자 네이티브 형식 (예: OpenAI)
const humanMessage = new HumanMessage({
  content: [
    { type: "text", text: "Hello, how are you?" },
    {
      type: "image_url",
      image_url: { url: "https://example.com/image.jpg" },
    },
  ],
});

// 표준 콘텐츠 블록 목록
const humanMessage = new HumanMessage({
  contentBlocks: [
    { type: "text", text: "Hello, how are you?" },
    { type: "image", url: "https://example.com/image.jpg" },
  ],
});

표준 콘텐츠 블록

LangChain은 제공자 간에 작동하는 메시지 콘텐츠에 대한 표준 표현을 제공합니다. 메시지 객체는 content 속성을 표준 타입 안전 표현으로 지연 파싱하는 contentBlocks 속성을 구현합니다. 예를 들어, ChatAnthropic 또는 ChatOpenAI에서 생성된 메시지에는 각 제공자의 형식으로 thinking 또는 reasoning 블록이 포함되지만 일관된 ReasoningContentBlock 표현으로 지연 파싱될 수 있습니다:
  • Anthropic
  • OpenAI
import { AIMessage } from "@langchain/core/messages";

const message = new AIMessage({
  content: [
    {
      "type": "thinking",
      "thinking": "...",
      "signature": "WaUjzkyp...",
    },
    {
      "type":"text",
      "text": "...",
      "id": "msg_abc123",
    },
  ],
  response_metadata: { model_provider: "anthropic" },
});

console.log(message.contentBlocks);
선택한 추론 제공자로 시작하려면 통합 가이드를 참조하세요.
표준 콘텐츠 직렬화LangChain 외부의 애플리케이션이 표준 콘텐츠 블록 표현에 액세스해야 하는 경우 메시지 콘텐츠에 콘텐츠 블록을 저장하도록 선택할 수 있습니다.이를 위해 LC_OUTPUT_VERSION 환경 변수를 v1으로 설정할 수 있습니다. 또는 outputVersion: "v1"로 채팅 모델을 초기화하세요:
import { initChatModel } from "langchain";

const model = await initChatModel(
  "openai:gpt-5-nano",
  { outputVersion: "v1" }
);

멀티모달

멀티모달리티는 텍스트, 오디오, 이미지, 비디오와 같이 다양한 형태로 제공되는 데이터로 작업할 수 있는 기능을 의미합니다. LangChain에는 제공자 간에 사용할 수 있는 이러한 데이터에 대한 표준 타입이 포함되어 있습니다. 채팅 모델은 멀티모달 데이터를 입력으로 받아들이고 출력으로 생성할 수 있습니다. 아래에서 멀티모달 데이터가 포함된 입력 메시지의 짧은 예제를 보여드립니다:
Extra keys can be included top-level in the content block or nested in "extras": {"key": value}.OpenAI and AWS Bedrock Converse, for example, require a filename for PDFs. See the provider page for your chosen model for specifics.
// URL에서
const message = new HumanMessage({
  content: [
    { type: "text", text: "Describe the content of this image." },
    {
      type: "image",
      source_type: "url",
      url: "https://example.com/path/to/image.jpg"
    },
  ],
});

// base64 데이터에서
const message = new HumanMessage({
  content: [
    { type: "text", text: "Describe the content of this image." },
    {
      type: "image",
      source_type: "base64",
      data: "AAAAIGZ0eXBtcDQyAAAAAGlzb21tcDQyAAACAGlzb2...",
    },
  ],
});

// 제공자 관리 파일 ID에서
const message = new HumanMessage({
  content: [
    { type: "text", text: "Describe the content of this image." },
    { type: "image", source_type: "id", id: "file-abc123" },
  ],
});
모든 모델이 모든 파일 타입을 지원하는 것은 아닙니다. 지원되는 형식과 크기 제한은 모델 제공자의 참조 문서를 확인하세요.

콘텐츠 블록 레퍼런스

콘텐츠 블록은 (메시지를 생성하거나 contentBlocks 필드에 액세스할 때) 타입이 지정된 객체 목록으로 표현됩니다. 목록의 각 항목은 다음 블록 타입 중 하나를 준수해야 합니다:
목적: 표준 텍스트 출력
type
string
required
항상 "text"
text
string
required
텍스트 콘텐츠
annotations
Citation[]
텍스트에 대한 주석 목록
예제:
{
    type: "text",
    text: "Hello world",
    annotations: []
}
목적: 모델 추론 단계
type
string
required
항상 "reasoning"
reasoning
string
required
추론 콘텐츠
예제:
{
    type: "reasoning",
    reasoning: "The user is asking about..."
}
목적: 이미지 데이터
type
string
required
항상 "image"
url
string
이미지 위치를 가리키는 URL입니다.
data
string
Base64로 인코딩된 이미지 데이터입니다.
fileId
string
외부에 저장된 이미지에 대한 참조 ID입니다 (예: 제공자의 파일 시스템 또는 버킷).
mimeType
string
이미지 MIME 타입 (예: image/jpeg, image/png)
목적: 오디오 데이터
type
string
required
항상 "audio"
url
string
오디오 위치를 가리키는 URL입니다.
data
string
Base64로 인코딩된 오디오 데이터입니다.
fileId
string
외부에 저장된 오디오 파일에 대한 참조 ID입니다 (예: 제공자의 파일 시스템 또는 버킷).
mimeType
string
오디오 MIME 타입 (예: audio/mpeg, audio/wav)
목적: 비디오 데이터
type
string
required
항상 "video"
url
string
비디오 위치를 가리키는 URL입니다.
data
string
Base64로 인코딩된 비디오 데이터입니다.
fileId
string
외부에 저장된 비디오 파일에 대한 참조 ID입니다 (예: 제공자의 파일 시스템 또는 버킷).
mimeType
string
비디오 MIME 타입 (예: video/mp4, video/webm)
목적: 일반 파일 (PDF 등)
type
string
required
항상 "file"
url
string
파일 위치를 가리키는 URL입니다.
data
string
Base64로 인코딩된 파일 데이터입니다.
fileId
string
외부에 저장된 파일에 대한 참조 ID입니다 (예: 제공자의 파일 시스템 또는 버킷).
mimeType
string
파일 MIME 타입 (예: application/pdf)
목적: 문서 텍스트 (.txt, .md)
type
string
required
항상 "text-plain"
text
string
required
텍스트 콘텐츠
title
string
텍스트 콘텐츠의 제목
mimeType
string
텍스트의 MIME 타입 (예: text/plain, text/markdown)
목적: 함수 호출
type
string
required
항상 "tool_call"
name
string
required
호출할 도구의 이름
args
object
required
도구에 전달할 인수
id
string
required
이 도구 호출의 고유 식별자
예제:
{
    type: "tool_call",
    name: "search",
    args: { query: "weather" },
    id: "call_123"
}
목적: 스트리밍 도구 조각
type
string
required
항상 "tool_call_chunk"
name
string
호출되는 도구의 이름
args
string
부분 도구 인수 (불완전한 JSON일 수 있음)
id
string
도구 호출 식별자
index
number | string
required
스트림에서 이 청크의 위치
목적: 잘못된 호출
type
string
required
항상 "invalid_tool_call"
name
string
호출에 실패한 도구의 이름
args
string
파싱에 실패한 원시 인수
error
string
required
무엇이 잘못되었는지에 대한 설명
일반적인 오류: 잘못된 JSON, 필수 필드 누락
목적: 서버 측에서 실행되는 도구 호출
type
string
required
항상 "server_tool_call"
id
string
required
도구 호출과 연결된 식별자입니다.
name
string
required
호출할 도구의 이름입니다.
args
string
required
부분 도구 인수 (불완전한 JSON일 수 있음)
목적: 스트리밍 서버 측 도구 호출 조각
type
string
required
항상 "server_tool_call_chunk"
id
string
도구 호출과 연결된 식별자입니다.
name
string
호출되는 도구의 이름
args
string
부분 도구 인수 (불완전한 JSON일 수 있음)
index
number | string
스트림에서 이 청크의 위치
목적: 검색 결과
type
string
required
항상 "server_tool_result"
tool_call_id
string
required
해당 서버 도구 호출의 식별자입니다.
id
string
서버 도구 결과와 연결된 식별자입니다.
status
string
required
서버 측 도구의 실행 상태입니다. "success" 또는 "error".
output
실행된 도구의 출력입니다.
목적: 제공자별 탈출구
type
string
required
항상 "non_standard"
value
object
required
제공자별 데이터 구조
사용법: 실험적 또는 제공자 고유 기능용
추가 제공자별 콘텐츠 타입은 각 모델 제공자의 참조 문서에서 찾을 수 있습니다.
위에서 언급한 각 콘텐츠 블록은 @[ContentBlock] 타입을 가져올 때 타입으로 개별적으로 주소를 지정할 수 있습니다.
import { ContentBlock } from "langchain";

// 텍스트 블록
const textBlock: ContentBlock.Text = {
    type: "text",
    text: "Hello world",
}

// 이미지 블록
const imageBlock: ContentBlock.Multimodal.Image = {
    type: "image",
    url: "https://example.com/image.png",
    mimeType: "image/png",
}
정규 타입 정의는 @[API reference][langchain.messages]에서 확인하세요.
콘텐츠 블록은 기존 코드와의 하위 호환성을 유지하면서 제공자 간 콘텐츠 형식을 표준화하기 위해 LangChain v1의 메시지에 새로운 속성으로 도입되었습니다. 콘텐츠 블록은 @[content][BaseMessage(content)] 속성을 대체하는 것이 아니라 표준화된 형식으로 메시지 콘텐츠에 액세스하는 데 사용할 수 있는 새로운 속성입니다.

채팅 모델과 함께 사용

채팅 모델은 메시지 객체의 시퀀스를 입력으로 받아 AIMessage를 출력으로 반환합니다. 상호작용은 종종 상태 비저장이므로 간단한 대화 루프는 증가하는 메시지 목록으로 모델을 호출하는 것을 포함합니다. 자세한 내용은 아래 가이드를 참조하세요:
Connect these docs programmatically to Claude, VSCode, and more via MCP for real-time answers.
I