Skip to content

feat: add async LLM completion support across the SDK - #3284

Merged
malhotra5 merged 22 commits into
mainfrom
feat/async-llm-completions
May 20, 2026
Merged

malhotra5 merged 22 commits into
mainfrom
feat/async-llm-completions

Conversation

@malhotra5

@malhotra5 malhotra5 commented May 17, 2026 •

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

Why

The agent server currently wraps synchronous conversation.run() via ThreadPoolExecutor/run_in_executor, which ties up a thread-pool worker for the entire duration of each LLM call. Since litellm provides native async APIs (acompletion, aresponses), we can free the event loop during LLM I/O by propagating async support through the entire call chain.

Summary

  • Add async equivalents (acompletion, aresponses, _atransport_call) to the LLM class using litellm's native async APIs
  • Propagate async support through the full call chain: retry mixin → condenser → agent step → conversation loop → agent server
  • All base classes provide sync-delegating defaults so custom subclasses work without changes
  • Agent server EventService.run() now prefers conversation.arun() when available, falling back to thread-pool execution for backward compatibility

Architecture (8 layers)

EventService.run() → conversation.arun() → agent.astep() → amake_llm_completion()
    → LLM.acompletion() / LLM.aresponses() → _atransport_call()
    → litellm.acompletion / litellm.aresponses (native async HTTP)

Files changed (14 files, +1099 lines)

Layer Key Changes
Transport AsyncTokenCallbackType, AnyTokenCallbackType (sync/async union), _invoke_token_callback()
Retry RetryMixin.async_retry() → tenacity.AsyncRetrying; shared _build_before_sleep()
LLM acompletion(), aresponses(), _atransport_call(), _ahandle_error()
Condenser acondense() on all condenser classes; LLMSummarizingCondenser async overrides
Agent AgentBase.astep() + Agent.astep(), aprepare_llm_messages(), amake_llm_completion()
Conversation BaseConversation.arun() + LocalConversation.arun()
Agent server EventService.run() prefers async path
Title utils agenerate_title_with_llm(), agenerate_title_from_message()

How to Test

All sync paths remain unchanged. Existing tests pass unmodified:

uv run pytest tests/sdk/llm/ -x -q          # 738 passed
uv run pytest tests/sdk/context/condenser/ -x -q  # 60 passed
uv run pytest tests/sdk/agent/ -x -q        # 462 passed
uv run pytest tests/sdk/conversation/ -x -q  # 25 passed

Pre-commit (ruff, pyright, pycodestyle, import rules) all pass on all 14 changed files.

For end-to-end async testing, the agent server integration would need to be run with a real LLM provider to verify the async path is exercised (litellm acompletion calls are coroutines that go through httpx async transport).

Type

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

Notes

  • Token callbacks use AnyTokenCallbackType (union of sync and async) with _invoke_token_callback() for transparent dispatch — existing sync callbacks work in the async path without changes
  • Fallback strategy execution remains sync in the async path (pragmatic choice for a rare codepath)
  • Tool execution stays synchronous inside _handle_tool_calls() since it involves filesystem/process I/O
  • MCP tools are already async (call_tool is async), no changes needed

@malhotra5 can click here to continue refining the PR


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:b5c3ded-python

Run

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

All tags pushed for this build

ghcr.io/openhands/agent-server:b5c3ded-golang-amd64
ghcr.io/openhands/agent-server:b5c3ded0c03bb8274314cd6607d4c2c6df27aa54-golang-amd64
ghcr.io/openhands/agent-server:feat-async-llm-completions-golang-amd64
ghcr.io/openhands/agent-server:b5c3ded-golang_tag_1.21-bookworm-amd64
ghcr.io/openhands/agent-server:b5c3ded-golang-arm64
ghcr.io/openhands/agent-server:b5c3ded0c03bb8274314cd6607d4c2c6df27aa54-golang-arm64
ghcr.io/openhands/agent-server:feat-async-llm-completions-golang-arm64
ghcr.io/openhands/agent-server:b5c3ded-golang_tag_1.21-bookworm-arm64
ghcr.io/openhands/agent-server:b5c3ded-java-amd64
ghcr.io/openhands/agent-server:b5c3ded0c03bb8274314cd6607d4c2c6df27aa54-java-amd64
ghcr.io/openhands/agent-server:feat-async-llm-completions-java-amd64
ghcr.io/openhands/agent-server:b5c3ded-eclipse-temurin_tag_17-jdk-amd64
ghcr.io/openhands/agent-server:b5c3ded-java-arm64
ghcr.io/openhands/agent-server:b5c3ded0c03bb8274314cd6607d4c2c6df27aa54-java-arm64
ghcr.io/openhands/agent-server:feat-async-llm-completions-java-arm64
ghcr.io/openhands/agent-server:b5c3ded-eclipse-temurin_tag_17-jdk-arm64
ghcr.io/openhands/agent-server:b5c3ded-python-amd64
ghcr.io/openhands/agent-server:b5c3ded0c03bb8274314cd6607d4c2c6df27aa54-python-amd64
ghcr.io/openhands/agent-server:feat-async-llm-completions-python-amd64
ghcr.io/openhands/agent-server:b5c3ded-nikolaik_s_python-nodejs_tag_python3.13-nodejs22-slim-amd64
ghcr.io/openhands/agent-server:b5c3ded-python-arm64
ghcr.io/openhands/agent-server:b5c3ded0c03bb8274314cd6607d4c2c6df27aa54-python-arm64
ghcr.io/openhands/agent-server:feat-async-llm-completions-python-arm64
ghcr.io/openhands/agent-server:b5c3ded-nikolaik_s_python-nodejs_tag_python3.13-nodejs22-slim-arm64
ghcr.io/openhands/agent-server:b5c3ded-golang
ghcr.io/openhands/agent-server:b5c3ded0c03bb8274314cd6607d4c2c6df27aa54-golang
ghcr.io/openhands/agent-server:feat-async-llm-completions-golang
ghcr.io/openhands/agent-server:b5c3ded-golang_tag_1.21-bookworm
ghcr.io/openhands/agent-server:b5c3ded-java
ghcr.io/openhands/agent-server:b5c3ded0c03bb8274314cd6607d4c2c6df27aa54-java
ghcr.io/openhands/agent-server:feat-async-llm-completions-java
ghcr.io/openhands/agent-server:b5c3ded-eclipse-temurin_tag_17-jdk
ghcr.io/openhands/agent-server:b5c3ded-python
ghcr.io/openhands/agent-server:b5c3ded0c03bb8274314cd6607d4c2c6df27aa54-python
ghcr.io/openhands/agent-server:feat-async-llm-completions-python
ghcr.io/openhands/agent-server:b5c3ded-nikolaik_s_python-nodejs_tag_python3.13-nodejs22-slim

About Multi-Architecture Support

  • Each variant tag (e.g., b5c3ded-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., b5c3ded-python-amd64) are also available if needed

Add async equivalents for all components in the LLM completion call chain,
from transport to conversation loop, allowing the event loop to remain free
during LLM I/O instead of tying up ThreadPoolExecutor workers.

Layer 1 - Transport:
  - LLM._atransport_call() using litellm.acompletion
  - AsyncTokenCallbackType and AnyTokenCallbackType for sync/async compat
  - _invoke_token_callback() helper for transparent sync/async dispatch

Layer 2 - Public LLM methods:
  - LLM.acompletion() - async Chat Completion API
  - LLM.aresponses() - async Responses API (uses litellm.aresponses)
  - LLM._ahandle_error() - async error handling with fallback

Layer 3 - Retry:
  - RetryMixin.async_retry() returning tenacity.AsyncRetrying
  - Refactored _build_before_sleep() shared by sync/async decorators

Layer 4 - Condenser:
  - CondenserBase.acondense() with sync delegation default
  - RollingCondenser.acondense/aget_condensation/ahard_context_reset
  - LLMSummarizingCondenser async overrides using LLM.acompletion()
  - PipelineCondenser.acondense() chaining async condensers

Layer 5 - Agent:
  - AgentBase.astep() with sync delegation default
  - Agent.astep() using aprepare_llm_messages + amake_llm_completion
  - aprepare_llm_messages() and amake_llm_completion() in agent/utils.py

Layer 6 - Conversation:
  - BaseConversation.arun() with sync delegation default
  - LocalConversation.arun() with full async agent step loop

Layer 7 - Agent server:
  - EventService.run() now prefers conversation.arun() when available,
    falling back to thread-pool execution for backward compatibility

