Streaming Basic Agent
Code
1from typing import Iterator2from kern.agent import Agent, RunOutput3from kern.models.ibm import WatsonX45agent = Agent(model=WatsonX(id="ibm/granite-20b-code-instruct"), markdown=True)67# Get the response in a variable8# run_response: Iterator[RunOutputEvent] = agent.run("Share a 2 sentence horror story", stream=True)9# for chunk in run_response:10# print(chunk.content)1112# Print the response in the terminal13agent.print_response("Share a 2 sentence horror story", stream=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 kern-aiRun Agent
1python cookbook/11_models/ibm/watsonx/basic_stream.pyThis example shows how to use streaming with IBM WatsonX. Setting stream=True when calling print_response() or run() enables token-by-token streaming, which can provide a more interactive user experience.