메시지를 사용하는 가장 간단한 방법은 메시지 객체를 생성하고 호출할 때 모델에 전달하는 것입니다.
Copy
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 반환
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);
@[SystemMessage]는 모델의 동작을 설정하는 초기 지침 세트를 나타냅니다. 시스템 메시지를 사용하여 톤을 설정하고, 모델의 역할을 정의하며, 응답에 대한 가이드라인을 수립할 수 있습니다.
Basic instructions
Copy
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
Copy
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);
AIMessage 객체는 모델을 호출할 때 반환되며, 응답에서 연결된 모든 메타데이터를 포함합니다. 그러나 이것이 생성/수정될 수 있는 유일한 곳은 아닙니다.제공자는 메시지 타입에 따라 다르게 가중치를 부여하고 컨텍스트화하므로, 때로는 새로운 AIMessage 객체를 생성하여 마치 모델에서 나온 것처럼 메시지 기록에 삽입하는 것이 유용합니다.
Copy
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);
도구 호출을 지원하는 모델의 경우 AI 메시지에 도구 호출이 포함될 수 있습니다. 도구 메시지는 단일 도구 실행 결과를 모델에 다시 전달하는 데 사용됩니다.도구는 @[ToolMessage] 객체를 직접 생성할 수 있습니다. 아래에 간단한 예제를 보여드립니다. 자세한 내용은 도구 가이드를 참조하세요.
Copy
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); // 모델이 결과를 처리
artifact 필드는 모델에 전송되지 않지만 프로그래밍 방식으로 액세스할 수 있는 보조 데이터를 저장합니다. 이는 모델의 컨텍스트를 어지럽히지 않고 원시 결과, 디버깅 정보 또는 다운스트림 처리를 위한 데이터를 저장하는 데 유용합니다.
예제: 검색 메타데이터에 artifact 사용
예를 들어, 검색 도구는 모델이 참조할 문서에서 구절을 검색할 수 있습니다. 메시지 content에 모델이 참조할 텍스트가 포함되어 있는 경우, artifact에는 애플리케이션이 사용할 수 있는 문서 식별자 또는 기타 메타데이터가 포함될 수 있습니다(예: 페이지 렌더링). 아래 예제를 참조하세요:
Copy
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 속성에서 메시지 콘텐츠를 수락하며 다음을 포함할 수 있습니다:
LangChain은 제공자 간에 작동하는 메시지 콘텐츠에 대한 표준 표현을 제공합니다.메시지 객체는 content 속성을 표준 타입 안전 표현으로 지연 파싱하는 contentBlocks 속성을 구현합니다. 예를 들어, ChatAnthropic 또는 ChatOpenAI에서 생성된 메시지에는 각 제공자의 형식으로 thinking 또는 reasoning 블록이 포함되지만 일관된 ReasoningContentBlock 표현으로 지연 파싱될 수 있습니다:
표준 콘텐츠 직렬화LangChain 외부의 애플리케이션이 표준 콘텐츠 블록 표현에 액세스해야 하는 경우 메시지 콘텐츠에 콘텐츠 블록을 저장하도록 선택할 수 있습니다.이를 위해 LC_OUTPUT_VERSION 환경 변수를 v1으로 설정할 수 있습니다. 또는
outputVersion: "v1"로 채팅 모델을 초기화하세요:
Copy
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.
Copy
// 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" }, ],});
모든 모델이 모든 파일 타입을 지원하는 것은 아닙니다. 지원되는 형식과 크기 제한은 모델 제공자의 참조 문서를 확인하세요.
위에서 언급한 각 콘텐츠 블록은 @[ContentBlock] 타입을 가져올 때 타입으로 개별적으로 주소를 지정할 수 있습니다.
Copy
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)] 속성을 대체하는 것이 아니라 표준화된 형식으로 메시지 콘텐츠에 액세스하는 데 사용할 수 있는 새로운 속성입니다.