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 pgvector
32. Run: `pip install openai sqlalchemy 'psycopg[binary]' pgvector kern-ai` to install the dependencies
43. Run: `python cookbook/rag/02_agentic_rag_pgvector.py` to run the agent
5"""
6
7from kern.agent import Agent
8from kern.knowledge.embedder.openai import OpenAIEmbedder
9from kern.knowledge.knowledge import Knowledge
10from kern.models.openai import OpenAIResponses
11from kern.vectordb.pgvector import PgVector, SearchType
12
13db_url = "postgresql+psycopg://ai:ai@localhost:5532/ai"
14knowledge = Knowledge(
15 # Use PgVector as the vector database and store embeddings in the `ai.recipes` table
16 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)
23
24knowledge.insert(
25 url="https://kern-public.s3.amazonaws.com/recipes/ThaiRecipes.pdf"
26)
27
28agent = 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=True
38)
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.12
2source .venv/bin/activate
1uv venv --python 3.12
2.venv\Scripts\activate

Install dependencies

1uv pip install -U kern-ai openai sqlalchemy psycopg pgvector

Setup 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_here

Run Agent

1python agentic_rag_pgvector.py