Skip to content

[Bug] openai_agents: a streamed run fails replay in a Worker process that did not run its model Activity #229

Closed

Description

@campoy

Package: temporalio-openai-agents 1.1.0 and main (c664a34); also temporalio.contrib.openai_agents in temporalio 1.33.0 and 1.34.0.

What happens

Runner.run_streamed works through OpenAIAgentsPlugin with
ModelActivityParameters(streaming_topic=...). When the provider's streamed response fails the
installed openai SDK's strict validation, the run works in the process that ran its model
Activity. Another Worker process reads response.completed as a different event class
(ResponseAudioDeltaEvent). The framework then finds no completed response and raises
ModelBehaviorError("Model did not produce a final response!") in Workflow code.

So the run's History fails replay in a fresh process. A live run fails the same way when its next
Workflow Task lands on another process: with the model Activity on its own task queue
(ModelActivityParameters(task_queue=...)), or after a Worker restart while the Workflow waits.
The Workflow Task fails and retries, and the run stays RUNNING.

A response fails strict validation when the API stops sending a field the SDK requires, or sends an
output item type the SDK does not know yet. The plugin's converter has a lenient fallback for this
("OpenAI's response models can drift from live API payloads"), but on the streaming route it loses
the event type:

  1. The SDK reads the streaming Activity's return type, list[TResponseStreamEvent], with
    typing.get_type_hints, which drops the Annotated part of TResponseStreamEvent. That part
    carries openai's type discriminator.
  2. The fallback calls openai's construct_type with the bare union. Without the discriminator,
    construct_type looks in openai's process-wide DISCRIMINATOR_CACHE. Only a process that has
    itself parsed an event that failed strict validation has that entry, such as the one whose
    model Activity parsed the stream. Elsewhere it returns the first union member that builds.

Responses that pass strict validation are not affected. Neither is Runner.run: the converter
rebuilds ModelResponse fields with include_extras=True, which keeps the discriminator.

Reproduction

One file, no network. A fake httpx.MockTransport behind the real OpenAIResponsesModel streams
response.created, response.output_item.done and response.completed, whose
usage.input_tokens_details has no cache_write_tokens, a field the SDK requires. The script runs
the Workflow on a local dev server (temporal CLI on PATH), replays its History in the same
process, then in a fresh subprocess. It exits 1 when the fresh-process replay fails.
python reproduce.py valid adds cache_write_tokens.

"""A streamed run's History fails to replay in a Worker process that did not run its model Activity.

The fake provider streams a response whose `usage.input_tokens_details` has no
`cache_write_tokens`, a field the openai SDK requires, as when the API stops sending
a field. The run completes, and its History replays in the same process. A fresh
process (another Worker, or the same Worker after a restart) fails the replay with
"Model did not produce a final response!".

    python reproduce.py          # exits 1 when the fresh-process replay fails
    python reproduce.py valid    # control: a response that passes strict validation
"""

import asyncio
import json
import shutil
import subprocess
import sys
import uuid

from temporalio import workflow

with workflow.unsafe.imports_passed_through():
    import httpx
    from agents import Agent, OpenAIProvider, Runner
    from openai import AsyncOpenAI
    from temporalio.client import WorkflowHistory
    from temporalio.contrib.workflow_streams import WorkflowStream
    from temporalio.openai_agents import ModelActivityParameters, OpenAIAgentsPlugin
    from temporalio.testing import WorkflowEnvironment
    from temporalio.worker import Replayer, Worker

VALID = "valid" in sys.argv[1:]
USAGE = {
    "input_tokens": 1, "output_tokens": 1, "total_tokens": 2,
    "input_tokens_details": {"cached_tokens": 0, **({"cache_write_tokens": 0} if VALID else {})},
    "output_tokens_details": {"reasoning_tokens": 0},
}
MESSAGE = {"type": "message", "id": "msg_1", "role": "assistant", "status": "completed",
           "content": [{"type": "output_text", "text": "hello", "annotations": []}]}


def response(status: str, output: list) -> dict:
    return {"id": "resp_1", "object": "response", "created_at": 0, "model": "gpt-test", "status": status,
            "output": output, "parallel_tool_calls": True, "tool_choice": "auto", "tools": [], "usage": USAGE}