Layer 8 - Title generation:
  - agenerate_title_with_llm() and agenerate_title_from_message()

All sync paths remain unchanged. Existing tests pass unmodified.

Co-authored-by: openhands <openhands@all-hands.dev>
Co-authored-by: openhands <openhands@all-hands.dev>
@github-actions

github-actions Bot commented May 17, 2026 •

Copy link
Copy Markdown
Contributor

Python API breakage checks — ✅ PASSED

Result: ✅ PASSED

Behavioral default changes detected

These public Field(default=...) changes were auto-marked with the release-note-required label:

  • openhands.sdk.llm.llm.LLM.model: 'claude-sonnet-4-20250514' → 'gpt-5.5'

Action log

@github-actions

github-actions Bot commented May 17, 2026 •

Copy link
Copy Markdown
Contributor

REST API breakage checks (OpenAPI) — ✅ PASSED

Result: ✅ PASSED

Action log

Demonstrates instant cancellation of in-flight LLM calls using
asyncio task cancellation with conversation.arun(). Shows streaming
tokens arriving and then being interrupted mid-generation, with a
Ctrl-C signal handler and auto-cancel timer.

Co-authored-by: openhands <openhands@all-hands.dev>
Add interrupt() API that cancels in-flight arun() LLM calls immediately,
unlike pause() which waits for the current LLM request to finish.

Layers:
- InterruptEvent: new event emitted when an interrupt takes effect
- BaseConversation.interrupt(): default falls back to pause()
- LocalConversation.interrupt(): cancels _arun_task via asyncio
- LocalConversation.arun(): tracks task, catches CancelledError → PAUSED
- EventService.interrupt(): delegates to conversation, publishes state
- ConversationService.interrupt_conversation(): service-layer method
- POST /{conversation_id}/interrupt: REST endpoint for remote interrupt

Design rationale: interrupt lives at conversation level only because
LLM and Agent are frozen/stateless Pydantic models that may be shared
across conversations. asyncio.CancelledError naturally propagates
through all layers without needing per-layer interrupt APIs.

Co-authored-by: openhands <openhands@all-hands.dev>
Co-authored-by: openhands <openhands@all-hands.dev>
- EventService._run_and_publish now checks asyncio.iscoroutinefunction(arun)
  instead of just truthiness, preventing MagicMock from triggering the async
  path in tests
- Add TestLLM.acompletion() that delegates to completion(), ensuring scripted
  test responses work in the async code path

Co-authored-by: openhands <openhands@all-hands.dev>
@github-actions

github-actions Bot commented May 17, 2026 •

Copy link
Copy Markdown
Contributor

Coverage

Coverage Report •
FileStmtsMissCoverMissing
openhands-agent-server/openhands/agent_server
   conversation_router.py1531192%206, 306, 397–400, 412–415, 449
   conversation_service.py59811580%144–145, 154, 180–181, 185–186, 191, 303–304, 335, 338, 345–351, 378, 384, 480, 486, 491, 497, 505–506, 515–518, 527, 539, 547, 570–571, 610, 639–643, 645–646, 649–650, 660, 672–677, 775, 782–786, 789–790, 794–798, 801–802, 806–810, 813–814, 836–837, 841–842, 844–846, 848, 851, 859–863, 866, 873–878, 880–881, 895, 905, 909, 911–912, 917–918, 924–925, 933, 948–949, 979, 994, 1022, 1316, 1319
   event_service.py46010277%84–85, 115, 118–119, 123–124, 131, 135, 141, 151–155, 158–161, 220, 241–242, 313, 364, 374, 398–399, 403, 411, 414, 462, 464, 468–470, 474, 483–484, 486, 490, 496, 498, 528–533, 559, 562, 613, 617, 788, 790–791, 795, 809–811, 813, 834, 839–842, 846–849, 857–860, 866–869, 915–916, 918–925, 927–928, 937–938, 940–941, 948–949, 951–952, 972, 978, 984, 993–994
openhands-sdk/openhands/sdk/agent
   agent.py3634487%101, 215, 340, 344, 612–613, 620–621, 703, 707–708, 713–717, 727–728, 745–746, 753–754, 762, 766, 772–774, 781, 785, 789, 792–793, 795–796, 810–811, 1098–1099, 1101, 1129, 1137–1138, 1172, 1179
   base.py3013787%60, 64, 73, 76, 79, 84, 234, 265, 291, 295, 299–300, 321, 417, 485–487, 536–538, 565, 575, 583–584, 626, 628–629, 701–703, 705–707, 743–744, 754–755
   parallel_executor.py791383%126, 139, 141–143, 147, 177, 181–185, 190
   response_dispatch.py80791%197, 247, 271, 275, 332–334
   utils.py1951791%116, 136–137, 234, 236, 238, 244, 254, 344, 591, 593–597, 602, 615
openhands-sdk/openhands/sdk/context/condenser
   base.py692366%58, 72, 186–187, 205–208, 210–211, 213–214, 216–218, 221–224, 226, 228, 237, 248
   llm_summarizing_condenser.py1585068%275–276, 278–280, 285, 288–289, 292–293, 298, 303, 305–306, 319–320, 353, 355, 360, 366–367, 369–373, 375, 386–387, 390–391, 395–396, 403–404, 409, 420–421, 423–425, 430–434, 437, 441, 443–444
   pipeline_condenser.py231343%46–51, 57–62, 65
openhands-sdk/openhands/sdk/conversation
   base.py95297%195, 249
   title_utils.py812569%35, 75, 216–217, 219, 221, 225–226, 262, 264, 267–270, 272–273, 275–277, 284, 286–289, 291
openhands-sdk/openhands/sdk/conversation/impl
   local_conversation.py5304491%307, 312, 456, 502, 539, 555, 620, 840–841, 844, 957, 968–971, 978–979, 982, 988–989, 992, 998, 1013, 1016, 1020–1021, 1025–1027, 1034, 1120, 1125, 1235, 1237, 1241–1242, 1253–1254, 1279, 1474, 1478, 1548, 1555–1556
openhands-sdk/openhands/sdk/event
   user_action.py21576%21, 36–38, 41
openhands-sdk/openhands/sdk/llm
   llm.py71320371%491, 515, 548, 735, 737–741, 749–754, 855, 949–951, 969, 985, 992–993, 1013–1016, 1022–1024, 1028–1032, 1038, 1041, 1044–1045, 1090, 1092–1093, 1123, 1169, 1180–1182, 1186, 1192–1195, 1197–1204, 1212–1214, 1224–1226, 1229–1230, 1234, 1237–1238, 1240–1241, 1243, 1299–1303, 1305, 1307, 1318, 1322–1323, 1326–1327, 1337–1338, 1346–1353, 1356, 1358, 1371–1373, 1378–1382, 1387–1393, 1397–1402, 1410–1412, 1423–1425, 1429–1430, 1435–1437, 1439–1440, 1442, 1446–1450, 1456, 1459–1461, 1609, 1622–1628, 1630, 1633, 1744–1745, 1977–1978, 1987, 1993, 1998, 2038, 2040–2045, 2047–2064, 2067–2071, 2073–2074, 2080–2089, 2146, 2148
   streaming.py12375%27–29
openhands-sdk/openhands/sdk/llm/utils
   retry_mixin.py581181%45, 48, 62, 132, 136, 140–141, 151, 156–157, 162
openhands-sdk/openhands/sdk/testing
   test_llm.py67789%182, 192, 225, 227–228, 255, 330
openhands-sdk/openhands/sdk/tool
   tool.py1881094%177, 277, 379, 385, 405–406, 574, 642–644
openhands-tools/openhands/tools/terminal
   impl.py23910157%110, 117–118, 146–150, 153–155, 157–161, 168, 187–188, 193–194, 223–226, 228, 246–255, 257, 262, 268–269, 292, 295, 298, 302, 320, 323, 331–332, 341, 374–375, 377, 385, 389–392, 394–395, 402, 404, 408, 432–433, 435–437, 442–443, 445–446, 448, 457, 459–460, 462, 482–485, 490–491, 513, 523–526, 530–531, 539, 544, 553–560, 568–569
TOTAL28651690675% 

Cross-tests monkeypatch LLM.completion but now the async path calls
acompletion instead. Add matching acompletion patches that delegate to
the existing fake_completion functions.

Co-authored-by: openhands <openhands@all-hands.dev>
@malhotra5
malhotra5 marked this pull request as ready for review May 17, 2026 16:31

@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

