"""A Temporal worker for the exe.dev Temporal page: https://exe.dev/deploy/temporal Pipeline runs a few steps. Each step is an activity that fails on its first two attempts, so you see Temporal retry it, followed by a durable timer. Stop this worker in the middle and start it again: the workflow carries on where it was, because its state lives in Temporal, not in this process. Summarize asks a model, through exe.dev's LLM gateway, to sum up some text. The model call is an activity, so Temporal retries it when the API fails. """ import asyncio import os from datetime import timedelta from temporalio import activity, workflow from temporalio.client import Client from temporalio.common import RetryPolicy from temporalio.worker import Worker # Workflows run in a sandbox that re-imports this file; let it reuse openai. with workflow.unsafe.imports_passed_through(): from openai import AsyncOpenAI TASK_QUEUE = "demo" @activity.defn async def flaky_step(n: int) -> str: attempt = activity.info().attempt if attempt < 3: raise RuntimeError(f"step {n}: simulated failure on attempt {attempt}") return f"step {n} succeeded on attempt {attempt}" @workflow.defn class Pipeline: @workflow.run async def run(self, steps: int) -> list[str]: results = [] for n in range(1, steps + 1): results.append( await workflow.execute_activity( flaky_step, n, start_to_close_timeout=timedelta(seconds=30), retry_policy=RetryPolicy(initial_interval=timedelta(seconds=2)), ) ) workflow.logger.info("step %d done, sleeping 30s", n) await workflow.sleep(timedelta(seconds=30)) return results @activity.defn async def ask_model(text: str) -> str: # exe.dev's LLM gateway speaks the OpenAI API; it needs no key on the VM. llm = AsyncOpenAI(base_url="https://llm.int.exe.xyz/v1", api_key="unused") reply = await llm.chat.completions.create( model=os.environ.get("LLM_MODEL", "gpt-5.4-mini"), messages=[{"role": "user", "content": f"Summarize in one sentence:\n\n{text}"}], ) return reply.choices[0].message.content @workflow.defn class Summarize: @workflow.run async def run(self, text: str) -> str: return await workflow.execute_activity( ask_model, text, start_to_close_timeout=timedelta(minutes=2), retry_policy=RetryPolicy(maximum_attempts=5), ) async def main(): client = await Client.connect( os.environ.get("TEMPORAL_ADDRESS", "localhost:7233"), namespace=os.environ.get("TEMPORAL_NAMESPACE", "default"), ) worker = Worker( client, task_queue=TASK_QUEUE, workflows=[Pipeline, Summarize], activities=[flaky_step, ask_model], ) print(f"worker polling task queue {TASK_QUEUE!r}", flush=True) await worker.run() if __name__ == "__main__": asyncio.run(main())