mirror of
https://github.com/hwchase17/langchain.git
synced 2025-08-02 01:23:07 +00:00
Template for multi-modal w/ multi-vector (#14618)
Results - 
This commit is contained in:
parent
97a91d9d0d
commit
7234335a9a
1
templates/rag-chroma-multi-modal-multi-vector/.gitignore
vendored
Normal file
1
templates/rag-chroma-multi-modal-multi-vector/.gitignore
vendored
Normal file
@ -0,0 +1 @@
|
||||
docs/img_*.jpg
|
21
templates/rag-chroma-multi-modal-multi-vector/LICENSE
Normal file
21
templates/rag-chroma-multi-modal-multi-vector/LICENSE
Normal file
@ -0,0 +1,21 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2023 LangChain, Inc.
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
108
templates/rag-chroma-multi-modal-multi-vector/README.md
Normal file
108
templates/rag-chroma-multi-modal-multi-vector/README.md
Normal file
@ -0,0 +1,108 @@
|
||||
|
||||
# rag-chroma-multi-modal-multi-vector
|
||||
|
||||
Presentations (slide decks, etc) contain visual content that challenges conventional RAG.
|
||||
|
||||
Multi-modal LLMs unlock new ways to build apps over visual content like presentations.
|
||||
|
||||
This template performs multi-modal RAG using Chroma with the multi-vector retriever (see [blog](https://blog.langchain.dev/multi-modal-rag-template/)):
|
||||
|
||||
* Extracts the slides as images
|
||||
* Uses GPT-4V to summarize each image
|
||||
* Embeds the image summaries with a link to the original images
|
||||
* Retrieves relevant image based on similarity between the image summary and the user input
|
||||
* Finally pass those images to GPT-4V for answer synthesis
|
||||
|
||||
## Storage
|
||||
|
||||
We will use Upstash to store the images, which offers Redis with a REST API.
|
||||
|
||||
Simply login [here](https://upstash.com/) and create a database.
|
||||
|
||||
This will give you a REST API with:
|
||||
|
||||
* UPSTASH_URL
|
||||
* UPSTASH_TOKEN
|
||||
|
||||
Set `UPSTASH_URL` and `UPSTASH_TOKEN` as environment variables to access your database.
|
||||
|
||||
We will use Chroma to store and index the image summaries, which will be created locally in the template directory.
|
||||
|
||||
## Input
|
||||
|
||||
Supply a slide deck as pdf in the `/docs` directory.
|
||||
|
||||
Create your vectorstore (Chroma) and populae Upstash with:
|
||||
|
||||
```
|
||||
poetry install
|
||||
python ingest.py
|
||||
```
|
||||
|
||||
## LLM
|
||||
|
||||
The app will retrieve images using multi-modal embeddings, and pass them to GPT-4V.
|
||||
|
||||
## Environment Setup
|
||||
|
||||
Set the `OPENAI_API_KEY` environment variable to access the OpenAI GPT-4V.
|
||||
|
||||
Set `UPSTASH_URL` and `UPSTASH_TOKEN` as environment variables to access your database.
|
||||
|
||||
## Usage
|
||||
|
||||
To use this package, you should first have the LangChain CLI installed:
|
||||
|
||||
```shell
|
||||
pip install -U langchain-cli
|
||||
```
|
||||
|
||||
To create a new LangChain project and install this as the only package, you can do:
|
||||
|
||||
```shell
|
||||
langchain app new my-app --package rag-chroma-multi-modal-multi-vector
|
||||
```
|
||||
|
||||
If you want to add this to an existing project, you can just run:
|
||||
|
||||
```shell
|
||||
langchain app add rag-chroma-multi-modal-multi-vector
|
||||
```
|
||||
|
||||
And add the following code to your `server.py` file:
|
||||
```python
|
||||
from rag_chroma_multi_modal_multi_vector import chain as rag_chroma_multi_modal_chain_mv
|
||||
|
||||
add_routes(app, rag_chroma_multi_modal_chain_mv, path="/rag-chroma-multi-modal-multi-vector")
|
||||
```
|
||||
|
||||
(Optional) Let's now configure LangSmith.
|
||||
LangSmith will help us trace, monitor and debug LangChain applications.
|
||||
LangSmith is currently in private beta, you can sign up [here](https://smith.langchain.com/).
|
||||
If you don't have access, you can skip this section
|
||||
|
||||
```shell
|
||||
export LANGCHAIN_TRACING_V2=true
|
||||
export LANGCHAIN_API_KEY=<your-api-key>
|
||||
export LANGCHAIN_PROJECT=<your-project> # if not specified, defaults to "default"
|
||||
```
|
||||
|
||||
If you are inside this directory, then you can spin up a LangServe instance directly by:
|
||||
|
||||
```shell
|
||||
langchain serve
|
||||
```
|
||||
|
||||
This will start the FastAPI app with a server is running locally at
|
||||
[http://localhost:8000](http://localhost:8000)
|
||||
|
||||
We can see all templates at [http://127.0.0.1:8000/docs](http://127.0.0.1:8000/docs)
|
||||
We can access the playground at [http://127.0.0.1:8000/rag-chroma-multi-modal-multi-vector/playground](http://127.0.0.1:8000/rag-chroma-multi-modal-multi-vector/playground)
|
||||
|
||||
We can access the template from code with:
|
||||
|
||||
```python
|
||||
from langserve.client import RemoteRunnable
|
||||
|
||||
runnable = RemoteRunnable("http://localhost:8000/rag-chroma-multi-modal-multi-vector")
|
||||
```
|
Binary file not shown.
197
templates/rag-chroma-multi-modal-multi-vector/ingest.py
Normal file
197
templates/rag-chroma-multi-modal-multi-vector/ingest.py
Normal file
@ -0,0 +1,197 @@
|
||||
import base64
|
||||
import io
|
||||
import os
|
||||
import uuid
|
||||
from io import BytesIO
|
||||
from pathlib import Path
|
||||
|
||||
import pypdfium2 as pdfium
|
||||
from langchain.chat_models import ChatOpenAI
|
||||
from langchain.embeddings import OpenAIEmbeddings
|
||||
from langchain.retrievers.multi_vector import MultiVectorRetriever
|
||||
from langchain.schema.document import Document
|
||||
from langchain.schema.messages import HumanMessage
|
||||
from langchain.storage import UpstashRedisByteStore
|
||||
from langchain.vectorstores import Chroma
|
||||
from PIL import Image
|
||||
|
||||
|
||||
def image_summarize(img_base64, prompt):
|
||||
"""
|
||||
Make image summary
|
||||
|
||||
:param img_base64: Base64 encoded string for image
|
||||
:param prompt: Text prompt for summarizatiomn
|
||||
:return: Image summarization prompt
|
||||
|
||||
"""
|
||||
chat = ChatOpenAI(model="gpt-4-vision-preview", max_tokens=1024)
|
||||
|
||||
msg = chat.invoke(
|
||||
[
|
||||
HumanMessage(
|
||||
content=[
|
||||
{"type": "text", "text": prompt},
|
||||
{
|
||||
"type": "image_url",
|
||||
"image_url": {"url": f"data:image/jpeg;base64,{img_base64}"},
|
||||
},
|
||||
]
|
||||
)
|
||||
]
|
||||
)
|
||||
return msg.content
|
||||
|
||||
|
||||
def generate_img_summaries(img_base64_list):
|
||||
"""
|
||||
Generate summaries for images
|
||||
|
||||
:param img_base64_list: Base64 encoded images
|
||||
:return: List of image summaries and processed images
|
||||
"""
|
||||
|
||||
# Store image summaries
|
||||
image_summaries = []
|
||||
processed_images = []
|
||||
|
||||
# Prompt
|
||||
prompt = """You are an assistant tasked with summarizing images for retrieval. \
|
||||
These summaries will be embedded and used to retrieve the raw image. \
|
||||
Give a concise summary of the image that is well optimized for retrieval."""
|
||||
|
||||
# Apply summarization to images
|
||||
for i, base64_image in enumerate(img_base64_list):
|
||||
try:
|
||||
image_summaries.append(image_summarize(base64_image, prompt))
|
||||
processed_images.append(base64_image)
|
||||
except Exception as e:
|
||||
print(f"Error with image {i+1}: {e}")
|
||||
|
||||
return image_summaries, processed_images
|
||||
|
||||
|
||||
def get_images_from_pdf(pdf_path):
|
||||
"""
|
||||
Extract images from each page of a PDF document and save as JPEG files.
|
||||
|
||||
:param pdf_path: A string representing the path to the PDF file.
|
||||
"""
|
||||
pdf = pdfium.PdfDocument(pdf_path)
|
||||
n_pages = len(pdf)
|
||||
pil_images = []
|
||||
for page_number in range(n_pages):
|
||||
page = pdf.get_page(page_number)
|
||||
bitmap = page.render(scale=1, rotation=0, crop=(0, 0, 0, 0))
|
||||
pil_image = bitmap.to_pil()
|
||||
pil_images.append(pil_image)
|
||||
return pil_images
|
||||
|
||||
|
||||
def resize_base64_image(base64_string, size=(128, 128)):
|
||||
"""
|
||||
Resize an image encoded as a Base64 string
|
||||
|
||||
:param base64_string: Base64 string
|
||||
:param size: Image size
|
||||
:return: Re-sized Base64 string
|
||||
"""
|
||||
# Decode the Base64 string
|
||||
img_data = base64.b64decode(base64_string)
|
||||
img = Image.open(io.BytesIO(img_data))
|
||||
|
||||
# Resize the image
|
||||
resized_img = img.resize(size, Image.LANCZOS)
|
||||
|
||||
# Save the resized image to a bytes buffer
|
||||
buffered = io.BytesIO()
|
||||
resized_img.save(buffered, format=img.format)
|
||||
|
||||
# Encode the resized image to Base64
|
||||
return base64.b64encode(buffered.getvalue()).decode("utf-8")
|
||||
|
||||
|
||||
def convert_to_base64(pil_image):
|
||||
"""
|
||||
Convert PIL images to Base64 encoded strings
|
||||
|
||||
:param pil_image: PIL image
|
||||
:return: Re-sized Base64 string
|
||||
"""
|
||||
|
||||
buffered = BytesIO()
|
||||
pil_image.save(buffered, format="JPEG") # You can change the format if needed
|
||||
img_str = base64.b64encode(buffered.getvalue()).decode("utf-8")
|
||||
img_str = resize_base64_image(img_str, size=(960, 540))
|
||||
return img_str
|
||||
|
||||
|
||||
def create_multi_vector_retriever(vectorstore, image_summaries, images):
|
||||
"""
|
||||
Create retriever that indexes summaries, but returns raw images or texts
|
||||
|
||||
:param vectorstore: Vectorstore to store embedded image sumamries
|
||||
:param image_summaries: Image summaries
|
||||
:param images: Base64 encoded images
|
||||
:return: Retriever
|
||||
"""
|
||||
|
||||
# Initialize the storage layer for images
|
||||
UPSTASH_URL = os.getenv("UPSTASH_URL")
|
||||
UPSTASH_TOKEN = os.getenv("UPSTASH_TOKEN")
|
||||
store = UpstashRedisByteStore(url=UPSTASH_URL, token=UPSTASH_TOKEN)
|
||||
id_key = "doc_id"
|
||||
|
||||
# Create the multi-vector retriever
|
||||
retriever = MultiVectorRetriever(
|
||||
vectorstore=vectorstore,
|
||||
byte_store=store,
|
||||
id_key=id_key,
|
||||
)
|
||||
|
||||
# Helper function to add documents to the vectorstore and docstore
|
||||
def add_documents(retriever, doc_summaries, doc_contents):
|
||||
doc_ids = [str(uuid.uuid4()) for _ in doc_contents]
|
||||
summary_docs = [
|
||||
Document(page_content=s, metadata={id_key: doc_ids[i]})
|
||||
for i, s in enumerate(doc_summaries)
|
||||
]
|
||||
retriever.vectorstore.add_documents(summary_docs)
|
||||
retriever.docstore.mset(list(zip(doc_ids, doc_contents)))
|
||||
|
||||
add_documents(retriever, image_summaries, images)
|
||||
|
||||
return retriever
|
||||
|
||||
|
||||
# Load PDF
|
||||
doc_path = Path(__file__).parent / "docs/DDOG_Q3_earnings_deck.pdf"
|
||||
rel_doc_path = doc_path.relative_to(Path.cwd())
|
||||
print("Extract slides as images")
|
||||
pil_images = get_images_from_pdf(rel_doc_path)
|
||||
|
||||
# Convert to b64
|
||||
images_base_64 = [convert_to_base64(i) for i in pil_images]
|
||||
|
||||
# Image summaries
|
||||
print("Generate image summaries")
|
||||
image_summaries, images_base_64_processed = generate_img_summaries(images_base_64)
|
||||
|
||||
# The vectorstore to use to index the images summaries
|
||||
vectorstore_mvr = Chroma(
|
||||
collection_name="image_summaries",
|
||||
persist_directory=str(Path(__file__).parent / "chroma_db_multi_modal"),
|
||||
embedding_function=OpenAIEmbeddings(),
|
||||
)
|
||||
|
||||
# Create documents
|
||||
images_base_64_processed_documents = [
|
||||
Document(page_content=i) for i in images_base_64_processed
|
||||
]
|
||||
|
||||
# Create retriever
|
||||
retriever_multi_vector_img = create_multi_vector_retriever(
|
||||
vectorstore_mvr,
|
||||
image_summaries,
|
||||
images_base_64_processed_documents,
|
||||
)
|
2949
templates/rag-chroma-multi-modal-multi-vector/poetry.lock
generated
Normal file
2949
templates/rag-chroma-multi-modal-multi-vector/poetry.lock
generated
Normal file
File diff suppressed because it is too large
Load Diff
38
templates/rag-chroma-multi-modal-multi-vector/pyproject.toml
Normal file
38
templates/rag-chroma-multi-modal-multi-vector/pyproject.toml
Normal file
@ -0,0 +1,38 @@
|
||||
[tool.poetry]
|
||||
name = "rag-chroma-multi-modal-multi-vector"
|
||||
version = "0.1.0"
|
||||
description = "Multi-modal RAG using Chroma and multi-vector retriever"
|
||||
authors = [
|
||||
"Lance Martin <lance@langchain.dev>",
|
||||
]
|
||||
readme = "README.md"
|
||||
|
||||
[tool.poetry.dependencies]
|
||||
python = ">=3.8.1,<4.0"
|
||||
langchain = ">=0.0.350"
|
||||
openai = "<2"
|
||||
tiktoken = ">=0.5.1"
|
||||
chromadb = ">=0.4.14"
|
||||
pypdfium2 = ">=4.20.0"
|
||||
langchain-experimental = "^0.0.43"
|
||||
upstash-redis = ">=1.0.0"
|
||||
pillow = ">=10.1.0"
|
||||
|
||||
[tool.poetry.group.dev.dependencies]
|
||||
langchain-cli = ">=0.0.15"
|
||||
|
||||
[tool.langserve]
|
||||
export_module = "rag_chroma_multi_modal_multi_vector"
|
||||
export_attr = "chain"
|
||||
|
||||
[tool.templates-hub]
|
||||
use-case = "rag"
|
||||
author = "LangChain"
|
||||
integrations = ["OpenAI", "Chroma"]
|
||||
tags = ["vectordbs"]
|
||||
|
||||
[build-system]
|
||||
requires = [
|
||||
"poetry-core",
|
||||
]
|
||||
build-backend = "poetry.core.masonry.api"
|
@ -0,0 +1,52 @@
|
||||
{
|
||||
"cells": [
|
||||
{
|
||||
"attachments": {},
|
||||
"cell_type": "markdown",
|
||||
"id": "681a5d1e",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"## Run Template\n",
|
||||
"\n",
|
||||
"In `server.py`, set -\n",
|
||||
"```\n",
|
||||
"add_routes(app, chain_rag_conv, path=\"/rag-chroma-multi-modal-multi-vector\")\n",
|
||||
"```"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"id": "d774be2a",
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"from langserve.client import RemoteRunnable\n",
|
||||
"\n",
|
||||
"rag_app = RemoteRunnable(\"http://localhost:8001/rag-chroma-multi-modal-multi-vector\")\n",
|
||||
"rag_app.invoke(\"What is the projected TAM for observability expected for each year through 2026?\")"
|
||||
]
|
||||
}
|
||||
],
|
||||
"metadata": {
|
||||
"kernelspec": {
|
||||
"display_name": "Python 3 (ipykernel)",
|
||||
"language": "python",
|
||||
"name": "python3"
|
||||
},
|
||||
"language_info": {
|
||||
"codemirror_mode": {
|
||||
"name": "ipython",
|
||||
"version": 3
|
||||
},
|
||||
"file_extension": ".py",
|
||||
"mimetype": "text/x-python",
|
||||
"name": "python",
|
||||
"nbconvert_exporter": "python",
|
||||
"pygments_lexer": "ipython3",
|
||||
"version": "3.9.16"
|
||||
}
|
||||
},
|
||||
"nbformat": 4,
|
||||
"nbformat_minor": 5
|
||||
}
|
@ -0,0 +1,3 @@
|
||||
from rag_chroma_multi_modal_multi_vector.chain import chain
|
||||
|
||||
__all__ = ["chain"]
|
@ -0,0 +1,133 @@
|
||||
import base64
|
||||
import io
|
||||
import os
|
||||
from pathlib import Path
|
||||
|
||||
from langchain.chat_models import ChatOpenAI
|
||||
from langchain.embeddings import OpenAIEmbeddings
|
||||
from langchain.pydantic_v1 import BaseModel
|
||||
from langchain.retrievers.multi_vector import MultiVectorRetriever
|
||||
from langchain.schema.document import Document
|
||||
from langchain.schema.messages import HumanMessage
|
||||
from langchain.schema.output_parser import StrOutputParser
|
||||
from langchain.schema.runnable import RunnableLambda, RunnablePassthrough
|
||||
from langchain.storage import UpstashRedisByteStore
|
||||
from langchain.vectorstores import Chroma
|
||||
from PIL import Image
|
||||
|
||||
|
||||
def resize_base64_image(base64_string, size=(128, 128)):
|
||||
"""
|
||||
Resize an image encoded as a Base64 string.
|
||||
|
||||
:param base64_string: A Base64 encoded string of the image to be resized.
|
||||
:param size: A tuple representing the new size (width, height) for the image.
|
||||
:return: A Base64 encoded string of the resized image.
|
||||
"""
|
||||
img_data = base64.b64decode(base64_string)
|
||||
img = Image.open(io.BytesIO(img_data))
|
||||
resized_img = img.resize(size, Image.LANCZOS)
|
||||
buffered = io.BytesIO()
|
||||
resized_img.save(buffered, format=img.format)
|
||||
return base64.b64encode(buffered.getvalue()).decode("utf-8")
|
||||
|
||||
|
||||
def get_resized_images(docs):
|
||||
"""
|
||||
Resize images from base64-encoded strings.
|
||||
|
||||
:param docs: A list of base64-encoded image to be resized.
|
||||
:return: Dict containing a list of resized base64-encoded strings.
|
||||
"""
|
||||
b64_images = []
|
||||
for doc in docs:
|
||||
if isinstance(doc, Document):
|
||||
doc = doc.page_content
|
||||
resized_image = resize_base64_image(doc, size=(1280, 720))
|
||||
b64_images.append(resized_image)
|
||||
return {"images": b64_images}
|
||||
|
||||
|
||||
def img_prompt_func(data_dict, num_images=2):
|
||||
"""
|
||||
GPT-4V prompt for image analysis.
|
||||
|
||||
:param data_dict: A dict with images and a user-provided question.
|
||||
:param num_images: Number of images to include in the prompt.
|
||||
:return: A list containing message objects for each image and the text prompt.
|
||||
"""
|
||||
messages = []
|
||||
if data_dict["context"]["images"]:
|
||||
for image in data_dict["context"]["images"][:num_images]:
|
||||
image_message = {
|
||||
"type": "image_url",
|
||||
"image_url": {"url": f"data:image/jpeg;base64,{image}"},
|
||||
}
|
||||
messages.append(image_message)
|
||||
text_message = {
|
||||
"type": "text",
|
||||
"text": (
|
||||
"You are an analyst tasked with answering questions about visual content.\n"
|
||||
"You will be give a set of image(s) from a slide deck / presentation.\n"
|
||||
"Use this information to answer the user question. \n"
|
||||
f"User-provided question: {data_dict['question']}\n\n"
|
||||
),
|
||||
}
|
||||
messages.append(text_message)
|
||||
return [HumanMessage(content=messages)]
|
||||
|
||||
|
||||
def multi_modal_rag_chain(retriever):
|
||||
"""
|
||||
Multi-modal RAG chain,
|
||||
|
||||
:param retriever: A function that retrieves the necessary context for the model.
|
||||
:return: A chain of functions representing the multi-modal RAG process.
|
||||
"""
|
||||
# Initialize the multi-modal Large Language Model with specific parameters
|
||||
model = ChatOpenAI(temperature=0, model="gpt-4-vision-preview", max_tokens=1024)
|
||||
|
||||
# Define the RAG pipeline
|
||||
chain = (
|
||||
{
|
||||
"context": retriever | RunnableLambda(get_resized_images),
|
||||
"question": RunnablePassthrough(),
|
||||
}
|
||||
| RunnableLambda(img_prompt_func)
|
||||
| model
|
||||
| StrOutputParser()
|
||||
)
|
||||
|
||||
return chain
|
||||
|
||||
|
||||
# Load chroma
|
||||
vectorstore_mvr = Chroma(
|
||||
collection_name="image_summaries",
|
||||
persist_directory=str(Path(__file__).parent.parent / "chroma_db_multi_modal"),
|
||||
embedding_function=OpenAIEmbeddings(),
|
||||
)
|
||||
|
||||
# Load redis
|
||||
UPSTASH_URL = os.getenv("UPSTASH_URL")
|
||||
UPSTASH_TOKEN = os.getenv("UPSTASH_TOKEN")
|
||||
store = UpstashRedisByteStore(url=UPSTASH_URL, token=UPSTASH_TOKEN)
|
||||
id_key = "doc_id"
|
||||
|
||||
# Create the multi-vector retriever
|
||||
retriever = MultiVectorRetriever(
|
||||
vectorstore=vectorstore_mvr,
|
||||
byte_store=store,
|
||||
id_key=id_key,
|
||||
)
|
||||
|
||||
# Create RAG chain
|
||||
chain = multi_modal_rag_chain(retriever)
|
||||
|
||||
|
||||
# Add typing for input
|
||||
class Question(BaseModel):
|
||||
__root__: str
|
||||
|
||||
|
||||
chain = chain.with_types(input_type=Question)
|
Loading…
Reference in New Issue
Block a user