multimodal_retrieval.pypythonfrom langchain_openai import ChatOpenAI
vision_llm = ChatOpenAI(model="gpt-4o", temperature=0)
def summarize_table(table_html: str) -> str:
"""Generate a text summary of a table for embedding."""
response = vision_llm.invoke(
f"Summarize the key information in this HTML table in 2-3 sentences. "
f"Include specific numbers and comparisons:\n{table_html}"
)
return response.content
def describe_image(image_path: str) -> str:
"""Generate a text description of an image for embedding."""
import base64
with open(image_path, "rb") as f:
image_data = base64.b64encode(f.read()).decode()
response = vision_llm.invoke([
{"type": "text", "text": "Describe this image in detail, including any text, data, or diagrams shown."},
{"type": "image_url", "image_url": {"url": f"data:image/png;base64,{image_data}"}}
])
return response.content
# Create unified text representations
all_chunks = []
for text in texts:
all_chunks.append({"content": text, "type": "text"})
for table in tables:
summary = summarize_table(table)
all_chunks.append({"content": summary, "type": "table", "raw": table})
for img_path in images:
description = describe_image(img_path)
all_chunks.append({"content": description, "type": "image", "path": img_path})
# Now embed and store all chunks uniformly
# Retrieval works the same as text-only RAG