Skip to content

refactor(sdk): de-duplicate Agent.step/astep via shared helpers (Q5 of #3341) - #3448

Closed
VascoSch92 wants to merge 3 commits into
mainfrom
vasco/q5
Closed

VascoSch92 wants to merge 3 commits into
mainfrom
vasco/q5

Conversation

@VascoSch92

@VascoSch92 VascoSch92 commented May 31, 2026 •

Copy link
Copy Markdown
Member
  • A human has tested these changes.

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:

  • _handle_step_error (+ _can_condense) — the two byte-identical ~55-line except blocks (malformed function call, malformed history, context-window exceeded), now a single match
    statement.
  • _RECOVERABLE_STEP_ERRORS — the recoverable-error set, shared by both except clauses and the match so the caught set and the handled set can't drift. Kept a tuple (Python's
    except rejects a set/frozenset) and marked Final.
  • _check_blocked_user_message — the duplicated UserPromptSubmit-hook check.
  • _dispatch_non_tool_response — the identical CONTENT / REASONING_ONLY / EMPTY dispatch arms.
  • _prepare_tool_call_actions — the ~30 identical lines of tool-action building shared by _handle_tool_calls / _ahandle_tool_calls.

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

  • Bug fix
  • Feature
  • Refactor
  • Breaking change
  • Docs / chore

Agent Server images for this PR

• GHCR package: https://github.com/OpenHands/agent-sdk/pkgs/container/agent-server

Variants & Base Images

Variant Architectures Base Image Docs / Tags
java amd64, arm64 eclipse-temurin:17-jdk Link
python amd64, arm64 nikolaik/python-nodejs:python3.13-nodejs22-slim Link
golang amd64, arm64 golang:1.21-bookworm Link

Pull (multi-arch manifest)

# Each variant is a multi-arch manifest supporting both amd64 and arm64
docker pull ghcr.io/openhands/agent-server:4b62631-python

Run

docker run -it --rm \
  -p 8000:8000 \
  --name agent-server-4b62631-python \
  ghcr.io/openhands/agent-server:4b62631-python

All tags pushed for this build

ghcr.io/openhands/agent-server:4b62631-golang-amd64
ghcr.io/openhands/agent-server:4b6263107af63d1ec5120fa1647bda5e8810b824-golang-amd64
ghcr.io/openhands/agent-server:vasco-q5-golang-amd64
ghcr.io/openhands/agent-server:4b62631-golang_tag_1.21-bookworm-amd64
ghcr.io/openhands/agent-server:4b62631-golang-arm64
ghcr.io/openhands/agent-server:4b6263107af63d1ec5120fa1647bda5e8810b824-golang-arm64
ghcr.io/openhands/agent-server:vasco-q5-golang-arm64
ghcr.io/openhands/agent-server:4b62631-golang_tag_1.21-bookworm-arm64
ghcr.io/openhands/agent-server:4b62631-java-amd64
ghcr.io/openhands/agent-server:4b6263107af63d1ec5120fa1647bda5e8810b824-java-amd64
ghcr.io/openhands/agent-server:vasco-q5-java-amd64
ghcr.io/openhands/agent-server:4b62631-eclipse-temurin_tag_17-jdk-amd64
ghcr.io/openhands/agent-server:4b62631-java-arm64
ghcr.io/openhands/agent-server:4b6263107af63d1ec5120fa1647bda5e8810b824-java-arm64
ghcr.io/openhands/agent-server:vasco-q5-java-arm64
ghcr.io/openhands/agent-server:4b62631-eclipse-temurin_tag_17-jdk-arm64
ghcr.io/openhands/agent-server:4b62631-python-amd64
ghcr.io/openhands/agent-server:4b6263107af63d1ec5120fa1647bda5e8810b824-python-amd64
ghcr.io/openhands/agent-server:vasco-q5-python-amd64
ghcr.io/openhands/agent-server:4b62631-nikolaik_s_python-nodejs_tag_python3.13-nodejs22-slim-amd64
ghcr.io/openhands/agent-server:4b62631-python-arm64
ghcr.io/openhands/agent-server:4b6263107af63d1ec5120fa1647bda5e8810b824-python-arm64
ghcr.io/openhands/agent-server:vasco-q5-python-arm64
ghcr.io/openhands/agent-server:4b62631-nikolaik_s_python-nodejs_tag_python3.13-nodejs22-slim-arm64
ghcr.io/openhands/agent-server:4b62631-golang
ghcr.io/openhands/agent-server:4b6263107af63d1ec5120fa1647bda5e8810b824-golang
ghcr.io/openhands/agent-server:vasco-q5-golang
ghcr.io/openhands/agent-server:4b62631-golang_tag_1.21-bookworm
ghcr.io/openhands/agent-server:4b62631-java
ghcr.io/openhands/agent-server:4b6263107af63d1ec5120fa1647bda5e8810b824-java
ghcr.io/openhands/agent-server:vasco-q5-java
ghcr.io/openhands/agent-server:4b62631-eclipse-temurin_tag_17-jdk
ghcr.io/openhands/agent-server:4b62631-python
ghcr.io/openhands/agent-server:4b6263107af63d1ec5120fa1647bda5e8810b824-python
ghcr.io/openhands/agent-server:vasco-q5-python
ghcr.io/openhands/agent-server:4b62631-nikolaik_s_python-nodejs_tag_python3.13-nodejs22-slim

