give me code to create an AI agent whose knowledge base is pgvector
- User
give me code to create an AI agent whose knowledge base is pgvector
Assistant
give me code to create an AI agent whose knowledge base is pgvector
Of course. Here is a comprehensive guide and complete Python code to create an AI agent whose knowledge base is powered by pgvector.
This type of agent uses a pattern called Retrieval-Augmented Generation (RAG). Here's how it works:
We will use the LangChain framework to orchestrate this process, as it simplifies the connections between the different components.
Before you start, you need to set up your environment.
1. PostgreSQL with pgvector Extension The easiest way is using Docker:
# Pull the official pgvector image
docker pull pgvector/pgvector:pg16
# Run the container
docker run --name pgvector-db -e POSTGRES_PASSWORD=mysecretpassword -p 5432:5432 -d pgvector/pgvector:pg16
This command starts a PostgreSQL 16 server with the pgvector extension already enabled on localhost:5432.
2. Python Dependencies Install all the necessary Python libraries.
pip install langchain langchain-community langchain-openai langchain-huggingface
pip install psycopg2-binary sentence-transformers
pip install python-dotenv
langchain-*: The core framework for building the agent.psycopg2-binary: The Python driver for PostgreSQL.sentence-transformers: To create the embeddings locally for free.langchain-openai: To use an LLM for the final answer generation (you can swap this out).python-dotenv: To manage environment variables like API keys and database URLs.Create a project folder (e.g., pgvector_agent).
Inside the folder, create a .env file to store your credentials securely. Do not commit this file to Git.
.env
# PostgreSQL Connection String
# Format: postgresql+psycopg2://USER:PASSWORD@HOST:PORT/DB_NAME
DB_CONNECTION_STRING="postgresql+psycopg2://postgres:mysecretpassword@localhost:5432/postgres"
# OpenAI API Key for the final answer generation
# Get one from https://platform.openai.com/account/api-keys
OPENAI_API_KEY="sk-..."
Create a text file with your knowledge base content. Let's call it knowledge.txt.
knowledge.txt
The Llama 2 family of models are a collection of pretrained and fine-tuned large language models (LLMs) from Meta.
They range in scale from 7 billion to 70 billion parameters. The fine-tuned models, called Llama-2-Chat, are optimized for dialogue use cases.
Project Orca is a research initiative from Microsoft that aims to reproduce the reasoning abilities of large foundation models like GPT-4.
The goal is to use a smaller, 13-billion parameter model (a fine-tuned Llama 2) to learn from the step-by-step reasoning explanations generated by GPT-4.
Orca learns from rich signals from GPT-4, including explanation traces, step-by-step thought processes, and other complex instructions.
This method allows the smaller model to achieve improved reasoning capabilities that were previously only found in much larger models.
The capital of France is Paris. Paris is known for its art, fashion, gastronomy and culture. Its 19th-century cityscape is crisscrossed by wide boulevards and the River Seine.
Here is the complete code for agent.py. It's heavily commented to explain each part of the process.
agent.py
Make sure your Docker container for PostgreSQL is running.
Open your terminal in the pgvector_agent folder.
Run the script:
python agent.py
First Run (Ingestion): The first time you run the script, you will see output indicating that it's ingesting data. This will take a few seconds.
Initializing embedding model...
Knowledge base not found. Starting data ingestion...
Data ingestion complete!
AI Agent is ready. Ask a question or type 'exit' to quit.
You:
Subsequent Runs: On later runs, it will detect that the data is already in the database and skip the ingestion step, making it much faster to start.
Initializing embedding model...
Knowledge base already exists in pgvector. Skipping ingestion.
AI Agent is ready. Ask a question or type 'exit' to quit.
You:
Now you can ask questions based on the content in your knowledge.txt file.
You: What is Project Orca?
Agent: Project Orca is a research initiative from Microsoft that aims to reproduce the reasoning abilities of large foundation models like GPT-4. It uses a smaller, 13-billion parameter model (a fine-tuned Llama 2) to learn from the step-by-step reasoning explanations and other complex instructions generated by GPT-4, enabling the smaller model to achieve improved reasoning capabilities.
You: What is Llama 2?
Agent: Llama 2 is a family of pretrained and fine-tuned large language models (LLMs) from Meta, with models ranging in size from 7 billion to 70 billion parameters. The fine-tuned versions, known as Llama-2-Chat, are specifically optimized for dialogue applications.
You: What is the capital of Spain?
Agent: I don't know. The provided context does not contain information about the capital of Spain.
This final answer is crucial—it demonstrates that the agent is correctly relying only on its pgvector knowledge base and not hallucinating an answer.
Create your main Python script, agent.py.
import os
from dotenv import load_dotenv
# --- Core LangChain components ---
from langchain_community.document_loaders import TextLoader
from langchain_community.vectorstores.pgvector import PGVector
from langchain_openai import ChatOpenAI
from langchain_huggingface import HuggingFaceEmbeddings
# --- LangChain utilities for building chains ---
from langchain.text_splitter import CharacterTextSplitter
from langchain.schema.runnable import RunnablePassthrough
from langchain.schema.output_parser import StrOutputParser
from langchain.prompts import ChatPromptTemplate
# --- Main Application Logic ---
def main():
"""
Main function to set up and run the RAG agent.
"""
# Load environment variables from .env file
load_dotenv()
db_connection_string = os.getenv("DB_CONNECTION_STRING")
if not db_connection_string:
raise ValueError("DB_CONNECTION_STRING environment variable not set.")
# Define a collection name for our vector store
# This helps organize data within the database
collection_name = "my_knowledge_base"
# --- 1. Set up the Embedding Model ---
# We use a Sentence-Transformers model to create embeddings locally.
# This is free and runs on your machine.
# 'all-MiniLM-L6-v2' is a good, fast, and small model.
print("Initializing embedding model...")
embeddings = HuggingFaceEmbeddings(model_name="all-MiniLM-L6-v2")
# --- 2. Ingest Data (if necessary) ---
# This part loads documents, splits them into chunks, creates embeddings,
# and stores them in pgvector. We can skip this if the data is already in the DB.
# Check if the vector store collection already exists
# A simple way is to try to connect and get a retriever. If it fails, we ingest.
try:
# Attempt to connect to an existing vector store
vectorstore = PGVector(
connection_string=db_connection_string,
collection_name=collection_name,
embedding_function=embeddings,
)
# Try a dummy search to confirm it's populated
vectorstore.similarity_search("test", k=1)
print("Knowledge base already exists in pgvector. Skipping ingestion.")
except Exception:
print("Knowledge base not found. Starting data ingestion...")
# Load the document
loader = TextLoader("./knowledge.txt")
documents = loader.load()
# Split the document into smaller chunks
text_splitter = CharacterTextSplitter(chunk_size=1000, chunk_overlap=50)
docs = text_splitter.split_documents(documents)
# Ingest documents into pgvector
# This one-time operation can take a few seconds
vectorstore = PGVector.from_documents(
documents=docs,
embedding=embeddings,
collection_name=collection_name,
connection_string=db_connection_string,
pre_delete_collection=True, # Deletes old collection if it exists
)
print("Data ingestion complete!")
# --- 3. Set up the RAG Chain ---
# Define the Large Language Model (LLM) for generation
# We are using OpenAI's gpt-3.5-turbo here
llm = ChatOpenAI(model_name="gpt-3.5-turbo", temperature=0.3)
# Create a retriever from our vector store
# The retriever's job is to find the most relevant documents for a given query
retriever = vectorstore.as_retriever(search_kwargs={"k": 3}) # Retrieve top 3 results
# Define the prompt template
# This guides the LLM to use the retrieved context to answer the question
prompt_template = """
You are an AI assistant. Answer the user's question based on the following context.
If the context does not contain the answer, state that you don't know.
Context:
{context}
Question:
{question}
Answer:
"""
prompt = ChatPromptTemplate.from_template(prompt_template)
# Build the RAG chain using LangChain Expression Language (LCEL)
rag_chain = (
{"context": retriever, "question": RunnablePassthrough()}
| prompt
| llm
| StrOutputParser()
)
print("\nAI Agent is ready. Ask a question or type 'exit' to quit.")
# --- 4. Interactive Q&A Loop ---
while True:
query = input("You: ")
if query.lower() == 'exit':
break
# Invoke the chain to get an answer
response = rag_chain.invoke(query)
print(f"Agent: {response}")
if __name__ == "__main__":
main()