RAG Agent

Code

1from kern.agent import Agent
2from kern.knowledge.knowledge import Knowledge
3from kern.models.ibm import WatsonX
4from kern.vectordb.pgvector import PgVector
5
6db_url = "postgresql+psycopg://ai:ai@localhost:5532/ai"
7
8knowledge_base = Knowledge(
9 vector_db=PgVector(table_name="recipes", db_url=db_url),
10)
11knowledge_base.insert(
12 url="https://kern-public.s3.amazonaws.com/recipes/ThaiRecipes.pdf"
13)
14
15agent = Agent(
16 model=WatsonX(id="ibm/granite-20b-code-instruct"),
17 knowledge=knowledge_base,
18 )
19agent.print_response("How to make Thai curry?", markdown=True)

Usage

Set up your virtual environment

1uv venv --python 3.12
2source .venv/bin/activate
1uv venv --python 3.12
2.venv\Scripts\activate

Set your API key

1export IBM_WATSONX_API_KEY=xxx
2export IBM_WATSONX_PROJECT_ID=xxx

Install dependencies

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

Set up PostgreSQL with pgvector

You need a PostgreSQL database with the pgvector extension installed. Adjust the db_url in the code to match your database configuration.

Run Agent

1python cookbook/11_models/ibm/watsonx/knowledge.py

For subsequent runs

After the first run, comment out the knowledge_base.load(recreate=True) line to avoid reloading the PDF.

This example shows how to integrate a knowledge base with IBM WatsonX. It loads a PDF from a URL, processes it into a vector database (PostgreSQL with pgvector in this case), and then creates an agent that can query this knowledge base.

Note: You need to install several packages (pgvector, pypdf, etc.) and have a PostgreSQL database with the pgvector extension available.