Add OpenRouter samples: prompt batch and budget gate - #366
Open
DABH wants to merge 1 commit into
Open
Conversation
Call OpenRouter from Activities with Temporal-owned retries, error classification, Retry-After handling, heartbeats, and OpenRouter response caching so a retried request is billed at zero. The budget_gate sample pauses the batch on a soft budget or on OpenRouter's 402 and resumes on a raise_budget Update. Also adds OpenRouter as a model provider for the OpenAI Agents SDK plugin sample.
This was referenced Sep 11, 2026
patbeqo
reviewed
Sep 11, 2026
|
|
||
| # Any OpenRouter model slug works here. A fixed, tool-capable model keeps the | ||
| # sample reproducible; swap in "openrouter/auto" to let OpenRouter choose. | ||
| OPENROUTER_MODEL = "openai/gpt-4o-mini" |
There was a problem hiding this comment.
Should we default to openrouter/auto since the README says and picks providers and models per request ?
There was a problem hiding this comment.
🟡 Changes recommended
Input deadlocks, serialized approval timeouts, duplicate-prompt state loss, and incomplete cost accounting need resolution.
Once you've addressed the issues Copilot identified, you can request another Copilot review.
Pull request overview
Adds OpenRouter integrations for durable prompt batching, budget-aware execution, and the OpenAI Agents SDK.
Changes:
- Adds prompt-batch and budget-gate workflows with retries, caching, and cost reporting.
- Adds mocked integration tests and dependency configuration.
- Adds an OpenRouter-backed Agents SDK example and documentation.
File summaries
| File | Description |
|---|---|
uv.lock |
Locks OpenRouter dependencies. |
pyproject.toml |
Adds the OpenRouter dependency group. |
README.md |
Registers the new sample. |
openrouter/__init__.py |
Initializes the package. |
openrouter/shared.py |
Defines shared inputs, results, and constants. |
openrouter/activities.py |
Implements OpenRouter requests and error handling. |
openrouter/README.md |
Documents the integration. |
openrouter/prompt_batch/__init__.py |
Initializes the prompt-batch package. |
openrouter/prompt_batch/workflow.py |
Implements concurrent prompt processing. |
openrouter/prompt_batch/run_worker.py |
Runs the prompt-batch worker. |
openrouter/prompt_batch/run_workflow.py |
Starts prompt-batch workflows. |
openrouter/prompt_batch/README.md |
Documents prompt batching. |
openrouter/budget_gate/__init__.py |
Initializes the budget-gate package. |
openrouter/budget_gate/workflow.py |
Implements budget reservations and pauses. |
openrouter/budget_gate/run_worker.py |
Runs the budget-gate worker. |
openrouter/budget_gate/run_workflow.py |
Starts budget-gate workflows. |
openrouter/budget_gate/raise_budget.py |
Sends budget updates. |
openrouter/budget_gate/README.md |
Documents budget controls. |
tests/openrouter/__init__.py |
Initializes the test package. |
tests/openrouter/activity_test.py |
Tests HTTP handling and caching. |
tests/openrouter/prompt_batch_test.py |
Tests batch result collection. |
tests/openrouter/budget_gate_test.py |
Tests pauses, updates, and timeouts. |
openai_agents/model_providers/workflows/openrouter_workflow.py |
Adds an OpenRouter agent workflow. |
openai_agents/model_providers/run_openrouter_workflow.py |
Starts the agent workflow. |
openai_agents/model_providers/run_openrouter_worker.py |
Configures the OpenRouter provider. |
openai_agents/model_providers/README.md |
Documents the provider example. |
Review details
Suppressed comments (1)
openrouter/activities.py:192
- This simulated successful first call is billed, but its result and cost are discarded when the Activity raises. The cached retry then reports
$0, soBatchResult.total_cost_usdand the budget ledger say zero even though the account was charged; the same gap occurs during the real post-response Worker crash being demonstrated. Persist/reconcile the first generation's charge externally, or clearly expose these totals as lower bounds and document that limitation for the budget gate.
if request.fail_once_after_call and activity.info().attempt == 1:
# Demo hook: the Worker "crashes" after the response arrived. The
# retry re-sends the identical request and gets a cache hit.
raise ApplicationError(
"Simulated failure after the response was received",
type="SimulatedFailure",
)
- Files reviewed: 21/26 changed files
- Comments generated: 5
- Review effort level: Balanced
💡 Add a code-review agent skill or configure MCP servers for context-aware, tailored reviews. Learn more in the docs.
| answer=_content_to_text((choices[0].get("message") or {}).get("content")) | ||
| if choices | ||
| else "", | ||
| cost_usd=float(cost) if isinstance(cost, (int, float)) else 0.0, |
Comment on lines
+57
to
+58
| self._budget_usd = gate.budget_usd | ||
| semaphore = asyncio.Semaphore(gate.max_concurrency) |
Comment on lines
+113
to
+115
| async with semaphore: | ||
| if not await self._reserve(prompt, gate.estimated_cost_usd, timeout): | ||
| return SkippedPrompt(prompt=prompt, reason="soft_budget_exhausted") |
| self._budget_usd, | ||
| prompt, | ||
| ) | ||
| self._paused[prompt] = "soft_budget_exhausted" |
| ) | ||
|
|
||
| # @@@SNIPSTART python-openrouter-prompt-batch-fan-out | ||
| semaphore = asyncio.Semaphore(batch.max_concurrency) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Adds an
openroutersample with two scenarios, plus OpenRouter as a model provider for the OpenAI Agents SDK sample.prompt_batch fans one Activity out per prompt with OpenRouter's Auto Router and returns answer, model, and reported cost per prompt. The Activity uses the
openaiclient pointed at OpenRouter withmax_retries=0, classifies 4xx as non-retryable and 408/429/5xx as retryable, passesRetry-Afterthrough asnext_retry_delay, heartbeats, and sendsX-OpenRouter-Cache: trueso a retried identical request is served from OpenRouter's cache at $0. A--fail-onceflag demonstrates that.budget_gate is the same batch, but it pauses on a soft budget or on OpenRouter's 402 and resumes on a
raise_budgetUpdate, with aspend_reportQuery.Tests use
httpx.MockTransportand a fake Activity; no API key needed. Verified live against OpenRouter, including a cache hit at $0 on retry.Docs page: temporalio/documentation#5307. TypeScript port: temporalio/samples-typescript#520.