We wrap a lot of LLM calls in Temporal activities. One mistake took a while to spot: the OpenAI Python client retries by itself (2 retries by default), and so does Temporal. That means one activity attempt can quietly turn into three HTTP calls, and your RetryPolicy and timeouts stop meaning what they say.
Here’s the pattern we use now. The SDK does no retries. Temporal retries 429s and 5xx with backoff. Requests that will fail every time (bad request, bad key, unknown model) fail the activity straight away.
# activities.py
import os
import openai
from openai import AsyncOpenAI
from temporalio import activity
from temporalio.exceptions import ApplicationError
# Temporal owns retries, so the SDK must not retry on its own.
llm = AsyncOpenAI(
base_url="https://api.china-aiapi.com/v1",
api_key=os.environ["APIGOTO_API_KEY"],
max_retries=0,
timeout=60.0,
)
@activity.defn
async def summarize(text: str) -> str:
try:
resp = await llm.chat.completions.create(
model=os.environ.get("MODEL_ID", "MODEL_ID"),
messages=[
{"role": "system", "content": "Summarize in 3 bullet points."},
{"role": "user", "content": text},
],
)
except openai.APIStatusError as e:
# Same request, same answer: retrying a 400/401/403/404/422 is wasted time.
if e.status_code in (400, 401, 403, 404, 422):
raise ApplicationError(
f"LLM call rejected ({e.status_code})",
type="LLMRejected",
non_retryable=True,
) from e
raise # 429 and 5xx: Temporal backs off and retries
return resp.choices[0].message.content or ""
# workflows.py
from datetime import timedelta
from temporalio import workflow
from temporalio.common import RetryPolicy
with workflow.unsafe.imports_passed_through():
from activities import summarize
@workflow.defn
class SummarizeDoc:
@workflow.run
async def run(self, text: str) -> str:
return await workflow.execute_activity(
summarize,
text,
start_to_close_timeout=timedelta(seconds=90),
retry_policy=RetryPolicy(
initial_interval=timedelta(seconds=2),
maximum_interval=timedelta(minutes=1),
maximum_attempts=6,
),
)
Register both in a normal Worker(client, task_queue="llm", workflows=[SummarizeDoc], activities=[summarize]) and start a run with:
temporal workflow start --type SummarizeDoc --task-queue llm --input '"some long text"'
Notes:
- I checked the retry behaviour in
WorkflowEnvironment.start_time_skipping()with a fake activity. Two 503s followed by a success finished on attempt 3. The non-retryable error stopped after 1 attempt. - Set
start_to_close_timeoutabove the clienttimeout. Then a slow model shows up as an OpenAI timeout error, which Temporal retries, instead of an activity timeout with no explanation. - The import goes through
imports_passed_through()so the workflow sandbox doesn’t re-importopenaiandhttpx. - Any OpenAI-compatible server works: change
base_url.
Disclosure: I work on the APIGOTO team; APIGOTO is independent of OpenAI, Anthropic and Google. The base URL above is ours (www.china-aiapi.com). The pattern itself is endpoint-agnostic.