Skip to content

feat: Add OpenAI Responses API support to LLM class - #142

Closed
enyst wants to merge 173 commits into
mainfrom
openhands/support-responses-api
Closed

enyst wants to merge 173 commits into
mainfrom
openhands/support-responses-api

Conversation

@enyst

@enyst enyst commented Sep 6, 2025 •

Copy link
Copy Markdown
Member

Summary

This PR implements OpenAI Responses API support in the agent-sdk LLM class alongside the existing ChatCompletions API, as requested in issue #138.

We route LLM.completion() to the OpenAI Responses API (via LiteLLM) when the model supports it, convert Responses payloads into a ChatCompletions-like format, surface assistant.message.reasoning_content, and record usage.reasoning_tokens. Telemetry persists raw Responses payloads for audit.

Changes

Core Implementation

  • Added supports_responses_api field to ModelFeatures dataclass
  • Created responses_converter.py with utilities to convert between ChatCompletions and Responses API formats
  • Implemented responses() method in LLM class using litellm.responses()

Features

  • Format conversion: between message formats and string input/output
  • Model compatibility detection: detects which models support Responses API
  • Backward compatibility: Existing completion() method remains unchanged

Supported Models

The implementation supports Responses API for:

  • OpenAI reasoning models: GPT-5, GPT-5-mini, o1-preview, o1-mini, o3-mini.

Usage Example

from openhands.sdk.llm import LLM

# For reasoning models that support Responses API
llm = LLM(model="o1-preview")
if llm.is_responses_api_supported():
    response = llm.responses(
        input="Solve this step by step: What is 2+2?"
    )
    print(response.choices[0].message.content)

# Traditional ChatCompletions API still works
response = llm.completion(
    messages=[{"role": "user", "content": "What is 2+2?"}]
)

Testing Results

All tests pass:

  • ✅ 7/7 converter utility tests
  • ✅ 22/22 model feature tests
  • ✅ 10/10 LLM responses method tests
  • ✅ All existing tests continue to pass

Fixes #138

@enyst can click here to continue refining the PR


Agent Server images for this PR

• GHCR package: https://github.com/All-Hands-AI/agent-sdk/pkgs/container/agent-server

Variants & Base Images

Variant Base Image Docs / Tags
golang golang:1.21-bookworm Link
java eclipse-temurin:17-jdk Link
python nikolaik/python-nodejs:python3.12-nodejs22 Link

Pull (multi-arch manifest)

docker pull ghcr.io/all-hands-ai/agent-server:68257dd-python

Run

docker run -it --rm \
  -p 8000:8000 \
  --name agent-server-68257dd-python \
  ghcr.io/all-hands-ai/agent-server:68257dd-python

All tags pushed for this build

ghcr.io/all-hands-ai/agent-server:68257dd-golang
ghcr.io/all-hands-ai/agent-server:v1.0.0_golang_tag_1.21-bookworm_golang
ghcr.io/all-hands-ai/agent-server:68257dd-java
ghcr.io/all-hands-ai/agent-server:v1.0.0_eclipse-temurin_tag_17-jdk_java
ghcr.io/all-hands-ai/agent-server:68257dd-python
ghcr.io/all-hands-ai/agent-server:v1.0.0_nikolaik_s_python-nodejs_tag_python3.12-nodejs22_python

The 68257dd tag is a multi-arch manifest (amd64/arm64); your client pulls the right arch automatically.

- Add supports_responses_api field to ModelFeatures dataclass
- Create responses_converter.py with message format conversion utilities
- Implement responses() method in LLM class using litellm.responses()
- Add comprehensive test coverage for all new functionality
- Support reasoning models like o1, o3, Claude, Gemini, and DeepSeek-R1
- Include usage example demonstrating both ChatCompletions and Responses APIs
- Maintain backward compatibility with existing completion() method

Fixes #138

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

github-actions Bot commented Sep 6, 2025 •

Copy link
Copy Markdown
Contributor

Coverage

Coverage Report
FileStmtsMissCoverMissing
openhands
   __init__.py10100% 
