Agentic Rag

Build an agentic RAG pipeline with autonomous retrieval.

  1. Run: ./cookbook/run_pgvector.sh to start a postgres container with pgvector.
1"""
2Agentic Rag
3=============================
4
51. Run: `./cookbook/run_pgvector.sh` to start a postgres container with pgvector.
6"""
7
8from kern.agent import Agent
9from kern.knowledge.embedder.openai import OpenAIEmbedder
10from kern.knowledge.knowledge import Knowledge
11from kern.models.openai import OpenAIResponses
12from kern.vectordb.pgvector import PgVector, SearchType
13
14db_url = "postgresql+psycopg://ai:ai@localhost:5532/ai"
15knowledge = Knowledge(
16 # Use PgVector as the vector database and store embeddings in the `ai.recipes` table
17 vector_db=PgVector(
18 table_name="recipes",
19 db_url=db_url,
20 search_type=SearchType.hybrid,
21 embedder=OpenAIEmbedder(id="text-embedding-3-small"),
22 ),
23)
24
25# ---------------------------------------------------------------------------
26# Create Agent
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)
36
37# ---------------------------------------------------------------------------
38# Run Agent
39# ---------------------------------------------------------------------------
40if __name__ == "__main__":
41 knowledge.insert(url="https://kern-public.s3.amazonaws.com/recipes/ThaiRecipes.pdf")
42 agent.print_response(
43 "How do I make chicken and galangal in coconut milk soup", stream=True
44 )
45 # agent.print_response(
46 # "Hi, i want to make a 3 course meal. Can you recommend some recipes. "
47 # "I'd like to start with a soup, then im thinking a thai curry for the main course and finish with a dessert",
48 # stream=True,
49 # )

Run the Example

1# Clone and setup repo
2git clone https://github.com/kern-ai/kern.git
3cd kern/cookbook/02_agents/07_knowledge
4
5# Create and activate virtual environment
6./scripts/demo_setup.sh
7source .venvs/demo/bin/activate
8
9# Optiona: Run PgVector (needs docker)
10./cookbook/scripts/run_pgvector.sh
11
12python agentic_rag.py