Async LLM completion functionality works end-to-end. The PR successfully enables non-blocking LLM I/O throughout the SDK while maintaining full backward compatibility.

Does this PR achieve its stated goal?

Yes. The PR set out to "enable async LLM completions throughout the SDK to avoid blocking the event loop during LLM I/O" and it delivers on this goal. I verified that:

  1. The async path (arun() → astep() → acompletion()) is used when calling conversation's async methods
  2. The sync path (run() → step() → completion()) still works unchanged for backward compatibility
  3. The new interrupt() method cancels in-flight async LLM calls instantly (0.00s vs waiting for completion)
  4. Async propagates correctly through the full call chain: LLM transport → retry logic → condenser → agent → conversation → agent server

The EventService now detects and prefers conversation.arun() when available, freeing the event loop during LLM I/O instead of tying up thread-pool workers.

Phase Result
Environment Setup ✅ Dependencies installed, project builds successfully
CI Status ⚠️ 1 check-examples failure (timing issue, not functional), all other checks pass
Functional Verification ✅ All async features work as described
Functional Verification

Test 1: Async path is used during arun()

Baseline: Created a SlowAsyncLLM that tracks whether sync or async completion methods are called.

Ran: conversation.arun() with the instrumented LLM

# Test output:
Status: ConversationExecutionStatus.FINISHED
Elapsed time: 0.51s
Async called: True
Sync called: False
✅ PASS: Async path is used correctly

Result: Confirms arun() uses LLM.acompletion() instead of the sync completion() method.


Test 2: Interrupt cancels in-flight LLM call instantly

Setup: Started arun() with a 10-second LLM sleep, called interrupt() after 0.1s.

Ran: conversation.interrupt() while LLM was yielding during async sleep

# Test output:
[163.34] Calling interrupt()
Status: ConversationExecutionStatus.PAUSED
Time from interrupt to completion: 0.00s
InterruptEvents found: 1
✅ PASS: Interrupt cancels in-flight async call

Result: The async task was cancelled instantly (0.00s), conversation transitioned to PAUSED, and an InterruptEvent was emitted. This is a major improvement over pause() which must wait for the current LLM request to complete.


Test 3: Backward compatibility with sync run()

Ran: conversation.run() (sync version) with the same instrumented LLM

# Test output:
Status: ConversationExecutionStatus.FINISHED
Elapsed time: 0.50s
Sync called: True
✅ PASS: Sync path still works for backward compatibility

Result: The sync run() method still uses LLM.completion(), confirming existing code continues to work unchanged.


Test 4: Full async chain (LLM → retry → condenser → agent → conversation)

Setup: Created an instrumented LLM with condenser to verify async propagates through all layers.

Ran: conversation.arun() and tracked which LLM methods were called

# Test output:
Async calls: 1 - ['acompletion']
Sync calls: 0 - []
Status: ConversationExecutionStatus.FINISHED
✅ PASS: Full async chain works correctly

Result: The async path flows correctly through the entire stack without falling back to sync methods.


Test 5: New interrupt tests pass

Ran: pytest tests/sdk/conversation/test_interrupt.py -xvs

============================= 4 passed, 5 warnings in 0.16s =========================
test_interrupt_cancels_arun_immediately PASSED
test_interrupt_without_arun_falls_back_to_pause PASSED
test_arun_task_cleared_after_interrupt PASSED
test_interrupt_is_resumable PASSED

Result: All new unit tests for the interrupt functionality pass.


Test 6: EventService async integration

Verified: LocalConversation.arun() exists and is a coroutine function

# Test output:
hasattr(conv, 'arun'): True
asyncio.iscoroutinefunction(arun): True
✅ PASS: LocalConversation.arun() is properly defined as a coroutine

Result: The EventService's check if arun is not None and asyncio.iscoroutinefunction(arun) will correctly detect and use the async path.


Test 7: New example syntax validation

Ran: python -m py_compile examples/01_standalone_sdk/50_async_cancellation.py

✅ Example syntax is valid

Result: The new async cancellation example is syntactically correct and can be imported.

CI Status Note

The check-examples CI check failed with:

##[error]A branch or tag with the name 'feat/async-llm-completions' could not be found

This is a timing issue where the CI workflow couldn't find the branch, not a functional problem with the code. All other CI checks pass:

  • ✅ sdk-tests (2m8s)
  • ✅ cross-tests (1m30s)
  • ✅ agent-server-tests (50s)
  • ✅ pre-commit (1m9s)
  • ✅ coverage-report (1m12s)
  • ✅ All build/binary tests pass

Issues Found

None.

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

Comprehensive review of async LLM completion support. Found several critical issues that must be addressed before merging, primarily around callback parameter propagation, thread safety, and test coverage. See inline comments for details.

Critical Issues: 6
Major Issues: 6
Improvements: Multiple minor inconsistencies

Comment thread openhands-sdk/openhands/sdk/llm/llm.py Resolved
Comment thread openhands-sdk/openhands/sdk/llm/llm.py Resolved
Comment thread openhands-sdk/openhands/sdk/llm/llm.py Resolved
Comment thread openhands-sdk/openhands/sdk/llm/llm.py Resolved
Comment thread openhands-sdk/openhands/sdk/llm/llm.py Resolved
@all-hands-bot

Copy link
Copy Markdown
Collaborator

Async LLM Completion - Detailed Review Summary

Taste Rating: 🟡 Acceptable - Core architecture is sound, but several critical issues must be fixed before merging.


Architecture Assessment

The async implementation follows a clean architectural pattern:

  • ✅ 8-layer propagation through the full stack (EventService → LocalConversation → Agent → LLM → litellm)
  • ✅ Backward compatibility preserved via sync-delegating base class defaults
  • ✅ Consistent pattern across all layers (async methods with sync fallbacks)
  • ⚠️ Mixed blocking/non-blocking - Tool execution, fallback strategy, and critic evaluation remain synchronous (acceptable per scope, but should be documented)

Critical Issues Summary

Must Fix Before Merge:

  1. Callback propagation bugs (2 instances in LLM layer)

    • Missing on_token in fallback callbacks breaks streaming
    • Lines: llm.py:1038, llm.py:1452
  2. Thread safety violations (2 instances in conversation layer)

    • State modifications without lock in exception handlers
    • Lines: local_conversation.py:1009, local_conversation.py:1014
    • Violates documented concurrency contract
  3. Asyncio contract violation

    • CancelledError not re-raised breaks asyncio semantics
    • Line: local_conversation.py:1007
    • Intentional design choice needs careful consideration
  4. Race condition in agent server

    • Task cleanup race allows concurrent runs
    • Line: event_service.py:814
  5. Test coverage gaps

    • No verification that async path is actually used
    • Missing edge case coverage (rapid interrupts, error handling, etc.)
    • File: tests/sdk/conversation/test_interrupt.py

Major Concerns

  1. Event loop blocking - Sync fallback and threading.RLock in async paths
  2. Test infrastructure - TestLLM.acompletion() drops callbacks
  3. Code duplication - ~350 lines of near-duplicate sync/async code

Architectural Concerns

Good Design Choices:

  • Interrupt mechanism via task cancellation is elegant
  • Base class delegation pattern maintains compatibility
  • Telemetry and retry logic properly shared between sync/async

Questionable Choices:

  • CancelledError suppression is non-standard (needs strong justification or redesign)
  • Mixing threading.RLock with async code (even in short critical sections)
  • Sync fallback strategy blocking the event loop (documented but problematic)

[RISK ASSESSMENT]

  • Overall PR: ⚠️ Risk Assessment: 🟡 MEDIUM

Risk Factors:

  • ✅ Core async/await usage is correct throughout
  • ✅ No breaking changes to public APIs
  • ✅ Backward compatibility maintained
  • ⚠️ Thread safety violations in error paths
  • ⚠️ Non-standard asyncio exception handling
  • ⚠️ Test coverage gaps could hide async path failures
  • ⚠️ Race condition in server task cleanup

Risk Mitigation:
The implementation is largely correct in the happy path, but error handling and edge cases need work. The critical issues are straightforward to fix, but the CancelledError design choice needs architectural review.


VERDICT

❌ Needs rework: Critical issues must be addressed before merging

Required Actions:

  1. Fix callback parameter propagation in LLM fallbacks
  2. Add state locks around exception handler state modifications
  3. Resolve CancelledError handling (re-raise or document extensively)
  4. Fix race condition in event_service interrupt()
  5. Add test coverage for async path verification
  6. Fix TestLLM and CountingLLM implementations

