Repository navigation
Description
On the experimental streaming route (Runner.run_streamed with ModelActivityParameters(streaming_topic=...)), an input guardrail in the default parallel mode can trip while the model is still streaming. The workflow's stream_events() then stops and raises InputGuardrailTripwireTriggered, as it does natively. But subscribers of the stream topic get the rest of the answer and a normal response.completed, with no sign that the request was rejected. A UI on the topic shows the whole answer to a rejected request.
This happens with or without heartbeat_timeout.
Why
invoke_model_activity_streaming publishes each event to the topic as the model sends it. In the workflow, _TemporalModelStub.stream_response awaits the whole activity and only then yields its events. The framework checks parallel input guardrails against the events it yields, so the check only gates the workflow's own stream_events() consumer, after everything has been published. Nothing cancels the activity when the guardrail trips.
Reproduction
One file. It needs temporalio-openai-agents; WorkflowEnvironment.start_local() starts a dev server. A fake model streams five deltas 300 ms apart, and a parallel input guardrail trips after one second.
"""A parallel input guardrail trips mid-stream, but stream topic subscribers get the whole answer.
Exits 1 when the subscriber gets `response.completed` after the trip (the bug), 0 otherwise.
"""
import asyncio
import uuid
from datetime import timedelta
from temporalio import workflow
from temporalio.client import Client
from temporalio.contrib.workflow_streams import WorkflowStream, WorkflowStreamClient
from temporalio.testing import WorkflowEnvironment
from temporalio.worker import Worker
with workflow.unsafe.imports_passed_through():
from agents import (
Agent,
GuardrailFunctionOutput,
InputGuardrailTripwireTriggered,
Model,
Runner,
input_guardrail,
)
from agents.items import TResponseStreamEvent
from openai.types.responses import (
Response,
ResponseCompletedEvent,
ResponseOutputMessage,
ResponseOutputText,
ResponseTextDeltaEvent,
)
from temporalio.openai_agents import ModelActivityParameters, OpenAIAgentsPlugin
from temporalio.openai_agents.testing import TestModelProvider
class SlowModel(Model):
"""Streams five deltas 300 ms apart, then response.completed."""
async def get_response(self, *args, **kwargs):
raise NotImplementedError
async def stream_response(self, *args, **kwargs):
text = ""
for i in range(5):
await asyncio.sleep(0.3)
text += f"part {i} "
yield ResponseTextDeltaEvent(
type="response.output_text.delta", delta=f"part {i} ", item_id="m1",
output_index=0, content_index=0, sequence_number=i, logprobs=[],
)
message = ResponseOutputMessage(
id="m1", type="message", role="assistant", status="completed",
content=[ResponseOutputText(type="output_text", text=text, annotations=[], logprobs=[])],
)
yield ResponseCompletedEvent(
type="response.completed", sequence_number=5,
response=Response(
id="r1", created_at=0, model="fake", object="response", output=[message],
parallel_tool_calls=False, tool_choice="auto", tools=[], status="completed",
),
)
@input_guardrail # runs in parallel with the model call, the default
async def refuse(context, agent, input) -> GuardrailFunctionOutput:
await workflow.sleep(1) # for example, waiting on a policy check
return GuardrailFunctionOutput(output_info=None, tripwire_triggered=True)
@workflow.defn
class StreamWorkflow:
@workflow.init
def __init__(self) -> None:
self.stream = WorkflowStream()
@workflow.run
async def run(self) -> str:
agent = Agent(name="Assistant", instructions="Answer.", input_guardrails=[refuse])
result = Runner.run_streamed(agent, "Hello")
try:
async for _ in result.stream_events():
pass
except InputGuardrailTripwireTriggered:
await workflow.sleep(3) # let the topic take any late events
return "refused"
return str(result.final_output)
async def main() -> int:
plugin = OpenAIAgentsPlugin(
model_provider=TestModelProvider(SlowModel()),
model_params=ModelActivityParameters(
start_to_close_timeout=timedelta(seconds=30),
heartbeat_timeout=timedelta(seconds=1), # recommended for streaming
streaming_topic="events",
),
)
async with await WorkflowEnvironment.start_local() as env:
client = await Client.connect(env.client.service_client.config.target_host, plugins=[plugin])
async with Worker(client, task_queue="tq", workflows=[StreamWorkflow]):
workflow_id = f"stream-{uuid.uuid4()}"
handle = await client.start_workflow(StreamWorkflow.run, id=workflow_id, task_queue="tq")
seen: list[str] = []
async def subscribe() -> None:
stream = WorkflowStreamClient.create(client, workflow_id)
async for item in stream.subscribe(
["events"], from_offset=0, result_type=TResponseStreamEvent,
poll_cooldown=timedelta(milliseconds=50),
):
event = item.data
seen.append(event.delta if event.type == "response.output_text.delta" else event.type)
if event.type in ("response.completed", "error"):
return
subscriber = asyncio.create_task(subscribe())
print("workflow result:", await handle.result())
await asyncio.wait_for(subscriber, timeout=10)
print("subscriber got:", seen)
if "response.completed" in seen:
print("BUG: the guardrail tripped, but the subscriber got the whole answer and response.completed")
return 1
print("OK: the subscriber did not get the rest of the answer")
return 0
if __name__ == "__main__":
raise SystemExit(asyncio.run(main()))On temporalio-openai-agents 1.1.0 (from PyPI, with temporalio 1.34.0 and openai-agents 0.22.3), and on main at c664a34 (openai-agents 0.22.0):
workflow result: refused
subscriber got: ['part 0 ', 'part 1 ', 'part 2 ', 'part 3 ', 'part 4 ', 'response.completed']
BUG: the guardrail tripped, but the subscriber got the whole answer and response.completed
It exits 1. Without heartbeat_timeout the subscriber gets the same.
Expected: once the guardrail trips, subscribers stop getting the answer and get a sign that it ended, as a native stream_events() consumer does. Natively, with a model and guardrail like these, the consumer got four deltas and then InputGuardrailTripwireTriggered.
Controls:
- With a guardrail that allows the request, the subscriber and
stream_events()both get all five deltas andresponse.completed. - With
run_in_parallel=Falseon the guardrail, the model is not called and nothing is published. That is the current workaround.
Proposed fix
When a parallel input guardrail trips while the streaming model activity is running, cancel the activity. When cancelled, the activity publishes an error event to the topic and stops. If the guardrail has already tripped when the model is called, don't start the activity. The cancel is a new command, so it needs a workflow.patched check for runs recorded before the change. The cancel reaches the activity through its heartbeat, so it needs heartbeat_timeout, which the parameter docs already recommend for streaming.
A PR follows.
Activity
Breaking: stop the OpenAI Agents streaming model activity when a para…
[typescript/openai-agents] give model calls a 10-second default heart…