首页  >  文章  >  后端开发  >  使用 LlamaIndex 和 Ollama 的高级索引技术:第 2 部分

使用 LlamaIndex 和 Ollama 的高级索引技术:第 2 部分

王林
王林原创
2024-08-14 22:34:02885浏览

Advanced Indexing Techniques with LlamaIndex and Ollama: Part 2

使用 LlamaIndex 和 Ollama 的高级索引技术:第 2 部分

代码可以在这里找到:GitHub - jamesbmour/blog_tutorials:

欢迎回到我们对 LlamaIndex 和 Ollama 的深入研究!在第 1 部分中,我们介绍了设置和使用这些强大工具进行高效信息检索的要点。现在,是时候探索高级索引技术了,它将把您的文档处理和查询能力提升到一个新的水平。

一、简介

在继续之前,让我们快速回顾一下第 1 部分的要点:

  • 设置 LlamaIndex 和 Ollama
  • 创建基本索引
  • 执行简单查询

在这一部分中,我们将深入研究不同的索引类型,学习如何自定义索引设置、管理多个文档以及探索高级查询技术。最后,您将对如何利用 LlamaIndex 和 Ollama 执行复杂的信息检索任务有一个深入的了解。

如果您尚未设置环境,请务必参阅第 1 部分,了解有关安装和配置 LlamaIndex 和 Ollama 的详细说明。

2. 探索不同的指数类型

LlamaIndex 提供各种索引类型,每种索引类型都针对不同的用例量身定制。让我们探讨四种主要类型:

2.1 列表索引

列表索引是 LlamaIndex 中最简单的索引形式。它是文本块的有序列表,非常适合简单的用例。

from llama_index.core import ListIndex, SimpleDirectoryReader, VectorStoreIndex
from dotenv import load_dotenv
from llama_index.llms.ollama import  Ollama
from llama_index.core import Settings
from IPython.display import Markdown, display
from llama_index.vector_stores.chroma import ChromaVectorStore
from llama_index.core import StorageContext
from llama_index.embeddings.ollama import OllamaEmbedding
import chromadb
from IPython.display import HTML
# make markdown display text color green for all cells
# Apply green color to all Markdown output
def display_green_markdown(text):
    green_style = """
    <style>
    .green-output {
        color: green;
    }
    </style>
    """
    green_markdown = f'<div class="green-output">{text}</div>'
    display(HTML(green_style + green_markdown))


# set the llm to ollama
Settings.llm = Ollama(model='phi3', base_url='http://localhost:11434',temperature=0.1)

load_dotenv()

documents = SimpleDirectoryReader('data').load_data()
index = ListIndex.from_documents(documents)

query_engine = index.as_query_engine()
response = query_engine.query("What is llama index used for?")

display_green_markdown(response)

优点:

  • 创建简单快捷
  • 最适合小型文档集

缺点:

  • 大型数据集效率较低
  • 语义理解有限

2.2 向量存储索引

矢量存储索引利用嵌入来创建文档的语义表示,从而实现更复杂的搜索。

# Create Chroma client
chroma_client = chromadb.EphemeralClient()

# Define collection name
collection_name = "quickstart"

# Check if the collection already exists
existing_collections = chroma_client.list_collections()

if collection_name in [collection.name for collection in existing_collections]:
    chroma_collection = chroma_client.get_collection(collection_name)
    print(f"Using existing collection '{collection_name}'.")
else:
    chroma_collection = chroma_client.create_collection(collection_name)
    print(f"Created new collection '{collection_name}'.")

# Set up embedding model
embed_model = OllamaEmbedding(
    model_name="snowflake-arctic-embed",
    base_url="http://localhost:11434",
    ollama_additional_kwargs={"prostatic": 0},
)

# Load documents
documents = SimpleDirectoryReader("./data/paul_graham/").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, embed_model=embed_model
)