Optional Improvements:

  1. Document blocking limitations (fallback, RLock, tools, critic)
  2. Consider extracting shared logic to reduce duplication
  3. Add more edge case tests
  4. Align error messages between sync/async paths

KEY INSIGHT

The async implementation demonstrates good architectural layering and maintains backward compatibility, but fails to account for concurrency edge cases that only manifest in error paths. The thread safety violations and non-standard CancelledError handling suggest the async implementation was primarily tested on the happy path. These are fixable issues, but they reveal a pattern of incomplete async thinking that should be addressed systematically.

Recommendation: Fix the critical issues, add comprehensive async path verification tests, and have an experienced asyncio developer review the CancelledError handling design choice before merging.


Testing Recommendations

Add these test scenarios to verify the async implementation is truly exercised:

# 1. Verify async path is used
async def test_arun_uses_acompletion():
    """Verify async LLM methods are called, not sync fallback"""
    call_log = []
    
    class SpyLLM(LLM):
        async def acompletion(self, messages, **kw):
            call_log.append("acompletion")
            return _make_response()
        
        def completion(self, messages, **kw):
            call_log.append("completion") 
            return _make_response()
    
    conv = _make_conversation(SpyLLM(...))
    await conv.arun()
    
    assert "acompletion" in call_log
    assert "completion" not in call_log

# 2. Verify CancelledError handling
async def test_cancelled_error_not_reraised():
    """Verify arun() returns cleanly on cancellation"""
    conv = _make_conversation(SlowLLM(sleep_seconds=60))
    task = asyncio.create_task(conv.arun())
    await asyncio.sleep(0.1)
    task.cancel()
    
    # Should not raise CancelledError
    await task
    
    # Should be in PAUSED state
    assert conv.state.execution_status == ConversationExecutionStatus.PAUSED

# 3. Verify exception propagation in async path
async def test_acompletion_exception_handling():
    """Verify exceptions from async LLM propagate correctly"""
    class FailingLLM(LLM):
        async def acompletion(self, messages, **kw):
            raise ValueError("Test error")
    
    conv = _make_conversation(FailingLLM(...))
    await conv.arun()
    
    assert conv.state.execution_status == ConversationExecutionStatus.ERROR
    assert any(isinstance(e, ConversationErrorEvent) for e in conv.state.events)

Improve this review? If any feedback above seems incorrect or irrelevant to this repository, you can teach the reviewer to do better:

  1. Add a .agents/skills/custom-codereview-guide.md file to your branch (or edit it if one already exists) with the /codereview trigger and the context the reviewer is missing. See the customization docs for the required frontmatter format.
  2. Re-request a review - the reviewer reads guidelines from the PR branch, so your changes take effect immediately.
  3. When your PR is merged, the guideline file goes through normal code review by repository maintainers.

Resolve with AI? Install the iterate skill in your agent and run /iterate to automatically drive this PR through CI, review, and QA until it's merge-ready.

Add ToolDefinition.acall() — async tool interface that defaults to
run_in_executor(self.__call__) so blocking tool I/O does not starve the
event loop. Tools with native async implementations can override acall.

Add ParallelToolExecutor.aexecute_batch() — dispatches each tool call
to a thread via run_in_executor and schedules them concurrently with
asyncio.gather + Semaphore for concurrency control.

Add _ActionBatch.aprepare(), Agent._aexecute_actions(), and
ResponseDispatchMixin._ahandle_tool_calls() as async variants of the
sync tool dispatch chain.

Update Agent.astep() to use the full async pipeline: async LLM
completion via acompletion, then async tool dispatch via aexecute_batch.
Each tool call is an individual await point, so the event loop stays
responsive and interrupt() cancellation can land between tool calls.

Update BaseAgent.astep() to wrap sync step() in run_in_executor so
subclasses that don't override astep also avoid blocking the loop.

Co-authored-by: openhands <openhands@all-hands.dev>
- Fix missing on_token in acompletion/aresponses fallback callbacks
  (Critical: streaming callbacks now forwarded to fallback LLMs)

- Run sync fallback in run_in_executor in _ahandle_error so blocking
  fallback LLM calls don't starve the event loop

- Wrap CancelledError/Exception handlers in local_conversation.arun()
  with state lock (with self._state:) for thread-safety

- Document CancelledError non-re-raise as intentional design choice
  (interrupt() expects clean return, not propagation)

- Fix race condition in EventService.interrupt() — only clear
  _run_task if the task actually finished after wait_for

- Fix TestLLM.acompletion on_token passthrough (document type mismatch)

- Add completion() method to CountingLLM for sync path compatibility

- Add 4 new tests: async path verification (acompletion actually
  called), CancelledError not propagated, interrupt after natural
  completion, multiple rapid interrupts

- Add explanatory comments to async path matching sync counterparts

Co-authored-by: openhands <openhands@all-hands.dev>
@malhotra5
malhotra5 requested a review from all-hands-bot May 17, 2026 17:36

@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

Async LLM completion support works end-to-end with full backward compatibility maintained.

Does this PR achieve its stated goal?

Yes. The PR successfully adds async LLM completion support throughout the SDK, enabling non-blocking LLM I/O that frees the event loop. Verified end-to-end: arun() → agent.astep() → amake_llm_completion() → llm.acompletion() → litellm.acompletion() (native async HTTP). All existing sync paths continue to work unmodified (360 conversation tests + 738 LLM tests passed). The agent server correctly prefers the async path when available while falling back to thread-pool execution for backward compatibility.

Phase Result
Environment Setup ✅ make build succeeded, all dependencies installed
CI Status ✅ Core tests passing (SDK, tools, workspace, agent-server); 2 admin checks failing (unresolved threads, optional docs)
Functional Verification ✅ Async path verified via tests, backward compatibility confirmed
Functional Verification

Test 1: Async Path Is Exercised

Verification approach: Run the interrupt test suite which explicitly verifies async path usage.

Step 1 — Baseline understanding:
Before this PR, the agent server wrapped conversation.run() via ThreadPoolExecutor, blocking thread-pool workers during LLM I/O.

Step 2 — Run async verification tests:

uv run pytest tests/sdk/conversation/test_interrupt.py -v

Result:

tests/sdk/conversation/test_interrupt.py::test_interrupt_cancels_arun_immediately PASSED
tests/sdk/conversation/test_interrupt.py::test_interrupt_without_arun_falls_back_to_pause PASSED
tests/sdk/conversation/test_interrupt.py::test_arun_task_cleared_after_interrupt PASSED
tests/sdk/conversation/test_interrupt.py::test_interrupt_is_resumable PASSED
tests/sdk/conversation/test_interrupt.py::test_arun_calls_acompletion_not_completion PASSED
tests/sdk/conversation/test_interrupt.py::test_arun_does_not_raise_cancelled_error PASSED
tests/sdk/conversation/test_interrupt.py::test_interrupt_after_natural_completion_is_noop PASSED
tests/sdk/conversation/test_interrupt.py::test_multiple_rapid_interrupts PASSED

8 passed in 0.54s

Interpretation: All tests pass. The test test_arun_calls_acompletion_not_completion explicitly verifies that arun() calls the async acompletion() method and NOT the sync completion() method. This confirms the async path is properly wired up and exercised.

Test 2: Backward Compatibility

Step 1 — Run existing sync tests:

uv run pytest tests/sdk/conversation/ -k "not remote" -v

Result:

360 passed, 133 deselected, 28 warnings in 81.07s

Interpretation: All 360 local conversation tests pass without modification. This confirms the sync path is unchanged and backward compatibility is maintained.

Test 3: LLM Async Methods

Step 1 — Run LLM test suite:

uv run pytest tests/sdk/llm/ -v

Result:

738 passed, 11 warnings in 36.30s

Interpretation: All 738 LLM tests pass, confirming both sync and async LLM methods work correctly.

Test 4: Agent Server Integration

Step 1 — Inspect EventService.run() implementation:

Code at openhands-agent-server/openhands/agent_server/event_service.py:744-746:

arun = getattr(conversation, "arun", None)
if arun is not None and asyncio.iscoroutinefunction(arun):
    await conversation.arun()  # Async path
else:
    await loop.run_in_executor(self._run_executor, conversation.run)  # Fallback

Interpretation: The agent server correctly checks for arun() and uses it when available, falling back to thread-pool execution for conversations without async support. This provides the claimed benefit (non-blocking LLM I/O) while maintaining backward compatibility.

Test 5: New Async Methods Exist

Verification: Checked that all claimed async methods exist and are coroutine functions.

