Letting Temporal own LLM retries: max_retries=0 in the SDK, non-retryable on 4xx

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_timeout above the client timeout. 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-import openai and httpx.
  • 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.

Thanks for sharing, I think in general your pattern is sound.
Couple small things that might help:

You could set "LLMRejected"in activity retry_policy and raise then just do like
raise LLMRejected(f"LLM call rejected ({e.status_code})") from e

For raise # 429 and 5xx: Temporal backs off and retries
the retries would always follow your activity retry policy (interval and backoff). Note that ApplicationError also has next_retry_delayoption you can set to have longer retries than ones set in your activity options (for example you can use that to set to the Retry-After header your downstream gives back as part of error resp).

Also yeah make sure Temporal is the only thing retrying. Turn off retries on the client lib.
Also if possible turn off retires if done by downstream services themselves. If this cannot be turned off then would move to pattern where your Temporal activity is short running and just invokes this downstream service, then complete activity and have workflow await signal from it to unblock and continue after this downstream as done all of its retries that has configured.

Thanks @tihomir, that’s really helpful. (Disclosure, as in the post: I work on the APIGOTO team, the gateway in the example; we’re independent of OpenAI/Anthropic/Google.)

Agreed on both points. Tidier version based on your suggestion:

class LLMRejected(Exception):
    pass

# in the activity
raise LLMRejected(f"LLM call rejected ({e.status_code})") from e

# in the workflow
retry_policy=RetryPolicy(
    initial_interval=timedelta(seconds=2),
    maximum_interval=timedelta(minutes=1),
    maximum_attempts=6,
    non_retryable_error_types=["LLMRejected"],
)

And honoring Retry-After on 429s with next_retry_delay:

except openai.RateLimitError as e:
    ra = e.response.headers.get("retry-after", "")
    if ra.isdigit():
        raise ApplicationError(
            "rate limited", next_retry_delay=timedelta(seconds=int(ra))
        ) from e
    raise

Good point on downstream retries too. Where a downstream service retries internally and can’t be switched off, a short activity plus a signal / async completion keeps Temporal’s retry policy honest.