EVENTS = [
    {"type": "response.created", "sequence_number": 0, "response": response("in_progress", [])},
    {"type": "response.output_item.done", "sequence_number": 1, "output_index": 0, "item": MESSAGE},
    {"type": "response.completed", "sequence_number": 2, "response": response("completed", [MESSAGE])},
]


def handler(request: httpx.Request) -> httpx.Response:
    body = "".join(f"event: {e['type']}\ndata: {json.dumps(e)}\n\n" for e in EVENTS)
    return httpx.Response(200, headers={"content-type": "text/event-stream"}, content=body.encode())


def plugin() -> OpenAIAgentsPlugin:
    client = AsyncOpenAI(api_key="x", base_url="http://fake-openai.test/v1", max_retries=0,
                         http_client=httpx.AsyncClient(transport=httpx.MockTransport(handler)))
    return OpenAIAgentsPlugin(model_provider=OpenAIProvider(openai_client=client, use_responses=True),
                              model_params=ModelActivityParameters(streaming_topic="events"))


@workflow.defn
class StreamedAgent:
    def __init__(self) -> None:
        self.stream = WorkflowStream()  # the streaming model Activity publishes here

    @workflow.run
    async def run(self) -> str:
        result = Runner.run_streamed(Agent(name="assistant", model="gpt-test"), "hi")
        async for _ in result.stream_events():
            pass
        return result.final_output


async def replay(history: WorkflowHistory) -> str:
    result = await Replayer(workflows=[StreamedAgent], plugins=[plugin()]).replay_workflow(
        history, raise_on_replay_failure=False)
    return "ok" if result.replay_failure is None else f"failed: {str(result.replay_failure)[:160]}"


async def main() -> int:
    if "fresh-replay" in sys.argv[1:]:
        data = json.load(sys.stdin)
        print(await replay(WorkflowHistory.from_json(data["workflow_id"], data["history"])))
        return 0
    async with await WorkflowEnvironment.start_local(
        plugins=[plugin()], dev_server_existing_path=shutil.which("temporal")
    ) as env:
        async with Worker(env.client, task_queue="tq", workflows=[StreamedAgent]):
            wid = f"streamed-{uuid.uuid4().hex[:6]}"
            output = await env.client.execute_workflow(StreamedAgent.run, id=wid, task_queue="tq")
            history = await env.client.get_workflow_handle(wid).fetch_history()
    print(f"live run: {output!r}")
    print(f"replay in the same process: {await replay(history)}")
    fresh = subprocess.run(
        [sys.executable, __file__, "fresh-replay", *sys.argv[1:]], capture_output=True, text=True,
        input=json.dumps({"workflow_id": wid, "history": history.to_json()}))
    lines = fresh.stdout.strip().splitlines() or [fresh.stderr.strip()[-300:]]
    fresh_result = lines[-1]  # the replay result; the SDK's own log lines come first
    print(f"replay in a fresh process: {fresh_result}")
    return 0 if fresh_result == "ok" else 1


if __name__ == "__main__":
    sys.exit(asyncio.run(main()))

Output with temporalio-openai-agents 1.1.0 (temporalio 1.34.0, openai-agents 0.22.3,
openai 3.39.0), Python 3.13.16, Temporal CLI 1.9.1, without the dev server banner and the SDK's log
lines:

$ python reproduce.py
live run: 'hello'
replay in the same process: ok
replay in a fresh process: failed: 4: Workflow activation completion failed: Failure { failure: Some(Failure { message: "Model did not produce a final response!", source: "", stack_trace: "  File
$ echo $?
1

main at c664a34 (its lock: openai-agents 0.22.0, openai 3.8.0) gives the same, exit 1. With
valid, all three lines end in ok on both, exit 0.

Expected

Each streamed event decodes as its own class in every Worker process, so the History replays and
the run continues wherever its next Workflow Task runs.

Proposed fix

Have the Workflow decode the streaming Activity's result with the full list[TResponseStreamEvent]
type, so the fallback keeps the discriminator. Results that pass strict validation decode as
today. Workflow code can catch the run's error and go on, so a run that decoded such a result the
old way may have taken another path. A workflow.patched check, asked only when strict validation
fails, keeps the old decoding for those runs.

A PR follows.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    bug

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions