feat: add LiteLLM as AI gateway provider
Summary
- Adds LiteLLM as a new AI provider, following the existing
GroqProviderdelegation pattern.LiteLLMProviderwrapsOpenAIProviderwith the user's LiteLLM proxy URL, enabling access to 100+ LLM providers (Anthropic, Google, Bedrock, Azure, Ollama, etc.) through a single OpenAI-compatible gateway. - Users who self-host a LiteLLM proxy can consolidate multiple provider keys, enable fallback routing, and use any model configured on the proxy without adding new provider packages.
Checklist
- [x] Tests added/updated
- [ ] Docs updated (README or typedoc)
- [x] Conventional commit title/body
Changes:
src/core/llm/providers/implementations/LiteLLMProvider.ts- new provider (delegates toOpenAIProvider, dynamic model discovery via/v1/models)src/core/llm/providers/AIModelProviderManager.ts- registered'litellm'casesrc/core/llm/providers/__tests__/LiteLLMProvider.test.ts- 12 unit tests
$ npx vitest run src/core/llm/providers/__tests__/LiteLLMProvider.test.ts
✓ initialization > throws when API key is missing
✓ initialization > initializes with valid config
✓ initialization > uses custom default model
✓ initialization > delegates to OpenAIProvider with proxy baseURL
✓ generateCompletion > delegates to OpenAIProvider
✓ generateCompletionStream > yields streamed chunks from delegate
✓ generateEmbeddings > delegates to OpenAIProvider
✓ listAvailableModels > fetches models from proxy /v1/models
✓ listAvailableModels > returns empty array on fetch error
✓ listAvailableModels > returns empty array on network failure
✓ checkHealth > delegates to OpenAIProvider
✓ shutdown > delegates and resets state
12 passed
Live E2E against a real LiteLLM proxy (routing to Claude via Azure Foundry):
$ litellm --config config.yaml --port 4000
const provider = new LiteLLMProvider();
await provider.initialize({
apiKey: 'sk-test',
baseURL: 'http://localhost:4000/v1',
});
Models: [ 'anthropic/claude-sonnet-4-6' ]
content: OK
finishReason: stop
usage: { promptTokens: 13, completionTokens: 4, totalTokens: 17 }
Usage:
// In agent config:
{
providers: [{
providerId: 'litellm',
enabled: true,
config: {
apiKey: process.env.LITELLM_API_KEY,
baseURL: 'http://localhost:4000/v1',
defaultModelId: 'anthropic/claude-sonnet-4-6',
},
}],
}
Additive only. No existing providers modified. Zero new dependencies.
Summary by Sourcery
Add a new LiteLLM provider that delegates to the existing OpenAI provider and register it with the AI model provider manager.
New Features:
- Introduce LiteLLMProvider to access multiple LLM backends via an OpenAI-compatible LiteLLM proxy.
- Enable dynamic LiteLLM model discovery through the proxy's /v1/models endpoint and integrate LiteLLM into the provider manager under the 'litellm' ID.
Tests:
- Add unit tests covering LiteLLMProvider initialization, delegation behavior, model listing, health checks, and shutdown.
Summary by CodeRabbit
- New Features
- Added support for LiteLLM provider, enabling integration with self-hosted LiteLLM proxy servers using OpenAI-compatible APIs. Users can now configure and connect to self-hosted LiteLLM instances for language model completions and embeddings.
Codex usage limits have been reached for code reviews. Please check with the admins of this repo to increase the limits by adding credits. Credits must be used to enable repository wide code reviews.
📝 Walkthrough
Walkthrough
This PR introduces LiteLLMProvider, a new LLM provider implementation that wraps OpenAIProvider to interface with self-hosted LiteLLM proxies. The provider includes configuration, initialization with proxy settings, request delegation, dynamic model discovery, and full test coverage. Integration into the manager's provider registry is minimal.
Changes
LiteLLM Provider Support
| Layer / File(s) | Summary |
|---|---|
Provider Configuration Contract src/core/llm/providers/implementations/LiteLLMProvider.ts |
LiteLLMProviderConfig interface captures API key (required) and optional proxy base URL, default model ID, and request timeout. |
Provider Implementation - Core Methods src/core/llm/providers/implementations/LiteLLMProvider.ts |
LiteLLMProvider class initializes by validating the API key and configuring an OpenAIProvider delegate with proxy settings. Completion, streaming, and embedding methods pass through to the delegate. |
Provider Implementation - Model Discovery & Lifecycle src/core/llm/providers/implementations/LiteLLMProvider.ts |
listAvailableModels calls the proxy's /v1/models endpoint and parses returned model metadata, with optional capability filtering. getModelInfo, checkHealth, and shutdown complete the lifecycle, delegating where appropriate and resetting state on shutdown. |
Manager Integration src/core/llm/providers/AIModelProviderManager.ts |
LiteLLMProvider is imported and instantiated in the provider switch when providerId lowercases to litellm. |
Test Suite - Setup & Mocking src/core/llm/providers/__tests__/LiteLLMProvider.test.ts |
Vitest suite with complete mock of OpenAIProvider to isolate unit testing from external HTTP calls. |
Test Suite - Initialization & Core Delegation src/core/llm/providers/__tests__/LiteLLMProvider.test.ts |
Tests verify API key validation, successful initialization with proxy configuration, and delegation of completions, streaming completions, and embeddings to the mocked OpenAIProvider. |
Test Suite - Model Discovery & Lifecycle src/core/llm/providers/__tests__/LiteLLMProvider.test.ts |
Tests for listAvailableModels success and error modes (HTTP error, network failure) via stubbed fetch, and verification of checkHealth and shutdown delegation with state reset. |
Estimated code review effort
🎯 3 (Moderate) | ⏱️ ~20 minutes
Poem
A rabbit hops through proxies fair,
LiteLLM magic in the air,
Completions flow, models align,
OpenAI wrapped in perfect design.
Tests stand guard, all passing bright,
New provider shining in the light! 🐰✨
🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
| Check name | Status | Explanation |
|---|---|---|
| Title check | ✅ Passed | The title accurately describes the main change: adding LiteLLM as a new AI gateway provider, which is the primary objective of the PR. |
| Description check | ✅ Passed | The description comprehensively covers the summary, rationale, implementation details, test results, usage example, and checklist status, matching the template structure and requirements. |
| Docstring Coverage | ✅ Passed | No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check. |
| Linked Issues check | ✅ Passed | Check skipped because no linked issues were found for this pull request. |
| Out of Scope Changes check | ✅ Passed | Check skipped because no linked issues were found for this pull request. |
✏️ Tip: You can configure your own custom pre-merge checks in the settings.
✨ Finishing Touches
🧪 Generate unit tests (beta)
- [ ] Create PR with unit tests
[!WARNING] There were issues while running some tools. Please review the errors and either fix the tool's configuration or disable the tool if it's a critical failure.
🔧 ESLint
If the error stems from missing dependencies, add them to the package.json file. For unrecoverable errors (e.g., due to private dependencies), disable the tool in the CodeRabbit configuration.
ESLint install failed. For unrecoverable errors, disable the tool in CodeRabbit configuration.
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.
Comment @coderabbitai help to get the list of available commands and usage tips.
Reviewer's Guide
Adds a new LiteLLMProvider that wraps the existing OpenAIProvider, wires it into AIModelProviderManager under the litellm providerId, and introduces unit tests covering initialization, delegation behavior, dynamic model discovery via the LiteLLM /v1/models endpoint, and shutdown/health flows.
Sequence diagram for LiteLLMProvider model discovery via /v1/models
sequenceDiagram
actor Client
participant LiteLLMProvider
participant LiteLLMProxy
Client->>LiteLLMProvider: listAvailableModels(filter)
LiteLLMProvider->>LiteLLMProxy: fetch /v1/models
LiteLLMProxy-->>LiteLLMProvider: models JSON
LiteLLMProvider-->>Client: ModelInfo[]
File-Level Changes
| Change | Details | Files |
|---|---|---|
Introduce LiteLLMProvider as a thin wrapper around OpenAIProvider configured to talk to a LiteLLM proxy, including dynamic model discovery via the proxy's /v1/models endpoint. |
|
src/core/llm/providers/implementations/LiteLLMProvider.ts |
Register the new LiteLLMProvider in the AIModelProviderManager so it can be instantiated from configuration via providerId litellm. |
|
src/core/llm/providers/AIModelProviderManager.ts |
| Add unit tests to validate LiteLLMProvider behavior, including configuration validation, delegation, model listing, error handling, and lifecycle methods. |
|
src/core/llm/providers/__tests__/LiteLLMProvider.test.ts |
Tips and commands
Interacting with Sourcery
- Trigger a new review: Comment
@sourcery-ai reviewon the pull request. - Continue discussions: Reply directly to Sourcery's review comments.
- Generate a GitHub issue from a review comment: Ask Sourcery to create an
issue from a review comment by replying to it. You can also reply to a
review comment with
@sourcery-ai issueto create an issue from it. - Generate a pull request title: Write
@sourcery-aianywhere in the pull request title to generate a title at any time. You can also comment@sourcery-ai titleon the pull request to (re-)generate the title at any time. - Generate a pull request summary: Write
@sourcery-ai summaryanywhere in the pull request body to generate a PR summary at any time exactly where you want it. You can also comment@sourcery-ai summaryon the pull request to (re-)generate the summary at any time. - Generate reviewer's guide: Comment
@sourcery-ai guideon the pull request to (re-)generate the reviewer's guide at any time. - Resolve all Sourcery comments: Comment
@sourcery-ai resolveon the pull request to resolve all Sourcery comments. Useful if you've already addressed all the comments and don't want to see them anymore. - Dismiss all Sourcery reviews: Comment
@sourcery-ai dismisson the pull request to dismiss all existing Sourcery reviews. Especially useful if you want to start fresh with a new review - don't forget to comment@sourcery-ai reviewto trigger a new review!
Customizing Your Experience
Access your dashboard to:
- Enable or disable review features such as the Sourcery-generated pull request summary, the reviewer's guide, and others.
- Change the review language.
- Add, remove or edit custom review instructions.
- Adjust other review settings.
Getting Help
- Contact our support team for questions or feedback.
- Visit our documentation for detailed guides and information.
- Keep in touch with the Sourcery team by following us on X/Twitter, LinkedIn or GitHub.
Review Summary by Qodo
Add LiteLLM as AI gateway provider with dynamic model discovery
✨ Enhancement
Walkthroughs
Description
• Adds LiteLLMProvider as new AI gateway supporting 100+ LLM providers • Delegates to OpenAIProvider with custom proxy baseURL configuration • Implements dynamic model discovery via proxy /v1/models endpoint • Includes 12 comprehensive unit tests covering initialization and delegation
Diagram
flowchart LR
A["LiteLLMProvider"] -->|"delegates to"| B["OpenAIProvider"]
A -->|"queries"| C["LiteLLM Proxy /v1/models"]
C -->|"returns"| D["Available Models"]
B -->|"routes requests"| E["100+ LLM Providers"]
A -->|"registered in"| F["AIModelProviderManager"]
File Changes
1. src/core/llm/providers/implementations/LiteLLMProvider.ts
✨ Enhancement +209/-0
LiteLLMProvider implementation with proxy delegation
• New provider implementation wrapping OpenAIProvider with LiteLLM proxy configuration • Implements IProvider interface with delegation pattern for all core methods • Dynamic model discovery via /v1/models endpoint with error handling • Supports custom baseURL, API key, and default model configuration
2. src/core/llm/providers/__tests__/LiteLLMProvider.test.ts
🧪 Tests +225/-0
Comprehensive test suite for LiteLLMProvider
• 12 unit tests covering initialization, delegation, and error scenarios • Tests verify API key validation, config handling, and OpenAIProvider delegation • Tests for dynamic model discovery with success and failure cases • Tests for streaming, embeddings, health checks, and shutdown
3. src/core/llm/providers/AIModelProviderManager.ts
✨ Enhancement +4/-0
Register LiteLLMProvider in provider manager
• Added import for LiteLLMProvider and LiteLLMProviderConfig • Registered 'litellm' case in provider factory switch statement • Instantiates LiteLLMProvider when providerId matches 'litellm'
Code Review by Qodo
🐞 Bugs (3) 📘 Rule violations (0)
1. Unbounded model fetch 🐞 Bug ☼ Reliability
Description
LiteLLMProvider.listAvailableModels() calls fetch() without any timeout/AbortController, so AIModelProviderManager.initialize() and listAllAvailableModels() can hang indefinitely while waiting for model discovery.
Code
src/core/llm/providers/implementations/LiteLLMProvider.ts[R161-168]+ public async listAvailableModels( + filter?: { capability?: string }, + ): Promise<ModelInfo[]> { + try { + const url = this.proxyBaseURL.replace(/\/+$/, '') + '/models'; + const response = await fetch(url, { + headers: { Authorization: `Bearer ${this.proxyApiKey}` }, + });
Evidence
LiteLLMProvider performs /models discovery via a bare fetch without any abort/timeout, while AIModelProviderManager awaits provider.listAvailableModels() during both initialization caching and aggregate model listing, meaning the whole manager operation can block on an unresponsive proxy.
src/core/llm/providers/implementations/LiteLLMProvider.ts[161-169]src/core/llm/providers/AIModelProviderManager.ts[175-176]src/core/llm/providers/AIModelProviderManager.ts[207-216]src/core/llm/providers/AIModelProviderManager.ts[264-286]
Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution ## Issue description `LiteLLMProvider.listAvailableModels()` uses a bare `fetch()` with no timeout/abort handling. Since `AIModelProviderManager` awaits `listAvailableModels()` during initialization and when listing all models, an unresponsive LiteLLM proxy can stall these flows indefinitely. ## Issue Context Other providers in this codebase bound network calls with request timeouts (often via `AbortController`). LiteLLMProvider already accepts `requestTimeout` in config, but it is only passed to the OpenAI delegate and not applied to `/models` discovery. ## Fix Focus Areas - src/core/llm/providers/implementations/LiteLLMProvider.ts[106-122] - src/core/llm/providers/implementations/LiteLLMProvider.ts[161-190] ## Suggested fix - Persist a `requestTimeoutMs` field on `LiteLLMProvider` during `initialize()` (default to 60000). - In `listAvailableModels()`, use `AbortController` + `setTimeout(() => controller.abort(), requestTimeoutMs)` and pass `{ signal: controller.signal }` to `fetch`. - Ensure the timer is cleared in `finally` to avoid leaks.
ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools
2. Discovery failures misroute models 🐞 Bug ≡ Correctness
Description
LiteLLMProvider.listAvailableModels() returns [] for non-OK responses and all exceptions, preventing AIModelProviderManager from populating modelToProviderMap and causing getProviderForModel() to fall back to its '/'-prefix heuristic (e.g., routing "anthropic/..." to the Anthropic provider instead of LiteLLM).
Code
src/core/llm/providers/implementations/LiteLLMProvider.ts[R169-189]+ if (!response.ok) { + return []; + } + const data = (await response.json()) as { + data?: Array<{ id: string; owned_by?: string }>; + }; + const models: ModelInfo[] = (data.data ?? []).map((m) => ({ + modelId: m.id, + providerId: 'litellm', + displayName: m.id, + capabilities: ['chat'] as string[], + supportsStreaming: true, + status: 'active' as const, + })); + if (filter?.capability) { + return models.filter((m) => m.capabilities.includes(filter.capability!)); + } + return models; + } catch { + return []; + }
Evidence
LiteLLMProvider returns [] on HTTP failure and in a blanket catch, so the manager won't map LiteLLM model IDs. When no mapping exists, the manager routes modelId values containing / by treating the first segment as a providerId, and the codebase uses model IDs like anthropic/claude-sonnet-4-6, making wrong-provider selection deterministic in that scenario.
src/core/llm/providers/implementations/LiteLLMProvider.ts[169-189]src/core/llm/providers/AIModelProviderManager.ts[240-258]src/core/llm/providers/tests/LiteLLMProvider.test.ts[16-21]src/core/llm/providers/tests/LiteLLMProvider.test.ts[88-95]
Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution ## Issue description `LiteLLMProvider.listAvailableModels()` silently converts both HTTP failures and runtime errors into an empty model list. This means `AIModelProviderManager` cannot map discovered model IDs to the `litellm` provider; when a modelId contains `/`, the manager may route by prefix instead (treating the first segment as a providerId), which can select the wrong provider. ## Issue Context - Manager routing prefers `modelToProviderMap`, then falls back to splitting `modelId` on `/`. - LiteLLM model IDs commonly include provider prefixes like `anthropic/claude-...` (tests and docs). ## Fix Focus Areas - src/core/llm/providers/implementations/LiteLLMProvider.ts[161-190] - src/core/llm/providers/AIModelProviderManager.ts[240-258] ## Suggested fix - Do not fully swallow discovery failures: - At minimum: `console.warn` (or debug-gated log) with status code / error when `/models` fails. - Preferably: throw an Error on non-OK and on caught exceptions so `AIModelProviderManager`’s existing `catch` paths can log the providerId and context. - To reduce misrouting when discovery is temporarily unavailable, consider returning a minimal fallback catalog containing at least `defaultModelId` (if set) so the manager can still map the primary configured model to `litellm`. - Update/extend tests to assert the new behavior (log/throw and/or fallback model inclusion).
ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools
3. Fragile global fetch cleanup 🐞 Bug ☼ Reliability
Description
LiteLLMProvider tests stub the global fetch and manually call vi.unstubAllGlobals() at the end of each test; if a test throws before cleanup, the stub can leak into subsequent tests and cause cascading failures.
Code
src/core/llm/providers/tests/LiteLLMProvider.test.ts[R160-205]+ describe('listAvailableModels', () => { + it('fetches models from proxy /v1/models', async () => { + const mockFetch = vi.fn().mockResolvedValue({ + ok: true, + json: async () => ({ + data: [ + { id: 'gpt-4o-mini' }, + { id: 'anthropic/claude-sonnet-4-6' }, + ], + }), + }); + vi.stubGlobal('fetch', mockFetch); + + await provider.initialize({ apiKey: 'sk-test' }); + const models = await provider.listAvailableModels(); + + expect(models).toHaveLength(2); + expect(models[0].modelId).toBe('gpt-4o-mini'); + expect(models[1].modelId).toBe('anthropic/claude-sonnet-4-6'); + + vi.unstubAllGlobals(); + }); + + it('returns empty array on fetch error', async () => { + const mockFetch = vi.fn().mockResolvedValue({ ok: false }); + vi.stubGlobal('fetch', mockFetch); + + await provider.initialize({ apiKey: 'sk-test' }); + const models = await provider.listAvailableModels(); + + expect(models).toEqual([]); + + vi.unstubAllGlobals(); + }); + + it('returns empty array on network failure', async () => { + const mockFetch = vi.fn().mockRejectedValue(new Error('ECONNREFUSED')); + vi.stubGlobal('fetch', mockFetch); + + await provider.initialize({ apiKey: 'sk-test' }); + const models = await provider.listAvailableModels(); + + expect(models).toEqual([]); + + vi.unstubAllGlobals(); + });
Evidence
The tests stub globalThis.fetch and only unstub it at the end of each test body, which is not guaranteed to execute if the test fails mid-way.
src/core/llm/providers/tests/LiteLLMProvider.test.ts[160-205]
Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution ## Issue description The tests manually call `vi.unstubAllGlobals()` within each test. If an assertion fails earlier, cleanup won’t run and the stubbed global `fetch` may persist into later tests. ## Issue Context This is test hygiene; it makes failures harder to debug when one test contaminates others. ## Fix Focus Areas - src/core/llm/providers/__tests__/LiteLLMProvider.test.ts[62-69] - src/core/llm/providers/__tests__/LiteLLMProvider.test.ts[160-205] ## Suggested fix - Add `afterEach(() => vi.unstubAllGlobals())` (and import `afterEach`) and remove per-test unstub calls. - Alternatively, wrap stubbing in `try/finally` blocks to guarantee cleanup.
ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools