Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions examples/basic/typed_answer_repair.md
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.
141 changes: 141 additions & 0 deletions examples/basic/typed_answer_repair.py
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),
)
Comment thread
markstuart-oai marked this conversation as resolved.
Resolved
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())
1 change: 1 addition & 0 deletions examples/mcp/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ These examples connect agents to Model Context Protocol servers. Follow the [exa
| Inspect a Git repository | [Git](git_example/README.md) | `uvx`, Git, and a repository path. |
| Prefetch tools | [Get all tools](get_all_mcp_tools_example/README.md) | `npx`. |
| Restrict available tools | [Tool filtering](tool_filter_example/README.md) | `npx`. |
| Retrieve large reports privately | [Bounded tool output](bounded_tool_output/README.md) | Runs offline with a local server and no API key. |
| Start or configure an SSE server | [SSE](sse_example/README.md) and [remote SSE](sse_remote_example/README.md) | Local development environment or configured endpoint. |
| Use Streamable HTTP | [Local server](streamablehttp_example/README.md), [remote server](streamable_http_remote_example/README.md), and [custom client](streamablehttp_custom_client_example/README.md) | See each README for dependencies and endpoints. |
| Load MCP prompts | [Prompt server](prompt_server/README.md) | Local development environment. |
Expand Down
48 changes: 48 additions & 0 deletions examples/mcp/bounded_tool_output/README.md
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.
Loading
Loading