Repository navigation
refactor(sdk): de-duplicate Agent.step/astep via shared helpers (Q5 of #3341) - #3448
VascoSch92 wants to merge 3 commits into
Conversation
Python API breakage checks — ✅ PASSEDResult: ✅ PASSED |
REST API breakage checks (OpenAPI) — ✅ PASSEDResult: ✅ PASSED |
|
✅ Review complete. This review was performed through OpenHands Cloud Automation. You can log in and view the conversation here. |
all-hands-bot
left a comment
There was a problem hiding this comment.
Clean, well-scoped refactoring that achieves the stated goal. The _RECOVERABLE_STEP_ERRORS constant, _handle_step_error, and _prepare_tool_call_actions helpers are good patterns that prevent the sync/async drift described in #3341. Three actionable items below; the rest is solid.
This review was generated by an AI agent (OpenHands) on behalf of the user through OpenHands Automation. View conversation
all-hands-bot
left a comment
There was a problem hiding this comment.
✅ QA Report: PASS
Exercised the refactored Agent.step/Agent.astep paths through real SDK conversations, and the PR branch preserved the same observable behavior as main for content, tool execution, and malformed tool-call recovery.
Does this PR achieve its stated goal?
Yes. The stated goal is a refactor that de-duplicates sync/async Agent step logic without changing behavior. I verified this by running the same SDK conversations on origin/main and vasco/q5: sync and async content responses finished with the expected assistant messages, sync and async terminal tool calls executed and resumed to final assistant messages, and malformed function-call recovery emitted the same corrective user messages before and after the PR.
| Phase | Result |
|---|---|
| Environment Setup | ✅ make build completed successfully and installed the uv workspace environment. |
| CI Status | 🟡 Completed checks were green at refresh time; qa-changes plus three Agent Server build/push jobs were still in progress. |
| Functional Verification | ✅ Real SDK Conversation.run() / Conversation.arun() flows matched base behavior before and after the refactor. |
Functional Verification
Test 1: Sync/async content and terminal tool-call paths remain unchanged
Step 1 — Establish baseline (without the PR):
Ran git checkout origin/main && git rev-parse --short HEAD && OPENHANDS_SUPPRESS_BANNER=1 uv run python /tmp/qa_agent_behavior.py:
HEAD is now at a7f6d8fb fix(sdk): count tools for condenser token limits (#3445)
a7f6d8fb
SYNC_CONTENT status=FINISHED assistants=['SYNC_CONTENT_OK']
ASYNC_CONTENT status=FINISHED assistants=['ASYNC_CONTENT_OK']
SYNC_TOOL status=FINISHED calls=2 marker_seen=True assistants=['SYNC_TOOL_DONE']
ASYNC_TOOL status=FINISHED calls=2 marker_seen=True assistants=['ASYNC_TOOL_DONE']
This establishes the pre-refactor behavior: content responses finish, terminal tool calls execute (marker_seen=True), and both sync/async tool flows make two LLM calls (tool request then final response).
Step 2 — Apply the PR's changes:
Checked out vasco/q5 at fc58d0c7.
Step 3 — Re-run with the PR in place:
Ran git checkout vasco/q5 && git rev-parse --short HEAD && OPENHANDS_SUPPRESS_BANNER=1 uv run python /tmp/qa_agent_behavior.py:
fc58d0c7
SYNC_CONTENT status=FINISHED assistants=['SYNC_CONTENT_OK']
ASYNC_CONTENT status=FINISHED assistants=['ASYNC_CONTENT_OK']
SYNC_TOOL status=FINISHED calls=2 marker_seen=True assistants=['SYNC_TOOL_DONE']
ASYNC_TOOL status=FINISHED calls=2 marker_seen=True assistants=['ASYNC_TOOL_DONE']
This shows the refactored PR branch preserves the same user-visible SDK behavior for both step and astep, including real TerminalTool execution and continuation after the observation.
Test 2: Malformed function-call recovery remains unchanged
Step 1 — Establish baseline (without the PR):
Ran git checkout origin/main && git rev-parse --short HEAD && OPENHANDS_SUPPRESS_BANNER=1 uv run python /tmp/qa_error_behavior.py:
a7f6d8fb
SYNC_MALFORMED status=ERROR user_texts=['Trigger malformed sync recovery.', 'QA_SYNC_BAD_TOOL_CALL']
ASYNC_MALFORMED status=ERROR user_texts=['Trigger malformed async recovery.', 'QA_ASYNC_BAD_TOOL_CALL']
This confirms baseline behavior for FunctionCallValidationError: both sync and async paths add the validation text back as a user message.
Step 2 — Apply the PR's changes:
Checked out vasco/q5 at fc58d0c7.
Step 3 — Re-run with the PR in place:
Ran OPENHANDS_SUPPRESS_BANNER=1 uv run python /tmp/qa_error_behavior.py on the PR branch:
SYNC_MALFORMED status=ERROR user_texts=['Trigger malformed sync recovery.', 'QA_SYNC_BAD_TOOL_CALL']
ASYNC_MALFORMED status=ERROR user_texts=['Trigger malformed async recovery.', 'QA_ASYNC_BAD_TOOL_CALL']
This matches the baseline output, confirming the shared error handler preserves the malformed-call recovery behavior for both sync and async execution.
Issues Found
None.
This review was created by an AI agent (OpenHands) on behalf of the user.
|
✅ Review complete. This review was performed through OpenHands Cloud Automation. You can log in and view the conversation here. |
all-hands-bot
left a comment
There was a problem hiding this comment.
Clean refactoring that achieves its goal. The three concerns from the previous review (_dispatch_non_tool_response exhaustiveness guard, method naming, docstring cross-reference) are already resolved in the current branch head — the case _: raise AssertionError guard is present, the helper is named _handle_blocked_user_message, and the docstring cross-references _RECOVERABLE_STEP_ERRORS. Two new minor observations below.
Minor: PR description / implementation name mismatch — The PR description still says _check_blocked_user_message in the bullet list, but the code uses _handle_blocked_user_message. Worth a quick description edit for accuracy.
Minor: No unit tests for extracted helpers — _handle_step_error (especially the no-condenser error paths), _prepare_tool_call_actions (the None return on confirmation), and _dispatch_non_tool_response (the case _: guard) are now independently testable units. The QA report confirms end-to-end behavior is preserved, but targeted unit tests would catch regressions earlier. Not blocking, but a follow-up issue would be worthwhile.
This review was generated by an AI agent (OpenHands) on behalf of the user through OpenHands Automation. View conversation
|
|
||
| def _handle_step_error( | ||
| self, | ||
| error: Exception, |
There was a problem hiding this comment.
🟡 Suggestion: The error: Exception annotation is broader than what can actually arrive here — the caller's except _RECOVERABLE_STEP_ERRORS guarantees only FunctionCallValidationError, LLMMalformedConversationHistoryError, or LLMContextWindowExceedError. Narrowing the type to Union[FunctionCallValidationError, LLMMalformedConversationHistoryError, LLMContextWindowExceedError] would let type-checkers verify match exhaustiveness without relying solely on the runtime case _: raise error guard. The defensive wildcard is still worth keeping regardless.
| error: Exception, | |
| error: FunctionCallValidationError | |
| | LLMMalformedConversationHistoryError | |
| | LLMContextWindowExceedError, |
all-hands-bot
left a comment
There was a problem hiding this comment.
Clean refactoring that achieves its goal. The three concerns from the previous review (_dispatch_non_tool_response exhaustiveness guard, method naming, docstring cross-reference) are already resolved in the current branch head — the case _: raise AssertionError guard is present, the helper is named _handle_blocked_user_message, and the docstring cross-references _RECOVERABLE_STEP_ERRORS. Two new minor observations below.
Minor: PR description / implementation name mismatch — The PR description still says _check_blocked_user_message in the bullet list, but the code uses _handle_blocked_user_message. Worth a quick description edit for accuracy.
Minor: No unit tests for extracted helpers — _handle_step_error (especially the no-condenser error paths), _prepare_tool_call_actions (the None return on confirmation), and _dispatch_non_tool_response (the case _: guard) are now independently testable units. The QA report confirms end-to-end behavior is preserved, but targeted unit tests would catch regressions earlier. Not blocking, but a follow-up issue would be worthwhile.
This review was generated by an AI agent (OpenHands) on behalf of the user through OpenHands Automation. View conversation
|
|
||
| def _handle_step_error( | ||
| self, | ||
| error: Exception, |
There was a problem hiding this comment.
🟡 Suggestion: The error: Exception annotation is broader than what can actually arrive here — the caller's except _RECOVERABLE_STEP_ERRORS guarantees only FunctionCallValidationError, LLMMalformedConversationHistoryError, or LLMContextWindowExceedError. Narrowing the type to Union[FunctionCallValidationError, LLMMalformedConversationHistoryError, LLMContextWindowExceedError] would let type-checkers verify match exhaustiveness without relying solely on the runtime case _: raise error guard. The defensive wildcard is still worth keeping regardless.
| error: Exception, | |
| error: FunctionCallValidationError | |
| | LLMMalformedConversationHistoryError | |
| | LLMContextWindowExceedError, |
| llm_response: LLMResponse, | ||
| conversation: LocalConversation, | ||
| state: ConversationState, | ||
| on_event: ConversationCallbackType, |
There was a problem hiding this comment.
🟡 Suggestion: _dispatch_non_tool_response is a synchronous method called from both the sync step and the async astep. This is intentional — _handle_content_response and _handle_no_content_response are also synchronous — but without a note in the docstring it's easy for a future contributor to question whether this should be async def. A single sentence would prevent that confusion:
| on_event: ConversationCallbackType, | |
| Shared by :meth:`Agent.step` and :meth:`Agent.astep`. Tool-call | |
| dispatch is the only colour-divergent branch (sync ``_handle_tool_calls`` | |
| vs awaited ``_ahandle_tool_calls``), so those methods handle it inline | |
| and delegate every other response type here. This method is intentionally | |
| synchronous: all non-tool-call handlers (``_handle_content_response``, | |
| ``_handle_no_content_response``) are sync and do not need to be awaited. |
all-hands-bot
left a comment
There was a problem hiding this comment.
✅ QA Report: PASS
The refactor preserves the exercised Agent.step/Agent.astep behavior across sync/async content responses, finish tool execution, and malformed function-call recovery.
Does this PR achieve its stated goal?
Yes. The PR set out to de-duplicate Agent.step/astep without changing behavior; I exercised the SDK through the real Conversation.run() and Conversation.arun() entry points on both origin/main and the PR branch. The structured outputs were identical before and after the PR: all six scenarios finished, finish tool calls emitted matching action/observation events, and sync/async recoverable function-call errors both produced corrective user messages followed by recovery.
| Phase | Result |
|---|---|
| Environment Setup | ✅ make build completed and installed the uv-managed workspace dependencies. |
| CI Status | 🟡 Completed checks observed green/skipped; qa-changes and one agent-server image build were still in progress when checked. |
| Functional Verification | ✅ Real SDK conversations passed on PR branch and matched the base-branch baseline. |
Functional Verification
Test 1: Agent sync/async step behavior remains unchanged
Step 1 — Establish baseline without the refactor:
Checked out origin/main and ran a temporary SDK script outside the repo using Conversation.run() and Conversation.arun() with deterministic LLM responses. The script exercised:
- sync content response
- async content response
- sync
finishtool call - async
finishtool call - sync
FunctionCallValidationErrorrecovery - async
FunctionCallValidationErrorrecovery
Ran:
git checkout --detach origin/main
OPENHANDS_SUPPRESS_BANNER=1 uv run python /tmp/agent_step_refactor_qa.py > /tmp/qa_main_raw.log 2>&1Baseline summary:
main scenario_statuses= {'async_content': 'FINISHED', 'async_finish_tool': 'FINISHED', 'async_recovery': 'FINISHED', 'sync_content': 'FINISHED', 'sync_finish_tool': 'FINISHED', 'sync_recovery': 'FINISHED'}
main finish_actions= {'sync_finish_tool': [{'tool_call_id': 'call-finish-sync', 'tool_name': 'finish'}], 'async_finish_tool': [{'tool_call_id': 'call-finish-async', 'tool_name': 'finish'}]}
main recovery_messages= {'sync_recovery': ['Run sync_recovery', 'malformed sync tool call', 'Recovered sync'], 'async_recovery': ['Run async_recovery', 'malformed async tool call', 'Recovered async']}
This shows the pre-refactor behavior for the user-facing SDK conversation paths: both sync and async conversations finish successfully, tool calls execute, and recoverable malformed function calls are fed back and recovered.
Step 2 — Apply the PR's changes:
Checked out vasco/q5 at 0df5470e93353d35469666fb93fdd7b7af100814.
Step 3 — Re-run with the refactor in place:
Ran:
OPENHANDS_SUPPRESS_BANNER=1 uv run python /tmp/agent_step_refactor_qa.py > /tmp/qa_pr_raw.log 2>&1PR summary and comparison:
pr scenario_statuses= {'async_content': 'FINISHED', 'async_finish_tool': 'FINISHED', 'async_recovery': 'FINISHED', 'sync_content': 'FINISHED', 'sync_finish_tool': 'FINISHED', 'sync_recovery': 'FINISHED'}
pr finish_actions= {'sync_finish_tool': [{'tool_call_id': 'call-finish-sync', 'tool_name': 'finish'}], 'async_finish_tool': [{'tool_call_id': 'call-finish-async', 'tool_name': 'finish'}]}
pr recovery_messages= {'sync_recovery': ['Run sync_recovery', 'malformed sync tool call', 'Recovered sync'], 'async_recovery': ['Run async_recovery', 'malformed async tool call', 'Recovered async']}
main_pr_structured_outputs_equal= True
This confirms the changed behavior is unchanged for the exercised critical paths: the PR branch produced the same statuses, event shapes, tool action/observation records, and recovery messages as main.
Issues Found
None.
This review was created by an AI agent (OpenHands) on behalf of the user.
|
[Automatic Post]: It has been a while since there was any activity on this PR. @VascoSch92, are you still working on it? If so, please go ahead, if not then please request review, close it, or request that someone else follow up. This comment was created by an AI agent (OpenHands) on behalf of the user. |
|
[Automatic Post]: It has been a while since there was any activity on this PR. @VascoSch92, are you still working on it? If so, please go ahead, if not then please request review, close it, or request that someone else follow up. This comment was posted by an AI agent (OpenHands) on behalf of the user. |
|
[Automatic Post]: It has been a while since there was any activity on this PR. @VascoSch92, are you still working on it? If so, please go ahead, if not then please request review, close it, or request that someone else follow up. This comment was created by an AI agent (OpenHands) on behalf of the user. |
|
[Automatic Post]: It has been a while since there was any activity on this PR. @VascoSch92, are you still working on it? If so, please go ahead, if not then please request review, close it, or request that someone else follow up. This comment was created by an AI agent (OpenHands) on behalf of the user. |
|
This PR is stale because it has been open for 40 days with no activity. Remove the stale label or leave a comment, otherwise it will be closed in 10 days. |
|
This PR was closed because it had no activity for 50 days. If you feel this was closed in error, and you would like to continue the PR, please resubmit or let us know. |
Summary
Part of #3341 (Q5). The async LLM path added in #3284 was written as near-verbatim copies of the sync methods, and that twin duplication is what let the async path silently
diverge (the root cause of B1/B2). This is the first slice: the Agent.step / astep pair.
Extract the color-agnostic logic into shared helpers so the sync and async paths have one source of truth instead of two ~130-line copies:
statement.
except rejects a set/frozenset) and marked Final.
After this, step and astep drop from ~130 lines each to ~40 and differ only by irreducible color: the awaits plus the single tool-call branch (_execute_actions vs await
_aexecute_actions). Logging in the recovery paths is unified to f-strings (the house style), which also removes the prior sync/async log-wording inconsistency. Behavior is
unchanged — the action-build → confirmation → execute → emit-tokens ordering is preserved exactly.
Issue Number
#3341
Type
Agent Server images for this PR
• GHCR package: https://github.com/OpenHands/agent-sdk/pkgs/container/agent-server
Variants & Base Images
eclipse-temurin:17-jdknikolaik/python-nodejs:python3.13-nodejs22-slimgolang:1.21-bookwormPull (multi-arch manifest)
# Each variant is a multi-arch manifest supporting both amd64 and arm64 docker pull ghcr.io/openhands/agent-server:4b62631-pythonRun
All tags pushed for this build
About Multi-Architecture Support
4b62631-python) is a multi-arch manifest supporting both amd64 and arm644b62631-python-amd64) are also available if needed