Skip to content

refactor(llm): add LiteLLM-backed provider abstraction - #2363

Merged
enyst merged 21 commits into
mainfrom
openhands/llm-provider-abstraction
Jul 31, 2026
Merged

enyst merged 21 commits into
mainfrom
openhands/llm-provider-abstraction

Conversation

@enyst

@enyst enyst commented Mar 9, 2026 •

Copy link
Copy Markdown
Member

HUMAN:
This PR proposes to abstract a provider out of the mixed string "provider/model" that we were using.

  • A human has tested these changes.

AGENT:

The AGENT section was generated and updated by OpenHands on behalf of the user.

Why

A provider abstraction is useful for other things in the future, such as defining keys per provider, thus saving time and annoyance for the user who needs to enter the same provider key for every LLM profile that has a model from the same provider. Endless copy-paste at various intervals is no fun.

Summary

Refactor SDK LLM provider handling around an internal LLMProvider helper backed by LiteLLM, so provider-specific logic stops re-splitting raw provider/model strings across the SDK.

This PR now takes the simpler direction discussed in issue #2274 and PR review:

  • accept the full model string at the SDK boundary
  • parse it once with LiteLLM
  • use LiteLLM's parsed provider + model view for LiteLLM-facing runtime paths
  • initialize LiteLLM transport provider parsing once per LLM instance instead of refreshing provider state during each transport call