openhands/agent_server
   __init__.py00100% 
   __main__.py15150%1, 3, 6–8, 11, 14, 22, 24–27, 29, 38–39
   api.py20200%1–2, 4, 6, 9, 12, 15, 18, 24–28, 31–32, 36–37, 40–42
   config.py42420%1–4, 6, 10–11, 14, 17, 21, 28–29, 32, 35, 40, 43, 49, 56, 63, 69, 75, 79, 81–82, 84, 87–89, 91–92, 95–98, 100, 103, 106, 109, 111–112, 115–116
   conversation_router.py50500%3–4, 6, 8, 11, 18, 21–22, 28–29, 48–50, 55–56, 63–64, 67–68, 70–73, 76–77, 82–84, 90–91, 95–96, 99, 102–106, 109, 112–116, 119–124
   conversation_service.py1951950%1–6, 8, 10–12, 19–22, 25, 28–29, 35–39, 41–48, 50, 57–58, 61–63, 69–70, 72, 75–82, 85–86, 89–93, 96–98, 100–103, 105, 107, 112–113, 115–117, 120–121, 123, 125, 127, 132–136, 140, 144–148, 151–152, 159–160, 173–177, 180, 182–183, 185–191, 193–199, 201–210, 212–215, 217–225, 230–231, 234–236, 238–242, 244, 251–253, 261–263, 265–266, 269–274, 276, 278, 280–281, 283, 285–286, 288, 290–291, 293–294, 297–299, 302, 308–311, 318–319, 323–327, 329, 334, 337, 340, 342–343, 345, 349–351
   event_router.py87870%5–8, 10, 18, 20, 23, 30–32, 35–37, 42–43, 65–70, 73–74, 84–88, 91–92, 94–100, 103–104, 109–113, 119–120, 122–127, 130, 133, 137–141, 147–148, 152–156, 159–168, 170, 173–175, 177–182
   event_service.py1221220%1–4, 6, 12–14, 21–22, 25–26, 32–36, 38–40, 42–45, 47–50, 53, 56, 58, 65–66, 69–71, 73, 78–79, 82–85, 88–89, 92–96, 99–101, 103–106, 108, 110, 115–116, 118–120, 122, 127–128, 130, 132, 134–138, 140–147, 149–150, 152–153, 155, 157–161, 177–178, 180, 182–185, 187–189, 191, 193–196, 198–202, 204–207, 209–211, 213–215
   middleware.py26260%1, 3–6, 9, 14–15, 23–26, 29–30, 33–34, 37, 46–48, 50, 53–57
   models.py50500%1–4, 6, 8–9, 16–18, 21, 24–27, 30, 33–34, 37, 43–45, 50–52, 55, 63, 68, 71, 79, 82–85, 88, 91, 94–96, 99–101, 104, 107–108, 111–112, 115–117
   openapi.py20200%3–6, 8, 11, 18–22, 25, 27–29, 32–36
   pub_sub.py35350%1–4, 6–7, 10, 13–15, 18, 22–23, 30, 32, 39–42, 44, 51–54, 56, 59, 61, 68–72, 74–75, 78
   utils.py330%1, 4, 6
openhands/sdk
   __init__.py17288%27–28
   logger.py732171%33, 57, 64–67, 69–71, 124, 129–131, 134–135, 141–143, 150, 155–156
openhands/sdk/agent
   __init__.py40100% 
   agent.py1944676%64, 72, 79, 83, 100, 118, 125–126, 131–132, 208–209, 211–213, 215–217, 255, 269, 292, 331, 336–338, 341–342, 345, 375–377, 381–383, 393–394, 398–401, 408–409, 413, 417–418, 449
   base.py91792%111, 125, 133–135, 150, 169
   spec.py160100% 
openhands/sdk/context
   __init__.py40100% 
   agent_context.py57296%146, 152
   manager.py330%1, 4–5
   view.py97198%89
openhands/sdk/context/condenser
   __init__.py50100% 
   base.py190100% 
   llm_summarizing_condenser.py39392%44–46
   no_op_condenser.py60100% 
   pipeline_condenser.py13653%45–50
openhands/sdk/context/microagents
   __init__.py40100% 
   exceptions.py50100% 
   microagent.py1432582%130, 133–136, 218–221, 229, 251–252, 257–258, 260, 264, 271–273, 281–283, 337, 339–340
   types.py210100% 
openhands/sdk/context/prompts
   __init__.py20100% 
   prompt.py30583%12, 15, 24, 44–45
openhands/sdk/conversation
   __init__.py70100% 
   conversation.py1181190%121, 129–131, 135–136, 199, 281–282, 290–291
   event_store.py100892%49–50, 59, 66, 71–72, 128, 141
   persistence_const.py50100% 
   secrets_manager.py41197%107
   serialization_diff.py00100% 
   state.py102595%142, 165, 201–203
   types.py60100% 
   visualizer.py95693%90, 147, 169, 186, 218, 220
openhands/sdk/event
   __init__.py70100% 
   base.py72888%52, 63, 75–76, 82, 85–86, 88
   condenser.py28775%38, 40, 42–46
   llm_convertible.py1861790%54, 64–65, 70–71, 244, 263, 297–298, 303, 311, 352–353, 358, 391–392, 397
   metric_events.py130100% 
   types.py70100% 
   user_action.py12191%21
   utils.py130100% 
openhands/sdk/io
   __init__.py40100% 
   base.py14471%7, 11, 15, 19
   local.py561671%43–44, 58, 66–78
   memory.py43490%16, 20, 53–54
openhands/sdk/llm
   __init__.py80100% 
   exceptions.py360100% 
   llm.py4758881%290, 295, 314–315, 347, 374, 425, 659, 670, 689–691, 703–705, 821–824, 831, 849–850, 878, 884–885, 935, 984, 1001–1002, 1011, 1022, 1043, 1045–1050, 1052–1069, 1072–1076, 1078–1079, 1085–1094, 1098–1109, 1122, 1136, 1141
   llm_registry.py380100% 
   message.py109496%96, 99, 222–223
   metadata.py150100% 
openhands/sdk/llm/mixins
   fn_call_converter.py3439472%74, 343, 345, 349, 367, 369, 375, 381, 383, 422, 424, 426, 428, 433–434, 481–482, 518–520, 522, 524, 545–547, 553, 575, 601–602, 610–613, 615, 617, 639, 648, 656, 701–704, 708–711, 723, 727, 738, 748, 797–798, 800, 829, 833, 859, 867, 870–871, 876, 905–908, 912–913, 918–919, 924, 973–974, 980, 994, 1006, 1008–1009, 1012–1014, 1016–1017, 1023–1025, 1027–1028, 1030, 1032, 1036, 1038, 1043, 1045–1046, 1049
   non_native_fc.py39392%64, 75, 91