# Create query engine and perform query
query_engine = index.as_query_engine()
response = query_engine.query("What is llama index best suited for?")
display_green_markdown(response)

这种索引类型在语义搜索和可扩展性方面表现出色,非常适合大型数据集。

2.3 树索引

树索引分层组织信息,这有利于结构化数据。

from llama_index.core import TreeIndex, SimpleDirectoryReader

documents = SimpleDirectoryReader('data').load_data()
tree_index = TreeIndex.from_documents(documents)
query_engine = tree_index.as_query_engine()
response = query_engine.query("Explain the tree index structure.")
display_green_markdown(response)

树索引对于具有自然层次结构的数据特别有效,例如组织结构或分类法。

2.4 关键字表索引

关键字表索引针对基于关键字的高效检索进行了优化。

from llama_index.core import KeywordTableIndex, SimpleDirectoryReader

documents = SimpleDirectoryReader('data/paul_graham').load_data()
keyword_index = KeywordTableIndex.from_documents(documents)
query_engine = keyword_index.as_query_engine()
response = query_engine.query("What is the keyword table index in llama index?")
display_green_markdown(response)

该索引类型非常适合需要根据特定关键字快速查找的场景。

3. 自定义索引设置

3.1 分块策略

有效的文本分块对于索引性能至关重要。 LlamaIndex 提供了多种分块方法:

from llama_index.core.node_parser import SimpleNodeParser

parser = SimpleNodeParser.from_defaults(chunk_size=1024)

documents = SimpleDirectoryReader('data').load_data()
nodes = parser.get_nodes_from_documents(documents)
print(nodes[0])

尝试不同的分块策略,以找到上下文保留和查询性能之间的最佳平衡。

3.2 嵌入模型

LlamaIndex 支持各种嵌入模型。以下是如何使用 Ollama 进行嵌入:

from llama_index.core import VectorStoreIndex, SimpleDirectoryReader
from llama_index.embeddings.ollama import OllamaEmbedding

embed_model = OllamaEmbedding(
    model_name="snowflake-arctic-embed",
    base_url="http://localhost:11434",
    ollama_additional_kwargs={"mirostat": 0},
)
index = VectorStoreIndex.from_documents(documents, embed_model=embed_model)
query_engine = index.as_query_engine()
response = query_engine.query("What is an embedding model used for in LlamaIndex?")
display_green_markdown(response)

尝试不同的 Ollama 模型并调整参数,以针对您的特定用例优化嵌入质量。

4. 处理多个文档

4.1 创建多文档索引

LlamaIndex 简化了从不同类型的多个文档创建索引的过程:

txt_docs = SimpleDirectoryReader('data/paul_graham').load_data()
web_docs = SimpleDirectoryReader('web_pages').load_data()
data = txt_docs  + web_docs
all_docs = txt_docs  + web_docs
index = VectorStoreIndex.from_documents(all_docs)

query_engine = index.as_query_engine()
response = query_engine.query("How do you create a multi-document index in LlamaIndex?")
display_green_markdown(response)

4.2 跨文档查询

要有效地查询多个文档,您可以实施相关性评分并管理上下文边界:

from llama_index.core import QueryBundle
from llama_index.core.query_engine import RetrieverQueryEngine

retriever = index.as_retriever(similarity_top_k=5)
query_engine = RetrieverQueryEngine.from_args(retriever, response_mode="compact")
query = QueryBundle("How do you query across multiple documents?")
response = query_engine.query(query)
display_green_markdown(response)

5. 结论和后续步骤

在 LlamaIndex 和 Ollama 系列的第二部分中,我们探索了高级索引技术,包括:

  • 不同的索引类型及其用例
  • 自定义索引设置以获得最佳性能
  • 处理多个文档和跨文档查询

如果您想支持我或给我买啤酒,请随时加入我的 Patreon jamesbmour

以上是使用 LlamaIndex 和 Ollama 的高级索引技术:第 2 部分的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn