ImageFileToImageContent
ImageFileToImageContent 读取本地图片文件并将其转换为ImageContent 对象。这些对象可用于多模态 AI 管道,包括图像字幕生成、视觉问答或基于提示的生成等任务。
| pipeline 中的最常见位置 | 在查询管道中的ChatPromptBuilder 之前 |
| 强制运行变量 | "sources": 图片文件路径或字节流列表 |
| 输出变量 | "image_contents": ImageContent 对象列表 |
| API 参考 | 图像转换器 |
| GitHub 链接 | https://github.com/deepset-ai/haystack/blob/main/haystack/components/converters/image/file_to_image.py |
概述
ImageFileToImageContent 处理一系列图片源并将其转换为ImageContent 对象。这些对象可用于需要 base64 编码图片输入的模态管道。
每个源都可以是
- 文件路径(字符串或
Path),或 - 一个
ByteStream对象。
可选地,您可以使用meta 参数。这可以是一个字典(应用于所有图片),也可以是与长度匹配的列表。sources.
使用size 参数,用于在保持纵横比的同时调整图片大小。这可以减少内存使用和传输大小,在处理远程模型或资源受限的环境时非常有用。
此组件通常在查询管道中使用,紧接在ChatPromptBuilder.
用法
单独使用
from haystack.components.converters.image import ImageFileToImageContent
converter = ImageFileToImageContent(detail="high", size=(800, 600))
sources = ["cat.jpg", "scenery.png"]
result = converter.run(sources=sources)
image_contents = result["image_contents"]
print(image_contents)
# [
# ImageContent(
# base64_image="/9j/4A...", mime_type="image/jpeg", detail="high",
# meta={"file_path": "cat.jpg"}
# ),
# ImageContent(
# base64_image="/9j/4A...", mime_type="image/png", detail="high",
# meta={"file_path": "scenery.png"}
# )
# ]
在 pipeline 中
使用ImageFileToImageContent 之前,以便为ChatPromptBuilder 提供图片数据,用于多模态问答或与 LLM 进行字幕生成。
from haystack import Pipeline
from haystack.components.builders import ChatPromptBuilder
from haystack.components.generators.chat import OpenAIChatGenerator
from haystack.components.converters.image import ImageFileToImageContent
# Query pipeline
pipeline = Pipeline()
pipeline.add_component("image_converter", ImageFileToImageContent(detail="auto"))
pipeline.add_component(
"chat_prompt_builder",
ChatPromptBuilder(
required_variables=["question"],
template="""{% message role="system" %}
You are a helpful assistant that answers questions using the provided images.
{% endmessage %}
{% message role="user" %}
Question: {{ question }}
{% for img in image_contents %}
{{ img | templatize_part }}
{% endfor %}
{% endmessage %}
"""
)
)
pipeline.add_component("llm", OpenAIChatGenerator(model="gpt-4o-mini"))
pipeline.connect("image_converter", "chat_prompt_builder.image_contents")
pipeline.connect("chat_prompt_builder", "llm")
sources = ["apple.jpg", "haystack-logo.png"]
result = pipeline.run(
data={
"image_converter": {"sources": sources},
"chat_prompt_builder": {"question": "Describe the Haystack logo."}
}
)
print(result)
# {
# "llm": {
# "replies": [
# ChatMessage(
# _role=<ChatRole.ASSISTANT: 'assistant'>,
# _content=[TextContent(text="The Haystack logo features...")],
# ...
# )
# ]
# }
# }
其他参考资料
🧑🍳 食谱:M 模态简介
更新于 3 个月前
