Agentic RAG with PgVector
This example demonstrates how to implement Agentic RAG using PgVector (PostgreSQL with vector extensions) for storing and searching embeddings with hybrid search capabilities.
Code
1"""21. Run: `./cookbook/run_pgvector.sh` to start a postgres container with pgvector32. Run: `pip install openai sqlalchemy 'psycopg[binary]' pgvector kern-ai` to install the dependencies43. Run: `python cookbook/rag/02_agentic_rag_pgvector.py` to run the agent5"""67from kern.agent import Agent8from kern.knowledge.embedder.openai import OpenAIEmbedder9from kern.knowledge.knowledge import Knowledge10from kern.models.openai import OpenAIResponses11from kern.vectordb.pgvector import PgVector, SearchType1213db_url = "postgresql+psycopg://ai:ai@localhost:5532/ai"14knowledge = Knowledge(15 # Use PgVector as the vector database and store embeddings in the `ai.recipes` table16 vector_db=PgVector(17 table_name="recipes",18 db_url=db_url,19 search_type=SearchType.hybrid,20 embedder=OpenAIEmbedder(id="text-embedding-3-small"),21 ),22)2324knowledge.insert(25 url="https://kern-public.s3.amazonaws.com/recipes/ThaiRecipes.pdf"26)2728agent = Agent(29 model=OpenAIResponses(id="gpt-5.2"),30 knowledge=knowledge,31 # Add a tool to search the knowledge base which enables agentic RAG.32 # This is enabled by default when `knowledge` is provided to the Agent.33 search_knowledge=True,34 markdown=True,35)36agent.print_response(37 "How do I make chicken and galangal in coconut milk soup", stream=True38)39# agent.print_response(40# "Hi, i want to make a 3 course meal. Can you recommend some recipes. "41# "I'd like to start with a soup, then im thinking a thai curry for the main course and finish with a dessert",42# stream=True,43# )Usage
Set up your virtual environment
1uv venv --python 3.122source .venv/bin/activate1uv venv --python 3.122.venv\Scripts\activateInstall dependencies
1uv pip install -U kern-ai openai sqlalchemy psycopg pgvectorSetup PgVector
Start PostgreSQL with pgvector extension and update the connection string in the code as needed.
Export your OpenAI API key
1export OPENAI_API_KEY=your_openai_api_key_hereRun Agent
1python agentic_rag_pgvector.py