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는 모델의 동작을 설정하는 초기 지침 세트를 나타냅니다. 시스템 메시지를 사용하여 톤을 설정하고, 모델의 역할을 정의하며, 응답에 대한 가이드라인을 수립할 수 있습니다.
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# AI 메시지를 수동으로 생성 (예: 대화 기록용)ai_msg = AIMessage("I'd be happy to help you with that question!")# 대화 기록에 추가messages = [ SystemMessage("You are a helpful assistant"), HumanMessage("Can you help me?"), ai_msg, # 모델에서 나온 것처럼 삽입 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']}")
도구 호출을 지원하는 모델의 경우 AI 메시지에 도구 호출이 포함될 수 있습니다. 도구 메시지는 단일 도구 실행 결과를 모델에 다시 전달하는 데 사용됩니다.도구는 ToolMessage 객체를 직접 생성할 수 있습니다. 아래에 간단한 예제를 보여드립니다. 자세한 내용은 도구 가이드를 참조하세요.
Copy
# 모델이 도구 호출을 수행한 후ai_message = AIMessage( content=[], tool_calls=[{ "name": "get_weather", "args": {"location": "San Francisco"}, "id": "call_123" }])# 도구를 실행하고 결과 메시지 생성weather_result = "Sunny, 72°F"tool_message = ToolMessage( content=weather_result, tool_call_id="call_123" # 호출 ID와 일치해야 함)# 대화 계속messages = [ HumanMessage("What's the weather in San Francisco?"), ai_message, # 모델의 도구 호출 tool_message, # 도구 실행 결과]response = model.invoke(messages) # 모델이 결과를 처리
artifact 필드는 모델에 전송되지 않지만 프로그래밍 방식으로 액세스할 수 있는 보조 데이터를 저장합니다. 이는 모델의 컨텍스트를 어지럽히지 않고 원시 결과, 디버깅 정보 또는 다운스트림 처리를 위한 데이터를 저장하는 데 유용합니다.
예제: 검색 메타데이터에 artifact 사용
예를 들어, 검색 도구는 모델이 참조할 문서에서 구절을 검색할 수 있습니다. 메시지 content에 모델이 참조할 텍스트가 포함되어 있는 경우, artifact에는 애플리케이션이 사용할 수 있는 문서 식별자 또는 기타 메타데이터가 포함될 수 있습니다(예: 페이지 렌더링). 아래 예제를 참조하세요:
Copy
from langchain.messages import ToolMessage# 모델에 전송됨message_content = "It was the best of times, it was the worst of times."# 다운스트림에서 사용 가능한 아티팩트artifact = {"document_id": "doc_123", "page": 0}tool_message = ToolMessage( content=message_content, tool_call_id="call_123", name="search_books", artifact=artifact,)
LangChain으로 검색 에이전트를 구축하는 엔드투엔드 예제는 RAG 튜토리얼을 참조하세요.
메시지의 콘텐츠는 모델로 전송되는 데이터의 페이로드로 생각할 수 있습니다. 메시지에는 문자열과 타입이 지정되지 않은 객체 목록(예: 딕셔너리)을 지원하는 느슨하게 타입이 지정된 content 속성이 있습니다. 이를 통해 멀티모달 콘텐츠 및 기타 데이터와 같은 제공자 네이티브 구조를 LangChain 채팅 모델에서 직접 지원할 수 있습니다.별도로 LangChain은 텍스트, 추론, 인용, 멀티모달 데이터, 서버 측 도구 호출 및 기타 메시지 콘텐츠에 대한 전용 콘텐츠 타입을 제공합니다. 아래 콘텐츠 블록을 참조하세요.LangChain 채팅 모델은 content 속성에서 메시지 콘텐츠를 수락하며 다음을 포함할 수 있습니다:
from langchain.messages import HumanMessage# 문자열 콘텐츠human_message = HumanMessage("Hello, how are you?")# 제공자 네이티브 형식 (예: OpenAI)human_message = HumanMessage(content=[ {"type": "text", "text": "Hello, how are you?"}, {"type": "image_url", "image_url": {"url": "https://example.com/image.jpg"}}])# 표준 콘텐츠 블록 목록human_message = HumanMessage(content_blocks=[ {"type": "text", "text": "Hello, how are you?"}, {"type": "image", "url": "https://example.com/image.jpg"},])
메시지를 초기화할 때 content_blocks를 지정하면 여전히 메시지
content를 채우지만 타입 안전 인터페이스를 제공합니다.
LangChain은 제공자 간에 작동하는 메시지 콘텐츠에 대한 표준 표현을 제공합니다.메시지 객체는 content 속성을 표준 타입 안전 표현으로 지연 파싱하는 content_blocks 속성을 구현합니다. 예를 들어, ChatAnthropic 또는 ChatOpenAI에서 생성된 메시지에는 각 제공자의 형식으로 thinking 또는 reasoning 블록이 포함되지만 일관된 ReasoningContentBlock 표현으로 지연 파싱될 수 있습니다:
표준 콘텐츠 직렬화LangChain 외부의 애플리케이션이 표준 콘텐츠 블록 표현에 액세스해야 하는 경우 메시지 콘텐츠에 콘텐츠 블록을 저장하도록 선택할 수 있습니다.이를 위해 LC_OUTPUT_VERSION 환경 변수를 v1으로 설정할 수 있습니다. 또는
output_version="v1"로 채팅 모델을 초기화하세요:
Copy
from langchain.chat_models import init_chat_modelmodel = init_chat_model("openai:gpt-5-nano", output_version="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에서message = { "role": "user", "content": [ {"type": "text", "text": "Describe the content of this image."}, {"type": "image", "url": "https://example.com/path/to/image.jpg"}, ]}# base64 데이터에서message = { "role": "user", "content": [ {"type": "text", "text": "Describe the content of this image."}, { "type": "image", "base64": "AAAAIGZ0eXBtcDQyAAAAAGlzb21tcDQyAAACAGlzb2...", "mime_type": "image/jpeg", }, ]}# 제공자 관리 파일 ID에서message = { "role": "user", "content": [ {"type": "text", "text": "Describe the content of this image."}, {"type": "image", "file_id": "file-abc123"}, ]}
모든 모델이 모든 파일 타입을 지원하는 것은 아닙니다. 지원되는 형식과 크기 제한은 모델 제공자의 참조 문서를 확인하세요.
콘텐츠 블록은 기존 코드와의 하위 호환성을 유지하면서 제공자 간 콘텐츠 형식을 표준화하기 위해 LangChain v1의 메시지에 새로운 속성으로 도입되었습니다. 콘텐츠 블록은 content 속성을 대체하는 것이 아니라 표준화된 형식으로 메시지 콘텐츠에 액세스하는 데 사용할 수 있는 새로운 속성입니다.