Repository navigation
Conversation
- 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>
… 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>
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 fix the failing llm tests |
|
Uh oh! There was an unexpected error starting the job :( |
…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>
…s/support-responses-api
|
@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: 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. |
|
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:
Positive feedback:
|
- 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
left a comment
There was a problem hiding this comment.
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
This comment was marked as outdated.
This comment was marked as outdated.
This reverts commit 1133d42.
…top\n\nCo-authored-by: OpenHands-GPT-4.1 openhands@all-hands.dev\nCo-authored-by: openhands <openhands@all-hands.dev>
|
@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'} |
- 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
|
OpenHands-GPT-5 here. Thanks for the thorough review. Actions taken:
Considered and deferred:
If you see anything else blocking, I can iterate quickly. |
…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
…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
|
Agent Server image for this PR Pull (multi-arch manifest): docker pull ghcr.io/all-hands-ai/agent-server:f64f931Run: docker run -it --rm \
-p 8000:8000 \
--name agent-server-f64f931 \
ghcr.io/all-hands-ai/agent-server:f64f931This tag is a multi-arch manifest (amd64/arm64). Your client pulls the right arch automatically. |
|
LiteLLM crashes before reaching the provider due to its logging deepcopy interacting with Pydantic-validated messages. Context:
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
Co-authored-by: OpenHands-GPT-4o openhands@all-hands.dev
…e_serialization suite Co-authored-by: openhands <openhands@all-hands.dev>
|
Looks like there are a few issues preventing this PR from being merged!
If you'd like me to help, just leave a comment, like Feel free to include any additional details that might help me get this PR into a better state. You can manage your notification settings |
OpenHands#371) Co-authored-by: Xingyao Wang <xingyao@all-hands.dev>
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, convertResponsespayloads into a ChatCompletions-like format, surfaceassistant.message.reasoning_content, and recordusage.reasoning_tokens. Telemetry persists raw Responses payloads for audit.Changes
Core Implementation
supports_responses_apifield toModelFeaturesdataclassresponses_converter.pywith utilities to convert between ChatCompletions and Responses API formatsresponses()method in LLM class usinglitellm.responses()Features
completion()method remains unchangedSupported Models
The implementation supports Responses API for:
Usage Example
Testing Results
All tests 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
golang:1.21-bookwormeclipse-temurin:17-jdknikolaik/python-nodejs:python3.12-nodejs22Pull (multi-arch manifest)
Run
All tags pushed for this build
The
68257ddtag is a multi-arch manifest (amd64/arm64); your client pulls the right arch automatically.