跳转到内容

使用LlamaIndex的Chroma多模态演示

Chroma is a AI-native open-source vector database focused on developer productivity and happiness. Chroma is licensed under Apache 2.0.

Discord    License    Integration Tests

Chroma是完全类型化、完全测试和完全文档化的。

使用以下命令安装 Chroma:

Terminal window
pip install chromadb

Chroma 可在多种模式下运行。以下是与 LangChain 集成的每种模式示例。

  • in-memoryin-memory - 在 Python 脚本或 Jupyter 笔记本中
  • in-memory with persistencein-memory with persistence - 在脚本或笔记本中,并保存/加载到磁盘
  • in a docker containerin a docker container - 作为在您本地机器或云端运行的服务器

与任何其他数据库一样,您可以:

  • .add
  • .get
  • .update
  • .upsert
  • .delete
  • .peek
  • and .query runs the similarity search.

View full docs at docs.

在这个基础示例中,我们选取一篇保罗·格雷厄姆的文章,将其分割成多个片段,使用开源嵌入模型进行嵌入处理,加载到Chroma中,然后进行查询。

如果您在 Colab 上打开这个笔记本,您可能需要安装 LlamaIndex 🦙。

%pip install llama-index-vector-stores-qdrant
%pip install llama-index-embeddings-huggingface
%pip install llama-index-vector-stores-chroma
!pip install llama-index
!pip install llama-index chromadb --quiet
!pip install chromadb==0.4.17
!pip install sentence-transformers
!pip install pydantic==1.10.11
!pip install open-clip-torch
# import
from llama_index.core import VectorStoreIndex, SimpleDirectoryReader
from llama_index.vector_stores.chroma import ChromaVectorStore
from llama_index.core import StorageContext
from llama_index.embeddings.huggingface import HuggingFaceEmbedding
from IPython.display import Markdown, display
import chromadb
# set up OpenAI
import os
import openai
OPENAI_API_KEY = ""
openai.api_key = OPENAI_API_KEY
os.environ["OPENAI_API_KEY"] = OPENAI_API_KEY
import requests
def get_wikipedia_images(title):
response = requests.get(
"https://en.wikipedia.org/w/api.php",
params={
"action": "query",
"format": "json",
"titles": title,
"prop": "imageinfo",
"iiprop": "url|dimensions|mime",
"generator": "images",
"gimlimit": "50",
},
).json()
image_urls = []
for page in response["query"]["pages"].values():
if page["imageinfo"][0]["url"].endswith(".jpg") or page["imageinfo"][
0
]["url"].endswith(".png"):
image_urls.append(page["imageinfo"][0]["url"])
return image_urls
from pathlib import Path
import urllib.request
image_uuid = 0
MAX_IMAGES_PER_WIKI = 20
wiki_titles = {
"Tesla Model X",
"Pablo Picasso",
"Rivian",
"The Lord of the Rings",
"The Matrix",
"The Simpsons",
}
data_path = Path("mixed_wiki")
if not data_path.exists():
Path.mkdir(data_path)
for title in wiki_titles:
response = requests.get(
"https://en.wikipedia.org/w/api.php",
params={
"action": "query",
"format": "json",
"titles": title,
"prop": "extracts",
"explaintext": True,
},
).json()
page = next(iter(response["query"]["pages"].values()))
wiki_text = page["extract"]
with open(data_path / f"{title}.txt", "w") as fp:
fp.write(wiki_text)
images_per_wiki = 0
try:
# page_py = wikipedia.page(title)
list_img_urls = get_wikipedia_images(title)
# print(list_img_urls)
for url in list_img_urls:
if url.endswith(".jpg") or url.endswith(".png"):
image_uuid += 1
# image_file_name = title + "_" + url.split("/")[-1]
urllib.request.urlretrieve(
url, data_path / f"{image_uuid}.jpg"
)
images_per_wiki += 1
# Limit the number of images downloaded per wiki page to 15
if images_per_wiki > MAX_IMAGES_PER_WIKI:
break
except:
print(str(Exception("No images found for Wikipedia page: ")) + title)
continue
from chromadb.utils.embedding_functions import OpenCLIPEmbeddingFunction
# set defalut text and image embedding functions
embedding_function = OpenCLIPEmbeddingFunction()
/Users/haotianzhang/llama_index/venv/lib/python3.11/site-packages/tqdm/auto.py:21: TqdmWarning: IProgress not found. Please update jupyter and ipywidgets. See https://ipywidgets.readthedocs.io/en/stable/user_install.html
from .autonotebook import tqdm as notebook_tqdm
from llama_index.core.indices import MultiModalVectorStoreIndex
from llama_index.vector_stores.qdrant import QdrantVectorStore
from llama_index.core import SimpleDirectoryReader, StorageContext
from chromadb.utils.data_loaders import ImageLoader
image_loader = ImageLoader()
# create client and a new collection
chroma_client = chromadb.EphemeralClient()
chroma_collection = chroma_client.create_collection(
"multimodal_collection",
embedding_function=embedding_function,
data_loader=image_loader,
)
# load documents
documents = SimpleDirectoryReader("./mixed_wiki/").load_data()
# set up ChromaVectorStore and load in data
vector_store = ChromaVectorStore(chroma_collection=chroma_collection)
storage_context = StorageContext.from_defaults(vector_store=vector_store)
index = VectorStoreIndex.from_documents(
documents,
storage_context=storage_context,
)
retriever = index.as_retriever(similarity_top_k=50)
retrieval_results = retriever.retrieve("Picasso famous paintings")
# print(retrieval_results)
from llama_index.core.schema import ImageNode
from llama_index.core.response.notebook_utils import (
display_source_node,
display_image_uris,
)
image_results = []
MAX_RES = 5
cnt = 0
for r in retrieval_results:
if isinstance(r.node, ImageNode):
image_results.append(r.node.metadata["file_path"])
else:
if cnt < MAX_RES:
display_source_node(r)
cnt += 1
display_image_uris(image_results, [3, 3], top_k=2)

节点ID: 13adcbba-fe8b-4d51-9139-fb1c55ffc6be
相似度: 0.774399292477267
文本: == 艺术遗产 == 毕加索的影响力过去和现在都极为深远,并广受认可…

节点ID: 4100593e-6b6a-4b5f-8384-98d1c2468204
相似度: 0.7695965506408678
文本: === 晚期作品至最终岁月:1949–1973 === 毕加索是参与第三届…

节点ID: aeed9d43-f9c5-42a9-a7b9-1a3c005e3745
相似度: 0.7693110304140338
文本: 巴勃罗·鲁伊斯·毕加索(1881年10月25日-1973年4月8日)是一位西班牙画家、雕塑家、版画家……

节点ID: 5a6613b6-b599-4e40-92f2-231e10ed54f6
相似度: 0.7656537748231977
文本: === 巴塞尔投票 === 20世纪40年代,一家总部位于巴塞尔的瑞士保险公司购买了两幅画作…

节点ID: cc17454c-030d-4f86-a12e-342d0582f4d3
相似度: 0.7639671751819532
文本: == 风格与技巧 ==

毕加索在他漫长的一生中创作异常丰富。在他…

png