Repository navigation
Add bounded typed-answer repair and private result examples #6214
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
markstuart-oai
wants to merge
12
commits into
markstuart/sdk-controls-07-approved-output
Choose a base branch
from
markstuart/sdk-controls-08-typed-large-results
base: markstuart/sdk-controls-07-approved-output
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
12 commits
Select commit
Hold shift + click to select a range
2c8df11
Show how to limit function and MCP tool output and retrieve the original
markstuart-oai 334676d
Check report access and limit output inside the example tools
markstuart-oai 4b6c922
Merge feat/simple-codex into feat/bounded-tool-output-example
markstuart-oai d441233
Merge feat/simple-codex into feat/bounded-tool-output-example
markstuart-oai 95737b7
Display only reports issued to the current owner
markstuart-oai 4c0fcf0
List saved reports for the authorized reader in the MCP example
markstuart-oai 482dac6
Protect the report on the selected server regardless of its display name
markstuart-oai 94b6747
Require an owner before storing private reports
markstuart-oai e1f1365
Merge the prerequisite from #6120 into markstuart/sdk-controls-08-typ…
markstuart-oai d9d9820
Demonstrate bounded answer repair and private result retrieval
markstuart-oai 957a53e
Integrate the corrected parent before updating this branch
markstuart-oai c43b1ad
Preserve model provider ownership in typed answer repair
markstuart-oai File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,9 @@ | ||
| # Repair typed answers within a fixed budget | ||
|
|
||
| Run `uv run python examples/basic/typed_answer_repair.py` and `uv run python examples/mcp/bounded_tool_output/main.py` from this checkout with development dependencies. Neither needs model credentials. | ||
|
|
||
| The semantic repair example parses a Pydantic Verdict and checks its evidence count in the existing final-output policy. Dynamic instructions read fixed feedback from application-owned context. A second invalid candidate raises a fixed RepairLimitError. Provisional candidates may remain in private model history; approve only the validated final answer for display. By default, Runner closes the provider it creates. If you pass a `run_config`, you must close its provider, such as `CodexProvider`, after its last use. The helper disables tracing for its own run and leaves your configuration unchanged. Offline checks do not prove live/native behavior. | ||
|
|
||
| Malformed JSON or incompatible types fail during SDK parsing before final_output_policy. The separate tool-free `repair_schema` helper demonstrates two fresh synthetic attempts, with no session and no rejected text in the next request. It catches the SDK parser error without displaying its text, then fails with a fixed message when exhausted. Do not generalize new-run retries to providers that may perform native side effects. | ||
|
|
||
| The bounded-output recipe reuses PR #6120 at `482dac681ab40a5d9f037f11b7bfa90f482862b7`. Originals stay in a per-owner ephemeral store; authorized reads retrieve them privately and close revokes every reference. The integration converts local source-read exceptions into a fixed unavailable result before SDK tracing/history. It preserves the recipe's limits for small results, remote MCP errors, images, metadata, unselected results and native/hosted execution. A configured summary must itself be safe to disclose. |
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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,141 @@ | ||
| """Bounded semantic repair through the existing final-output policy, offline.""" | ||
|
|
||
| import asyncio | ||
| from dataclasses import dataclass, replace | ||
| from typing import Literal | ||
|
|
||
| from pydantic import BaseModel | ||
|
|
||
| from agents import ( | ||
| Agent, | ||
| AgentHooks, | ||
| ModelBehaviorError, | ||
| ProposedFinalOutput, | ||
| RunConfig, | ||
| RunContextWrapper, | ||
| Runner, | ||
| RunResultStreaming, | ||
| ) | ||
| from agents.models.interface import Model | ||
| from agents.testing import ScriptedModel, assistant_message | ||
|
|
||
|
|
||
| class Verdict(BaseModel): | ||
| decision: Literal["approve", "reject"] | ||
| evidence_count: int | ||
|
|
||
|
|
||
| class RepairLimitError(RuntimeError): | ||
| """The application declined to accept a candidate within its fixed budget.""" | ||
|
|
||
|
|
||
| @dataclass | ||
| class Review: | ||
| attempts: int = 0 | ||
| feedback: str = "Return a verdict supported by at least one evidence item." | ||
|
|
||
|
|
||
| def validate_candidate( | ||
| context: RunContextWrapper[Review], proposal: ProposedFinalOutput[Review] | ||
| ) -> Literal["finish", "continue"]: | ||
| context.context.attempts += 1 | ||
| candidate = proposal.output | ||
| if isinstance(candidate, Verdict) and candidate.evidence_count > 0: | ||
| return "finish" | ||
| if context.context.attempts >= 2: | ||
| raise RepairLimitError("No acceptable verdict within two candidates") | ||
| # Dynamic instructions give fixed feedback without copying the rejected text. | ||
| context.context.feedback = "Repair the verdict: include a positive evidence_count." | ||
| return "continue" | ||
|
|
||
|
|
||
| async def _drain_stream(run: RunResultStreaming) -> None: | ||
| """Discard raw events and join provider cleanup before returning.""" | ||
|
|
||
| async def drain() -> None: | ||
| async for _ in run.stream_events(): | ||
| pass | ||
|
|
||
| # Cancelling the reader itself can let it return before cleanup finishes. | ||
| reader = asyncio.create_task(drain()) | ||
| try: | ||
| await asyncio.shield(reader) | ||
| except asyncio.CancelledError: | ||
| run.cancel() | ||
| while not reader.done(): | ||
| try: | ||
| await asyncio.wait((reader,)) | ||
| except asyncio.CancelledError: | ||
| pass | ||
| if not reader.cancelled(): | ||
| reader.exception() # A secondary error must not replace caller cancellation. | ||
| raise | ||
|
|
||
|
|
||
| async def repair( | ||
| model: Model | str | None, *, streamed: bool = False, run_config: RunConfig | None = None | ||
| ) -> tuple[Verdict, Review]: | ||
| context = Review() | ||
| agent = Agent[Review]( | ||
| name="reviewer", | ||
| model=model, | ||
| output_type=Verdict, | ||
| instructions=lambda ctx, agent: ctx.context.feedback, | ||
| hooks=AgentHooks(final_output_policy=validate_candidate), | ||
| ) | ||
| config = ( | ||
| {"tracing_disabled": True} | ||
| if run_config is None | ||
| else replace(run_config, tracing_disabled=True) | ||
| ) | ||
| if streamed: | ||
| result = Runner.run_streamed( | ||
| agent, "Review the synthetic evidence.", context=context, run_config=config, max_turns=2 | ||
| ) | ||
| # Discard raw events privately, even if the producer has already started. | ||
| await _drain_stream(result) | ||
| else: | ||
| result = await Runner.run( | ||
| agent, "Review the synthetic evidence.", context=context, run_config=config, max_turns=2 | ||
| ) | ||
| return result.final_output_as(Verdict), context | ||
|
|
||
|
|
||
| async def repair_schema(model: ScriptedModel) -> tuple[Verdict, int]: | ||
| """Retry malformed synthetic answers at most twice without replaying bad text. | ||
|
|
||
| This separate offline recipe uses a tool-free scripted model. Do not apply | ||
| automatic new-run retries to a provider that may perform native side effects. | ||
| Each attempt has no session, so a malformed candidate enters no next request. | ||
| """ | ||
| for attempt in range(1, 3): | ||
| try: | ||
| result = await Runner.run( | ||
| Agent(name="schema reviewer", model=model, output_type=Verdict), | ||
| "Return JSON with decision approve/reject and positive evidence_count.", | ||
| run_config={"tracing_disabled": True}, | ||
| max_turns=1, | ||
| ) | ||
| except ModelBehaviorError: | ||
| # Parsing precedes final_output_policy. Never feed the error or raw | ||
| # rejected text back into the next request or display it to a user. | ||
| continue | ||
| answer = result.final_output_as(Verdict) | ||
| if answer.evidence_count > 0: | ||
| return answer, attempt | ||
| raise RepairLimitError("No acceptable typed verdict within two attempts") | ||
|
|
||
|
|
||
| async def main() -> None: | ||
| model = ScriptedModel( | ||
| [ | ||
| [assistant_message('{"decision":"approve","evidence_count":0}')], | ||
| [assistant_message('{"decision":"reject","evidence_count":1}')], | ||
| ] | ||
| ) | ||
| answer, review = await repair(model) | ||
| print(answer.model_dump_json(), f"Candidates: {review.attempts}") | ||
|
|
||
|
|
||
| if __name__ == "__main__": | ||
| asyncio.run(main()) | ||
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
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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,48 @@ | ||
| # Keep large tool results out of the conversation | ||
|
|
||
| Run the example from this source checkout. It uses a scripted model and a local MCP server over stdio. No API key is needed. | ||
|
|
||
| ```sh | ||
| uv run python examples/mcp/bounded_tool_output/main.py | ||
| ``` | ||
|
|
||
| Both inspection reports exceed the example's 128-byte text budget. The next model request, SDK history and caller receive warning counts of 20 and 8 with random references. The example prints each saved summary and checks the first page privately. | ||
|
|
||
| ## Choose what to share | ||
|
|
||
| [main.py](main.py) uses two routes. | ||
|
|
||
| - `reports.site_tool()` binds `inspect_site` to the private store. The function checks access before reading the report, applies the budget and checks access again before returning. Any output editor receives the result after those checks. | ||
| - For SDK-discovered MCP tools, each `ReportServer` applies the policy to `read.report` by raw tool name, regardless of the server's display name. Its `call_tool` method checks `isError` and sees every block. It replaces large successful reports before SDK conversion, custom data extraction and function span output capture. Other tools and ordinary `MCPServerStdio` instances keep their usual behavior. | ||
|
|
||
| For a nonempty structured object, the wrapper uses its JSON in place of the fallback text. It resolves the sample `{"ticket": "site"}` by awaiting a local report. Runner calls `authorize_call` with the run context before sending the request. Direct calls to `server.call_tool()` skip this access check. Never let a server pick another user's record or an arbitrary file or URL. | ||
|
|
||
| At the tool boundary, the budget covers the sum of UTF-8 text bytes per result, including the reference. Smaller reports pass through in full. For large reports, the summary shares only the count of literal `WARN:` markers. Choose facts safe to disclose for your data. The first text slot holds the replacement and the other text slots stay empty. A structured result without a text slot gets one. | ||
|
|
||
| ## Retrieve privately | ||
|
|
||
| Create one `Reports` instance per run. Load the owner's nonblank string ID from a trusted application record. The store compares IDs exactly. Pass only the authenticated requester as the run context. Never accept either identity from tool arguments or a reference. The reader uses only summaries and references issued by this store. It ignores tool output, including short reports, errors and text that looks like a reference. Without an authorized saved report, it prints a fixed message. | ||
|
|
||
| After the run, inside the `closing` block, application code can read the first page of each saved text part. Keep these pages out of tool results and model input. | ||
|
|
||
| ```python | ||
| for reference, summary, part_count in reports.saved(requester): | ||
| for part in range(part_count): | ||
| first_page = reports.fetch(requester, reference, part=part) | ||
| ``` | ||
|
|
||
| `saved()` returns an empty tuple for an empty or closed store or a different requester. Images do not count as text parts. A structured report has one JSON part. Each `fetch()` checks access again and returns up to 64 characters. To read the next page, advance `offset` by the page length. | ||
|
|
||
| The originals stay in process memory outside SDK context. Leaving the `closing` block revokes every reference, including on failure or cancellation. Saved conversations cannot restore the originals. This example has no storage quota or durable store. | ||
|
|
||
| ## Limits | ||
|
|
||
| - Selected successes support text and images. Images retain their contents and positions. Other media stop the run. The budget excludes images, block metadata and serialization overhead. Use this policy only for tools that accept a text replacement without a required output schema. | ||
| - Unselected results and MCP errors pass through, even when large. The local function converts source-read exceptions into a fixed unavailable status before SDK publication; it preserves cancellation. Other selected-operation exceptions and invalid summaries stop the run. Cancelling the run during preparation withholds the pending output. It cannot undo a remote action or stop counting already underway in a worker thread. | ||
| - This example disables tracing. Keep tool-data logging disabled and check logs, exceptions and other observers separately. Small reports, images and errors can still contain sensitive data. | ||
| - The recipe covers SDK-executed tools. It excludes native tools and provider-hosted MCP. Editing later requests cannot retract data already received by a provider. | ||
|
|
||
|
|
||
| ## Source attribution | ||
|
|
||
| This recipe has been reusing PR #6120 at `4c0fcf035faa12d34480329af49c6f634ddcc276`. The integration has been adding fixed local source-error handling and tests without changing the original ownership and media limits. |
Oops, something went wrong.
Oops, something went wrong.
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.
Uh oh!
There was an error while loading. Please reload this page.