Agent with Storage
Code
1from kern.agent import Agent2from kern.db.postgres import PostgresDb3from kern.models.ibm import WatsonX4from kern.tools.hackernews import HackerNewsTools56# Setup the database7db_url = "postgresql+psycopg://ai:ai@localhost:5532/ai"8db = PostgresDb(db_url=db_url)910agent = Agent(11 model=WatsonX(id="mistralai/mistral-small-3-1-24b-instruct-2503"),12 db=db,13 tools=[HackerNewsTools()],14 add_history_to_context=True,15)16agent.print_response("How many people live in Canada?")17agent.print_response("What is their national anthem called?")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 psycopg sqlalchemy ibm-watsonx-ai kern-aiSet up PostgreSQL
Make sure you have a PostgreSQL database running. You can adjust the db_url in the code to match your database configuration.
Run Agent
1python cookbook/11_models/ibm/watsonx/db.pyThis example shows how to use PostgreSQL storage with IBM WatsonX to maintain conversation state across multiple interactions. It creates an agent with a PostgreSQL storage backend and sends multiple messages, with the conversation history being preserved between them.
Note: You need to install the sqlalchemy package and have a PostgreSQL database available.