Result:

✅ LLM.acompletion exists and is async
✅ LLM.aresponses exists and is async
✅ LLM._atransport_call exists and is async
✅ Agent.astep exists and is async
✅ LocalConversation.arun exists and is async

Interpretation: All async methods are properly implemented as coroutine functions.

Issues Found

None.

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

Code Review: Async LLM Completion Support

Taste Rating: 🟡 Acceptable architecture, critical bugs in execution

Architecture Assessment

The async propagation architecture is well-designed:

  • ✅ Clean separation between sync/async paths
  • ✅ Proper fallback delegation for backward compatibility
  • ✅ Thoughtful handling of CancelledError (intentionally not re-raised)
  • ⚠️ Code duplication between sync/async justified by auditability but adds maintenance burden

[CRITICAL ISSUES]

These must be fixed before merge:

  1. Callback dispatch bug (openhands-sdk/openhands/sdk/llm/streaming.py:25) - asyncio.iscoroutinefunction() doesn't detect callable objects whose __call__ returns a coroutine, leading to unawaited coroutines. Need to add inspect.iscoroutine() check.

  2. Async-to-sync callback casts (openhands-sdk/openhands/sdk/llm/llm.py:1044, 1460) - Casting async callbacks to sync type masks errors in fallback paths. Should pass None for async callbacks instead of casting.

  3. Missing cancellation safety (openhands-sdk/openhands/sdk/llm/llm.py streaming loops) - Async streaming loops lack try/finally for cleanup on interrupt, causing resource leaks.

  4. State mutation without lock (openhands-sdk/openhands/sdk/conversation/impl/local_conversation.py:880) - Exception handler in run() modifies state without acquiring lock, creating race with concurrent access.

  5. Race condition in task cleanup (openhands-agent-server/openhands/agent_server/event_service.py:763) - _run_task = None executes in finally without holding _run_lock, racing with concurrent run() and interrupt() calls.

  6. TestLLM blocks event loop (openhands-sdk/openhands/sdk/testing/test_llm.py:221) - acompletion() calls sync completion() directly, defeating async testing. Must use run_in_executor().

[IMPROVEMENT OPPORTUNITIES]

  1. Thread safety (event_service.py:811-820) - Task reference checks and cleanup need lock protection
  2. Timeout mismatch (event_service.py:813) - 5s timeout insufficient for task that needs 30s cleanup
  3. TOCTOU race (local_conversation.py:1082) - Status check before lock acquisition creates race window
  4. Blocking critic calls (agent.py:798, 802) - Critic evaluation uses sync httpx.Client.post() that blocks event loop during async execution
  5. Test coverage gaps - Cross-tests in tests/cross/ don't verify async path is exercised vs sync fallback

[RISK ASSESSMENT]

⚠️ Risk Level: 🔴 HIGH

Key Risk Factors:

  • Multiple thread-safety violations in concurrent code paths
  • Callback handling bugs that could cause subtle runtime failures
  • Resource leaks on cancellation due to missing cleanup
  • Test infrastructure doesn't properly verify async behavior

Recommendation: Do not merge until critical thread safety and callback handling issues are resolved. Request review from a human architect to validate the async/sync fallback strategy and concurrency model.

VERDICT

❌ Needs rework: Critical thread safety and callback handling bugs must be addressed

KEY INSIGHT

The async architecture is sound, but the execution has critical concurrency bugs. The dual sync/async paths create complexity that requires rigorous lock discipline and careful callback type handling. Several places where sync and async code interact (fallbacks, critic evaluation, test infrastructure) have bugs that will cause runtime failures.


Improve this review? If any feedback above seems incorrect or irrelevant to this repository, you can teach the reviewer to do better:

  1. Add a .agents/skills/custom-codereview-guide.md file to your branch (or edit it if one already exists) with the /codereview trigger and the context the reviewer is missing. See the customization docs for the required frontmatter format.
  2. Re-request a review - the reviewer reads guidelines from the PR branch, so your changes take effect immediately.
  3. When your PR is merged, the guideline file goes through normal code review by repository maintainers.

Resolve with AI? Install the iterate skill in your agent and run /iterate to automatically drive this PR through CI, review, and QA until it's merge-ready.


This review was created by an AI agent (OpenHands) on behalf of the code review automation.

Add CancellationToken (thread-safe flag) that propagates interrupt()
signals to in-flight tool executions running in thread-pool workers.

- New CancellationToken class using threading.Event
- LocalConversation creates/clears token per run()/arun()
- interrupt() sets token before cancelling asyncio task
- ParallelToolExecutor skips pending tools when token is set
- Orphaned ActionEvents get synthetic AgentErrorEvent so LLM
  history stays consistent (no tool-call without tool-result)

Co-authored-by: openhands <openhands@all-hands.dev>
- Fix callback dispatch in _invoke_token_callback: use
  asyncio.iscoroutine(result) instead of iscoroutinefunction(cb)
  to correctly handle callable objects with async __call__
- Add state lock (with self._state:) around sync run() exception
  handler for thread-safety consistency with async handler
- Wrap TestLLM.acompletion() in run_in_executor to avoid blocking
  the event loop (even though deque.popleft is effectively instant)

Co-authored-by: openhands <openhands@all-hands.dev>

Copy link
Copy Markdown
Member Author

Addressing code review feedback (pullrequestreview-4306019785)

Fixed in commits 38e50605 and 429e3e74:

Critical Issues — Status

  1. Callback dispatch bug (streaming.py:25) — ✅ Fixed in 429e3e74. Changed from asyncio.iscoroutinefunction(cb) to calling cb(chunk) then checking asyncio.iscoroutine(result). This correctly handles both plain coroutine functions and callable objects whose __call__ is async.

  2. Async-to-sync callback casts (llm.py:1044, 1460) — ✅ Already fixed in a5f254d0. on_token is forwarded to fallback callbacks. The cast is needed because AnyTokenCallbackType (sync|async union) is not assignable to the sync-only signature.

  3. Missing cancellation safety (streaming loops) — ✅ Not an issue. Python's async iteration protocol (PEP 525) automatically calls aclose() on the async iterator when CancelledError propagates through async for. The streams (CustomStreamWrapper, ResponsesAPIStreamingIterator) are properly cleaned up by the language runtime.

  4. State mutation without lock (local_conversation.py:880) — ✅ Fixed in 429e3e74. The sync run() exception handler now wraps state mutations in with self._state:, matching the async handler.

  5. Race condition in task cleanup (event_service.py:763) — ✅ Already fixed in a5f254d0. _run_task is only cleared if task.done() is True after wait_for.

  6. TestLLM blocks event loop (test_llm.py:221) — ✅ Fixed in 429e3e74. acompletion() now wraps the sync call in run_in_executor(). (The underlying operation is a deque.popleft() which is O(1), but wrapping it is good practice for async correctness.)

Additional work in 38e50605

Added cooperative cancellation for tool calls during interrupt:

  • New CancellationToken class (thread-safe threading.Event flag)
  • interrupt() now cancels the token before cancelling the asyncio task, so thread-pool tool workers see it immediately
  • ParallelToolExecutor skips pending tools when token is set
  • Orphaned ActionEvents get synthetic AgentErrorEvent so LLM history stays consistent
  • 6 new tests covering token lifecycle, executor cancellation, and batch skip

This comment was posted by an AI agent (OpenHands).

openhands-agent and others added 4 commits May 17, 2026 18:23
Replace streaming-based example with a simpler non-streaming design
that gives the user two natural windows to try interrupt():

1. During LLM completion — the model reasons about writing a bash
   countdown script (several seconds of generation)
2. During tool execution — the agent runs the script which sleeps
   for 30 seconds, giving plenty of time to Ctrl-C

Uses a live event callback to show tool calls and results as they
happen, and tracks which phase (llm vs tool) the interrupt landed in.

Co-authored-by: openhands <openhands@all-hands.dev>
When interrupt() fires during a tool call (e.g., terminal running
'sleep 30'), the asyncio task is cancelled but the thread-pool worker
keeps running because Python threads cannot be cancelled.  The process
hangs until the command finishes.

Fix: add ToolExecutor.interrupt() (no-op by default) and override it
in TerminalExecutor to send Ctrl+C to active terminal sessions.
ParallelToolExecutor._arun_safe now catches CancelledError and calls
tool.executor.interrupt() so the subprocess exits quickly and the
worker thread returns.

Chain: interrupt() → Task.cancel() → CancelledError in _arun_safe
       → tool.executor.interrupt() → session.interrupt() → Ctrl+C
       → subprocess exits → thread returns → clean process exit

