Skip to main content

Adding a workflow

When building AI agents, it can be useful to combine them with workflows that perform multi-step tasks or fetch structured data. Timbal lets you pass workflows to an agent using the workflows parameter. Workflows provide a way for agents to trigger predefined sequences of steps, giving them access to more complex operations than a single tool can provide.

Prerequisites

This example uses the openai model. Make sure to add OPENAI_API_KEY to your .env file.

.env
OPENAI_API_KEY=your_api_key_here

Creating a workflow

This workflow retrieves English Premier League fixtures for a given date. Clear input and output schemas keep the data predictable and easy for the agent to use.

import asyncio
import json
import urllib.request
from typing import Any
from timbal.core import Workflow, Tool
async def get_fixtures(date: str) -> dict[str, Any]:
"""Fetch match fixtures for English Premier League matches."""
url = f"https://www.thesportsdb.com/api/v1/json/123/eventsday.php?d={date}&l=English_Premier_League"
# Use run_in_executor to run the blocking urllib.request.urlopen in a thread
response = await asyncio.get_event_loop().run_in_executor(None, lambda: urllib.request.urlopen(url))
data = await asyncio.get_event_loop().run_in_executor(None, lambda: response.read())
response_data = json.loads(data.decode())
# Debug: print the full API response
print(f"API Response: {response_data}")
events = response_data.get("events", [])
return {
"fixtures": events,
"raw_response": response_data,
"url": url
}
# Create the Tool for fetching fixtures
get_fixtures_tool = Tool(
name="get_fixtures",
description="Fetch match fixtures for English Premier League matches",
handler=get_fixtures
)
# Create the workflow
soccer_workflow = (
Workflow(name="soccer_workflow")
.step(get_fixtures_tool)
)

Adding a workflow to an agent

This agent uses soccer_workflow to answer fixture questions. The instructions tell it to compute the date, pass it in YYYY-MM-DD format, and return team names, match times, and dates.

from datetime import datetime
from timbal.core import Agent
soccer_agent = Agent(
name="soccer-agent",
description="A premier league soccer specialist",
system_prompt=f"""You are a premier league soccer specialist. Use the soccerWorkflow to fetch match data.
Calculate dates from {datetime.now().strftime("%Y-%m-%d")} and pass to workflow in YYYY-MM-DD format.
Only show team names, match times, and dates.""",
model="openai/gpt-4.1",
workflows=[soccer_workflow]
)

Example usage

Use the agent directly by calling it with a prompt message.

import asyncio
async def main():
response = await soccer_agent(prompt="What matches are being played this weekend?").collect()
response_text = response.output.content[0].text
print(response_text)
if __name__ == "__main__":
asyncio.run(main())