openhands/sdk/llm/utils
   metrics.py111397%17, 117, 311
   model_features.py420100% 
   responses_converter.py1252877%76–79, 105–106, 129–131, 145–147, 178–179, 182, 189, 191–194, 196, 203, 209–212, 220, 262
   retry_mixin.py501178%47, 50, 64, 86, 90, 94–95, 105, 110–111, 116
   telemetry.py1361588%71, 94, 99–100, 112–113, 120, 134, 199, 216, 222, 229, 232, 234, 241
   unverified_models.py69494%45–46, 51, 73
   verified_models.py50100% 
openhands/sdk/mcp
   __init__.py50100% 
   client.py26676%48–49, 62–63, 72–73
   definition.py541670%81, 101–106, 108–116
   tool.py702367%45–48, 52, 55, 58–61, 95, 121–122, 125–127, 129, 144, 172–173, 178, 186, 214
   utils.py30486%23–24, 27, 30
openhands/sdk/preset
   __init__.py00100% 
   default.py211242%13, 15, 22, 28–29, 31–33, 35–36, 43, 45
openhands/sdk/security
   __init__.py20100% 
   analyzer.py34876%39, 72, 74–75, 77–78, 80, 83
   llm_analyzer.py90100% 
   risk.py12283%21, 33
openhands/sdk/tool
   __init__.py50100% 
   schema.py101793%23–25, 27, 36, 185, 200
   spec.py150100% 
   tool.py116893%68, 111, 185, 190–194
openhands/sdk/tool/builtins
   __init__.py40100% 
   finish.py26196%33
   think.py321359%24, 27–28, 31, 33–37, 39, 51, 57, 74
openhands/sdk/utils
   __init__.py30100% 
   async_executor.py52786%39, 55–56, 84, 88, 102–103
   async_utils.py120100% 
   json.py28280%1–3, 5, 7–8, 11, 14–21, 25, 28, 30–31, 34, 37–38, 40, 43, 45–48
   models.py142497%164, 211, 243–244
   protocol.py30100% 
   pydantic_diff.py571573%36, 44, 50–58, 60–62, 65
   truncate.py100100% 
   visualize.py17664%14–16, 19–20, 22
openhands/tools
   __init__.py17382%29–30, 79
openhands/tools/browser_use
   __init__.py330%3, 37, 40
   definition.py1101100%3, 5, 7–11, 15, 18, 21–23, 27–30, 32, 36, 38–39, 41, 47, 50–51, 56, 69, 84, 87–89, 102, 105, 108, 114, 126, 141, 144–146, 159, 162, 165, 168, 180, 195, 198–200, 213, 216, 222, 231, 246, 249–251, 264, 267, 271, 278, 283, 298, 301–303, 316, 319, 325, 334, 349, 352–354, 367, 370, 373, 379, 394, 397–399, 412, 415, 418, 424, 439, 442–444, 457, 460, 466, 474, 489, 492–494, 507, 510, 515, 523, 538, 541–543, 553, 560–563
   impl.py1131130%3–4, 6–8, 12, 15, 18, 25, 28, 33–34, 36, 38, 42, 44, 58–59, 61–70, 73–82, 84–85, 87–91, 93, 95, 97–98, 101, 103–104, 106, 108–109, 112, 114–115, 117, 119–120, 122, 124–125, 127, 129, 131–132, 134–137, 140–141, 144, 146, 148, 151, 153–154, 156, 158–159, 161, 163–164, 167, 169–170, 174, 176–180, 182, 184–189, 191, 193, 195–197, 200, 202, 204–207
   server.py45450%1, 4, 10–11, 13–14, 16–17, 20–21, 24–25, 28, 30–32, 34–35, 38–39, 41, 44, 47–48, 51, 54–55, 57–61, 64–66, 68, 73–78, 80, 87, 89
openhands/tools/execute_bash
   __init__.py40100% 
   constants.py90100% 
   definition.py966136%40, 43, 46–47, 49, 52–54, 56–58, 60, 90, 94–103, 108, 111–113, 116, 118–120, 122, 126–127, 130–132, 134–135, 138–141, 145–147, 152, 156–158, 161–163, 167–168, 170, 247, 249–250, 253, 263
   impl.py402440%52–55, 57–58, 60–62, 64–67, 69, 72, 82–83, 86–89, 91, 95–96
   metadata.py502354%67–73, 77–78, 83, 85, 87–96, 100–101
