-
Notifications
You must be signed in to change notification settings - Fork 2.3k
fix(responses): normalize reasoning items by inserting placeholder as… #1593
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
Draft
fitzjalen
wants to merge
3
commits into
openai:main
Choose a base branch
from
fitzjalen:main
base: main
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.
+68
−0
Draft
Changes from all commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
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 | ||||||||
---|---|---|---|---|---|---|---|---|---|---|
|
@@ -2,6 +2,7 @@ | |||||||||
|
||||||||||
import json | ||||||||||
from collections.abc import AsyncIterator | ||||||||||
import secrets | ||||||||||
from dataclasses import dataclass | ||||||||||
from typing import TYPE_CHECKING, Any, Literal, cast, overload | ||||||||||
|
||||||||||
|
@@ -241,6 +242,73 @@ async def _fetch_response( | |||||||||
) -> Response | AsyncStream[ResponseStreamEvent]: | ||||||||||
list_input = ItemHelpers.input_to_new_input_list(input) | ||||||||||
|
||||||||||
# --- Defensive normalization for reasoning items | ||||||||||
# Server requires: every reasoning item must be immediately followed by an assistant | ||||||||||
# message. We preserve all reasoning items (needed for references) and, when the next | ||||||||||
# item is NOT a message, we synthesize a minimal placeholder assistant message. | ||||||||||
# This prevents 400 errors like: | ||||||||||
# "Item '<id>' of type 'reasoning' was provided without its required following item." | ||||||||||
# and also preserves required reasoning when a subsequent function_call references it. | ||||||||||
def _ensure_reasoning_followed(seq: list[dict[str, Any]]) -> list[dict[str, Any]]: | ||||||||||
"""Ensure each reasoning item is immediately followed by an allowed follower. | ||||||||||
|
||||||||||
Allowed followers (no placeholder inserted): | ||||||||||
- message (assistant response text) | ||||||||||
- function_call (the model decided to call a tool directly) | ||||||||||
- code_interpreter_call (direct code interpreter invocation) | ||||||||||
|
||||||||||
We only synthesize a placeholder assistant message when the next item is | ||||||||||
missing or is NOT one of the allowed follower types. This preserves the | ||||||||||
original adjacency requirements enforced by the Responses API. | ||||||||||
""" | ||||||||||
existing_ids = {d.get("id") for d in seq if isinstance(d, dict)} | ||||||||||
allowed_followers = {"message", "function_call", "code_interpreter_call"} | ||||||||||
out: list[dict[str, Any]] = [] | ||||||||||
for idx, item in enumerate(seq): | ||||||||||
out.append(item) | ||||||||||
if not isinstance(item, dict) or item.get("type") != "reasoning": | ||||||||||
continue | ||||||||||
nxt = seq[idx + 1] if idx + 1 < len(seq) else None | ||||||||||
if isinstance(nxt, dict) and nxt.get("type") in allowed_followers: | ||||||||||
continue # already satisfied by allowed follower | ||||||||||
# Insert placeholder assistant message (safe follower) | ||||||||||
placeholder_id = None | ||||||||||
for _ in range(5): | ||||||||||
cand = f"msg_{secrets.token_hex(24)}" | ||||||||||
if cand not in existing_ids: | ||||||||||
placeholder_id = cand | ||||||||||
existing_ids.add(cand) | ||||||||||
break | ||||||||||
if not placeholder_id: | ||||||||||
placeholder_id = "msg_placeholder" | ||||||||||
out.append( | ||||||||||
{ | ||||||||||
"id": placeholder_id, | ||||||||||
"type": "message", | ||||||||||
"role": "assistant", | ||||||||||
"status": "completed", | ||||||||||
"content": [ | ||||||||||
{ | ||||||||||
"type": "output_text", | ||||||||||
"text": "(placeholder – reasoning context)", | ||||||||||
"annotations": [], | ||||||||||
} | ||||||||||
], | ||||||||||
} | ||||||||||
) | ||||||||||
return out | ||||||||||
|
||||||||||
try: | ||||||||||
# list_input is List[TResponseInputItem]; we only mutate dict entries. | ||||||||||
list_input = [dict(x) if isinstance(x, dict) else x for x in list_input] # shallow copy | ||||||||||
# Only fix if there exists at least one reasoning item. | ||||||||||
if any(isinstance(x, dict) and x.get("type") == "reasoning" for x in list_input): | ||||||||||
dict_seq = [x for x in list_input if isinstance(x, dict)] | ||||||||||
fixed = _ensure_reasoning_followed(dict_seq) | ||||||||||
list_input = fixed # type: ignore[assignment] | ||||||||||
Comment on lines
+306
to
+308
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. This logic filters out non-dict items from
Suggested change
Copilot uses AI. Check for mistakes. Positive FeedbackNegative Feedback |
||||||||||
except Exception as _norm_exc: # fail-open | ||||||||||
logger.debug(f"Reasoning normalization skipped due to error: {_norm_exc}") | ||||||||||
|
||||||||||
parallel_tool_calls = ( | ||||||||||
True | ||||||||||
if model_settings.parallel_tool_calls and tools and len(tools) > 0 | ||||||||||
|
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.
The magic number 5 for retry attempts should be defined as a named constant (e.g.,
MAX_ID_GENERATION_ATTEMPTS = 5
) to improve code readability and maintainability.Copilot uses AI. Check for mistakes.