Repository navigation
refactor(llm): add LiteLLM-backed provider abstraction - #2363
Conversation
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>
Python API breakage checks — ✅ PASSEDResult: ✅ PASSED |
REST API breakage checks (OpenAPI) — ✅ PASSEDResult: ✅ PASSED |
Coverage Report •
|
|||||||||||||||||||||||||||||||||||
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>
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>
Co-authored-by: openhands <openhands@all-hands.dev>
Co-authored-by: openhands <openhands@all-hands.dev>
Co-authored-by: openhands <openhands@all-hands.dev>
Co-authored-by: openhands <openhands@all-hands.dev>
|
@OpenHands Babysit this PR, monitor CI, fix until green. |
|
I'm on it! enyst can track my progress at all-hands.dev |
|
Final summary:
Conciseness:
Current state:
PR link: #2363 |
|
@OpenHands /codereview-roasted |
|
I'm on it! enyst can track my progress at all-hands.dev |
enyst
left a comment
There was a problem hiding this comment.
🔴 Needs improvement
[CRITICAL ISSUES]
- [openhands-sdk/openhands/sdk/llm/llm.py, Lines 495-499, 893-899, 1049-1056] Breaking change / duplicate state:
_provider_infois cached once during initialization and then reused for every transport call. That would be fine ifLLMwere actually immutable, but it isn't:model_copy(update=...)shallow-copies private attrs and does not rerun validators. So a copy with an updatedmodelorbase_urlnow keeps stale provider metadata. I verified this locally: copying agpt-4oLLM withmodel_copy(update={"model": "ollama/llama2"})leaves_provider_infoasopenai/gpt-4o, so transport kwargs are wrong. The old code re-inferred provider fromself.model/self.base_urlon 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_infois initialized on construction. Add coverage formodel_copy(update={"model": ...})andmodel_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.
This comment was marked as duplicate.
This comment was marked as duplicate.
|
[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
|
[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. |
|
[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. |
Co-authored-by: openhands <openhands@all-hands.dev>
|
[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. |
|
@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. |
|
I'm on it! enyst can track my progress at all-hands.dev |
Co-authored-by: openhands <openhands@all-hands.dev>
|
I merged current Conflict handling:
Local validation passed:
Live smoke tests that worked:
Live coverage caveats:
Assessment:
What is still missing before I would call it review/merge-ready:
This PR comment was created by an AI agent (OpenHands) on behalf of the user. |
|
[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
|
[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. |
|
[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. |
|
[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. |
|
[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. |
|
[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. |
|
🤖 OpenHands is reviewing this PR. Head commit: This comment was posted by an AI agent (OpenHands). |
all-hands-bot
left a comment
There was a problem hiding this comment.
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
-
Unused provider-surface cluster (maintainability).
LLMProvider.provider_enum,model_info,canonical_name,infer_api_base, and_api_base_or_noneare not consumed by any runtime path —infer_api_baseis referenced only by tests, and the rest only byinfer_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 wireinfer_api_baseinto 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. -
Telemetry re-parses the provider per cost computation (minor inconsistency).
_compute_costconstructs a freshLLMProvider.from_model(...)on every call, which partially undercuts the PR's stated goal of parsing once perLLMinstance.Telemetryonly receivesmodel_name, so it can't reuse theLLM-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 intoTelemetry. See inline. -
Cost-calc input change for slash-less models (behavioral). Previously telemetry sent
model=<bare>with nocustom_llm_providerfor models without a/; now it sendscustom_llm_provider=<inferred>(e.g.openaiforgpt-4o). This is generally more correct, but it is a real change to the inputs handed tolitellm_completion_costand could shift cost results for models where LiteLLM's provider inference differs from its name-only lookup. Worth a conscious ack; the updatedtest_compute_cost_model_name_processingcovers the happy path but not the no-slash inference delta. -
PR-description REST contract summary looks unrelated. The
agent-server-rest-api-contract-summaryblock advertises new/api/plugins/marketplaceschemas and renamedMarketplaceCatalogResponseschemas, 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_copyoverride (refreshing_provider_infoonly whenmodel/base_urlare inupdate) cleanly resolves the stale-cache regression and correctly avoids spurious refreshes forcaching_prompt-only copies. - Bedrock
api_keystripping is now colocated with provider parsing inapi_key_for_litellm, matching the AGENTS.md guidance. get_features(model: str | None)correctly widens the signature to match helpers that already acceptedNone, removing a# type: ignore.cached_propertyon afrozen=Truedataclass works (writes to__dict__, doesn't break__hash__/equality), verified at runtime.- New tests cover
model_copyrefresh for bothmodelandbase_urlupdates, 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.
|
@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. |
|
I'm on it! enyst can track my progress at all-hands.dev |
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>
|
Completed work on PR #2363.
Validation:
|
all-hands-bot
left a comment
There was a problem hiding this comment.
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_metadataeagerly rebuilds provider info + capabilities, which actually fixes a latent issue: previouslymodel_copy(update={"model": X})produced an LLM with stale_model_info/token caps from the original model (validators don't re-run onmodel_copy). The new refresh path corrects that.- The
from_modelfailure path is robust: it never returnsNone, so theassert provider_info is not Noneguards in transport are safe —_provider_infois 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)
resolved_api_basenow drives transportapi_base. Previously transport spreadself._litellm_call_kwargs(), soapi_basewas the rawself.base_url(orNone). Now it isprovider_info.resolved_api_base, i.e. LiteLLM's post-resolution base. For most providers this is identical, but for providers whereget_llm_providerinjects 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 custombase_urlis forwarded as-is for an unrecognized model (the local-LLM case) to lock in the no-regression guarantee.- Eager work on
model_copy._refresh_litellm_metadata->_init_model_info_and_capscan make a network call (get_litellm_model_infodoes anhttpx.getagainst the proxy forlitellm_proxy/models).model_copyis now O(network) whenmodel/base_urlchange, 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 thecaching_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.
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>
Behavior-parity audit vs
|
|
🚦 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 This is an automated check - no AI was used to generate this comment. |
|
🤖 OpenHands is reviewing this PR. Head commit: This comment was posted by an AI agent (OpenHands). |
all-hands-bot
left a comment
There was a problem hiding this comment.
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
LLMin_post_init(_refresh_litellm_metadata) and reused for the lifetime of the instance, replacing the prior lazy_litellm_providercache. Themodel_copyoverride correctly rebuilds derived metadata whenmodelorbase_urlchange, and leaves it untouched otherwise (e.g. thestream/usage_id/secret-field copies used throughout the codebase). I verified theupdate-key guard covers exactly the fields that feed_litellm_call_kwargs(model,base_url);api_versionand other transport fields are not part of provider parsing, so the check is complete. - Bedrock
api_keystripping is preserved and moved intoLLMProvider.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 intoas_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-suppliedauth_valuespath (subscription credentials). No correctness issue. - Verbatim
api_baseforwarding is a real improvement: discarding LiteLLM's resolvedapi_base(which can be rewritten, e.g. mistral/v1appending, 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 parsedmodel+custom_llm_providerform resolves identically to the full string via LiteLLM's ownget_llm_provider, locking in wire-equivalence. - Cost calculation now reuses the same
LLMProviderview instead of re-splitting on/. For OpenHands-provider models this yieldslitellm_proxy+ bare model -- identical to the oldsplit("/", 1)result. The telemetry fallback (whenprovider_info is None, e.g. directTelemetryuse in tests) reconstructs fromlitellm_call_kwargs(self.model_name, None), matching theLLM-driven path. - Capability/feature lookups correctly stay on the canonical model string (
model_canonical_name or model), avoiding a second provider abstraction. Themodel_features.pychanges widening signatures tostr | Noneare 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 previouslymodel_copynever refreshed model info. This is arguably more correct (model-info fetch can depend onbase_url) and is covered bytest_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 copiesbase_urlin a hot path, so impact is negligible; flagging for awareness.
Maintainability / Style
LLMProvideris a focused frozen dataclass with well-placed comments explaining the non-obviousapi_basediscard 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 Noneguards in the transport methods are safe given_post_initalways populates_provider_infoandmodel_copypreserves/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.
HUMAN:
This PR proposes to abstract a provider out of the mixed string "provider/model" that we were using.
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
LLMProviderhelper backed by LiteLLM, so provider-specific logic stops re-splitting rawprovider/modelstrings across the SDK.This PR now takes the simpler direction discussed in issue #2274 and PR review:
provider+modelview for LiteLLM-facing runtime pathsLLMinstance instead of refreshing provider state during each transport callConcretely, this PR:
openhands.sdk.llm.utils.litellm_provider.LLMProvideras a thin wrapper around LiteLLM provider parsing, provider model info lookup, API base inference, and call kwargs generationLLMProviderfocused on LiteLLM's parsed runtime shape (provider, parsedmodel) plus the user-requested API base, rather than storing duplicaterequested_*fieldsLLMchat/responses transport calls to use provider-owned LiteLLM kwargs generation (model+custom_llm_provider, plus Bedrock-awareapi_keyforwarding) instead of repeatedly passing or re-splitting the full stringapi_keyhandling intoLLMProviderso provider-sensitive transport behavior lives alongside provider parsingmodel_featureslookups on the canonical model string (model_canonical_nameormodel) instead of introducing a second provider abstractionLLMsetup, so chat/responses transport paths reuse the same resolved provider metadata for the lifetime of the instancebase_url(orNone) verbatim asapi_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 mainget_llm_provider) that sending parsedmodel+custom_llm_providerresolves identically to sending the fullprovider/modelstringCloses #2274.
How to Test
uv run pytest tests/sdk/llm -q(verified: 936 passed).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).Checklist
Agent Server images for this PR
• GHCR package: https://github.com/OpenHands/agent-sdk/pkgs/container/agent-server
Variants & Base Images
eclipse-temurin:17-jdknikolaik/python-nodejs:python3.13-nodejs22-slimgolang:1.21-bookwormPull (multi-arch manifest)
# Each variant is a multi-arch manifest supporting both amd64 and arm64 docker pull ghcr.io/openhands/agent-server:7fb2c0a-pythonRun
All tags pushed for this build
About Multi-Architecture Support
7fb2c0a-python) is a multi-arch manifest supporting both amd64 and arm647fb2c0a-python-amd64) are also available if needed