openhands/tools/execute_bash/terminal
   __init__.py60100% 
   factory.py492842%24–25, 30, 32, 35, 37–38, 44–46, 74–77, 79–83, 87–89, 91, 97, 107, 111–113
   interface.py692071%43, 52, 62, 71, 76, 85, 94, 99, 104, 112, 145, 157, 162, 171, 180, 185, 189–191, 193
   subprocess_terminal.py23620313%33–34, 50–53, 56, 59–61, 67–68, 71–74, 76, 79, 81–83, 97–100, 102, 105–106, 109, 112–113, 117–118, 124–126, 128, 131–132, 134, 138–139, 141–142, 144–150, 152–158, 161–166, 168–169, 171–172, 177, 179–187, 191–193, 195–196, 198–199, 202–204, 206–209, 211–212, 214–215, 217–222, 227–229, 231, 234, 237–238, 241–242, 248–250, 252–259, 261–264, 268–276, 289–290, 292, 309–310, 313–314, 316, 318, 320–322, 325–326, 328–330, 332–333, 335–336, 345–346, 350, 352–357, 361–362, 364–367, 369–375, 377–378, 380–384, 388–389, 391–397, 401–402, 405–406, 408–409, 411–413
   terminal_session.py17813921%43, 85–88, 92, 96–98, 107–108, 119–121, 123–126, 135–136, 140, 144, 147–148, 150, 155, 161, 163–164, 169, 177, 182–185, 198–200, 205, 208–209, 213, 219, 233–235, 240, 243–244, 248, 255, 264, 273–274, 276, 279–283, 285, 288, 290–292, 296–297, 300–302, 306, 311–312, 316–317, 323–325, 336–337, 340–342, 344–346, 349, 359, 363, 366, 369–370, 376–377, 383, 388–389, 392–396, 402, 404–406, 412–416, 419, 422, 425–426, 428–431, 438, 442, 447–448, 455–457, 461, 465, 470–471, 475–476, 479–482, 488–489, 492
   tmux_terminal.py803457%36, 45, 90–95, 97–98, 107–108, 110, 118–119, 121, 128, 133, 145–152, 160–161, 163–164, 166, 168–170
openhands/tools/execute_bash/utils
   command.py817211%15–19, 27, 32, 34–35, 37–38, 41–46, 48, 51–53, 55, 58–67, 74–75, 77–79, 81, 83, 90–91, 93, 95–97, 99, 101–102, 105–106, 109, 117, 120–121, 123–124, 127–129, 132–138, 141–145, 150
openhands/tools/str_replace_editor
   __init__.py30100% 
   definition.py631280%86, 98, 118, 121, 124, 131, 133, 135, 137, 209, 212, 215
   editor.py22817025%74, 76–77, 80, 98, 101, 111–115, 121–129, 131, 149–150, 170–171, 175, 179–180, 189, 193–196, 204–205, 209–211, 217, 220, 225, 228, 231–232, 235, 238–239, 243, 247, 262–264, 273, 276, 282, 287, 289–293, 295, 297, 301–302, 306–307, 316–317, 319–322, 324, 331–332, 338–340, 348–352, 356, 358–359, 366, 369, 374–375, 377, 401–402, 424–425, 427–428, 434, 437, 441–447, 450–451, 454–459, 462, 465–466, 470, 473–474, 477, 479–480, 486, 490, 509, 514–517, 519, 527, 534, 541, 552–555, 557, 559, 586–589, 598–599, 628–630, 632–641, 646–649, 662–663, 668, 673, 679, 685
   exceptions.py221340%5–6, 9, 16–18, 25–27, 38–41
   impl.py261157%31–32, 51–52, 54–56, 65–68
openhands/tools/str_replace_editor/utils
   __init__.py00100% 
   config.py20100% 
   constants.py50100% 
   diff.py641576%24, 40–42, 45–47, 50, 90–93, 107–108, 115
   encoding.py542750%42–43, 46–48, 51, 54, 60, 64–65, 67, 69, 78, 80–81, 84, 87–90, 93, 96–97, 114, 128, 130–131
   file_cache.py954849%43–46, 49–50, 54, 59, 61, 64, 69, 72–73, 87, 95–98, 108–112, 115–120, 126–130, 133–135, 138–140, 143–148, 151, 154
   history.py663645%58–60, 66–68, 70–71, 74–76, 78–79, 82, 85–86, 88, 92–94, 98–99, 102–104, 107, 111–113, 115–120, 122
   shell.py231630%30, 32–34, 38, 40, 51–55, 62–63, 70–72
openhands/tools/task_tracker
   __init__.py220%1, 10
   definition.py1321320%1–4, 6–7, 9–11, 21, 24–27, 34, 37, 41, 46–47, 49, 52–54, 56–57, 60–61, 63, 66, 69, 72–73, 77–79, 81–82, 84, 86, 88–89, 92, 95–97, 99–100, 103–109, 111–113, 116, 118–121, 123, 126, 129–130, 132–133, 135–136, 138, 141, 144, 151–152, 155–156, 158, 160, 162, 164–166, 172, 174–175, 180–181, 185, 192, 194–195, 197–199, 203–204, 206–209, 211, 213, 215–216, 218–220, 222–226, 230, 232, 234–235, 237–238, 240, 242–246, 250, 383, 397, 400–401, 408, 411
openhands/tools/utils
   __init__.py00100% 
TOTAL6896264461% 

@openhands-ai openhands-ai Bot mentioned this pull request Sep 6, 2025
Comment thread openhands/sdk/llm/llm.py Resolved
… OpenAI Responses API support

- Removed Claude, Gemini, and DeepSeek models from RESPONSES_API_PATTERNS
- These models have their own reasoning/thinking APIs but do not support OpenAI's Responses API natively
- LiteLLM provides bridge support for these models, but that's different from native API support
- Updated tests to reflect the corrected model support patterns
- Only OpenAI models (o1*, o3*, o4-mini*, gpt-4o*, gpt-4.1*, gpt-5*) have native Responses API support

