RAG Agent
Code
1from kern.agent import Agent2from kern.knowledge.knowledge import Knowledge3from kern.models.ibm import WatsonX4from kern.vectordb.pgvector import PgVector56db_url = "postgresql+psycopg://ai:ai@localhost:5532/ai"78knowledge_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)1415agent = 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.122source .venv/bin/activate1uv venv --python 3.122.venv\Scripts\activateSet your API key
1export IBM_WATSONX_API_KEY=xxx2export IBM_WATSONX_PROJECT_ID=xxxInstall dependencies
1uv pip install -U ibm-watsonx-ai sqlalchemy pgvector psycopg pypdf openai kern-aiSet 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.pyFor 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.