Co-authored-by: openhands <openhands@all-hands.dev>
@github-actions github-actions Bot added the release-note-required PR requires explicit release-note coverage for behavioral or default changes label May 18, 2026
malhotra5 and others added 3 commits May 20, 2026 10:32
close() now calls _run_task.cancel() before awaiting it, so the
native arun() CancelledError handler can transition to PAUSED
promptly instead of blocking for the full LLM latency.

Updated test_close_blocks_until_executor_thread_finishes to verify
fast cancellation semantics and removed the unused TimedSlowTestLLM
helper and PrivateAttr import.

Co-authored-by: openhands <openhands@all-hands.dev>
After cancel(), awaiting the task raises CancelledError (a
BaseException, not Exception). Suppress it explicitly so close()
proceeds to teardown normally.

Co-authored-by: openhands <openhands@all-hands.dev>
Add test_interrupt_endpoint_cancels_running_conversation that exercises
the full POST /{conversation_id}/interrupt path end-to-end against a
real FastAPI server with a slow (asyncio.sleep) LLM.

Verifies:
- Conversation reaches RUNNING state
- POST /interrupt returns 200 and cancels the in-flight arun() task
- Conversation transitions to PAUSED
- An InterruptEvent is emitted in the event log

Addresses review feedback requesting direct /interrupt endpoint proof.

Co-authored-by: openhands <openhands@all-hands.dev>

Copy link
Copy Markdown
Member Author

Addressed in b5c3ded — added test_interrupt_endpoint_cancels_running_conversation in tests/cross/test_remote_conversation_live_server.py. This is a live-server e2e test that:

  1. Creates a conversation with a slow LLM (patched acompletion using asyncio.sleep)
  2. Sends a message and starts a run via POST /run
  3. Waits for execution_status == running
  4. Sends POST /{id}/interrupt
  5. Verifies the conversation transitions to paused
  6. Verifies an InterruptEvent appears in the event log via the search endpoint

This directly exercises the new public POST /{conversation_id}/interrupt path end-to-end against a real FastAPI server.

This comment was generated by an AI agent (OpenHands) on behalf of the user.

@tofarr tofarr 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.

I like it - we can refine in future!

@malhotra5 malhotra5 added the integration-test Runs the integration tests and comments the results label May 20, 2026
@github-actions

Copy link
Copy Markdown
Contributor

Hi! I started running the integration tests on your PR. You will receive a comment with the results shortly.

@malhotra5 malhotra5 added the test-examples Run all applicable "examples/" files. Expensive operation. label May 20, 2026
@github-actions

github-actions Bot commented May 20, 2026 •

Copy link
Copy Markdown
Contributor

🔄 Running Examples with openhands/claude-haiku-4-5-20251001

Generated: 2026-05-20 18:29:55 UTC

Example Status Duration Cost
01_standalone_sdk/02_custom_tools.py ✅ PASS 1m 18s $0.13
01_standalone_sdk/03_activate_skill.py ✅ PASS 19.4s $0.03
01_standalone_sdk/05_use_llm_registry.py ✅ PASS 12.0s $0.01
01_standalone_sdk/07_mcp_integration.py ✅ PASS 33.0s $0.03
01_standalone_sdk/09_pause_example.py ✅ PASS 10.9s $0.01
01_standalone_sdk/10_persistence.py ✅ PASS 32.1s $0.02
01_standalone_sdk/11_async.py ✅ PASS 27.4s $0.04
01_standalone_sdk/12_custom_secrets.py ✅ PASS 10.2s $0.00
01_standalone_sdk/13_get_llm_metrics.py ✅ PASS 37.9s $0.03
01_standalone_sdk/14_context_condenser.py ✅ PASS 3m 55s $0.26
01_standalone_sdk/17_image_input.py ✅ PASS 20.2s $0.02
01_standalone_sdk/18_send_message_while_processing.py ✅ PASS 17.1s $0.01
01_standalone_sdk/19_llm_routing.py ✅ PASS 14.8s $0.02
01_standalone_sdk/20_stuck_detector.py ✅ PASS 12.7s $0.02
01_standalone_sdk/21_generate_extraneous_conversation_costs.py ✅ PASS 8.8s $0.00
01_standalone_sdk/22_anthropic_thinking.py ✅ PASS 16.6s $0.01
01_standalone_sdk/23_responses_reasoning.py ✅ PASS 1m 2s $0.01
01_standalone_sdk/24_planning_agent_workflow.py ✅ PASS 2m 47s $0.21
01_standalone_sdk/25_agent_delegation.py ❌ FAIL
Exit code 1
7.9s --
01_standalone_sdk/26_custom_visualizer.py ✅ PASS 20.9s $0.04
01_standalone_sdk/28_ask_agent_example.py ✅ PASS 40.6s $0.03
01_standalone_sdk/29_llm_streaming.py ✅ PASS 27.6s $0.02
01_standalone_sdk/30_tom_agent.py ✅ PASS 9.7s $0.01
01_standalone_sdk/31_iterative_refinement.py ✅ PASS 3m 23s $0.25
01_standalone_sdk/32_configurable_security_policy.py ✅ PASS 18.7s $0.02
01_standalone_sdk/33_hooks/main.py ✅ PASS 34.8s $0.04
01_standalone_sdk/34_critic_example.py ✅ PASS 2m 16s $0.17
01_standalone_sdk/36_event_json_to_openai_messages.py ✅ PASS 11.3s $0.01
01_standalone_sdk/37_llm_profile_store/main.py ✅ PASS 7.3s $0.00
01_standalone_sdk/38_browser_session_recording.py ✅ PASS 32.6s $0.03
01_standalone_sdk/39_llm_fallback.py ✅ PASS 9.8s $0.01
01_standalone_sdk/40_acp_agent_example.py ✅ PASS 28.3s $0.30
01_standalone_sdk/41_task_tool_set.py ✅ PASS 32.2s $0.03
01_standalone_sdk/42_file_based_subagents.py ✅ PASS 48.0s $0.05
01_standalone_sdk/43_mixed_marketplace_skills/main.py ✅ PASS 7.6s $0.00
01_standalone_sdk/44_model_switching_in_convo.py ✅ PASS 8.4s $0.01
01_standalone_sdk/45_parallel_tool_execution.py ✅ PASS 4m 28s $0.37
01_standalone_sdk/46_agent_settings.py ✅ PASS 10.0s $0.00
01_standalone_sdk/47_defense_in_depth_security.py ✅ PASS 3.3s $0.00
01_standalone_sdk/48_conversation_fork.py ✅ PASS 16.9s $0.00
01_standalone_sdk/49_switch_llm_tool.py ✅ PASS 11.3s $0.03
01_standalone_sdk/50_async_cancellation.py ✅ PASS 12.7s $0.01
02_remote_agent_server/01_convo_with_local_agent_server.py ✅ PASS 38.2s $0.02
02_remote_agent_server/02_convo_with_docker_sandboxed_server.py ✅ PASS 1m 11s $0.04
02_remote_agent_server/03_browser_use_with_docker_sandboxed_server.py ✅ PASS 1m 41s $0.07
02_remote_agent_server/04_convo_with_api_sandboxed_server.py ✅ PASS 1m 42s $0.03
02_remote_agent_server/06_custom_tool/main.py ✅ PASS 5m 42s $0.06
02_remote_agent_server/07_convo_with_cloud_workspace.py ✅ PASS 31.7s $0.04
02_remote_agent_server/08_convo_with_apptainer_sandboxed_server.py ✅ PASS 4m 6s $0.02
02_remote_agent_server/09_acp_agent_with_remote_runtime.py ❌ FAIL
Timed out after 600 seconds
10m 0s --
02_remote_agent_server/10_cloud_workspace_share_credentials.py ✅ PASS 39.0s $0.06
02_remote_agent_server/11_conversation_fork.py ✅ PASS 1m 31s $0.00
02_remote_agent_server/12_settings_and_secrets_api.py ✅ PASS 2m 19s $0.02
02_remote_agent_server/13_workspace_get_llm.py ✅ PASS 36.4s $0.02
04_llm_specific_tools/01_gpt5_apply_patch_preset.py ✅ PASS 44.5s $0.05
04_llm_specific_tools/02_gemini_file_tools.py ✅ PASS 42.7s $0.05
05_skills_and_plugins/01_loading_agentskills/main.py ✅ PASS 14.9s $0.02
05_skills_and_plugins/02_loading_plugins/main.py ✅ PASS 16.5s $0.02

