ImageContent
ImageContent
ImageContent는 채팅 메시지와 멀티모달 AI 파이프라인에서 이미지 기반 콘텐츠를 나타내는 데 사용하는 Haystack 데이터 클래스예요. 보통 다음과 함께 사용해요:
- 멀티모달 LLM
- vision-language 모델
- 이미지 인식 채팅 애플리케이션
- 문서/이미지 처리 워크플로
ImageContent는 이미지를 base64 인코딩 문자열로 저장하고, MIME 타입과 이미지 디테일 레벨 같은 메타데이터와 함께 저장해요. 전체 API reference를 찾고 있다면 API 문서를 보세요.
출처: 문서
본문
Creating ImageContent
base64 문자열에서 직접 ImageContent 객체를 만들 수 있어요:
from haystack.dataclasses import ImageContent
image = ImageContent(base64_image="your_base64_encoded_image", mime_type="image/png")
print(image)
Loading Images from a File Path
from_file_path() 클래스 메서드는 로컬 이미지 파일을 로드하는 편리한 방법을 제공해요.
from haystack.dataclasses import ImageContent
image = ImageContent.from_file_path("sample.png", detail="low")
print(image)
선택적 detail 파라미터는 현재 OpenAI vision 모델이 지원하며 다음 값을 받아들여요:
"auto""high""low"
로드하면서 이미지 크기를 조절할 수도 있어요:
image = ImageContent.from_file_path("sample.png", size=(512, 512))
멀티모달 LLM API로 작업할 때 이렇게 하면 메모리 사용량, 처리 시간, 페이로드 크기를 줄이는 데 도움이 돼요.
Loading Images from a URL
이미지 URL에서 직접 ImageContent 객체를 만들 수도 있어요:
from haystack.dataclasses import ImageContent
image = ImageContent.from_url(
"https://images.unsplash.com/photo-1546182990-dffeafbe841d",
detail="low",
)
print(image)
내부적으로 Haystack이 이미지를 다운로드해 base64 표현으로 변환해요.
Producing ImageContent with Converters
파이프라인에서 보통 ImageContent 객체를 손으로 만들지 않아요. 대신 파일을 읽고 ImageContent를 생성하는 컨버터 구성 요소를 사용해요:
- ImageFileToImageContent는 로컬 이미지 파일(PNG, JPEG 등)을
ImageContent객체로 변환해요. - PDFToImageContent는 PDF 파일의 페이지를
ImageContent객체로 렌더링해요.
from haystack.components.converters.image import (
ImageFileToImageContent,
PDFToImageContent,
)
image_converter = ImageFileToImageContent()
image_contents = image_converter.run(sources=["image.jpg", "another_image.png"])[
"image_contents"
]
pdf_converter = PDFToImageContent()
pdf_image_contents = pdf_converter.run(sources=["file.pdf"])["image_contents"]
두 컨버터 모두 선택적 detail과 size 파라미터를 받아들이며, 이것들은 생성하는 ImageContent 객체에 전달돼요.
Using ImageContent with ChatMessage
ImageContent는 멀티모달 대화를 위해 ChatMessage와 함께 자주 사용돼요.
from haystack.dataclasses import ChatMessage, ImageContent
image = ImageContent.from_url(
"https://images.unsplash.com/photo-1546182990-dffeafbe841d",
detail="low",
)
message = ChatMessage.from_user(content_parts=["What does this image show?", image])
print(message)
이렇게 하면 멀티모달 LLM이 같은 메시지 안에서 텍스트 프롬프트와 이미지 입력을 모두 처리할 수 있어요. 더 동적인 프롬프트를 위해 ChatPromptBuilder와 Jinja2 문자열 템플릿으로 멀티모달 메시지를 만들 수 있어요. | templatize_part 필터가 ImageContent 객체를 일반 텍스트 대신 구조화된 콘텐츠 파트로 삽입해요:
from haystack.components.builders import ChatPromptBuilder
from haystack.dataclasses import ChatMessage, ImageContent
template = """{% message role="user" %}Hello! I am {{user_name}}. What's the difference between the following images?
{% for image in images %}{{ image | templatize_part }}{% endfor %}
{% endmessage %}"""
builder = ChatPromptBuilder(template=template)
images = [
ImageContent.from_file_path("apple.jpg"),
ImageContent.from_file_path("kiwi.jpg"),
]
result = builder.run(user_name="John", images=images)
print(result["prompt"])
Metadata
선택적 meta 파라미터로 이미지에 커스텀 메타데이터를 첨부할 수 있어요.
image = ImageContent.from_url(
"https://images.unsplash.com/photo-1546182990-dffeafbe841d",
meta={"source": "example-dataset"},
)
이것은 트레이싱, 데이터셋 추적, 워크플로 메타데이터, 커스텀 애플리케이션 로직에 유용할 수 있어요.
Validation
기본적으로 ImageContent는 다음을 검증해요:
- base64 인코딩
- MIME 타입 정확성
- 이미지 MIME 호환성
성능을 위해 검증을 비활성화할 수 있어요:
image = ImageContent(
base64_image="your_base64_encoded_image",
mime_type="image/png",
validation=False,
)
Serialization
ImageContent는 딕셔너리 직렬화를 지원해요.
image_dict = image.to_dict()
restored_image = ImageContent.from_dict(image_dict)
Displaying Images
show() 메서드는 다음에서 이미지를 직접 표시할 수 있어요:
- Jupyter 노트북
- 로컬 데스크톱 환경
image.show()
이것은 Pillow 패키지가 필요해요:
pip install pillow
Related Components
ImageContent는 자주 다음과 함께 사용돼요:
- ChatMessage — 멀티모달 메시지 구축
- ChatPromptBuilder — 멀티모달 프롬프트 템플릿화
- ImageFileToImageContent — 이미지 파일을
ImageContent로 변환 - PDFToImageContent — PDF 페이지를
ImageContent로 변환