Async Streaming Agent

Code

1import asyncio
2
3from kern.agent import Agent, RunOutput
4from kern.models.ibm import WatsonX
5
6agent = Agent(
7 model=WatsonX(id="ibm/granite-20b-code-instruct"), debug_mode=True, markdown=True
8)
9
10# Get the response in a variable
11# run_response: Iterator[RunOutputEvent] = agent.run("Share a 2 sentence horror story", stream=True)
12# for chunk in run_response:
13# print(chunk.content)
14
15# Print the response in the terminal
16asyncio.run(agent.aprint_response("Share a 2 sentence horror story", stream=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 kern-ai

Run Agent

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

This example combines asynchronous execution with streaming. It creates an agent with debug_mode=True for additional logging and uses the asynchronous API with streaming to get and display responses as they're generated.