Co-authored-by: openhands <openhands@all-hands.dev>
@enyst
enyst marked this pull request as draft September 6, 2025 19:41
enyst and others added 2 commits September 6, 2025 19:42
The usage object from Responses API always contains input_tokens,
output_tokens, and total_tokens when present. These are required
fields in the ResponseAPIUsage type definition, making the hasattr()
conditionals unnecessary defensive programming.

Evidence from litellm repository:
- ResponseAPIUsage class defines these as required fields (not Optional)
- Test code directly accesses these properties without hasattr() checks
- Mock responses always include these fields

This simplifies the code by eliminating special cases that don't exist.

Co-authored-by: openhands <openhands@all-hands.dev>
- Remove unnecessary getattr for 'id' field (always present in ResponsesAPIResponse)
- Fix field name from 'created' to 'created_at' (correct field name in ResponsesAPIResponse)
- Keep getattr for 'model' field (Optional[str] in ResponsesAPIResponse, can be None)
- Update test mock to use correct 'created_at' field name

Based on analysis of litellm ResponsesAPIResponse class definition:
- id: str (required, always present)
- created_at: int (required, always present)
- model: Optional[str] = None (optional, can be None)

Co-authored-by: openhands <openhands@all-hands.dev>
@OpenHands OpenHands deleted a comment from openhands-ai Bot Sep 7, 2025
@OpenHands OpenHands deleted a comment from openhands-ai Bot Sep 7, 2025
@OpenHands OpenHands deleted a comment from openhands-ai Bot Sep 7, 2025
@enyst

enyst commented Sep 7, 2025

Copy link
Copy Markdown
Member Author

@OpenHands fix the failing llm tests

@openhands-ai

openhands-ai Bot commented Sep 7, 2025

Copy link
Copy Markdown

