An interactive bedtime story creation agent powered by Temporal durable execution and large language models (OpenAI or Anthropic).
The agent guides you through a conversation to collaboratively create a personalized bedtime story, complete with AI-generated illustrations.
- Conversational story creation (character, quest, companion or ending)
- AI-generated bedtime stories (3 paragraphs)
- Automatic illustration generation from story descriptions
- Durable execution via Temporal (workflows survive failures and restarts)
- Multi-language support (the agent detects the user's language)
graph LR
A[Browser UI<br/>SPA] <-->|REST| B[FastAPI<br/>webui]
B <--> C[Temporal Server]
C <--> D[Temporal Worker<br/>workflows + activities]
D -->|Story text| E[LLM<br/>OpenAI gpt-6-luna]
D -->|Illustration| F[OpenAI Images API<br/>gpt-image-2.5-flare]
- Web UI (webui) — FastAPI backend that serves the single-page app and exposes a REST API. It receives user messages and forwards them to Temporal as signals.
- Temporal Server — Orchestrates the story creation workflow with durable execution. It guarantees that workflows survive failures and restarts, and coordinates communication between the web UI and the worker.
- Worker — Executes the workflows and activities. It drives the conversational flow, calls the configured LLM to generate story text, and calls OpenAI to generate illustrations.
The conversational agent is a pure Pydantic AI agent that knows nothing about Temporal. Durability is layered on top without changing a single line of the agent:
agent/— the pure agent, with no Temporal dependency: the Pydantic AI agent factory (build_story_agent), its structured-output schema (StoryResponse), the system prompt, and aConversationobject that drives the multi-turn flow (per-turn hints, history rebuilding). It runs standalone — see Run the pure agent.worker/durable_agent.py— the durability layer: it builds the same agent with Pydantic AI's Temporal durability capability, turning each LLM call into a retryable Temporal activity. The agent definition is untouched.worker/workflow_story_session.py— the workflow that orchestrates the conversation, reusing the sameConversationobject as the standalone agent, then generates the illustration in a child workflow (worker/workflow_illustration_generation.py).
The dependency is strictly one-directional — worker depends on agent, never the reverse — which is what lets the very same agent run both as a plain CLI and as a durable workflow.
Temporal brings durable execution to this project: the workflow state is automatically persisted, so the story creation process is resilient to failures without any custom recovery logic.
Here are a few scenarios where Temporal makes a difference:
- Worker crashes mid-story — The user is chatting with the agent and the worker process crashes (OOM, deployment, bug). Without Temporal, the entire conversation and story progress would be lost. With Temporal, the workflow state is preserved: when the worker restarts, the conversation resumes exactly where it left off.
- LLM API timeout — A call to Claude or OpenAI times out or returns a transient error. Temporal automatically retries the failed activity with configurable backoff, without duplicating work that already succeeded (e.g., the story text is not regenerated if only the illustration call failed).
- Long-running interaction — A user starts a story, closes the browser, and comes back hours later. The workflow keeps waiting for the next user message; there is no session timeout to manage and no state to serialize to a database.
- Multiple workers — In production, several worker instances can run in parallel. Temporal dispatches activities across workers, retries failed ones and never re-runs completed ones, making the system horizontally scalable with no extra coordination code.
- Python 3.11+
- uv — fast Python package manager
- Temporal Server running locally (see below)
- OpenAI API key — for story generation (gpt-6-luna) and illustration generation
- Anthropic API key — only if using an Anthropic model for story generation
cp .env-sample .envEdit .env and fill in your API keys:
| Variable | Description | Default |
|---|---|---|
OPENAI_API_KEY |
OpenAI API key for LLM and image generation (required) | — |
ANTHROPIC_API_KEY |
Anthropic API key (required only if using an Anthropic model) | — |
PYDANTIC_AI_MODEL |
LLM model identifier. Examples: openai:gpt-6-luna (OpenAI GPT-6 Luna), anthropic:claude-sonnet-5 (Claude Sonnet 5) |
openai:gpt-6-luna |
OPENAI_IMAGE_MODEL |
OpenAI image generation model (see note below) | gpt-image-2.5-flare |
TEMPORAL_ADDRESS |
Temporal server address | localhost:7233 |
TEMPORAL_TASK_QUEUE |
Temporal task queue name | bedtime-story |
WEBUI_HOST |
Web UI bind address | 0.0.0.0 |
WEBUI_PORT |
Web UI port | 8000 |
The default image model gpt-image-2.5-flare (GPT Image 2.5) may require a verified OpenAI organization. If your organization is not verified, illustration generation will fail with:
Your organization must be verified to use the model
gpt-image-2.5-flare.
You have two options:
-
Verify your organization on platform.openai.com/settings/organization/general. Access propagates within ~15 minutes.
-
Use
gpt-image-1.5instead, which works without verification. Set this in your.env:OPENAI_IMAGE_MODEL=gpt-image-1.5
docker compose up --buildThis starts the Temporal server, the worker, and the web UI. Open http://localhost:8000 to start creating a story, and http://localhost:8233 for the Temporal dashboard.
After changing
.env, recreate the worker containers so they pick up the new values. For example, to switch the LLM provider from Anthropic to OpenAI, edit.env:PYDANTIC_AI_MODEL=openai:gpt-6-lunaThen recreate the worker:
docker compose up --build -d workerDocker Compose only reads
.envat container creation time, so a simpledocker compose restartis not enough — you need to recreate the containers.
uv syncStart each command in a separate terminal:
# Terminal 1 — Temporal Server
temporal server start-dev
# Terminal 2 — Temporal Worker
uv run worker
# Terminal 3 — Web UI
uv run webuiThen open http://localhost:8000 in your browser and start creating a bedtime story!
You need the Temporal CLI to run
temporal server start-dev.
The agent in agent/ is a plain Pydantic AI agent with no Temporal dependency, so you can run it as a standalone command-line chat — no Temporal server, no worker, no web UI:
uv run agentThis drives the exact same Conversation and agent definition the durable workflow uses; only the execution model differs (in-process here, durable activities under Temporal). It needs only an LLM API key (OPENAI_API_KEY, or ANTHROPIC_API_KEY with an Anthropic model). Note that it is not durable: if the process stops, the conversation is lost — which is precisely the resilience Temporal adds in the full app.
The recommended way to develop is to run each component separately so you get hot-reload and direct log output.
# 1. Install dependencies (including dev extras)
uv sync
# 2. Start the Temporal dev server (requires the Temporal CLI)
temporal server start-dev
# 3. Start the worker (auto-reloads on file changes via watchfiles)
uv run worker
# 4. Start the web UI (auto-reloads on file changes via uvicorn)
uv run webuiEach command runs in its own terminal. The worker watches the agent/ and worker/ directories; any saved change restarts it automatically. The web UI reloads on Python changes; static files are served fresh on each request.
Alternatively, make dev starts the Temporal server in Docker and runs the worker and web UI on the host, and make app-up runs the whole stack in Docker (make help lists every target).
Run the tests with:
uv run pytestOpen http://localhost:8000 for the app and http://localhost:8233 for the Temporal dashboard.
The Temporal dev server exposes a web dashboard at http://localhost:8233 where you can:
- List and inspect running/completed workflows
- View workflow execution history (events, signals, queries)
- Send signals or queries to a running workflow manually
Both the worker and the web UI use structlog with JSON output. Filter logs by component:
# Worker logs include events like "Connecting to Temporal", "Worker started"
uv run worker 2>&1 | jq .
# Web UI logs include events like "Creating session", "Message sent"
uv run webui 2>&1 | jq .| Symptom | Cause | Fix |
|---|---|---|
Connection refused on port 7233 |
Temporal server not running | Start it with temporal server start-dev |
| Worker starts but no workflows execute | Task queue mismatch | Check TEMPORAL_TASK_QUEUE matches in .env |
ANTHROPIC_API_KEY / OPENAI_API_KEY errors |
Missing or invalid API keys | Verify keys in .env |
| Illustration not generated | OpenAI API key missing or model unavailable | Check OPENAI_API_KEY and OPENAI_IMAGE_MODEL in .env |
Your organization must be verified to use the model 'gpt-image-2.5-flare' |
Default model requires a verified OpenAI org | Either verify your org, or set OPENAI_IMAGE_MODEL=gpt-image-1.5 in .env |
├── agent/ # Pure Pydantic AI agent — NO Temporal dependency
│ ├── __init__.py # StoryResponse schema + build_story_agent()
│ ├── prompt.py # System prompt
│ ├── conversation.py # Conversation: multi-turn flow (turns, hints, history)
│ ├── config.py # LLM model selection (PYDANTIC_AI_MODEL)
│ └── __main__.py # Standalone CLI: `uv run agent`
├── worker/ # Temporal worker (durability layer)
│ ├── durable_agent.py # Builds the agent with Temporal durability
│ ├── workflow_story_session.py # Conversation workflow (parent)
│ ├── workflow_illustration_generation.py # Illustration child workflow
│ ├── activities.py # Illustration generation (OpenAI Images)
│ ├── models.py # Session state shared with the web UI
│ └── __main__.py # Worker entry point: `uv run worker`
├── webui/ # FastAPI REST API serving the frontend
├── static/ # Single-page app (HTML, JS, CSS)
├── tests/ # Unit tests (`uv run pytest`)
├── Dockerfile # One image for the worker and the web UI
├── compose.yaml # Temporal + worker + web UI stack
├── Makefile # Dev shortcuts (`make help`)
├── pyproject.toml # Project metadata and dependencies
└── .env-sample # Environment variable template

