Traditional RAG with LanceDB

This example demonstrates how to implement traditional RAG using LanceDB vector database, where knowledge is added to context rather than searched dynamically by the agent.

Code

1"""
21. Run: `pip install openai lancedb tantivy pypdf sqlalchemy kern-ai` to install the dependencies
32. Run: `python cookbook/rag/03_traditional_rag_lancedb.py` to run the agent
4"""
5
6from kern.agent import Agent
7from kern.knowledge.embedder.openai import OpenAIEmbedder
8from kern.knowledge.knowledge import Knowledge
9from kern.models.openai import OpenAIResponses
10from kern.vectordb.lancedb import LanceDb, SearchType
11
12knowledge = Knowledge(
13 # Use LanceDB as the vector database and store embeddings in the `recipes` table
14 vector_db=LanceDb(
15 table_name="recipes",
16 uri="tmp/lancedb",
17 search_type=SearchType.vector,
18 embedder=OpenAIEmbedder(id="text-embedding-3-small"),
19 ),
20)
21
22knowledge.insert(
23 name="Recipes",
24 url="https://kern-public.s3.amazonaws.com/recipes/ThaiRecipes.pdf",
25)
26
27agent = Agent(
28 model=OpenAIResponses(id="gpt-5.2"),
29 knowledge=knowledge,
30 # Enable RAG by adding references from Knowledge to the user prompt.
31 add_knowledge_to_context=True,
32 # Set as False because Agents default to `search_knowledge=True`
33 search_knowledge=False,
34 markdown=True,
35)
36agent.print_response(
37 "How do I make chicken and galangal in coconut milk soup", stream=True
38)

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 lancedb tantivy pypdf sqlalchemy

Export your OpenAI API key

1export OPENAI_API_KEY=your_openai_api_key_here

Run Agent

1python traditional_rag_lancedb.py