Certainly! Semantic search leverages the power of language models to understand the intent and contextual meaning behind a user's query, rather than relying solely on keyword matching. This approach enables more accurate and relevant search results.
LlamaIndex (formerly known as GPT Index) is a Python library that provides tools to connect your external data with large language models (LLMs) like OpenAI's GPT-3 or GPT-4. It simplifies the process of building a semantic search system by handling data ingestion, indexing, and querying.
In this guide, I'll walk you through setting up a semantic search system using LlamaIndex and Python.
Table of Contents
Prerequisites
Installation
Setting Up LlamaIndex
Loading and Indexing Data
Performing Semantic Search
Full Code Example
Advanced Usage
Conclusion
Prerequisites
Python 3.7 or higher
An OpenAI API key (if using OpenAI's language models)
Basic understanding of Python programming
Some text data to index (e.g., articles, documents)
Installation
First, you need to install the necessary libraries:
bash
pip install llama-index
pip install openai
llama-index: The main library for indexing and searching.
openai: The OpenAI API client library.
Setting Up LlamaIndex
1. Import the Libraries
python
import os
from llama_index import VectorStoreIndex, SimpleDirectoryReader
from llama_index import ServiceContext, StorageContext, load_index_from_storage
from llama_index.node_parser import SimpleNodeParser
from llama_index.llms import OpenAI
2. Set Up the OpenAI API Key
You need to set your OpenAI API key as an environment variable:
Replace "your-openai-api-key" with your actual API key from OpenAI.
3. Configure the LLM and Service Context
Set up the language model and the service context:
python
# Initialize the OpenAI LLM with desired parameters
llm = OpenAI(model="gpt-3.5-turbo", temperature=0)
# Create a service context
service_context = ServiceContext.from_defaults(llm=llm)
model: Choose the model you want to use (e.g., "gpt-3.5-turbo" or "gpt-4").
temperature: Controls randomness; lower values make the output more deterministic.
Loading and Indexing Data
1. Prepare Your Data
Ensure your text data is in a format that LlamaIndex can read. For example, if you're using text files, place them in a directory (e.g., data).
2. Load the Documents
python
# Load documents from a directory
documents = SimpleDirectoryReader('data').load_data()
Replace 'data' with the path to your directory containing text files.
3. Parse Documents into Nodes
LlamaIndex uses nodes as the basic units for indexing.
python
from llama_index import Document
parser = SimpleNodeParser()
nodes = parser.get_nodes_from_documents(documents)
4. Create the Index
python
# Create a vector store index
index = VectorStoreIndex(nodes, service_context=service_context)
With the index built, you can now perform queries.
1. Load the Index (If Needed)
If you've saved the index and want to load it later:
python
storage_context = StorageContext.from_defaults(persist_dir="index_storage")
index = load_index_from_storage(storage_context, service_context=service_context)
2. Query the Index
python
# Create a query engine
query_engine = index.as_query_engine()
# Perform a query
response = query_engine.query("Your search query here")
print(response)
Example:
python
response = query_engine.query("What are the health benefits of regular exercise?")
print(response)
3. Understanding the Response
The response from query_engine.query() contains the answer generated by the LLM based on the indexed documents. It leverages semantic understanding to provide relevant information even if the exact keywords don't match.
Full Code Example
Here's a complete example putting everything together:
python
import os
from llama_index import VectorStoreIndex, SimpleDirectoryReader
from llama_index.node_parser import SimpleNodeParser
from llama_index import ServiceContext
from llama_index.llms import OpenAI
# Set OpenAI API key
os.environ["OPENAI_API_KEY"] = "your-openai-api-key"
# Initialize OpenAI LLM
llm = OpenAI(model="gpt-3.5-turbo", temperature=0)
service_context = ServiceContext.from_defaults(llm=llm)
# Load and parse documents
documents = SimpleDirectoryReader('data').load_data()
parser = SimpleNodeParser()
nodes = parser.get_nodes_from_documents(documents)
# Create the index
index = VectorStoreIndex(nodes, service_context=service_context)
# Save the index
index.storage_context.persist(persist_dir="index_storage")
# Load the index (if needed)
from llama_index import StorageContext, load_index_from_storage
storage_context = StorageContext.from_defaults(persist_dir="index_storage")
index = load_index_from_storage(storage_context, service_context=service_context)
# Query the index
query_engine = index.as_query_engine()
response = query_engine.query("Explain the theory of relativity in simple terms.")
print(response)
Advanced Usage
Using Different Vector Stores
LlamaIndex supports different vector stores such as FAISS, Weaviate, Pinecone, etc.
Example using FAISS:
python
from llama_index import VectorStoreIndex, SimpleDirectoryReader
from llama_index.vector_stores import FaissVectorStore
# Create a FAISS vector store
vector_store = FaissVectorStore()
# Create the index with FAISS vector store
index = VectorStoreIndex.from_documents(
documents, service_context=service_context, vector_store=vector_store
)
Customizing Embeddings
You can customize the embedding model used for vectorization.