메시지를 사용하는 가장 간단한 방법은 메시지 객체를 생성하고 호출할 때 모델에 전달하는 것입니다.
Copy
from langchain.chat_models import init_chat_modelfrom langchain.messages import HumanMessage, AIMessage, SystemMessagemodel = init_chat_model("openai:gpt-5-nano")system_msg = SystemMessage("You are a helpful assistant.")human_msg = HumanMessage("Hello, how are you?")# Use with chat modelsmessages = [system_msg, human_msg]response = model.invoke(messages) # Returns AIMessage
from langchain.messages import SystemMessage, HumanMessage, AIMessagemessages = [ SystemMessage("You are a poetry expert"), HumanMessage("Write a haiku about spring"), AIMessage("Cherry blossoms bloom...")]response = model.invoke(messages)
SystemMessage는 모델의 동작을 준비시키는 초기 지침 세트를 나타냅니다. system message를 사용하여 톤을 설정하고, 모델의 역할을 정의하며, 응답에 대한 가이드라인을 설정할 수 있습니다.
Basic instructions
Copy
system_msg = SystemMessage("You are a helpful coding assistant.")messages = [ system_msg, HumanMessage("How do I create a REST API?")]response = model.invoke(messages)
Detailed persona
Copy
from langchain.messages import SystemMessage, HumanMessagesystem_msg = SystemMessage("""You are a senior Python developer with expertise in web frameworks.Always provide code examples and explain your reasoning.Be concise but thorough in your explanations.""")messages = [ system_msg, HumanMessage("How do I create a REST API?")]response = model.invoke(messages)
AIMessage 객체는 모델을 호출할 때 반환되며, 응답에 관련된 모든 메타데이터를 포함합니다.제공자는 메시지 타입에 따라 다르게 가중치를 부여하거나 컨텍스트화하므로, 때로는 새로운 AIMessage 객체를 수동으로 생성하고 모델에서 온 것처럼 메시지 기록에 삽입하는 것이 유용합니다.
Copy
from langchain.messages import AIMessage, SystemMessage, HumanMessage# Create an AI message manually (e.g., for conversation history)ai_msg = AIMessage("I'd be happy to help you with that question!")# Add to conversation historymessages = [ SystemMessage("You are a helpful assistant"), HumanMessage("Can you help me?"), ai_msg, # Insert as if it came from the model HumanMessage("Great! What's 2+2?")]response = model.invoke(messages)
from langchain.chat_models import init_chat_modelmodel = init_chat_model("openai:gpt-5-nano")def get_weather(location: str) -> str: """Get the weather at a location.""" ...model_with_tools = model.bind_tools([get_weather])response = model_with_tools.invoke("What's the weather in Paris?")for tool_call in response.tool_calls: print(f"Tool: {tool_call['name']}") print(f"Args: {tool_call['args']}") print(f"ID: {tool_call['id']}")
tool calling을 지원하는 모델의 경우, AI message에 tool call이 포함될 수 있습니다. Tool message는 단일 tool 실행 결과를 모델에 다시 전달하는 데 사용됩니다.Tool은 ToolMessage 객체를 직접 생성할 수 있습니다. 아래에 간단한 예제를 보여줍니다. tools 가이드에서 자세히 알아보세요.
Copy
# After a model makes a tool callai_message = AIMessage( content=[], tool_calls=[{ "name": "get_weather", "args": {"location": "San Francisco"}, "id": "call_123" }])# Execute tool and create result messageweather_result = "Sunny, 72°F"tool_message = ToolMessage( content=weather_result, tool_call_id="call_123" # Must match the call ID)# Continue conversationmessages = [ HumanMessage("What's the weather in San Francisco?"), ai_message, # Model's tool call tool_message, # Tool execution result]response = model.invoke(messages) # Model processes the result
artifact 필드는 모델에 전송되지 않지만 프로그래밍 방식으로 액세스할 수 있는 보조 데이터를 저장합니다. 이는 모델의 컨텍스트를 복잡하게 만들지 않으면서 원시 결과, 디버깅 정보 또는 다운스트림 처리를 위한 데이터를 저장하는 데 유용합니다.
예제: 검색 메타데이터에 artifact 사용
예를 들어, retrieval tool은 모델이 참조할 문서에서 구절을 검색할 수 있습니다. 메시지 content에는 모델이 참조할 텍스트가 포함되고, artifact에는 애플리케이션이 사용할 수 있는 문서 식별자 또는 기타 메타데이터(예: 페이지 렌더링)가 포함될 수 있습니다. 아래 예제를 참조하세요:
Copy
from langchain.messages import ToolMessage# Sent to modelmessage_content = "It was the best of times, it was the worst of times."# Artifact available downstreamartifact = {"document_id": "doc_123", "page": 0}tool_message = ToolMessage( content=message_content, tool_call_id="call_123", name="search_books", artifact=artifact,)
LangChain으로 검색 agent를 구축하는 엔드투엔드 예제는 RAG 튜토리얼을 참조하세요.
메시지의 콘텐츠는 모델에 전송되는 데이터의 페이로드로 생각할 수 있습니다. 메시지에는 문자열과 타입이 지정되지 않은 객체(예: dictionary) 목록을 지원하는 느슨하게 타입이 지정된 content 속성이 있습니다. 이를 통해 multimodal 콘텐츠 및 기타 데이터와 같은 제공자 네이티브 구조를 LangChain chat model에서 직접 지원할 수 있습니다.별도로, LangChain은 텍스트, 추론, 인용, 멀티모달 데이터, 서버 측 tool call 및 기타 메시지 콘텐츠에 대한 전용 콘텐츠 타입을 제공합니다. 아래 content block을 참조하세요.LangChain chat model은 content 속성에서 메시지 콘텐츠를 허용하며, 다음을 포함할 수 있습니다:
from langchain.messages import HumanMessage# String contenthuman_message = HumanMessage("Hello, how are you?")# Provider-native format (e.g., OpenAI)human_message = HumanMessage(content=[ {"type": "text", "text": "Hello, how are you?"}, {"type": "image_url", "image_url": {"url": "https://example.com/image.jpg"}}])# List of standard content blockshuman_message = HumanMessage(content_blocks=[ {"type": "text", "text": "Hello, how are you?"}, {"type": "image", "url": "https://example.com/image.jpg"},])
메시지를 초기화할 때 content_blocks를 지정하면 여전히 메시지 content가 채워지지만, 이를 수행하기 위한 타입 안전 인터페이스를 제공합니다.
LangChain은 제공자 간에 작동하는 메시지 콘텐츠에 대한 표준 표현을 제공합니다.Message 객체는 content 속성을 표준적이고 타입 안전한 표현으로 지연 파싱하는 content_blocks 속성을 구현합니다. 예를 들어, ChatAnthropic 또는 ChatOpenAI에서 생성된 메시지는 각 제공자의 형식으로 thinking 또는 reasoning block을 포함하지만, 일관된 ReasoningContentBlock 표현으로 지연 파싱될 수 있습니다:
표준 콘텐츠 직렬화LangChain 외부의 애플리케이션이 표준 content block 표현에 액세스해야 하는 경우, 메시지 콘텐츠에 content block을 저장하도록 선택할 수 있습니다.이를 위해 LC_OUTPUT_VERSION 환경 변수를 v1로 설정할 수 있습니다. 또는 output_version="v1"로 chat model을 초기화할 수 있습니다:
Copy
from langchain.chat_models import init_chat_modelmodel = init_chat_model("openai:gpt-5-nano", output_version="v1")
Multimodality는 텍스트, 오디오, 이미지, 비디오와 같은 다양한 형태의 데이터를 다루는 능력을 의미합니다. LangChain은 제공자 간에 사용할 수 있는 이러한 데이터에 대한 표준 타입을 포함합니다.Chat model은 멀티모달 데이터를 입력으로 받아들이고 출력으로 생성할 수 있습니다. 아래에서 멀티모달 데이터가 포함된 입력 메시지의 짧은 예제를 보여줍니다.
추가 키는 content block의 최상위 레벨에 포함되거나 "extras": {"key": value}에 중첩될 수 있습니다.예를 들어, OpenAI와 AWS Bedrock Converse는 PDF에 대한 파일 이름이 필요합니다. 자세한 내용은 선택한 모델의 제공자 페이지를 참조하세요.
Copy
# From URLmessage = { "role": "user", "content": [ {"type": "text", "text": "Describe the content of this image."}, {"type": "image", "url": "https://example.com/path/to/image.jpg"}, ]}# From base64 datamessage = { "role": "user", "content": [ {"type": "text", "text": "Describe the content of this image."}, { "type": "image", "base64": "AAAAIGZ0eXBtcDQyAAAAAGlzb21tcDQyAAACAGlzb2...", "mime_type": "image/jpeg", }, ]}# From provider-managed File IDmessage = { "role": "user", "content": [ {"type": "text", "text": "Describe the content of this image."}, {"type": "image", "file_id": "file-abc123"}, ]}
모든 모델이 모든 파일 타입을 지원하는 것은 아닙니다. 지원되는 형식과 크기 제한은 모델 제공자의 reference를 확인하세요.
Content block은 제공자 간 콘텐츠 형식을 표준화하면서 기존 코드와의 하위 호환성을 유지하기 위해 LangChain v1에서 메시지의 새로운 속성으로 도입되었습니다. Content block은 content 속성을 대체하는 것이 아니라, 표준화된 형식으로 메시지의 콘텐츠에 액세스하는 데 사용할 수 있는 새로운 속성입니다.