About Multi-Architecture Support

  • Each variant tag (e.g., 4b62631-python) is a multi-arch manifest supporting both amd64 and arm64
  • Docker automatically pulls the correct architecture for your platform
  • Individual architecture tags (e.g., 4b62631-python-amd64) are also available if needed

@VascoSch92
VascoSch92 requested a review from all-hands-bot May 31, 2026 14:57
@github-actions

github-actions Bot commented May 31, 2026 •

Copy link
Copy Markdown
Contributor

Python API breakage checks — ✅ PASSED

Result: ✅ PASSED

Action log

@github-actions

github-actions Bot commented May 31, 2026 •

Copy link
Copy Markdown
Contributor

REST API breakage checks (OpenAPI) — ✅ PASSED

Result: ✅ PASSED

Action log

all-hands-bot commented May 31, 2026 •

Copy link
Copy Markdown
Collaborator

✅ Review complete.

This review was performed through OpenHands Cloud Automation. You can log in and view the conversation here.

@all-hands-bot all-hands-bot left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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 all-hands-bot left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

✅ 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.

@VascoSch92
VascoSch92 requested a review from all-hands-bot May 31, 2026 15:12

all-hands-bot commented May 31, 2026 •

Copy link
Copy Markdown
Collaborator

✅ Review complete.

This review was performed through OpenHands Cloud Automation. You can log in and view the conversation here.

@all-hands-bot all-hands-bot left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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,

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 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.

Suggested change
error: Exception,
error: FunctionCallValidationError
| LLMMalformedConversationHistoryError
| LLMContextWindowExceedError,

@all-hands-bot all-hands-bot left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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,

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 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.

Suggested change
error: Exception,
error: FunctionCallValidationError
| LLMMalformedConversationHistoryError
| LLMContextWindowExceedError,

llm_response: LLMResponse,
conversation: LocalConversation,
state: ConversationState,
on_event: ConversationCallbackType,

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 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:

Suggested change
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.

@VascoSch92
VascoSch92 requested a review from malhotra5 May 31, 2026 15:17

@all-hands-bot all-hands-bot left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

✅ 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 finish tool call
  • async finish tool call
  • sync FunctionCallValidationError recovery
  • async FunctionCallValidationError recovery

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>&1

Baseline 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>&1

PR 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.

@all-hands-bot

Copy link
Copy Markdown
Collaborator

[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.

@all-hands-bot

Copy link
Copy Markdown
Collaborator

[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.

@all-hands-bot

Copy link
Copy Markdown
Collaborator

[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.

@OpenHands OpenHands deleted a comment from all-hands-bot Jul 28, 2026
@OpenHands OpenHands deleted a comment from all-hands-bot Jul 28, 2026
@OpenHands OpenHands deleted a comment from all-hands-bot Jul 28, 2026
@OpenHands OpenHands deleted a comment from all-hands-bot Jul 28, 2026
@OpenHands OpenHands deleted a comment from all-hands-bot Jul 28, 2026
@all-hands-bot

Copy link
Copy Markdown
Collaborator

[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.

@github-actions

Copy link
Copy Markdown
Contributor

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.

@github-actions github-actions Bot added the Stale label Sep 10, 2026
@github-actions

Copy link
Copy Markdown
Contributor

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.

@github-actions github-actions Bot closed this Sep 21, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants