Compare commits

...

1 Commits

Author SHA1 Message Date
Lance Martin
c0f3a99893 Multi modal RAG template 2023-11-03 15:07:04 -07:00
14 changed files with 5736 additions and 0 deletions

View 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.

View File

@@ -0,0 +1,77 @@
# rag-multi-modal
This template performs RAG on multi-modal data, such as a PDF with text and images.
XXX
## Environment Setup
Set the `OPENAI_API_KEY` environment variable to access the OpenAI models.
This uses [Unstructured](https://unstructured-io.github.io/unstructured/) for PDF parsing, which requires some system-level package installations.
On Mac, you can install the necessary packages with the following:
```shell
brew install tesseract poppler
```
## Usage
To use this package, you should first have the LangChain CLI installed:
```shell
pip install -U "langchain-cli[serve]"
```
To create a new LangChain project and install this as the only package, you can do:
```shell
langchain app new my-app --package rag-multi-modal
```
If you want to add this to an existing project, you can just run:
```shell
langchain app add rag-multi-modal
```
And add the following code to your `server.py` file:
```python
from rag_semi_structured import chain as rag_semi_structured_chain
add_routes(app, rag_semi_structured_chain, path="/rag-multi-modal")
```
(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-multi-modal/playground](http://127.0.0.1:8000/rag-multi-modal/playground)
We can access the template from code with:
```python
from langserve.client import RemoteRunnable
runnable = RemoteRunnable("http://localhost:8000/rag-multi-modal")
```
For more details on how to connect to the template, refer to the Jupyter notebook `rag-multi-modal`.

2890
templates/rag-multi-modal/poetry.lock generated Normal file

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,27 @@
[tool.poetry]
name = "rag-semi-structured"
version = "0.1.0"
description = ""
authors = [
"Lance Martin <lance@langchain.dev>",
]
readme = "README.md"
[tool.poetry.dependencies]
python = ">=3.8.1,<4.0"
langchain = ">=0.0.325"
tiktoken = ">=0.5.1"
chromadb = ">=0.4.14"
openai = ">=0.27.9"
unstructured = ">=0.10.19"
pdf2image = ">=1.16.3"
[tool.langserve]
export_module = "rag_semi_structured"
export_attr = "chain"
[build-system]
requires = [
"poetry-core",
]
build-backend = "poetry.core.masonry.api"

View File

@@ -0,0 +1,51 @@
{
"cells": [
{
"cell_type": "markdown",
"id": "30fc2c27",
"metadata": {},
"source": [
"## Run Template\n",
"\n",
"In `server.py`, set -\n",
"```\n",
"add_routes(app, chain_rag_conv, path=\"/multi-modal-rag\")\n",
"```"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "65f5b560",
"metadata": {},
"outputs": [],
"source": [
"from langserve.client import RemoteRunnable\n",
"\n",
"rag_app = RemoteRunnable(\"http://localhost:8001/multi-modal-rag\")\n",
"rag_app.invoke(\"How does the share of large-large AI results shift from 2012 to 2022?\")"
]
}
],
"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
}

View File

@@ -0,0 +1,3 @@
from rag_multi_modal.chain import chain
__all__ = ["chain"]

View File

@@ -0,0 +1,94 @@
# Load
import os
import uuid
import chromadb
import numpy as np
from chromadb.utils.embedding_functions import OpenCLIPEmbeddingFunction
from langchain.chat_models import ChatOpenAI
from langchain.prompts import ChatPromptTemplate
from langchain.schema.output_parser import StrOutputParser
from langchain.schema.runnable import RunnablePassthrough
from langchain.vectorstores import Chroma
from PIL import Image as _PILImage
from pydantic import BaseModel
from unstructured.partition.pdf import partition_pdf
# File
path = "tests/ai_labs/"
paper = "ai_labs.pdf"
# Load and partition
raw_pdf_elements = partition_pdf(
filename=path + paper,
extract_images_in_pdf=True, # Extract images
infer_table_structure=True, # Post processing to aggregate text into sections
chunking_strategy="by_title",
max_characters=4000,
new_after_n_chars=3800,
combine_text_under_n_chars=2000,
image_output_dir_path=path,
)
# Get texts and tables
tables = []
texts = []
for element in raw_pdf_elements:
if "unstructured.documents.elements.Table" in str(type(element)):
tables.append(str(element))
elif "unstructured.documents.elements.CompositeElement" in str(type(element)):
texts.append(str(element))
# Get images
image_files = [f for f in os.listdir(path) if f.endswith(".jpg")]
images = [np.array(_PILImage.open(path + f).convert("RGB")) for f in image_files]
# Store in Chroma with multimodal embd
## TO DO: Merge
client = chromadb.Client()
embedding_function = OpenCLIPEmbeddingFunction()
collection = client.create_collection("mm_rag", embedding_function=embedding_function)
image_ids = [str(uuid.uuid4()) for _ in images]
collection.add(ids=image_ids, images=images)
text_ids = [str(uuid.uuid4()) for _ in texts]
collection.add(ids=text_ids, documents=texts)
collection.get(include=["documents"])
# Pass Chroma Client to LangChain
vectorstore = Chroma(
client=client,
collection_name="mm_rag",
embedding_function=embedding_function,
)
retriever = vectorstore.as_retriever()
# RAG
# Prompt template
template = """Answer the question based only on the following context, which can include text and tables:
{context}
Question: {question}
""" # noqa: E501
prompt = ChatPromptTemplate.from_template(template)
# LLM
### placeholder ###
model = ChatOpenAI(temperature=0, model="gpt-4v")
# RAG pipeline
chain = (
{"context": retriever, "question": RunnablePassthrough()}
| prompt
| model
| StrOutputParser()
)
# Add typing for input
class Question(BaseModel):
__root__: str
chain = chain.with_types(input_type=Question)

View File

@@ -0,0 +1,10 @@
Paper,Question,Answer
wildfire.pdf,What is the difference in acres burned from Wildfires between 1993 and 2022?,"Acres burned from wildfires increases from ~2M in 1993 to ~8M in 2022, a ~4x increase."
wildfire.pdf,What is the trend in the total number of wildfires between 1993 and 2022?,The total number of wildfires between 1993 and 2022 has oscillated up and down without a clear trend in either direction. The total number of fires in 1993 is about equal to the number in 2022.
housing.pdf,How does housing compare to medical care in CPI weights?,Housing is 42% of CPI whereas medical care is 9%.
housing.pdf,Whats the share of recreation in the CPI weights?,Recreation is 6% of CPI.
ai_labs.pdf,How does the share of large-large AI results shift from 2012 to 2022?,The majority of results in 2012 came from academia whereas by 2022 research consortiums and academia have an equal share.
ai_labs.pdf,When did research consortiums start to play a role in large scale AI results?,Research consortiums started to produce large scale AI results in 2021.
nvda.pdf,What is the acceleration benefit from A100 on Physics HPC applications?,A100 achieves 1.9x and 2.1x acceleration on LAMMPS and Chroma for physics.
bridewater.pdf,What is the trend in call center employment from 2000 to 2023?,"Call center employment rose significantly between around 2005 and around 2015. It has then falling since around 2015, most notably in the past 19 months."
bridewater.pdf,What is the typical time lag between the first examples of a new technology and the resulting rise in productivity growth?,There is typically a multi-year lag between the fist demonstration of technology and their resulting impact on productivity growth: for electrification it was around 20 years and for PCs it was also around 20 years.
1 Paper Question Answer
2 wildfire.pdf What is the difference in acres burned from Wildfires between 1993 and 2022? Acres burned from wildfires increases from ~2M in 1993 to ~8M in 2022, a ~4x increase.
3 wildfire.pdf What is the trend in the total number of wildfires between 1993 and 2022? The total number of wildfires between 1993 and 2022 has oscillated up and down without a clear trend in either direction. The total number of fires in 1993 is about equal to the number in 2022.
4 housing.pdf How does housing compare to medical care in CPI weights? Housing is 42% of CPI whereas medical care is 9%.
5 housing.pdf What’s the share of recreation in the CPI weights? Recreation is 6% of CPI.
6 ai_labs.pdf How does the share of large-large AI results shift from 2012 to 2022? The majority of results in 2012 came from academia whereas by 2022 research consortiums and academia have an equal share.
7 ai_labs.pdf When did research consortiums start to play a role in large scale AI results? Research consortiums started to produce large scale AI results in 2021.
8 nvda.pdf What is the acceleration benefit from A100 on Physics HPC applications? A100 achieves 1.9x and 2.1x acceleration on LAMMPS and Chroma for physics.
9 bridewater.pdf What is the trend in call center employment from 2000 to 2023? Call center employment rose significantly between around 2005 and around 2015. It has then falling since around 2015, most notably in the past 19 months.
10 bridewater.pdf What is the typical time lag between the first examples of a new technology and the resulting rise in productivity growth? There is typically a multi-year lag between the fist demonstration of technology and their resulting impact on productivity growth: for electrification it was around 20 years and for PCs it was also around 20 years.

Binary file not shown.

File diff suppressed because one or more lines are too long

Binary file not shown.

File diff suppressed because one or more lines are too long