forked from cline/cline
-
Notifications
You must be signed in to change notification settings - Fork 2.1k
feat: Add API provider fallback support per mode (#7068) #7069
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
roomote
wants to merge
1
commit into
main
Choose a base branch
from
feature/api-provider-fallback
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+606
−3
Open
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,165 @@ | ||
import { Anthropic } from "@anthropic-ai/sdk" | ||
import type { ProviderSettingsWithId, ModelInfo } from "@roo-code/types" | ||
import { ApiHandler, ApiHandlerCreateMessageMetadata, buildApiHandler } from "./index" | ||
import { ApiStream, ApiStreamChunk, ApiStreamError } from "./transform/stream" | ||
import { logger } from "../utils/logging" | ||
|
||
/** | ||
* FallbackApiHandler wraps multiple API handlers and automatically falls back | ||
* to the next handler in the chain if the current one fails. | ||
*/ | ||
export class FallbackApiHandler implements ApiHandler { | ||
private handlers: ApiHandler[] | ||
private configurations: ProviderSettingsWithId[] | ||
private currentHandlerIndex: number = 0 | ||
private lastSuccessfulIndex: number = 0 | ||
|
||
constructor(configurations: ProviderSettingsWithId[]) { | ||
if (!configurations || configurations.length === 0) { | ||
throw new Error("At least one API configuration is required") | ||
} | ||
|
||
this.configurations = configurations | ||
this.handlers = configurations.map((config) => buildApiHandler(config)) | ||
} | ||
|
||
/** | ||
* Creates a message with automatic fallback to secondary providers if the primary fails. | ||
*/ | ||
createMessage( | ||
systemPrompt: string, | ||
messages: Anthropic.Messages.MessageParam[], | ||
metadata?: ApiHandlerCreateMessageMetadata, | ||
): ApiStream { | ||
// Return an async generator that handles fallback logic | ||
return this.createMessageWithFallback(systemPrompt, messages, metadata) | ||
} | ||
|
||
private async *createMessageWithFallback( | ||
systemPrompt: string, | ||
messages: Anthropic.Messages.MessageParam[], | ||
metadata?: ApiHandlerCreateMessageMetadata, | ||
): ApiStream { | ||
let lastError: Error | undefined | ||
|
||
// Try each handler in sequence until one succeeds | ||
for (let i = 0; i < this.handlers.length; i++) { | ||
this.currentHandlerIndex = i | ||
const handler = this.handlers[i] | ||
const config = this.configurations[i] | ||
|
||
try { | ||
logger.info(`Attempting API call with provider: ${config.apiProvider || "default"} (index ${i})`) | ||
|
||
// Create a stream from the current handler | ||
const stream = handler.createMessage(systemPrompt, messages, metadata) | ||
|
||
// Track if we've successfully received any chunks | ||
let hasReceivedChunks = false | ||
|
||
try { | ||
// Iterate through the stream and yield chunks | ||
for await (const chunk of stream) { | ||
hasReceivedChunks = true | ||
|
||
// Check if this is an error chunk | ||
if (chunk.type === "error") { | ||
// If we've already received some chunks, yield the error | ||
// Otherwise, throw to trigger fallback | ||
if (hasReceivedChunks) { | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. This condition seems redundant. At this point, is already true (set on line 63), so the check on line 69 will always evaluate to true. Should we be checking a different condition here, or can we simplify this logic? |
||
yield chunk | ||
} else { | ||
throw new Error(chunk.message || chunk.error) | ||
} | ||
} else { | ||
// Yield successful chunks | ||
yield chunk | ||
} | ||
} | ||
|
||
// If we successfully completed the stream, update the last successful index | ||
if (hasReceivedChunks) { | ||
this.lastSuccessfulIndex = i | ||
logger.info(`API call succeeded with provider: ${config.apiProvider || "default"}`) | ||
return // Successfully completed, exit the function | ||
} | ||
} catch (streamError) { | ||
// Stream failed, try the next handler | ||
lastError = streamError as Error | ||
logger.warn( | ||
`API call failed with provider: ${config.apiProvider || "default"} (index ${i}). Error: ${lastError.message}`, | ||
) | ||
|
||
// If this is not the last handler, continue to the next one | ||
if (i < this.handlers.length - 1) { | ||
logger.info(`Falling back to next provider...`) | ||
continue | ||
} | ||
} | ||
} catch (error) { | ||
lastError = error as Error | ||
logger.warn( | ||
`API call failed with provider: ${config.apiProvider || "default"} (index ${i}). Error: ${lastError.message}`, | ||
) | ||
|
||
// If this is not the last handler, continue to the next one | ||
if (i < this.handlers.length - 1) { | ||
logger.info(`Falling back to next provider...`) | ||
continue | ||
} | ||
} | ||
} | ||
|
||
// All handlers failed, yield an error chunk | ||
const errorMessage = `All API providers failed. Last error: ${lastError?.message || "Unknown error"}` | ||
logger.error(errorMessage) | ||
|
||
const errorChunk: ApiStreamError = { | ||
type: "error", | ||
error: lastError?.message || "Unknown error", | ||
message: errorMessage, | ||
} | ||
|
||
yield errorChunk | ||
} | ||
|
||
/** | ||
* Returns the model information from the currently active handler. | ||
*/ | ||
getModel(): { id: string; info: ModelInfo } { | ||
// Return the model from the last successful handler, or the first one if none have succeeded yet | ||
const index = this.lastSuccessfulIndex | ||
return this.handlers[index].getModel() | ||
} | ||
|
||
/** | ||
* Counts tokens using the currently active handler. | ||
*/ | ||
async countTokens(content: Array<Anthropic.Messages.ContentBlockParam>): Promise<number> { | ||
// Use the last successful handler for token counting | ||
const index = this.lastSuccessfulIndex | ||
return this.handlers[index].countTokens(content) | ||
} | ||
|
||
/** | ||
* Gets the current provider name for logging/debugging purposes. | ||
*/ | ||
getCurrentProvider(): string { | ||
return this.configurations[this.currentHandlerIndex]?.apiProvider || "default" | ||
} | ||
|
||
/** | ||
* Gets all configured providers in order. | ||
*/ | ||
getConfiguredProviders(): string[] { | ||
return this.configurations.map((config) => config.apiProvider || "default") | ||
} | ||
|
||
/** | ||
* Resets the handler to use the primary provider again. | ||
*/ | ||
reset(): void { | ||
this.currentHandlerIndex = 0 | ||
this.lastSuccessfulIndex = 0 | ||
} | ||
} |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Consider using DEBUG level instead of INFO for routine operations to avoid flooding logs during normal operation. INFO level might be too verbose when the fallback mechanism is working as expected.