❌ Some tests failed

Total: 58 | Passed: 56 | Failed: 2 | Total Cost: $2.82

Failed examples:

  • examples/01_standalone_sdk/25_agent_delegation.py: Exit code 1
  • examples/02_remote_agent_server/09_acp_agent_with_remote_runtime.py: Timed out after 600 seconds

View full workflow run

@xingyaoww xingyaoww added the run-eval-50 Runs evaluation on 50 SWE-bench instances label May 20, 2026
@github-actions

Copy link
Copy Markdown
Contributor

Evaluation Triggered

@github-actions

Copy link
Copy Markdown
Contributor

🧪 Integration Tests Results

Overall Success Rate: 74.3%
Total Cost: $1.00
Models Tested: 4
Timestamp: 2026-05-20 18:20:39 UTC

📁 Detailed Logs & Artifacts

Click the links below to access detailed agent/LLM logs showing the complete reasoning process for each model. On the GitHub Actions page, scroll down to the 'Artifacts' section to download the logs.

📊 Summary

Model Overall Tests Passed Skipped Total Cost Tokens
litellm_proxy_deepseek_deepseek_v4_flash 100.0% 8/8 1 9 $0.00 368,573
litellm_proxy_gemini_3.1_pro_preview 100.0% 9/9 0 9 $0.15 314,339
litellm_proxy_openai_gpt_5.5 100.0% 9/9 0 9 $0.85 288,636
litellm_proxy_moonshot_kimi_k2.6 0.0% 0/9 0 9 $0.00 0

📋 Detailed Results

litellm_proxy_deepseek_deepseek_v4_flash

  • Success Rate: 100.0% (8/8)
  • Total Cost: $0.00
  • Token Usage: prompt: 363,511, completion: 5,062, cache_read: 319,744, reasoning: 1,345
  • Run Suffix: litellm_proxy_deepseek_deepseek_v4_flash_b5c3ded_deepseek_v4_flash_run_N9_20260520_180603
  • Skipped Tests: 1

Skipped Tests:

  • t08_image_file_viewing: This test requires a vision-capable LLM model. Please use a model that supports image input.

litellm_proxy_gemini_3.1_pro_preview

  • Success Rate: 100.0% (9/9)
  • Total Cost: $0.15
  • Token Usage: prompt: 310,110, completion: 4,229, cache_read: 289,465, reasoning: 2,807
  • Run Suffix: litellm_proxy_gemini_3.1_pro_preview_b5c3ded_gemini_3_1_pro_run_N9_20260520_180611

litellm_proxy_openai_gpt_5.5

  • Success Rate: 100.0% (9/9)
  • Total Cost: $0.85
  • Token Usage: prompt: 283,438, completion: 5,198, cache_read: 161,280, reasoning: 1,747
  • Run Suffix: litellm_proxy_openai_gpt_5.5_b5c3ded_gpt_5_5_run_N9_20260520_180612

litellm_proxy_moonshot_kimi_k2.6

  • Success Rate: 0.0% (0/9)
  • Total Cost: $0.00
  • Token Usage: 0
  • Run Suffix: litellm_proxy_moonshot_kimi_k2.6_b5c3ded_kimi_k2_6_run_N9_20260520_180606