Uh oh! There was an unexpected error starting the job :(

enyst and others added 3 commits September 8, 2025 02:28
…se validation\n\n- Coerce created/created_at robustly; avoid MagicMock\n- Coerce usage token fields safely\n- Preserve model id as string\n\nCo-authored-by: openhands <openhands@all-hands.dev>
@enyst

enyst commented Sep 9, 2025

Copy link
Copy Markdown
Member Author

@OpenHands Read this PR and understand what it aims to achieve.

Then read this file and copy it in your workspace, in agent-sdk examples/ for testing:

https://raw.githubusercontent.com/All-Hands-AI/agent-sdk/1b06c01eac7f9170bd92591aa5f03e9bfa988b78/examples/10_reasoning_debug.py

Check the agent-sdk README.md file for how to run these example files easily, same applies to the new file.

Add gpt-5-mini-2025-08-07 or another gpt-5-mini model that exists on the litellm proxy, to the new examples file in the list of default models. Comment out all the other models.

Goal: run the debug file to verify that it works to show reasoning for GPT-5-mini*, and fix any issues.

When you are done, make a PR to this PR, so we can see.

@openhands-ai

openhands-ai Bot commented Sep 9, 2025

Copy link
Copy Markdown

I'm on it! enyst can track my progress at all-hands.dev

🟡 Solvability: MEDIUM

This looks MEDIUM: the goal is clear and there’s a concrete file and docs to follow, but solving it depends on coordinating multiple parts (PR context, agent-sdk example, and a litellm proxy) and missing environment/configuration details could block progress. Success hinges on access to the right PR and having the correct proxy/model setup to run and validate the example.

You can make the issue easier to resolve by addressing these concerns in the conversation:

  • Provide the PR URL/branch and the exact commands to run the example from the repo root.
  • Specify the litellm proxy endpoint, required credentials/API keys, and the exact GPT‑5‑mini model ID available there.
  • Describe the expected output (what “shows reasoning” should look like) and share any errors observed when you run the script locally.

Positive feedback:

  • Clear, focused goal to enable and verify reasoning output for GPT‑5‑mini.
  • Includes a direct file link and references the README for running examples.
  • The requested change is confined to the example’s model list, keeping the scope limited.

- Add gpt-5-mini-2025-08-07 to reasoning debug example
- Fix GPT-5 temperature handling (only supports temperature=1.0)
- Add comprehensive reasoning debug example with responses API testing
- Verify GPT-5 models work with agent-sdk and show reasoning tokens

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

@xingyaoww xingyaoww left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Some GPT-5 suggestion into how we might simplify the llm.py code

from typing import Any, Literal, Union, Annotated, cast
from pydantic import BaseModel, Field, ConfigDict
# ... keep your existing imports

CallKind = Literal["chat", "responses"]

# ---------------------------
# Discriminated union context
# ---------------------------

class _BaseCtxModel(BaseModel):
    model_config = ConfigDict(extra="forbid")
    call_kwargs: dict[str, Any]
    log_ctx: dict[str, Any]
    tools: list[ChatCompletionToolParam] = Field(default_factory=list)

class ChatCtx(_BaseCtxModel):
    kind: Literal["chat"]
    messages: list[dict[str, Any]]
    # internal to support mocked tool-calls
    nonfn_msgs: list[dict[str, Any]] | None = None
    raw_resp_needed: bool = False

class ResponsesCtx(_BaseCtxModel):
    kind: Literal["responses"]
    input: str

ReqCtx = Annotated[Union[ChatCtx, ResponsesCtx], Field(discriminator="kind")]

# ---------------------------
# Public wrappers: unchanged API
# ---------------------------

def completion(
    self,
    messages: list[dict[str, Any]] | list[Message],
    tools: list[ChatCompletionToolParam] | None = None,
    return_metrics: bool = False,
    **kwargs,
) -> ModelResponse:
    if kwargs.get("stream", False):
        raise ValueError("Streaming is not supported")

    # Serialize Message objects if present
    if messages and isinstance(messages[0], Message):
        messages = self.format_messages_for_llm(cast(list[Message], messages))
    else:
        messages = cast(list[dict[str, Any]], messages)

    return self._unified_request(
        kind="chat",
        messages=messages,
        tools=tools or [],
        **kwargs,
    )


def responses(
    self,
    messages: list[dict[str, Any]] | list[Message] | str | None = None,
    input: str | None = None,
    **kwargs,
) -> ModelResponse:
    if not self.is_responses_api_supported():
        raise ValueError(
            f"Model {self.model} does not support the Responses API. Use completion()."
        )
    if kwargs.get("stream", False):
        raise ValueError("Streaming is not supported in responses() method")

    # Determine input text
    if input is None:
        if messages is None:
            raise ValueError("Either 'messages' or 'input' must be provided")
        if isinstance(messages, str):
            input = messages
        else:
            input = messages_to_responses_input(messages)

    return self._unified_request(kind="responses", input=input, **kwargs)

# ---------------------------
# Unified engine
# ---------------------------

def _unified_request(
    self,
    *,
    kind: CallKind,
    messages: list[dict[str, Any]] | None = None,
    input: str | None = None,
    tools: list[ChatCompletionToolParam] | None = None,
    **kwargs,
) -> ModelResponse:
    assert self._telemetry is not None

    # 1) Build validated context (Pydantic will enforce required fields by kind)
    ctx: ReqCtx = self._build_ctx(kind=kind, messages=messages, input=input, tools=tools or [], opts=kwargs)

    # 2) Telemetry (request)
    self._telemetry.on_request(log_ctx=ctx.log_ctx)

    # 3) Retry wrapper
    @self.retry_decorator(
        num_retries=self.num_retries,
        retry_exceptions=LLM_RETRY_EXCEPTIONS,
        retry_min_wait=self.retry_min_wait,
        retry_max_wait=self.retry_max_wait,
        retry_multiplier=self.retry_multiplier,
        retry_listener=self.retry_listener,
    )
    def _one_attempt() -> ModelResponse:
        # Transport
        resp = self._transport_dispatch(ctx)
        # Post-process (mocked tool-calls)
        resp = self._postprocess_dispatch(ctx, resp)
        # Response telemetry + invariant
        self._telemetry.on_response(resp)
        if not resp.get("choices") or len(resp["choices"]) < 1:
            raise LLMNoResponseError("Response choices is less than 1. Response: " + str(resp))
        return resp

    try:
        return _one_attempt()
    except Exception as e:
        self._telemetry.on_error(e)
        raise

# ---------------------------
# Build + normalize once
# ---------------------------

def _build_ctx(
    self,
    *,
    kind: CallKind,
    messages: list[dict[str, Any]] | None,
    input: str | None,
    tools: list[ChatCompletionToolParam],
    opts: dict[str, Any],
) -> ReqCtx:
    use_native_fc = self.is_function_calling_active()

    nonfn_msgs: list[dict[str, Any]] | None = None
    raw_resp_needed = False

    # Mock tool-calls only for chat when native FC is off
    if kind == "chat" and tools and not use_native_fc:
        nonfn_msgs = copy.deepcopy(messages or [])
        messages, opts = self._pre_request_prompt_mock(messages or [], tools, opts)
        raw_resp_needed = True

    has_tools = bool(tools) and (kind == "chat") and use_native_fc
    call_kwargs = self._normalize_kwargs(kind, opts, has_tools=has_tools)

    # Build log context (what we write is exactly what we send)
    log_ctx: dict[str, Any] = {
        "kwargs": {k: v for k, v in call_kwargs.items()},
        "context_window": self.max_input_tokens,
    }
    if kind == "chat":
        log_ctx["messages"] = (messages or [])[:]
        log_ctx["tools"] = tools if has_tools else None
        if nonfn_msgs is not None:
            log_ctx["raw_messages"] = nonfn_msgs
        return ChatCtx(
            kind="chat",
            messages=messages or [],
            nonfn_msgs=nonfn_msgs,
            raw_resp_needed=raw_resp_needed,
            call_kwargs=call_kwargs,
            log_ctx=log_ctx,
            tools=tools,
        )
    else:
        log_ctx["input"] = input or ""
        return ResponsesCtx(
            kind="responses",
            input=input or "",
            call_kwargs=call_kwargs,
            log_ctx=log_ctx,
            tools=tools,
        )

def _normalize_kwargs(self, kind: CallKind, opts: dict, *, has_tools: bool) -> dict:
    out = dict(opts)

    # Sampling defaults
    if self.top_k is not None: out.setdefault("top_k", self.top_k)
    if self.top_p is not None: out.setdefault("top_p", self.top_p)
    if self.temperature is not None: out.setdefault("temperature", self.temperature)

    # Max tokens (chat vs responses)
    if kind == "chat":
        if self.max_output_tokens is not None:
            out.setdefault("max_completion_tokens", self.max_output_tokens)
        if self.model.startswith("azure") and "max_completion_tokens" in out:
            out["max_tokens"] = out.pop("max_completion_tokens")
    else:
        if self.max_output_tokens is not None:
            out.setdefault("max_output_tokens", self.max_output_tokens)

    # Reasoning-model quirks
    if get_features(self.model).supports_reasoning_effort:
        if self.reasoning_effort is not None:
            out["reasoning_effort"] = self.reasoning_effort
        out.pop("temperature", None)
        out.pop("top_p", None)
        if "gemini-2.5-pro" in self.model and out.get("reasoning_effort") in (None, "none"):
            out["reasoning_effort"] = "low"

    # Mistral / Gemini safety
    if self.safety_settings:
        ml = self.model.lower()
        if "mistral" in ml or "gemini" in ml:
            out["safety_settings"] = self.safety_settings

    # Tools only when chat+native FC
    if kind != "chat" or not has_tools:
        out.pop("tools", None)
        out.pop("tool_choice", None)

    # Responses API doesn't support stop/tools
    if kind == "responses":
        out.pop("stop", None)

    # Only keep extra_body for litellm_proxy
    if "litellm_proxy" not in self.model:
        out.pop("extra_body", None)

    return out

# ---------------------------
# Transport + postprocess
# ---------------------------

def _transport_dispatch(self, ctx: ReqCtx) -> ModelResponse:
    with self._litellm_modify_params_ctx(self.modify_params):
        with warnings.catch_warnings():
            warnings.filterwarnings("ignore", category=DeprecationWarning, module="httpx.*")
            warnings.filterwarnings("ignore", message=r".*content=.*upload.*", category=DeprecationWarning)

            if ctx.kind == "chat":
                ret = litellm_completion(
                    model=self.model,
                    api_key=self.api_key.get_secret_value() if self.api_key else None,
                    base_url=self.base_url,
                    api_version=self.api_version,
                    timeout=self.timeout,
                    drop_params=self.drop_params,
                    seed=self.seed,
                    messages=ctx.messages,               # type: ignore[attr-defined]
                    **ctx.call_kwargs,
                )
                assert isinstance(ret, ModelResponse)
                return ret
            else:
                raw = litellm_responses(
                    model=self.model,
                    api_key=self.api_key.get_secret_value() if self.api_key else None,
                    base_url=self.base_url,
                    api_version=self.api_version,
                    timeout=self.timeout,
                    input=ctx.input,                      # type: ignore[attr-defined]
                    **ctx.call_kwargs,
                )
                return responses_to_completion_format(raw)

def _postprocess_dispatch(self, ctx: ReqCtx, resp: ModelResponse) -> ModelResponse:
    # tool-mocking only applies to chat when we mocked pre-request
    if ctx.kind == "chat" and getattr(ctx, "raw_resp_needed", False):  # type: ignore[attr-defined]
        raw_resp = copy.deepcopy(resp)
        resp = self._post_response_prompt_mock(
            resp,
            nonfncall_msgs=getattr(ctx, "nonfn_msgs") or [],              # type: ignore[attr-defined]
            tools=ctx.tools,
        )
        # keep raw vs converted for telemetry parity
        self._telemetry.on_response(resp, raw_resp=raw_resp)
        return resp
    return resp

Comment thread openhands/sdk/llm/llm.py Resolved
@openhands-ai

This comment was marked as outdated.

…top\n\nCo-authored-by: OpenHands-GPT-4.1 openhands@all-hands.dev\nCo-authored-by: openhands <openhands@all-hands.dev>
@enyst

enyst commented Sep 9, 2025

Copy link
Copy Markdown
Member Author

@OpenHands fix this test

FAILED tests/sdk/llm/test_llm_responses.py::test_responses_method_parameter_normalization - AssertionError: assert 'tools' not in {'model': 'o1-preview', 'api_key': None, 'base_url': None, 'api_version': None, 'timeout': None, 'input': 'Test input', 'tools': [{'type': 'function', 'function': {'name': 'test'}}], 'max_output_tokens': 1000, 'reasoning_effort': 'medium'}
================== 1 failed, 499 passed, 2 warnings in 22.24s ==================
Error: Process completed with exit code 1.

- Use "tools" instead of "tool" when trimming duplicate entries
- Keeps log payloads minimal and accurate

Co-authored-by: OpenHands-GPT-5 openhands@all-hands.dev
…i_base

- Ensure parity with chat path by forwarding seed where supported
- Remove duplicate api_base param; rely on base_url consistently
- Minor cleanup: remove duplicate TYPE_CHECKING import, drop unused arg in _select_kind

Co-authored-by: OpenHands-GPT-5 openhands@all-hands.dev
@enyst

enyst commented Sep 22, 2025

Copy link
Copy Markdown
Member Author

OpenHands-GPT-5 here. Thanks for the thorough review.

Actions taken:

  • Fixed telemetry duplicate key: corrected to trim "tools" in kwargs (not "tool").
  • Transport parity: Responses path now forwards seed and no longer sends redundant api_base; kept base_url consistent.
  • Cleanup: removed duplicate TYPE_CHECKING import and redundant comments; left _select_kind signature clean (no unused tools arg).

Considered and deferred:

  • Message.to_llm_dict naming/contract: it intentionally returns litellm AllMessageValues; callers/tests rely on this; we’ll keep the name for now.
  • _normalize_kwargs split: kept unified for now to avoid churn—happy to revisit after landing this PR.
  • Converter "tolerance": we prefer strict typing over hypothetical fallbacks; leaving converter strict.
  • Tests: existing tests touch dict-like access; since litellm models currently behave compatibly and suite passes, no change.

If you see anything else blocking, I can iterate quickly.

enyst and others added 4 commits September 22, 2025 20:09
…geValues and removes raw dict path; tighten conversion logic and update tests

- Enforce typed input (AllMessageValues) in converter
- Remove dict fallback and normalize via TypedDict access
- Keep strong typing while operating on canonical shapes
- Update tests to build messages via Message.to_llm_dict()

Co-authored-by: OpenHands-GPT-5 openhands@all-hands.dev
…s-AI/agent-sdk into openhands/support-responses-api
Comment thread .openhands/microagents/repo.md Resolved
enyst and others added 6 commits September 23, 2025 13:23
…eam llm_convertible split and retain Responses API typing

- Resolve modify/delete by removing monolithic openhands/sdk/event/llm_convertible.py
- Keep typed Responses converter and LLM wiring
- All pre-commit hooks and tests pass locally

Co-authored-by: OpenHands-GPT-5 openhands@all-hands.dev
…via telemetry logs

Co-authored-by: OpenHands-GPT-5 openhands@all-hands.dev
…d direct tool-role messages

- Send same task twice through agent to observe cache re-use
- Add direct tool-role message calls (system -> tool -> user) twice
- Keep telemetry parsing for cache_read and cache_write

Co-authored-by: OpenHands-GPT-5 openhands@all-hands.dev
…n logging enabled

- Adds request-*.json files containing the outbound payload we send via LiteLLM
- Helps verify Anthropic cache_control fields and precise message shapes

Co-authored-by: OpenHands-GPT-5 openhands@all-hands.dev
@github-actions

Copy link
Copy Markdown
Contributor

Agent Server image for this PR

Pull (multi-arch manifest):

docker pull ghcr.io/all-hands-ai/agent-server:f64f931

Run:

docker run -it --rm \
  -p 8000:8000 \
  --name agent-server-f64f931 \
  ghcr.io/all-hands-ai/agent-server:f64f931

This tag is a multi-arch manifest (amd64/arm64). Your client pulls the right arch automatically.

@enyst

enyst commented Sep 24, 2025 •

Copy link
Copy Markdown
Member Author

LiteLLM crashes before reaching the provider due to its logging deepcopy interacting with Pydantic-validated messages.

Context:

  • Our request context is a Pydantic discriminated union (ReqCtx = Union[ChatCtx | ResponsesCtx], discriminator="kind"). For chat, ChatCtx(messages: list[AllMessageValues]) causes Pydantic v2 to validate LiteLLM's OpenAI message types.
  • During validation of user.content (declared in LiteLLM types as Iterable[Union[ChatCompletionTextObject | ...]]), pydantic_core produces a ValidatorIterator => the structure stored in ChatCtx.messages for user.content is no longer a plain list.
  • LiteLLM's logging layer (function_setup -> LiteLLMLogging.init) does copy.deepcopy(messages). deepcopy attempts to pickle that ValidatorIterator and throws:
    TypeError: cannot pickle 'pydantic_core._pydantic_core.ValidatorIterator' object

Net effect: the call fails inside LiteLLM pre-call logging (before any provider call), because Pydantic validation—triggered by our discriminated ChatCtx/messages typing—injects a pydantic_core iterator into user.content, and LiteLLM then deep-copies it.

… service_id to LLM in state serialization tests

Co-authored-by: OpenHands-GPT-4o openhands@all-hands.dev
… cache_control for tool role

Co-authored-by: OpenHands-GPT-4o openhands@all-hands.dev
- Keep main LLMResponse return contract in completion()
- Align Message serialization: move cache_control to message level for tool role; adjust tests
- LiteLLM boundary coercion retained
- Fix state serialization tests (service_id, tool factories)

Co-authored-by: OpenHands-GPT-4o openhands@all-hands.dev
enyst and others added 2 commits September 25, 2025 22:20
Co-authored-by: OpenHands-GPT-4o openhands@all-hands.dev
…e_serialization suite

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

openhands-ai Bot commented Oct 1, 2025

Copy link
Copy Markdown

Looks like there are a few issues preventing this PR from being merged!

  • GitHub Actions are failing:
    • Pre-commit checks
    • Run tests

If you'd like me to help, just leave a comment, like

@OpenHands please fix the failing actions on PR #142 at branch `openhands/support-responses-api`

Feel free to include any additional details that might help me get this PR into a better state.

You can manage your notification settings

@enyst enyst closed this Oct 10, 2025
StressTestor pushed a commit to StressTestor/software-agent-sdk that referenced this pull request Jun 1, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Support Responses API

3 participants