Код: Выделить всё
from pathlib import Path
from llama_index.core import VectorStoreIndex, SimpleDirectoryReader, Settings
from llama_index.embeddings.ollama import OllamaEmbedding
from llama_index.llms.ollama import Ollama
# Initialize the embedding model
embed_model = OllamaEmbedding(
model_name="nomic-embed-text",
request_timeout=300.0, # Increased timeout for large documents
)
# Initialize the LLM with optimized settings
llm = Ollama(
model="llama3.1:latest", # Confirm with `ollama list`
request_timeout=300.0,
temperature=0.1, # Lower temperature for more factual responses
)
# Set global configurations
Settings.embed_model = embed_model
Settings.llm = llm
Settings.chunk_size = 1024 # Default: good for most documents
Settings.chunk_overlap = 200 # Maintains context between chunks
def load_and_index_documents(data_dir="data"):
"""Load documents and create vector index"""
# Check if data directory exists
if not Path(data_dir).exists():
raise FileNotFoundError(f"Data directory '{data_dir}' not found. Please create it and add your PDF files.")
# Load documents from the data folder
docs = SimpleDirectoryReader(data_dir).load_data()
if not docs:
raise ValueError(f"No documents found in {data_dir}")
# Build vector index from documents
index = VectorStoreIndex.from_documents(docs, embed_model=embed_model)
return index
def create_query_engine(index, similarity_top_k=3):
"""Create query engine with specified retrieval parameters"""
query_engine = index.as_query_engine(
llm=llm,
similarity_top_k=similarity_top_k, # Number of relevant chunks to retrieve
response_mode="compact" # Compact response generation
)
return query_engine
def test_rag_system():
"""Test the RAG system with sample queries"""
try:
# Load documents and create index
index = load_and_index_documents()
# Create query engine
query_engine = create_query_engine(index)
# Sample test queries
test_queries = [
"Summarize this document in 3 lines",
"What are the main topics covered in these documents?",
]
print("RAG System Test Results")
print("=" * 50)
for i, query in enumerate(test_queries, 1):
print(f"\nTest {i}: {query}")
print("-" * 40)
try:
response = query_engine.query(query)
print(f"Response: {response}")
print(f"Status: SUCCESS")
except Exception as e:
print(f"Error: {str(e)}")
print(f"Status: FAILED")
print("-" * 40)
return True
except Exception as e:
print(f"System Error: {str(e)}")
return False
# Main execution
if __name__ == "__main__":
print("Starting RAG Pipeline Test...")
# Test the complete system
success = test_rag_system()
if success:
print("\nRAG system is working correctly!")
print("You can now use the query_engine to ask questions about your documents.")
else:
print("\nRAG system test failed. Check the error messages above.")
Когда я запускаю python test_rag.py, результат следующий:
Код: Выделить всё
Starting RAG Pipeline Test...
RAG System Test Results
==================================================
Test 1: Summarize this document in 3 lines
----------------------------------------
Error: llama runner process has terminated: exit status 2 (status code: 500)
Status: FAILED
----------------------------------------
Test 2: What are the main topics covered in these documents?
----------------------------------------
Error: llama runner process has terminated: exit status 2 (status code: 500)
Status: FAILED
----------------------------------------
RAG system is working correctly!
You can now use the query_engine to ask questions about your documents.
Я не новичок в Python, хотя прошло уже несколько лет с тех пор, как я использовал его в реальном качестве, и я заржавел, однако я совершенно новичок в AI. Я все еще пытаюсь понять, как это работает и как такие системы, как RAG, взаимодействуют с LLM и с Олламой. Итак, потенциально это может быть что-то очень простое, что я просто упускаю из виду, и я надеялся, что кто-нибудь укажет мне здесь правильное направление.
Поисковые системы говорят мне, что это может быть связано с ограничениями памяти, но у меня есть только модель с 8B-параметрами на видеокарте на 16 ГБ. Он сказал, что это может быть связано с проблемами с разрешениями, поэтому я запустил sudo python test_rag.py просто как выстрел в темноте, и результат все тот же. В нем говорится, что это также может быть связано с неправильным путем модели, но на самом деле это не раскрывается, и у меня нет достаточно мудрости, чтобы знать, о чем именно здесь идет речь, или где я мог бы это исправить, если это необходимо.
Подробнее здесь: https://stackoverflow.com/questions/798 ... tus-code-5
Мобильная версия