Concurrent Execution

Run multiple agents concurrently using asyncio.gather for parallel execution.

1"""
2Concurrent Execution
3=============================
4
5Concurrent Agent Execution with asyncio.gather.
6"""
7
8import asyncio
9
10from kern.agent import Agent
11from kern.models.openai import OpenAIResponses
12from kern.tools.duckduckgo import DuckDuckGoTools
13from rich.pretty import pprint
14
15# ---------------------------------------------------------------------------
16# Create Agent
17# ---------------------------------------------------------------------------
18providers = ["openai", "anthropic", "ollama", "cohere", "google"]
19instructions = """
20Your task is to write a well researched report on AI providers.
21The report should be unbiased and factual.
22"""
23
24# Create the agent ONCE outside the loop - this is the correct pattern
25agent = Agent(
26 model=OpenAIResponses(id="gpt-5-mini"),
27 instructions=instructions,
28 tools=[DuckDuckGoTools()],
29)
30
31
32async def get_reports():
33 """Run multiple research tasks concurrently using the same agent instance."""
34 tasks = [
35 agent.arun(f"Write a report on the following AI provider: {provider}")
36 for provider in providers
37 ]
38 results = await asyncio.gather(*tasks)
39 return results
40
41
42async def main():
43 results = await get_reports()
44 for result in results:
45 print("************")
46 pprint(result.content)
47 print("************")
48 print("\n")
49
50
51# ---------------------------------------------------------------------------
52# Run Agent
53# ---------------------------------------------------------------------------
54if __name__ == "__main__":
55 asyncio.run(main())

Run the Example

1# Clone and setup repo
2git clone https://github.com/kern-ai/kern.git
3cd kern/cookbook/02_agents/14_advanced
4
5# Create and activate virtual environment
6./scripts/demo_setup.sh
7source .venvs/demo/bin/activate
8
9python concurrent_execution.py