Failed Tests:

  • t03_jupyter_write_file: Test execution failed: Conversation run failed for id=dadd97cb-deef-4b51-8b55-d74f426b88e4: litellm.RateLimitError: Error code: 429 - {'error': {'message': "litellm.RateLimitError: RateLimitError: MoonshotException - Your account org-07601fd4e69e4430ac86ba5d415d7c06 is suspended due to insufficient balance, please recharge your account or check your plan and billing detailsNo fallback model group found for original model_group=moonshot/kimi-k2.6. Fallbacks=[{'minimax-m2.5': ['minimax-m2.5-api']}]. Received Model Group=moonshot/kimi-k2.6\nAvailable Model Group Fallbacks=None\nError doing the fallback: litellm.RateLimitError: RateLimitError: MoonshotException - Your account org-07601fd4e69e4430ac86ba5d415d7c06 is suspended due to insufficient balance, please recharge your account or check your plan and billing detailsNo fallback model group found for original model_group=moonshot/kimi-k2.6. Fallbacks=[{'minimax-m2.5': ['minimax-m2.5-api']}] LiteLLM Retried: 3 times, LiteLLM Max Retries: 3", 'type': 'throttling_error', 'param': None, 'code': '429'}} (Cost: $0.00)
  • t08_image_file_viewing: Test execution failed: Conversation run failed for id=1f7421cf-e0a5-4a8e-9681-9822dc5e3f58: litellm.RateLimitError: Error code: 429 - {'error': {'message': "litellm.RateLimitError: RateLimitError: MoonshotException - Your account org-07601fd4e69e4430ac86ba5d415d7c06 is suspended due to insufficient balance, please recharge your account or check your plan and billing detailsNo fallback model group found for original model_group=moonshot/kimi-k2.6. Fallbacks=[{'minimax-m2.5': ['minimax-m2.5-api']}]. Received Model Group=moonshot/kimi-k2.6\nAvailable Model Group Fallbacks=None\nError doing the fallback: litellm.RateLimitError: RateLimitError: MoonshotException - Your account org-07601fd4e69e4430ac86ba5d415d7c06 is suspended due to insufficient balance, please recharge your account or check your plan and billing detailsNo fallback model group found for original model_group=moonshot/kimi-k2.6. Fallbacks=[{'minimax-m2.5': ['minimax-m2.5-api']}] LiteLLM Retried: 3 times, LiteLLM Max Retries: 3", 'type': 'throttling_error', 'param': None, 'code': '429'}} (Cost: $0.00)
  • t01_fix_simple_typo: Test execution failed: Conversation run failed for id=39c043c0-990c-4287-bb16-a829089c64a1: litellm.RateLimitError: Error code: 429 - {'error': {'message': "litellm.RateLimitError: RateLimitError: MoonshotException - Your account org-07601fd4e69e4430ac86ba5d415d7c06 is suspended due to insufficient balance, please recharge your account or check your plan and billing detailsNo fallback model group found for original model_group=moonshot/kimi-k2.6. Fallbacks=[{'minimax-m2.5': ['minimax-m2.5-api']}]. Received Model Group=moonshot/kimi-k2.6\nAvailable Model Group Fallbacks=None\nError doing the fallback: litellm.RateLimitError: RateLimitError: MoonshotException - Your account org-07601fd4e69e4430ac86ba5d415d7c06 is suspended due to insufficient balance, please recharge your account or check your plan and billing detailsNo fallback model group found for original model_group=moonshot/kimi-k2.6. Fallbacks=[{'minimax-m2.5': ['minimax-m2.5-api']}] LiteLLM Retried: 3 times, LiteLLM Max Retries: 3", 'type': 'throttling_error', 'param': None, 'code': '429'}} (Cost: $0.00)
  • t06_github_pr_browsing: Test execution failed: Conversation run failed for id=929492b9-1ab7-43f4-8f6e-31b3fe61e7b5: litellm.RateLimitError: Error code: 429 - {'error': {'message': "litellm.RateLimitError: RateLimitError: MoonshotException - Your account org-07601fd4e69e4430ac86ba5d415d7c06 is suspended due to insufficient balance, please recharge your account or check your plan and billing detailsNo fallback model group found for original model_group=moonshot/kimi-k2.6. Fallbacks=[{'minimax-m2.5': ['minimax-m2.5-api']}]. Received Model Group=moonshot/kimi-k2.6\nAvailable Model Group Fallbacks=None\nError doing the fallback: litellm.RateLimitError: RateLimitError: MoonshotException - Your account org-07601fd4e69e4430ac86ba5d415d7c06 is suspended due to insufficient balance, please recharge your account or check your plan and billing detailsNo fallback model group found for original model_group=moonshot/kimi-k2.6. Fallbacks=[{'minimax-m2.5': ['minimax-m2.5-api']}] LiteLLM Retried: 3 times, LiteLLM Max Retries: 3", 'type': 'throttling_error', 'param': None, 'code': '429'}} (Cost: $0.00)
  • t09_invoke_skill: Test execution failed: Conversation run failed for id=3e7c3d78-d482-47ea-948c-50e7469cffb3: litellm.RateLimitError: Error code: 429 - {'error': {'message': "litellm.RateLimitError: RateLimitError: MoonshotException - Your account org-07601fd4e69e4430ac86ba5d415d7c06 is suspended due to insufficient balance, please recharge your account or check your plan and billing detailsNo fallback model group found for original model_group=moonshot/kimi-k2.6. Fallbacks=[{'minimax-m2.5': ['minimax-m2.5-api']}]. Received Model Group=moonshot/kimi-k2.6\nAvailable Model Group Fallbacks=None\nError doing the fallback: litellm.RateLimitError: RateLimitError: MoonshotException - Your account org-07601fd4e69e4430ac86ba5d415d7c06 is suspended due to insufficient balance, please recharge your account or check your plan and billing detailsNo fallback model group found for original model_group=moonshot/kimi-k2.6. Fallbacks=[{'minimax-m2.5': ['minimax-m2.5-api']}] LiteLLM Retried: 3 times, LiteLLM Max Retries: 3", 'type': 'throttling_error', 'param': None, 'code': '429'}} (Cost: $0.00)
  • t07_interactive_commands: Test execution failed: Conversation run failed for id=13dd34c4-4a20-41ac-b752-966c6530caaf: litellm.RateLimitError: Error code: 429 - {'error': {'message': "litellm.RateLimitError: RateLimitError: MoonshotException - Your account org-07601fd4e69e4430ac86ba5d415d7c06 is suspended due to insufficient balance, please recharge your account or check your plan and billing detailsNo fallback model group found for original model_group=moonshot/kimi-k2.6. Fallbacks=[{'minimax-m2.5': ['minimax-m2.5-api']}]. Received Model Group=moonshot/kimi-k2.6\nAvailable Model Group Fallbacks=None\nError doing the fallback: litellm.RateLimitError: RateLimitError: MoonshotException - Your account org-07601fd4e69e4430ac86ba5d415d7c06 is suspended due to insufficient balance, please recharge your account or check your plan and billing detailsNo fallback model group found for original model_group=moonshot/kimi-k2.6. Fallbacks=[{'minimax-m2.5': ['minimax-m2.5-api']}] LiteLLM Retried: 3 times, LiteLLM Max Retries: 3", 'type': 'throttling_error', 'param': None, 'code': '429'}} (Cost: $0.00)
  • t04_git_staging: Test execution failed: Conversation run failed for id=c4c8128c-3353-43ad-b9ed-87ee142ea25d: litellm.RateLimitError: Error code: 429 - {'error': {'message': "litellm.RateLimitError: RateLimitError: MoonshotException - Your account org-07601fd4e69e4430ac86ba5d415d7c06 is suspended due to insufficient balance, please recharge your account or check your plan and billing detailsNo fallback model group found for original model_group=moonshot/kimi-k2.6. Fallbacks=[{'minimax-m2.5': ['minimax-m2.5-api']}]. Received Model Group=moonshot/kimi-k2.6\nAvailable Model Group Fallbacks=None\nError doing the fallback: litellm.RateLimitError: RateLimitError: MoonshotException - Your account org-07601fd4e69e4430ac86ba5d415d7c06 is suspended due to insufficient balance, please recharge your account or check your plan and billing detailsNo fallback model group found for original model_group=moonshot/kimi-k2.6. Fallbacks=[{'minimax-m2.5': ['minimax-m2.5-api']}] LiteLLM Retried: 3 times, LiteLLM Max Retries: 3", 'type': 'throttling_error', 'param': None, 'code': '429'}} (Cost: $0.00)
  • t05_simple_browsing: Test execution failed: Conversation run failed for id=1e65c8ec-9ed1-4869-b17c-c4f7149cf826: litellm.RateLimitError: Error code: 429 - {'error': {'message': "litellm.RateLimitError: RateLimitError: MoonshotException - Your account org-07601fd4e69e4430ac86ba5d415d7c06 is suspended due to insufficient balance, please recharge your account or check your plan and billing detailsNo fallback model group found for original model_group=moonshot/kimi-k2.6. Fallbacks=[{'minimax-m2.5': ['minimax-m2.5-api']}]. Received Model Group=moonshot/kimi-k2.6\nAvailable Model Group Fallbacks=None\nError doing the fallback: litellm.RateLimitError: RateLimitError: MoonshotException - Your account org-07601fd4e69e4430ac86ba5d415d7c06 is suspended due to insufficient balance, please recharge your account or check your plan and billing detailsNo fallback model group found for original model_group=moonshot/kimi-k2.6. Fallbacks=[{'minimax-m2.5': ['minimax-m2.5-api']}] LiteLLM Retried: 3 times, LiteLLM Max Retries: 3", 'type': 'throttling_error', 'param': None, 'code': '429'}} (Cost: $0.00)
  • t02_add_bash_hello: Test execution failed: Conversation run failed for id=bb47f61a-89ce-4d3f-ab51-ad1e14891405: litellm.RateLimitError: Error code: 429 - {'error': {'message': "litellm.RateLimitError: RateLimitError: MoonshotException - Your account org-07601fd4e69e4430ac86ba5d415d7c06 is suspended due to insufficient balance, please recharge your account or check your plan and billing detailsNo fallback model group found for original model_group=moonshot/kimi-k2.6. Fallbacks=[{'minimax-m2.5': ['minimax-m2.5-api']}]. Received Model Group=moonshot/kimi-k2.6\nAvailable Model Group Fallbacks=None\nError doing the fallback: litellm.RateLimitError: RateLimitError: MoonshotException - Your account org-07601fd4e69e4430ac86ba5d415d7c06 is suspended due to insufficient balance, please recharge your account or check your plan and billing detailsNo fallback model group found for original model_group=moonshot/kimi-k2.6. Fallbacks=[{'minimax-m2.5': ['minimax-m2.5-api']}] LiteLLM Retried: 3 times, LiteLLM Max Retries: 3", 'type': 'throttling_error', 'param': None, 'code': '429'}} (Cost: $0.00)

@all-hands-bot

Copy link
Copy Markdown
Collaborator

🎉 Swebench Evaluation Complete

Evaluation: 26181563165-claude-son-eval
Model: litellm_proxy/claude-sonnet-4-5-20250929
Dataset: benchmark (test)
Commit: b5c3ded0c03bb8274314cd6607d4c2c6df27aa54
Timestamp: 2026-05-20 19:29:23 UTC
Triggered by: @xingyao Wang

📊 Results

  • Total instances: 500
  • Submitted instances: 50
  • Resolved instances: 40
  • Unresolved instances: 10
  • Empty patch instances: 0
  • Error instances: 0
  • Eval limit: 50
  • Success rate: 40/50 (80.0%)

🔗 Links

Full Archive
Eval Monitor

@malhotra5
malhotra5 merged commit 3996252 into main May 20, 2026
92 of 93 checks passed
@malhotra5
malhotra5 deleted the feat/async-llm-completions branch May 20, 2026 20:04
response_type=response_type,
)

async def astep(

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

This is more or less the same code as in the step() method. Can we not share with it? As it is is really difficult to maintain.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Yes good callout, I'm creating a follow on for shared utils

@VascoSch92 VascoSch92 left a comment •

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Hey @malhotra5 @tofarr

I'm a little concerned about this PR.

Why do we need async? Is there a real need for that?

Don't get me wrong, I really like async. It's just more about maintenability, testing and be sure about correctness.

See the issue: #3341

@@ -1,3 +1,5 @@
from __future__ import annotations

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

We don't need this import

be usable from both the event-loop thread and thread-pool workers.
"""

from __future__ import annotations

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

This is not used

# ---------------------------------------------------------------------------


async def agenerate_title_with_llm(

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

This is never used

return self._execute_single_session(action, conversation)

def interrupt(self) -> None:
"""Send Ctrl+C to all active terminal sessions.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Is this working with every terminal?

finally:
self._cancel_token = None

async def arun(self) -> None:

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

This is very hard to read. Can we not using short circuit strategies?

"Output must be dict or BaseModel when no output schema is defined"
)

async def acall(

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

This is dead-code

StressTestor pushed a commit to StressTestor/software-agent-sdk that referenced this pull request Jun 1, 2026
Co-authored-by: openhands <openhands@all-hands.dev>
pengzhang-create pushed a commit to Pyromind-Dynamics/software-agent-sdk that referenced this pull request Aug 13, 2026
Co-authored-by: openhands <openhands@all-hands.dev>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

integration-test Runs the integration tests and comments the results release-note-required PR requires explicit release-note coverage for behavioral or default changes run-eval-50 Runs evaluation on 50 SWE-bench instances test-examples Run all applicable "examples/" files. Expensive operation.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

7 participants