|
| 1 | +""" |
| 2 | +Example of using pgvector with py-pglite for a simple RAG application. |
| 3 | +
|
| 4 | +This test demonstrates how to: |
| 5 | +1. Enable the `pgvector` extension. |
| 6 | +2. Create a table for storing text chunks and their embeddings. |
| 7 | +3. Insert documents and their vector embeddings. |
| 8 | +4. Perform a similarity search to find the most relevant document chunk. |
| 9 | +5. Use the retrieved chunk to answer a question. |
| 10 | +""" |
| 11 | + |
| 12 | +from typing import TYPE_CHECKING |
| 13 | + |
| 14 | +import psycopg |
| 15 | +import pytest |
| 16 | + |
| 17 | +from py_pglite import PGliteManager |
| 18 | +from py_pglite.config import PGliteConfig |
| 19 | + |
| 20 | +if TYPE_CHECKING: |
| 21 | + import numpy as np |
| 22 | + from numpy.typing import NDArray |
| 23 | + from pgvector.psycopg import register_vector |
| 24 | + |
| 25 | +# Try to import optional dependencies, or skip tests |
| 26 | +try: |
| 27 | + import numpy as np |
| 28 | + from pgvector.psycopg import register_vector |
| 29 | +except ImportError: |
| 30 | + np = None |
| 31 | + register_vector = None |
| 32 | + |
| 33 | + |
| 34 | +@pytest.mark.skipif( |
| 35 | + not np or not register_vector, reason="numpy or pgvector not available" |
| 36 | +) |
| 37 | +def test_pgvector_rag_example(): |
| 38 | + """Demonstrates a simple RAG workflow using pgvector.""" |
| 39 | + # --- 1. Setup: Documents and a mock embedding function --- |
| 40 | + |
| 41 | + documents = { |
| 42 | + "doc1": "The sky is blue.", |
| 43 | + "doc2": "The sun is bright.", |
| 44 | + "doc3": "The cat walks on the street.", |
| 45 | + } |
| 46 | + |
| 47 | + # A mock function to simulate generating embeddings (e.g., from an API) |
| 48 | + def get_embedding(text: str) -> "NDArray": |
| 49 | + assert np is not None |
| 50 | + # In a real app, this would be a call to an embedding model |
| 51 | + if "sky" in text: |
| 52 | + return np.array([0.1, 0.9, 0.1]) |
| 53 | + if "sun" in text: |
| 54 | + return np.array([0.8, 0.2, 0.1]) |
| 55 | + if "cat" in text: |
| 56 | + return np.array([0.1, 0.1, 0.8]) |
| 57 | + return np.array([0.0, 0.0, 0.0]) |
| 58 | + |
| 59 | + # --- 2. Database Setup: Enable pgvector and create schema --- |
| 60 | + |
| 61 | + config = PGliteConfig(extensions=["pgvector"]) |
| 62 | + with PGliteManager(config=config) as db: |
| 63 | + with psycopg.connect(db.get_dsn(), autocommit=True) as conn: |
| 64 | + conn.execute("CREATE EXTENSION IF NOT EXISTS vector") |
| 65 | + assert register_vector is not None |
| 66 | + register_vector(conn) |
| 67 | + |
| 68 | + conn.execute( |
| 69 | + """ |
| 70 | + CREATE TABLE documents ( |
| 71 | + id SERIAL PRIMARY KEY, |
| 72 | + content TEXT, |
| 73 | + embedding vector(3) |
| 74 | + ) |
| 75 | + """ |
| 76 | + ) |
| 77 | + |
| 78 | + # --- 3. Ingestion: Store documents and embeddings --- |
| 79 | + |
| 80 | + for content in documents.values(): |
| 81 | + embedding = get_embedding(content) |
| 82 | + conn.execute( |
| 83 | + "INSERT INTO documents (content, embedding) VALUES (%s, %s)", |
| 84 | + (content, embedding), |
| 85 | + ) |
| 86 | + |
| 87 | + # --- 4. RAG Workflow: Ask a question and retrieve context --- |
| 88 | + |
| 89 | + question = "What color is the sky?" |
| 90 | + question_embedding = get_embedding(question) |
| 91 | + |
| 92 | + # Find the most similar document chunk |
| 93 | + result = conn.execute( |
| 94 | + "SELECT content FROM documents ORDER BY embedding <-> %s LIMIT 1", |
| 95 | + (question_embedding,), |
| 96 | + ).fetchone() |
| 97 | + |
| 98 | + assert result is not None |
| 99 | + retrieved_context = result[0] |
| 100 | + |
| 101 | + # --- 5. Generation: Use the context to answer the question --- |
| 102 | + |
| 103 | + # A mock generation step |
| 104 | + def generate_answer(context: str, question: str) -> str: |
| 105 | + if "sky" in question and "blue" in context: |
| 106 | + return "Based on the context, the sky is blue." |
| 107 | + return "I cannot answer the question based on the provided context." |
| 108 | + |
| 109 | + answer = generate_answer(retrieved_context, question) |
| 110 | + |
| 111 | + # --- 6. Verification --- |
| 112 | + |
| 113 | + print(f"\nQuestion: {question}") |
| 114 | + print(f"Retrieved Context: '{retrieved_context}'") |
| 115 | + print(f"Answer: {answer}") |
| 116 | + |
| 117 | + assert "The sky is blue" in retrieved_context |
| 118 | + assert "the sky is blue" in answer.lower() |
0 commit comments