-
Notifications
You must be signed in to change notification settings - Fork 6.9k
feat(agents): [1/n] return typed answers from session streams #4007
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
Merged
+775
−40
Merged
Changes from all commits
Commits
Show all changes
12 commits
Select commit
Hold shift + click to select a range
820319e
[skip ci] apcha/agents-typed-results
apcha-oai 9bfe88d
[agents] Bind typed output schemas to completed turn results
apcha-oai f0ae929
[agents] Sanitize parsing failures and reject unsupported schema nodes
apcha-oai 251ba24
fix(agents): preserve supported structured output model semantics
apcha-oai 03a8ac7
fix(agents): separate local parsing from hosted schema checks
apcha-oai 3f232cb
fix(agents): reject pattern-keyed structured output maps
apcha-oai ca0915a
fix(agents): reject unbounded output mappings locally
apcha-oai 03fdbb5
fix(agents): validate single-value output literals
apcha-oai fdf2aef
fix(agents): isolate shared model schemas for tools and outputs
apcha-oai eea0329
test(agents): preserve distinct input and output schema policies
apcha-oai a97921a
refactor(agents): align output schemas with Responses helpers
apcha-oai e8c9c54
fix(agents): parse final structured text parts independently
apcha-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
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,53 @@ | ||
| from __future__ import annotations | ||
|
|
||
| from typing import Any, cast | ||
| from typing_extensions import TypeVar | ||
|
|
||
| import pydantic | ||
|
|
||
| from ._schema import model_schema | ||
| from ...._types import Omit | ||
| from ...._compat import PYDANTIC_V1 | ||
| from ..._pydantic import is_basemodel_type, is_dataclass_like_type | ||
| from ....types.beta.agent_text_param import AgentTextParam | ||
| from ....types.beta.text_format_param import TextFormatParamJSONSchema | ||
| from ....types.beta.agents.session_create_params import Agent | ||
|
|
||
|
|
||
| def validate_output_type(output_type: type[Any]) -> None: | ||
| if not is_basemodel_type(output_type) and not (is_dataclass_like_type(output_type) and not PYDANTIC_V1): | ||
| raise TypeError("Agents output_type must be a Pydantic model or a Pydantic v2 dataclass") | ||
|
|
||
|
|
||
| def agent_text_format(output_type: type[Any]) -> TextFormatParamJSONSchema: | ||
| """Beta: build the Agents JSON-schema format for a Pydantic model.""" | ||
| validate_output_type(output_type) | ||
| if is_basemodel_type(output_type): | ||
| schema = model_schema(output_type, strict=True) | ||
| else: | ||
| schema = model_schema(pydantic.TypeAdapter(output_type), strict=True) | ||
| return {"type": "json_schema", "schema": schema} | ||
|
|
||
|
|
||
| def with_output_schema(agent: Agent | Omit, output_type: type[Any] | None) -> Agent | Omit: | ||
| if output_type is None: | ||
| return agent | ||
| config = cast(Agent, {} if isinstance(agent, Omit) else dict(agent)) | ||
| text = cast(AgentTextParam, dict(config.get("text") or {})) | ||
| if text.get("format") is not None: | ||
| raise ValueError("Pass output_type or agent.text.format, not both") | ||
| text["format"] = agent_text_format(output_type) | ||
| config["text"] = text | ||
| return config | ||
|
|
||
|
|
||
| ResponseT = TypeVar("ResponseT") | ||
|
|
||
|
|
||
| def bind_output_type(response: ResponseT, output_type: type[Any] | None) -> ResponseT: | ||
| from ._stream import AgentSessionEventStream, AsyncAgentSessionEventStream | ||
|
|
||
| if isinstance(response, (AgentSessionEventStream, AsyncAgentSessionEventStream)): | ||
| stream = cast("AgentSessionEventStream[Any] | AsyncAgentSessionEventStream[Any]", response) | ||
| stream._collection.output_type = output_type | ||
| return cast(ResponseT, response) | ||
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,22 @@ | ||
| from __future__ import annotations | ||
|
|
||
| from copy import deepcopy | ||
| from typing import Any, cast | ||
|
|
||
| import pydantic | ||
|
|
||
| from ...._compat import PYDANTIC_V1, model_json_schema | ||
| from ..._pydantic import _ensure_strict_json_schema | ||
|
|
||
|
|
||
| def model_schema( | ||
| model: type[pydantic.BaseModel] | pydantic.TypeAdapter[Any], *, strict: bool = False | ||
| ) -> dict[str, Any]: | ||
| # Pydantic v1 caches schema dictionaries. Input and output policies must not | ||
| # mutate each other's schemas or the model's cache. | ||
| schema = deepcopy( | ||
| model.json_schema() | ||
| if not PYDANTIC_V1 and isinstance(model, pydantic.TypeAdapter) | ||
| else model_json_schema(cast(type[pydantic.BaseModel], model)) | ||
| ) | ||
| return _ensure_strict_json_schema(schema, path=(), root=schema) if strict else schema |
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
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.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
[Medium] Preserve Pydantic v1 nullable fields in the output schema
Under Pydantic v1,
BaseModel.schema()omitsnullfromOptionalfield schemas because optionality is represented by the field not being required. The strict-schema pass then marks every property required, so after removing the v1 restoration a model such asreason: str | None = Noneis sent as a required string. In a real typed Agents request, a legitimatenullanswer is therefore excluded even though the bound model accepts it, forcing a different value or an API-generation failure.Suggested fix: Restore the Pydantic v1 nullability pass after
model_schema(...), or move that correction into the shared strict-schema helper, and keep a v1 regression assertion that nested/list/union optional fields include anullbranch.There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Agreed, this looks like a real Pydantic v1 nullability gap. I reproduced
reason: str | None = None: the model acceptsNone, but both the existing Responses helper and this Agents helper emit a required string without a null branch. Pydantic v2 includes the null branch in both paths.For now we're keeping the Agents helper aligned with existing Responses behavior, rather than restoring an Agents-only correction. A shared, model-aware Pydantic v1 conversion fix would be a better follow-up; the API cannot recover nullability that the submitted schema omits. Leaving this thread unresolved to track the gap.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Tracking the shared Pydantic v1 nullability gap in SDK-1129, with the reproduction and this discussion linked there. Agents continues matching existing Responses behavior for now; leaving this thread unresolved.