This repository was archived by the owner on Sep 18, 2025. It is now read-only.
Repository navigation
fix(anthropic): better 429/529 handling #22
Merged
Merged
Changes from all commits
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
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
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
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
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 |
|---|---|---|
|
|
@@ -4,7 +4,9 @@ import ( | |
| "context" | ||
| "encoding/json" | ||
| "errors" | ||
| "fmt" | ||
| "strings" | ||
| "time" | ||
|
|
||
| "github.com/anthropics/anthropic-sdk-go" | ||
| "github.com/anthropics/anthropic-sdk-go/option" | ||
|
|
@@ -68,21 +70,24 @@ func (a *anthropicProvider) SendMessages(ctx context.Context, messages []message | |
| anthropicMessages := a.convertToAnthropicMessages(messages) | ||
| anthropicTools := a.convertToAnthropicTools(tools) | ||
|
|
||
| response, err := a.client.Messages.New(ctx, anthropic.MessageNewParams{ | ||
| Model: anthropic.Model(a.model.APIModel), | ||
| MaxTokens: a.maxTokens, | ||
| Temperature: anthropic.Float(0), | ||
| Messages: anthropicMessages, | ||
| Tools: anthropicTools, | ||
| System: []anthropic.TextBlockParam{ | ||
| { | ||
| Text: a.systemMessage, | ||
| CacheControl: anthropic.CacheControlEphemeralParam{ | ||
| Type: "ephemeral", | ||
| response, err := a.client.Messages.New( | ||
| ctx, | ||
| anthropic.MessageNewParams{ | ||
| Model: anthropic.Model(a.model.APIModel), | ||
| MaxTokens: a.maxTokens, | ||
| Temperature: anthropic.Float(0), | ||
| Messages: anthropicMessages, | ||
| Tools: anthropicTools, | ||
| System: []anthropic.TextBlockParam{ | ||
| { | ||
| Text: a.systemMessage, | ||
| CacheControl: anthropic.CacheControlEphemeralParam{ | ||
| Type: "ephemeral", | ||
| }, | ||
| }, | ||
| }, | ||
| }, | ||
| }) | ||
| ) | ||
| if err != nil { | ||
| return nil, err | ||
| } | ||
|
|
@@ -121,83 +126,171 @@ func (a *anthropicProvider) StreamResponse(ctx context.Context, messages []messa | |
| temperature = anthropic.Float(1) | ||
| } | ||
|
|
||
| stream := a.client.Messages.NewStreaming(ctx, anthropic.MessageNewParams{ | ||
| Model: anthropic.Model(a.model.APIModel), | ||
| MaxTokens: a.maxTokens, | ||
| Temperature: temperature, | ||
| Messages: anthropicMessages, | ||
| Tools: anthropicTools, | ||
| Thinking: thinkingParam, | ||
| System: []anthropic.TextBlockParam{ | ||
| { | ||
| Text: a.systemMessage, | ||
| CacheControl: anthropic.CacheControlEphemeralParam{ | ||
| Type: "ephemeral", | ||
| }, | ||
| }, | ||
| }, | ||
| }) | ||
|
|
||
| eventChan := make(chan ProviderEvent) | ||
|
|
||
| go func() { | ||
| defer close(eventChan) | ||
|
|
||
| accumulatedMessage := anthropic.Message{} | ||
| const maxRetries = 8 | ||
| attempts := 0 | ||
|
|
||
| for stream.Next() { | ||
| event := stream.Current() | ||
| err := accumulatedMessage.Accumulate(event) | ||
| if err != nil { | ||
| eventChan <- ProviderEvent{Type: EventError, Error: err} | ||
| return | ||
| for { | ||
| // If this isn't the first attempt, we're retrying | ||
| if attempts > 0 { | ||
| if attempts > maxRetries { | ||
| eventChan <- ProviderEvent{ | ||
| Type: EventError, | ||
| Error: errors.New("maximum retry attempts reached for rate limit (429)"), | ||
| } | ||
| return | ||
| } | ||
|
|
||
| // Inform user we're retrying with attempt number | ||
| eventChan <- ProviderEvent{ | ||
| Type: EventWarning, | ||
| Info: fmt.Sprintf("[Retrying due to rate limit... attempt %d of %d]", attempts, maxRetries), | ||
| } | ||
|
|
||
| // Calculate backoff with exponential backoff and jitter | ||
| backoffMs := 2000 * (1 << (attempts - 1)) // 2s, 4s, 8s, 16s, 32s | ||
|
Contributor
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. I think since we now have
Contributor
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. I think you tried handling this by But i think the code will always reach here and wait for an additional amount of time
Contributor
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. I will merge what is here so far and clean in up after. |
||
| jitterMs := int(float64(backoffMs) * 0.2) | ||
| totalBackoffMs := backoffMs + jitterMs | ||
|
|
||
| // Sleep with backoff, respecting context cancellation | ||
| select { | ||
| case <-ctx.Done(): | ||
| eventChan <- ProviderEvent{Type: EventError, Error: ctx.Err()} | ||
| return | ||
| case <-time.After(time.Duration(totalBackoffMs) * time.Millisecond): | ||
| // Continue with retry | ||
| } | ||
| } | ||
|
|
||
| switch event := event.AsAny().(type) { | ||
| case anthropic.ContentBlockStartEvent: | ||
| eventChan <- ProviderEvent{Type: EventContentStart} | ||
| attempts++ | ||
|
|
||
| // Create new streaming request | ||
| stream := a.client.Messages.NewStreaming( | ||
| ctx, | ||
| anthropic.MessageNewParams{ | ||
| Model: anthropic.Model(a.model.APIModel), | ||
| MaxTokens: a.maxTokens, | ||
| Temperature: temperature, | ||
| Messages: anthropicMessages, | ||
| Tools: anthropicTools, | ||
| Thinking: thinkingParam, | ||
| System: []anthropic.TextBlockParam{ | ||
| { | ||
| Text: a.systemMessage, | ||
| CacheControl: anthropic.CacheControlEphemeralParam{ | ||
| Type: "ephemeral", | ||
| }, | ||
| }, | ||
| }, | ||
| }, | ||
| ) | ||
|
|
||
| case anthropic.ContentBlockDeltaEvent: | ||
| if event.Delta.Type == "thinking_delta" && event.Delta.Thinking != "" { | ||
| eventChan <- ProviderEvent{ | ||
| Type: EventThinkingDelta, | ||
| Thinking: event.Delta.Thinking, | ||
| // Process stream events | ||
| accumulatedMessage := anthropic.Message{} | ||
| streamSuccess := false | ||
|
|
||
| // Process the stream until completion or error | ||
| for stream.Next() { | ||
| event := stream.Current() | ||
| err := accumulatedMessage.Accumulate(event) | ||
| if err != nil { | ||
| eventChan <- ProviderEvent{Type: EventError, Error: err} | ||
| return // Don't retry on accumulation errors | ||
| } | ||
|
|
||
| switch event := event.AsAny().(type) { | ||
| case anthropic.ContentBlockStartEvent: | ||
| eventChan <- ProviderEvent{Type: EventContentStart} | ||
|
|
||
| case anthropic.ContentBlockDeltaEvent: | ||
| if event.Delta.Type == "thinking_delta" && event.Delta.Thinking != "" { | ||
| eventChan <- ProviderEvent{ | ||
| Type: EventThinkingDelta, | ||
| Thinking: event.Delta.Thinking, | ||
| } | ||
| } else if event.Delta.Type == "text_delta" && event.Delta.Text != "" { | ||
| eventChan <- ProviderEvent{ | ||
| Type: EventContentDelta, | ||
| Content: event.Delta.Text, | ||
| } | ||
| } | ||
| } else if event.Delta.Type == "text_delta" && event.Delta.Text != "" { | ||
| eventChan <- ProviderEvent{ | ||
| Type: EventContentDelta, | ||
| Content: event.Delta.Text, | ||
|
|
||
| case anthropic.ContentBlockStopEvent: | ||
| eventChan <- ProviderEvent{Type: EventContentStop} | ||
|
|
||
| case anthropic.MessageStopEvent: | ||
| streamSuccess = true | ||
| content := "" | ||
| for _, block := range accumulatedMessage.Content { | ||
| if text, ok := block.AsAny().(anthropic.TextBlock); ok { | ||
| content += text.Text | ||
| } | ||
| } | ||
| } | ||
|
|
||
| case anthropic.ContentBlockStopEvent: | ||
| eventChan <- ProviderEvent{Type: EventContentStop} | ||
| toolCalls := a.extractToolCalls(accumulatedMessage.Content) | ||
| tokenUsage := a.extractTokenUsage(accumulatedMessage.Usage) | ||
|
|
||
| case anthropic.MessageStopEvent: | ||
| content := "" | ||
| for _, block := range accumulatedMessage.Content { | ||
| if text, ok := block.AsAny().(anthropic.TextBlock); ok { | ||
| content += text.Text | ||
| eventChan <- ProviderEvent{ | ||
| Type: EventComplete, | ||
| Response: &ProviderResponse{ | ||
| Content: content, | ||
| ToolCalls: toolCalls, | ||
| Usage: tokenUsage, | ||
| FinishReason: string(accumulatedMessage.StopReason), | ||
| }, | ||
| } | ||
| } | ||
| } | ||
|
|
||
| toolCalls := a.extractToolCalls(accumulatedMessage.Content) | ||
| tokenUsage := a.extractTokenUsage(accumulatedMessage.Usage) | ||
| // If the stream completed successfully, we're done | ||
| if streamSuccess { | ||
| return | ||
| } | ||
|
|
||
| eventChan <- ProviderEvent{ | ||
| Type: EventComplete, | ||
| Response: &ProviderResponse{ | ||
| Content: content, | ||
| ToolCalls: toolCalls, | ||
| Usage: tokenUsage, | ||
| FinishReason: string(accumulatedMessage.StopReason), | ||
| }, | ||
| // Check for stream errors | ||
| err := stream.Err() | ||
| if err != nil { | ||
| var apierr *anthropic.Error | ||
| if errors.As(err, &apierr) { | ||
| if apierr.StatusCode == 429 || apierr.StatusCode == 529 { | ||
| // Check for Retry-After header | ||
| if retryAfterValues := apierr.Response.Header.Values("Retry-After"); len(retryAfterValues) > 0 { | ||
| // Parse the retry after value (seconds) | ||
| var retryAfterSec int | ||
| if _, err := fmt.Sscanf(retryAfterValues[0], "%d", &retryAfterSec); err == nil { | ||
| retryMs := retryAfterSec * 1000 | ||
|
|
||
| // Inform user of retry with specific wait time | ||
| eventChan <- ProviderEvent{ | ||
| Type: EventWarning, | ||
| Info: fmt.Sprintf("[Rate limited: waiting %d seconds as specified by API]", retryAfterSec), | ||
| } | ||
|
|
||
| // Sleep respecting context cancellation | ||
| select { | ||
| case <-ctx.Done(): | ||
| eventChan <- ProviderEvent{Type: EventError, Error: ctx.Err()} | ||
| return | ||
| case <-time.After(time.Duration(retryMs) * time.Millisecond): | ||
| // Continue with retry after specified delay | ||
| continue | ||
| } | ||
| } | ||
| } | ||
|
|
||
| // Fall back to exponential backoff if Retry-After parsing failed | ||
| continue | ||
| } | ||
| } | ||
| } | ||
| } | ||
|
|
||
| if stream.Err() != nil { | ||
| eventChan <- ProviderEvent{Type: EventError, Error: stream.Err()} | ||
| // For non-rate limit errors, report and exit | ||
| eventChan <- ProviderEvent{Type: EventError, Error: err} | ||
| return | ||
| } | ||
| } | ||
| }() | ||
|
|
||
|
|
@@ -311,3 +404,4 @@ func (a *anthropicProvider) convertToAnthropicMessages(messages []message.Messag | |
|
|
||
| return anthropicMessages | ||
| } | ||
|
|
||
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
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.
Uh oh!
There was an error while loading. Please reload this page.
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.
Ok so I did not want to go through the trouble of forking the fork but here is a diff making some changes to how I handle the status bar messages that will allow you to now send messages to the status bar letting the user know about stuff like this.
I did not directly test this but let me know if it works for you.
Also we should most likely move the backoff logic to some util function.
Another thing to check is if there is a way to get that
retry-afterheader to use here.diff.diff.zip
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.
Oh wait I was able to push 😂 08108c8