백엔드 개발 파이썬 튜토리얼 LlamaIndex 및 Ollama를 사용한 고급 인덱싱 기술: 2부

LlamaIndex 및 Ollama를 사용한 고급 인덱싱 기술: 2부

Aug 14, 2024 pm 10:34 PM

Advanced Indexing Techniques with LlamaIndex and Ollama: Part 2

LlamaIndex 및 Ollama를 사용한 고급 인덱싱 기술: 2부

코드는 여기에서 찾을 수 있습니다: GitHub - jamesbmour/blog_tutorials:

LlamaIndex와 Ollama에 대한 심층 분석에 다시 오신 것을 환영합니다! 1부에서는 효율적인 정보 검색을 위해 이러한 강력한 도구를 설정하고 사용하는 데 필요한 필수 사항을 다루었습니다. 이제 문서 처리 및 쿼리 기능을 한 단계 끌어올릴 고급 인덱싱 기술을 살펴볼 차례입니다.

1. 소개

진행하기 전에 파트 1의 주요 내용을 빠르게 요약해 보겠습니다.

  • LlamaIndex 및 Ollama 설정
  • 기본 인덱스 생성
  • 간단한 쿼리 수행

이번 부분에서는 다양한 인덱스 유형에 대해 알아보고, 인덱스 설정을 사용자 지정하는 방법, 여러 문서를 관리하는 방법, 고급 쿼리 기술을 살펴보겠습니다. 마지막에는 복잡한 정보 검색 작업에 LlamaIndex와 Ollama를 활용하는 방법을 확실하게 이해하게 될 것입니다.

아직 환경을 설정하지 않은 경우 LlamaIndex 및 Ollama 설치 및 구성에 대한 자세한 지침은 1부를 다시 참조하세요.

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으로 문의하세요.

핫 AI 도구

Undresser.AI Undress

Undresser.AI Undress

사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover

AI Clothes Remover

사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool

Undress AI Tool

무료로 이미지를 벗다

Clothoff.io

Clothoff.io

AI 옷 제거제

Video Face Swap

Video Face Swap

완전히 무료인 AI 얼굴 교환 도구를 사용하여 모든 비디오의 얼굴을 쉽게 바꾸세요!

뜨거운 도구

메모장++7.3.1

메모장++7.3.1

사용하기 쉬운 무료 코드 편집기

SublimeText3 중국어 버전

SublimeText3 중국어 버전

중국어 버전, 사용하기 매우 쉽습니다.

스튜디오 13.0.1 보내기

스튜디오 13.0.1 보내기

강력한 PHP 통합 개발 환경

드림위버 CS6

드림위버 CS6

시각적 웹 개발 도구

SublimeText3 Mac 버전

SublimeText3 Mac 버전

신 수준의 코드 편집 소프트웨어(SublimeText3)

Linux 터미널에서 Python 버전을 볼 때 발생하는 권한 문제를 해결하는 방법은 무엇입니까? Linux 터미널에서 Python 버전을 볼 때 발생하는 권한 문제를 해결하는 방법은 무엇입니까? Apr 01, 2025 pm 05:09 PM

Linux 터미널에서 Python 버전을 보려고 할 때 Linux 터미널에서 Python 버전을 볼 때 권한 문제에 대한 솔루션 ... Python을 입력하십시오 ...

중간 독서를 위해 Fiddler를 사용할 때 브라우저에서 감지되는 것을 피하는 방법은 무엇입니까? 중간 독서를 위해 Fiddler를 사용할 때 브라우저에서 감지되는 것을 피하는 방법은 무엇입니까? Apr 02, 2025 am 07:15 AM

Fiddlerevery Where를 사용할 때 Man-in-the-Middle Reading에 Fiddlereverywhere를 사용할 때 감지되는 방법 ...

한 데이터 프레임의 전체 열을 Python의 다른 구조를 가진 다른 데이터 프레임에 효율적으로 복사하는 방법은 무엇입니까? 한 데이터 프레임의 전체 열을 Python의 다른 구조를 가진 다른 데이터 프레임에 효율적으로 복사하는 방법은 무엇입니까? Apr 01, 2025 pm 11:15 PM

Python의 Pandas 라이브러리를 사용할 때는 구조가 다른 두 데이터 프레임 사이에서 전체 열을 복사하는 방법이 일반적인 문제입니다. 두 개의 dats가 있다고 가정 해

Uvicorn은 Serving_forever ()없이 HTTP 요청을 어떻게 지속적으로 듣습니까? Uvicorn은 Serving_forever ()없이 HTTP 요청을 어떻게 지속적으로 듣습니까? Apr 01, 2025 pm 10:51 PM

Uvicorn은 HTTP 요청을 어떻게 지속적으로 듣습니까? Uvicorn은 ASGI를 기반으로 한 가벼운 웹 서버입니다. 핵심 기능 중 하나는 HTTP 요청을 듣고 진행하는 것입니다 ...

10 시간 이내에 프로젝트 및 문제 중심 방법에서 컴퓨터 초보자 프로그래밍 기본 사항을 가르치는 방법? 10 시간 이내에 프로젝트 및 문제 중심 방법에서 컴퓨터 초보자 프로그래밍 기본 사항을 가르치는 방법? Apr 02, 2025 am 07:18 AM

10 시간 이내에 컴퓨터 초보자 프로그래밍 기본 사항을 가르치는 방법은 무엇입니까? 컴퓨터 초보자에게 프로그래밍 지식을 가르치는 데 10 시간 밖에 걸리지 않는다면 무엇을 가르치기로 선택 하시겠습니까?

Inversiting.com의 크롤링 메커니즘을 우회하는 방법은 무엇입니까? Inversiting.com의 크롤링 메커니즘을 우회하는 방법은 무엇입니까? Apr 02, 2025 am 07:03 AM

Investing.com의 크롤링 전략 이해 많은 사람들이 종종 Investing.com (https://cn.investing.com/news/latest-news)에서 뉴스 데이터를 크롤링하려고합니다.

See all articles