Concretely, this PR:

  • adds openhands.sdk.llm.utils.litellm_provider.LLMProvider as a thin wrapper around LiteLLM provider parsing, provider model info lookup, API base inference, and call kwargs generation
  • keeps LLMProvider focused on LiteLLM's parsed runtime shape (provider, parsed model) plus the user-requested API base, rather than storing duplicate requested_* fields
  • updates LLM chat/responses transport calls to use provider-owned LiteLLM kwargs generation (model + custom_llm_provider, plus Bedrock-aware api_key forwarding) instead of repeatedly passing or re-splitting the full string
  • moves Bedrock-specific LiteLLM api_key handling into LLMProvider so provider-sensitive transport behavior lives alongside provider parsing
  • updates telemetry cost calculation to reuse the same parsed provider/model view
  • keeps capability and model_features lookups on the canonical model string (model_canonical_name or model) instead of introducing a second provider abstraction
  • initializes transport provider parsing once during LLM setup, so chat/responses transport paths reuse the same resolved provider metadata for the lifetime of the instance
  • removes dead provider inference wrappers that became redundant after the simplification
  • adds focused tests for the slimmer helper and the updated transport/canonical capability lookup behavior
  • forwards the user-configured base_url (or None) verbatim as api_base, discarding LiteLLM's post-resolution base (which can be rewritten, e.g. mistral appends /v1, or have a provider default injected), so what we send to LiteLLM matches main
  • adds tests that lock in verbatim custom-base forwarding and prove (via LiteLLM's own get_llm_provider) that sending parsed model + custom_llm_provider resolves identically to sending the full provider/model string

Closes #2274.

How to Test

  • Run uv run pytest tests/sdk/llm -q (verified: 936 passed).
  • Run uv run pre-commit run --files openhands-sdk/openhands/sdk/llm/llm.py openhands-sdk/openhands/sdk/llm/utils/litellm_provider.py openhands-sdk/openhands/sdk/llm/utils/telemetry.py tests/sdk/llm/test_litellm_provider.py tests/sdk/llm/test_llm.py tests/sdk/llm/test_llm_telemetry.py (verified: all applicable hooks passed).
  • The model-copy regression test exercises both shallow and deep copies and verifies transport and cost calculation use the same parsed provider metadata.

Checklist

  • If the PR is changing/adding functionality, are there tests to reflect this?
  • If there is an example, have you run the example to make sure that it works? (N/A: no example changes)
  • If there are instructions on how to run the code, have you followed the instructions and made sure that it works?
  • If the feature is significant enough to require documentation, is there a PR open on the OpenHands/docs repository with the same branch name? (N/A: internal refactor)
  • Is the github CI passing? (pending)

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

Run

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

All tags pushed for this build

ghcr.io/openhands/agent-server:7fb2c0a-golang-amd64
ghcr.io/openhands/agent-server:7fb2c0a7a2b7a17f51c4f0215b3be90a24a20a76-golang-amd64
ghcr.io/openhands/agent-server:openhands-llm-provider-abstraction-golang-amd64
ghcr.io/openhands/agent-server:7fb2c0a-golang_tag_1.21-bookworm-amd64
ghcr.io/openhands/agent-server:7fb2c0a-golang-arm64
ghcr.io/openhands/agent-server:7fb2c0a7a2b7a17f51c4f0215b3be90a24a20a76-golang-arm64
ghcr.io/openhands/agent-server:openhands-llm-provider-abstraction-golang-arm64
ghcr.io/openhands/agent-server:7fb2c0a-golang_tag_1.21-bookworm-arm64
ghcr.io/openhands/agent-server:7fb2c0a-java-amd64
ghcr.io/openhands/agent-server:7fb2c0a7a2b7a17f51c4f0215b3be90a24a20a76-java-amd64
ghcr.io/openhands/agent-server:openhands-llm-provider-abstraction-java-amd64
ghcr.io/openhands/agent-server:7fb2c0a-eclipse-temurin_tag_17-jdk-amd64
ghcr.io/openhands/agent-server:7fb2c0a-java-arm64
ghcr.io/openhands/agent-server:7fb2c0a7a2b7a17f51c4f0215b3be90a24a20a76-java-arm64
ghcr.io/openhands/agent-server:openhands-llm-provider-abstraction-java-arm64
ghcr.io/openhands/agent-server:7fb2c0a-eclipse-temurin_tag_17-jdk-arm64
ghcr.io/openhands/agent-server:7fb2c0a-python-amd64
ghcr.io/openhands/agent-server:7fb2c0a7a2b7a17f51c4f0215b3be90a24a20a76-python-amd64
ghcr.io/openhands/agent-server:openhands-llm-provider-abstraction-python-amd64
ghcr.io/openhands/agent-server:7fb2c0a-nikolaik_s_python-nodejs_tag_python3.13-nodejs22-slim-amd64
ghcr.io/openhands/agent-server:7fb2c0a-python-arm64
ghcr.io/openhands/agent-server:7fb2c0a7a2b7a17f51c4f0215b3be90a24a20a76-python-arm64
ghcr.io/openhands/agent-server:openhands-llm-provider-abstraction-python-arm64
ghcr.io/openhands/agent-server:7fb2c0a-nikolaik_s_python-nodejs_tag_python3.13-nodejs22-slim-arm64
ghcr.io/openhands/agent-server:7fb2c0a-golang
ghcr.io/openhands/agent-server:7fb2c0a7a2b7a17f51c4f0215b3be90a24a20a76-golang
ghcr.io/openhands/agent-server:openhands-llm-provider-abstraction-golang
ghcr.io/openhands/agent-server:7fb2c0a-golang_tag_1.21-bookworm
ghcr.io/openhands/agent-server:7fb2c0a-java
ghcr.io/openhands/agent-server:7fb2c0a7a2b7a17f51c4f0215b3be90a24a20a76-java
ghcr.io/openhands/agent-server:openhands-llm-provider-abstraction-java
ghcr.io/openhands/agent-server:7fb2c0a-eclipse-temurin_tag_17-jdk
ghcr.io/openhands/agent-server:7fb2c0a-python
ghcr.io/openhands/agent-server:7fb2c0a7a2b7a17f51c4f0215b3be90a24a20a76-python
ghcr.io/openhands/agent-server:openhands-llm-provider-abstraction-python
ghcr.io/openhands/agent-server:7fb2c0a-nikolaik_s_python-nodejs_tag_python3.13-nodejs22-slim

About Multi-Architecture Support

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

Introduce an internal LLMProvider helper that wraps LiteLLM provider parsing,
provider model info lookup, and provider-aware API base inference.

Use the helper in LLM and Telemetry so Bedrock auth handling and
cost-calculation model/provider routing stop manually splitting model
strings. Extend model_features to accept an LLMProvider so provider-aware
rules can operate on parsed provider/model data while keeping the raw model
string available.

Add focused tests for the new helper and the updated feature lookup paths.

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

github-actions Bot commented Mar 9, 2026 •

Copy link
Copy Markdown
Contributor

Python API breakage checks — ✅ PASSED

Result: ✅ PASSED

Action log

@github-actions

github-actions Bot commented Mar 9, 2026 •

Copy link
Copy Markdown
Contributor

REST API breakage checks (OpenAPI) — ✅ PASSED

Result: ✅ PASSED

Action log

@github-actions

github-actions Bot commented Mar 9, 2026 •

Copy link
Copy Markdown
Contributor

Coverage

Coverage Report •
FileStmtsMissCoverMissing
openhands-sdk/openhands/sdk/llm
   llm.py10559291%669, 685, 724–725, 730, 836, 852, 1035, 1075–1077, 1111, 1118, 1268, 1396, 1599, 1603–1604, 1713, 1717–1718, 1781, 1788, 1799, 1863, 1867–1868, 1940, 1947, 1957, 1964, 1975, 2025, 2038, 2056, 2070, 2072, 2074, 2099, 2101, 2110–2111, 2184, 2405, 2561–2562, 2872–2873, 2882, 2900, 2927–2928, 2930, 2932, 2934, 2942, 2945, 2947, 2949, 2960–2961, 2969, 2972, 2975–2976, 2987–2989, 2993, 2997–2998, 3003, 3013, 3018, 3082, 3084, 3086–3089, 3091–3094, 3099–3102, 3117, 3128, 3188, 3190
openhands-sdk/openhands/sdk/llm/utils
   model_features.py141299%41, 311
   telemetry.py1781393%135, 160, 166–167, 177, 189–190, 229, 357, 359, 373, 379, 384
TOTAL386831108371% 

Rework the new LLMProvider helper so it no longer keeps both raw and
parsed model strings internally.

Accept full model strings at the SDK boundary, then immediately normalize to
LiteLLM's parsed provider/model pair for transport, telemetry, and feature
checks. Unknown models still remain opaque strings, but the provider
abstraction itself now avoids duplicate raw-vs-parsed state.

Also route chat/responses calls through parsed provider kwargs and tighten the
associated tests.

Co-authored-by: openhands <openhands@all-hands.dev>
Comment thread openhands-sdk/openhands/sdk/llm/llm.py Resolved
Keep LLMProvider for LiteLLM-facing transport logic only and use the canonical model string for capability/feature lookups.

Co-authored-by: openhands <openhands@all-hands.dev>
Comment thread openhands-sdk/openhands/sdk/AGENTS.md Resolved
Co-authored-by: openhands <openhands@all-hands.dev>
Comment thread openhands-sdk/openhands/sdk/llm/llm.py Resolved
Co-authored-by: openhands <openhands@all-hands.dev>
Comment thread openhands-sdk/openhands/sdk/llm/llm.py Resolved
@enyst

enyst commented Mar 18, 2026

Copy link
Copy Markdown
Member Author

@OpenHands Babysit this PR, monitor CI, fix until green.

@openhands-ai

openhands-ai Bot commented Mar 18, 2026

Copy link
Copy Markdown

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

@openhands-ai

openhands-ai Bot commented Mar 18, 2026

Copy link
Copy Markdown

Final summary:

  • Checked out context for PR refactor(llm): add LiteLLM-backed provider abstraction #2363 on branch openhands/llm-provider-abstraction
  • Verified the PR status and CI results using GitHub tooling
  • Confirmed all checks are green: 27 successful, 1 skipped, 0 failing, 0 pending
  • Confirmed the review-thread gate is also passing
  • Determined no code changes were needed, because there was nothing failing to fix

Conciseness:

  • No repository files were changed
  • No extraneous changes were introduced
  • No commit or push was necessary

Current state:

PR link: #2363

@enyst

enyst commented Mar 19, 2026

Copy link
Copy Markdown
Member Author

@OpenHands /codereview-roasted

@openhands-ai

openhands-ai Bot commented Mar 19, 2026

Copy link
Copy Markdown

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

@enyst enyst left a comment

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.

🔴 Needs improvement

[CRITICAL ISSUES]

  • [openhands-sdk/openhands/sdk/llm/llm.py, Lines 495-499, 893-899, 1049-1056] Breaking change / duplicate state: _provider_info is cached once during initialization and then reused for every transport call. That would be fine if LLM were actually immutable, but it isn't: model_copy(update=...) shallow-copies private attrs and does not rerun validators. So a copy with an updated model or base_url now keeps stale provider metadata. I verified this locally: copying a gpt-4o LLM with model_copy(update={"model": "ollama/llama2"}) leaves _provider_info as openai/gpt-4o, so transport kwargs are wrong. The old code re-inferred provider from self.model/self.base_url on each call, so this is a real regression introduced by the refactor.

[TESTING GAPS]

  • [tests/sdk/llm/test_llm.py, Lines 419-430] Missing regression test: the new tests only prove _provider_info is initialized on construction. Add coverage for model_copy(update={"model": ...}) and model_copy(update={"base_url": ...}) (or make those operations impossible). Right now the exact stale-cache failure mode above isn't exercised at all.

VERDICT: ❌ Needs rework

KEY INSIGHT: this refactor adds a second source of truth for provider routing, and because LLM instances are still copyable/mutable, that cached state can drift away from the public model/base_url fields.

Leaving this as a comment review rather than approval because this touches LLM runtime behavior and could affect eval-facing execution paths.

@openhands-ai

This comment was marked as duplicate.

@all-hands-bot

Copy link
Copy Markdown
Collaborator

[Automatic Post]: It has been a while since there was any activity on this PR. @enyst, are you still working on it? If so, please go ahead, if not then please request review, close it, or request that someone else follow up.

2 similar comments
@all-hands-bot

Copy link
Copy Markdown
Collaborator

[Automatic Post]: It has been a while since there was any activity on this PR. @enyst, are you still working on it? If so, please go ahead, if not then please request review, close it, or request that someone else follow up.

@all-hands-bot

Copy link
Copy Markdown
Collaborator

[Automatic Post]: It has been a while since there was any activity on this PR. @enyst, are you still working on it? If so, please go ahead, if not then please request review, close it, or request that someone else follow up.

@enyst enyst closed this May 8, 2026
@enyst enyst reopened this Jun 6, 2026
Co-authored-by: openhands <openhands@all-hands.dev>
@all-hands-bot

Copy link
Copy Markdown
Collaborator

[Automatic Post]: It has been a while since there was any activity on this PR. @enyst, are you still working on it? If so, please go ahead, if not then please request review, close it, or request that someone else follow up.

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

@enyst

enyst commented Jun 25, 2026

Copy link
Copy Markdown
Member Author

@OpenHands understand this PR deeply, and merge main into it fixing conflicts carefully.

Then take a step back and tell me what it's missing until we submit it for review. In particular, I want to know if its goal is clear to you and if we're achieving it; and if live tests confirm that it works without regressions.

@openhands-ai

openhands-ai Bot commented Jun 25, 2026

Copy link
Copy Markdown

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

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

enyst commented Jun 25, 2026

Copy link
Copy Markdown
Member Author

I merged current origin/main into this PR branch and pushed the result as 093d811ba38e64e628a58241543768dd542db1d0.

Conflict handling:

  • The only content conflict was in openhands-sdk/openhands/sdk/llm/llm.py.
  • I kept this PR's LLMProvider transport metadata path and combined it with main's newer subscription-auth and Vertex preflight changes:
    • chat/responses kwargs now still come from provider_info.as_litellm_call_kwargs(...)
    • subscription access tokens / extra headers are still injected on sync and async paths
    • Bedrock api-key stripping still lives in LLMProvider
    • Vertex SDK preflight still runs before chat transport calls

Local validation passed:

  • uv run pre-commit run --files openhands-sdk/openhands/sdk/llm/llm.py
  • uv run pytest tests/sdk/llm/test_litellm_provider.py tests/sdk/llm/test_llm.py tests/sdk/llm/test_llm_completion.py tests/sdk/llm/test_llm_telemetry.py tests/sdk/llm/auth/test_openai.py tests/sdk/llm/test_vertex_preflight.py tests/cross/test_conversation_restore_behavior.py -q → 184 passed
  • uv run pytest tests/sdk/llm -q → 862 passed

Live smoke tests that worked:

  • SDK chat through OpenHands/LiteLLM proxy: openhands/openai/gpt-4o-mini on https://llm-proxy.eval.all-hands.dev → parsed as litellm_proxy + openai/gpt-4o-mini, returned the expected response
  • SDK chat direct OpenAI: openai/gpt-4o-mini → parsed as openai + gpt-4o-mini, returned the expected response
  • SDK Responses direct OpenAI: openai/gpt-4.1-mini → parsed as openai + gpt-4.1-mini, returned the expected response
  • SDK Responses through OpenHands/LiteLLM proxy: openhands/openai/gpt-4.1-mini → parsed as litellm_proxy + openai/gpt-4.1-mini, returned the expected response

Live coverage caveats:

  • I could not validate direct Anthropic because the available Anthropic account returned an insufficient-credit error.
  • Some Claude proxy aliases I tried were blocked by proxy/model configuration rather than SDK transport behavior, so I would not treat those attempts as regressions.

Assessment:

  • The goal is clear to me: make LiteLLM provider parsing a single internal runtime abstraction while preserving the public LLM.model boundary string.
  • I think the PR is achieving that goal for the intended internal refactor. The transport paths now use one parsed provider/model view, while capability lookups still intentionally stay on model_canonical_name or model.
  • What this PR does not yet do is the future product-level provider-key/profile UX. It lays the runtime foundation, but it is not itself the provider-key settings feature.

What is still missing before I would call it review/merge-ready:

  1. The fresh post-merge GitHub CI run needs to finish green. At the time I checked, several checks were already green, but the full rollup was still running/queued, so mergeStateStatus was still BLOCKED.
  2. Because this changes LLM transport kwargs globally, I would prefer maintainer confidence from either full CI plus the live smoke tests above, or a lightweight integration/eval pass on representative production models. The live tests cover OpenAI and OpenHands proxy chat/responses paths, but not Bedrock/Azure/OpenRouter/Vertex live calls.
  3. There is a pre-existing-looking model_copy(update={"model": ...}) quirk worth deciding on separately: this PR refreshes provider metadata for the copied LLM, but metrics/telemetry private attrs still preserve the original model name unless a registry resets them. Tests cover the transport refresh, not metrics identity for that copied-object case. I do not think that blocks this provider abstraction unless we want model_copy(model=...) to be a fully supported runtime switching API.

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

@OpenHands OpenHands deleted a comment from openhands-ai Bot Jun 25, 2026
@all-hands-bot

Copy link
Copy Markdown
Collaborator

[Automatic Post]: It has been a while since there was any activity on this PR. @enyst, are you still working on it? If so, please go ahead, if not then please request review, close it, or request that someone else follow up.

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

2 similar comments
@all-hands-bot

Copy link
Copy Markdown
Collaborator

[Automatic Post]: It has been a while since there was any activity on this PR. @enyst, are you still working on it? If so, please go ahead, if not then please request review, close it, or request that someone else follow up.

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

@all-hands-bot

Copy link
Copy Markdown
Collaborator

[Automatic Post]: It has been a while since there was any activity on this PR. @enyst, are you still working on it? If so, please go ahead, if not then please request review, close it, or request that someone else follow up.

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

@all-hands-bot

Copy link
Copy Markdown
Collaborator

[Automatic Post]: It has been a while since there was any activity on this PR. @enyst, are you still working on it? If so, please go ahead, if not then please request review, close it, or request that someone else follow up.

This comment was created by an AI agent (OpenHands) on behalf of the repository maintainers.

@all-hands-bot

Copy link
Copy Markdown
Collaborator

[Automatic Post]: It has been a while since there was any activity on this PR. @enyst, are you still working on it? If so, please go ahead, if not then please request review, close it, or request that someone else follow up.

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

@all-hands-bot

Copy link
Copy Markdown
Collaborator

[Automatic Post]: It has been a while since there was any activity on this PR. @enyst, are you still working on it? If so, please go ahead, if not then please request review, close it, or request that someone else follow up.

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

@all-hands-bot

Copy link
Copy Markdown
Collaborator

🤖 OpenHands is reviewing this PR.

Head commit: 093d811ba38e64e628a58241543768dd542db1d0
View the conversation: https://oss-agent-canvas.ngrok.dev/conversations/17461bef-e57a-41c1-a569-f554e58245e9

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

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

Review: refactor(llm): add LiteLLM-backed provider abstraction

Overall this is a clean, well-scoped refactor that centralizes LiteLLM provider parsing into LLMProvider and addresses the stale-cache regression flagged in earlier reviews via the new model_copy override. I ran the LLM test suite locally (tests/sdk/llm/test_litellm_provider.py, test_llm.py, test_llm_completion.py, test_llm_telemetry.py, test_api_key_validation.py, test_model_features.py) — 314 passed. The transport kwargs (model + custom_llm_provider + Bedrock-aware api_key forwarding) are semantically equivalent to the prior per-call inference for the cases I exercised, and resolved_api_base correctly preserves None/custom-base behavior.

Risk assessment: 🟡 MEDIUM — this re-routes all completion/responses transport kwargs and cost calculation, so it can affect eval-facing paths. No security issues found; api_key handling is preserved.

Findings

  1. Unused provider-surface cluster (maintainability). LLMProvider.provider_enum, model_info, canonical_name, infer_api_base, and _api_base_or_none are not consumed by any runtime path — infer_api_base is referenced only by tests, and the rest only by infer_api_base. The PR description and the new AGENTS.md note explicitly call out removing "dead provider inference wrappers," so shipping a new batch of unused inference helpers works against that goal. Either wire infer_api_base into a real consumer or drop the cluster to keep the helper focused on the parsed runtime shape (model/name/resolved_api_base) that transport actually uses. See inline.

  2. Telemetry re-parses the provider per cost computation (minor inconsistency). _compute_cost constructs a fresh LLMProvider.from_model(...) on every call, which partially undercuts the PR's stated goal of parsing once per LLM instance. Telemetry only receives model_name, so it can't reuse the LLM-cached _provider_info. Not a bug (the old code also re-split per call), but if the parse-once goal matters, consider threading the parsed provider info into Telemetry. See inline.

  3. Cost-calc input change for slash-less models (behavioral). Previously telemetry sent model=<bare> with no custom_llm_provider for models without a /; now it sends custom_llm_provider=<inferred> (e.g. openai for gpt-4o). This is generally more correct, but it is a real change to the inputs handed to litellm_completion_cost and could shift cost results for models where LiteLLM's provider inference differs from its name-only lookup. Worth a conscious ack; the updated test_compute_cost_model_name_processing covers the happy path but not the no-slash inference delta.

  4. PR-description REST contract summary looks unrelated. The agent-server-rest-api-contract-summary block advertises new /api/plugins/marketplace schemas and renamed MarketplaceCatalogResponse schemas, but none of the 12 changed files touch agent-server plugins/skills routers — every file is SDK LLM internals or tests. This is most likely a base-branch drift artifact, but reviewers should confirm it isn't accidental scope leaking into the PR description.

What looks good

  • The model_copy override (refreshing _provider_info only when model/base_url are in update) cleanly resolves the stale-cache regression and correctly avoids spurious refreshes for caching_prompt-only copies.
  • Bedrock api_key stripping is now colocated with provider parsing in api_key_for_litellm, matching the AGENTS.md guidance.
  • get_features(model: str | None) correctly widens the signature to match helpers that already accepted None, removing a # type: ignore.
  • cached_property on a frozen=True dataclass works (writes to __dict__, doesn't break __hash__/equality), verified at runtime.
  • New tests cover model_copy refresh for both model and base_url updates, nested OpenRouter parsing, Bedrock api_key stripping, and unknown-model fallback.

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

@enyst

enyst commented Jul 31, 2026

Copy link
Copy Markdown
Member Author

@OpenHands Understand this PR and merge main into it, fixing conflicts carefully. Then take a step back and look at this review: #2363 (review) and its inline threads. Think deeply if it is valid because note, it's generated by an AI; if you think it's valid address it. Reply and solve as you see fit.

@openhands-ai

openhands-ai Bot commented Jul 31, 2026

Copy link
Copy Markdown

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

enyst and others added 2 commits July 31, 2026 17:39
Co-authored-by: openhands <openhands@all-hands.dev>
Remove unused provider inference helpers and pass the parsed transport provider into telemetry cost calculation, while retaining fallback parsing for standalone telemetry callers.

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

openhands-ai Bot commented Jul 31, 2026

Copy link
Copy Markdown

Completed work on PR #2363.

  • Merged latest main in commit 015cbfd5, carefully resolving conflicts in llm.py and model_features.py.
  • Determined both inline review findings were valid.
  • In commit 1a40ce15:
    • removed unused LLMProvider model-info/API-base helpers;
    • reused the cached parsed provider for telemetry cost calculation;
    • retained fallback parsing for standalone Telemetry callers;
    • added regression coverage for shallow/deep model copies and slash-less provider inference.
  • Replied to and resolved both inline review threads.
  • Removed the stale REST contract summary caused by base-branch drift.
  • Added the newly required How to Test PR section without changing the HUMAN note.

Validation:

  • Local LLM suite: 936 passed.
  • Pre-commit: all applicable hooks passed, including Ruff and Pyright.
  • GitHub CI: 34 successful, 5 skipped, 0 failing, 0 pending.
  • PR status: CLEAN, APPROVED, and ready to merge.

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

Review: refactor(llm): add LiteLLM-backed provider abstraction

Reviewed the full diff plus surrounding code in llm.py, litellm_provider.py, telemetry.py, and the test changes. I ran tests/sdk/llm (936 passed) and the cross/settings/switch tests (all green).

Overall verdict: Approve with minor observations. This is a clean, well-scoped refactor. Parsing the provider once at LLM setup and reusing the parsed provider/model view across transport, auth, and cost calculation is a real improvement over re-splitting raw provider/model strings ad hoc. Bedrock api_key suppression is correctly preserved and moved next to provider parsing. The new LLMProvider is small, frozen, and focused.

Risk assessment: Low. No security regressions; secret handling is unchanged. The one behavioral nuance worth flagging is the resolved_api_base source change (see inline).

Strengths

  • _refresh_litellm_metadata eagerly rebuilds provider info + capabilities, which actually fixes a latent issue: previously model_copy(update={"model": X}) produced an LLM with stale _model_info/token caps from the original model (validators don't re-run on model_copy). The new refresh path corrects that.
  • The from_model failure path is robust: it never returns None, so the assert provider_info is not None guards in transport are safe — _provider_info is always populated after _post_init.
  • Tests cover the helper, transport kwargs, cost kwargs, the model-copy refresh (shallow + deep), and the base_url-only refresh.

Observations (non-blocking)

  1. resolved_api_base now drives transport api_base. Previously transport spread self._litellm_call_kwargs(), so api_base was the raw self.base_url (or None). Now it is provider_info.resolved_api_base, i.e. LiteLLM's post-resolution base. For most providers this is identical, but for providers where get_llm_provider injects a default (e.g. mistral -> https://api.mistral.ai/v1) or appends a suffix to a user-supplied base, the value sent explicitly changes. This is almost always equivalent to what LiteLLM would infer internally, but it is a subtle, undocumented behavior change for custom-base provider endpoints. Worth a line in the PR description / a test asserting a custom base_url is forwarded as-is for an unrecognized model (the local-LLM case) to lock in the no-regression guarantee.
  2. Eager work on model_copy. _refresh_litellm_metadata -> _init_model_info_and_caps can make a network call (get_litellm_model_info does an httpx.get against the proxy for litellm_proxy/ models). model_copy is now O(network) when model/base_url change, whereas it used to be free. The only runtime caller that changes the model is the switch path (once per switch), so this is acceptable, but it's a good reason the caching_prompt-only copy path correctly stays exempt.

No material correctness or security issues found.

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

Comment thread openhands-sdk/openhands/sdk/llm/llm.py Resolved
Comment thread openhands-sdk/openhands/sdk/llm/llm.py Resolved
Keep transport behavior identical to main: forward the user-configured
base_url (or None) instead of LiteLLM's post-resolution api_base, which
may be rewritten (e.g. mistral appends /v1) or have a default injected.
Add tests locking in verbatim custom-base forwarding and proving the
parsed model + custom_llm_provider kwargs resolve identically to the
full provider/model string inside LiteLLM.

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

enyst commented Jul 31, 2026

Copy link
Copy Markdown
Member Author

Behavior-parity audit vs main (per @enyst's request)

I audited every kwarg this PR sends to LiteLLM against main and fixed the one real difference. Pushed in 7fb2c0a.

What differed and was fixed

  • api_base — the branch forwarded LiteLLM's post-resolution base (resolved_api_base) instead of the raw base_url. LiteLLM can rewrite that value (mistral appends /v1 to a custom base) or inject a provider default where main sent None. Fixed: the user-configured base_url (or None) is now forwarded verbatim, exactly as on main, and LiteLLM keeps doing its own per-call resolution.

What differs in shape but is provably equivalent

  • model + custom_llm_provider — main sent the full "provider/model" string; the branch sends LiteLLM's parsed model plus custom_llm_provider. test_split_kwargs_equivalent_to_full_model_string proves via LiteLLM's own get_llm_provider that both forms resolve to identical provider/model/api_base for openai, anthropic, openrouter (nested slashes), mistral (custom base), litellm_proxy, and local OpenAI-compatible endpoints.
  • api_key omission when None — main passed api_key=None explicitly; the branch omits the kwarg. LiteLLM's default for api_key is None, so this is a no-op.
  • cost calculation — for slash-less models (e.g. gpt-4o), custom_llm_provider is now passed to litellm_completion_cost where main passed none; this only affects internal cost lookup (more precise), never the completion request itself. Already covered by existing telemetry tests.

New tests locking parity in

  • test_llm_forwards_custom_base_url_as_is — custom base forwarded untouched for a local OpenAI-compatible endpoint and for mistral (the rewrite-prone case).
  • test_llm_forwards_none_api_base_when_no_base_url — no provider default leaks into api_base when base_url is unset.
  • test_llm_provider_keeps_requested_api_base_verbatim + test_split_kwargs_equivalent_to_full_model_string at the helper level.

Live verification (one small call, as suggested)

Ran a real openai/gpt-4o-mini completion with a spy on litellm_completion: wire kwargs were model='gpt-4o-mini', custom_llm_provider='openai', api_base=None; response returned and cost was recorded ($0.00000255). (Tried anthropic first but that key is out of credits.)

Validation: uv run pytest tests/sdk/llm -q → 946 passed; pre-commit hooks pass on all touched files.

This comment was created by an AI agent (OpenHands) on behalf of enyst.

@all-hands-bot

Copy link
Copy Markdown
Collaborator

🚦 CI is currently failing on this PR's latest commit.

Please fix the failing checks before OpenHands reviews it - this is re-checked automatically once you push a new commit. (A maintainer can also request @all-hands-bot as a reviewer to have it reviewed regardless of CI status.)

This is an automated check - no AI was used to generate this comment.

@all-hands-bot

Copy link
Copy Markdown
Collaborator

🤖 OpenHands is reviewing this PR.

Head commit: 7fb2c0a7a2b7a17f51c4f0215b3be90a24a20a76
View the conversation: https://oss-agent-canvas.ngrok.dev/conversations/ef76604e-834b-4ef3-b6ec-75e631ce9992

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

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

Review: refactor(llm): add LiteLLM-backed provider abstraction

Summary

This is a clean, well-scoped refactor. It replaces ad-hoc provider/model string splitting (in llm.py, telemetry.py, and the old infer_litellm_provider wrapper) with a single LLMProvider dataclass that parses the model string once via LiteLLM's get_llm_provider and exposes the parsed provider + model + verbatim api_base for all LiteLLM-facing runtime paths. The design aligns with the repo's stated principle of accepting the full model string at the boundary and normalizing once.

Correctness

  • Provider parsing is initialized once per LLM in _post_init (_refresh_litellm_metadata) and reused for the lifetime of the instance, replacing the prior lazy _litellm_provider cache. The model_copy override correctly rebuilds derived metadata when model or base_url change, and leaves it untouched otherwise (e.g. the stream/usage_id/secret-field copies used throughout the codebase). I verified the update-key guard covers exactly the fields that feed _litellm_call_kwargs (model, base_url); api_version and other transport fields are not part of provider parsing, so the check is complete.
  • Bedrock api_key stripping is preserved and moved into LLMProvider.api_key_for_litellm. The transport paths call _get_litellm_auth_values (which already normalizes via _normalize_litellm_api_key_value -> provider_info.api_key_for_litellm) and then pass the result into as_litellm_call_kwargs(api_key=...), which normalizes again. The second normalization is redundant for the internal path but harmless and provides defense-in-depth for the externally-supplied auth_values path (subscription credentials). No correctness issue.
  • Verbatim api_base forwarding is a real improvement: discarding LiteLLM's resolved api_base (which can be rewritten, e.g. mistral /v1 appending, or have a provider default injected) prevents freezing per-call resolution at parse time. The parametrized equivalence test (test_split_kwargs_equivalent_to_full_model_string) proves the parsed model + custom_llm_provider form resolves identically to the full string via LiteLLM's own get_llm_provider, locking in wire-equivalence.
  • Cost calculation now reuses the same LLMProvider view instead of re-splitting on /. For OpenHands-provider models this yields litellm_proxy + bare model -- identical to the old split("/", 1) result. The telemetry fallback (when provider_info is None, e.g. direct Telemetry use in tests) reconstructs from litellm_call_kwargs(self.model_name, None), matching the LLM-driven path.
  • Capability/feature lookups correctly stay on the canonical model string (model_canonical_name or model), avoiding a second provider abstraction. The model_features.py changes widening signatures to str | None are consistent and the "claude" in (model or "") guard is the right defensive adjustment.

Tests

Good coverage: the new test_litellm_provider.py exercises nested OpenRouter parsing, Bedrock parsing + api_key stripping, unknown-model fallback, verbatim base forwarding, and the cross-form equivalence matrix. The test_llm.py additions cover transport kwargs, Bedrock non-forwarding, model_copy refresh (shallow + deep, model + base_url), and custom/None base forwarding. The telemetry test was updated to assert the parsed provider/model pair. The cross-repo restore test was updated to assert custom_llm_provider separately, which is the right shape after the refactor.

Behavior changes worth noting (non-blocking)

  • model_copy(update={"base_url": ...}) now re-runs _init_model_info_and_caps (which may hit the LiteLLM proxy for model info), whereas previously model_copy never refreshed model info. This is arguably more correct (model-info fetch can depend on base_url) and is covered by test_llm_model_copy_refreshes_provider_for_base_url_update, but it does introduce a possible network call on base-url copies that did not occur before. No in-repo caller copies base_url in a hot path, so impact is negligible; flagging for awareness.

Maintainability / Style

  • LLMProvider is a focused frozen dataclass with well-placed comments explaining the non-obvious api_base discard decision. Provider-sensitive transport behavior (Bedrock api_key) now lives alongside provider parsing, which is an improvement over the prior scattered conditionals.
  • The assert provider_info is not None guards in the transport methods are safe given _post_init always populates _provider_info and model_copy preserves/refreshes it; LLM.model_construct (which bypasses validators) is not used anywhere in the codebase.

Security

No new concerns. api_key handling is unchanged in effect; from_model's debug log only records the model string and exception, never credentials.

Risk assessment

Low risk. This is an internal refactor with no public API changes, strong equivalence tests proving wire-behavior parity, and preserved Bedrock/subscription/auth semantics. The only behavioral delta (model-info refresh on base_url copy) is intentional, tested, and not exercised by hot paths.

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

@enyst
enyst merged commit ac225e5 into main Jul 31, 2026
44 of 46 checks passed
@enyst
enyst deleted the openhands/llm-provider-abstraction branch July 31, 2026 20:20
@github-actions github-actions Bot mentioned this pull request Aug 1, 2026
5 of 7 tasks
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.

Refactoring Proposal: Large Classes Identified for Decomposition

3 participants