-
Notifications
You must be signed in to change notification settings - Fork 148
Retry api logic #166
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
base: main
Are you sure you want to change the base?
Retry api logic #166
Conversation
WalkthroughThe update introduces retry logic with exponential attempts to the Changes
Assessment against linked issues
Poem
✨ Finishing Touches
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. 🪧 TipsChatThere are 3 ways to chat with CodeRabbit:
SupportNeed help? Create a ticket on our support page for assistance with any issues or questions. Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments. CodeRabbit Commands (Invoked using PR comments)
Other keywords and placeholders
CodeRabbit Configuration File (
|
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.
Actionable comments posted: 2
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (1)
background.js(3 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (1)
background.js (1)
content.js (2)
response(96-99)response(146-149)
🔇 Additional comments (5)
background.js (5)
178-178: LGTM! Function signature updated correctly.The addition of the
retriesparameter with a default value maintains backward compatibility while enabling configurable retry behavior.
192-200: Good optimization moving payload creation outside the retry loop.This prevents unnecessary object recreation on each retry attempt, improving performance.
251-251: LGTM! Function signature updated correctly.The addition of the
retriesparameter with a default value maintains backward compatibility while enabling configurable retry behavior.
278-286: Good optimization moving payload creation outside the retry loop.This prevents unnecessary object recreation on each retry attempt, improving performance.
58-58: Verified translateText/explainText default-retries usageAll invocations of
translateTextandexplainTextonly pass the requiredtextargument and rely on the defaultretries = 2. No other calls require changes.
| for (let attempt = 0; attempt <= retries; attempt++) { | ||
| try { | ||
| const response = await fetch( | ||
| "https://api.groq.com/openai/v1/chat/completions", | ||
| { | ||
| method: "POST", | ||
| headers: { | ||
| "Content-Type": "application/json", | ||
| Authorization: `Bearer ${groqApiKey}`, | ||
| }, | ||
| body: JSON.stringify(payload), | ||
| } | ||
| ); | ||
| } | ||
|
|
||
| const data = await response.json(); | ||
| const explanation = data.choices[0].message.content.trim(); | ||
| // If response not OK | ||
| if (!response.ok) { | ||
| const errorData = await response.json().catch(() => ({})); | ||
|
|
||
| if (!explanation) { | ||
| throw new Error("Empty explanation received"); | ||
| } | ||
| // Retry only if server error (5xx) | ||
| if (response.status >= 500 && attempt < retries) { | ||
| console.warn(`Retrying explainText (attempt ${attempt + 1})`); | ||
| continue; | ||
| } | ||
|
|
||
| throw new Error(errorData.error?.message || `API error: ${response.status}`); | ||
| } | ||
|
|
||
| // Successful response | ||
| const data = await response.json(); | ||
| const explanation = data.choices[0].message.content.trim(); | ||
|
|
||
| return explanation; | ||
| } catch (error) { | ||
| console.error("Explanation error:", error); | ||
| throw error; | ||
| if (!explanation) { | ||
| throw new Error("Empty explanation received"); | ||
| } | ||
|
|
||
| return explanation; | ||
|
|
||
| } catch (error) { | ||
| // Retry on failure, unless it's the last attempt | ||
| if (attempt === retries) { | ||
| throw error; | ||
| } | ||
| console.warn(`explainText failed on attempt ${attempt + 1}: ${error.message}`); | ||
| } | ||
| } |
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.
🛠️ Refactor suggestion
Apply the same retry improvements as translateText.
The retry logic correctly handles 5xx server errors but has the same enhancement opportunities as the translateText function:
- Missing exponential backoff: Rapid successive retries may overwhelm the server
- Network errors not handled: Fetch exceptions don't trigger retries
Apply the same exponential backoff and network error handling improvements as suggested for the translateText function to maintain consistency between both functions.
🤖 Prompt for AI Agents
In background.js from lines 289 to 333, the retry logic for the explainText
function lacks exponential backoff and does not handle network errors properly.
To fix this, implement an exponential backoff delay before each retry attempt to
avoid overwhelming the server, and ensure that fetch exceptions (network errors)
trigger retries as well. This will align the retry behavior with the
improvements made in the translateText function for consistency and robustness.
| for (let attempt = 0; attempt <= retries; attempt++) { | ||
| try { | ||
| const response = await fetch( | ||
| "https://api.groq.com/openai/v1/chat/completions", | ||
| { | ||
| method: "POST", | ||
| headers: { | ||
| "Content-Type": "application/json", | ||
| Authorization: `Bearer ${groqApiKey}`, | ||
| }, | ||
| body: JSON.stringify(payload), | ||
| } | ||
| ); | ||
| } | ||
|
|
||
| const data = await response.json(); | ||
| const translatedText = data.choices[0].message.content.trim(); | ||
| if (!response.ok) { | ||
| const errorData = await response.json().catch(() => ({})); | ||
|
|
||
| if (!translatedText) { | ||
| throw new Error("Empty translation received"); | ||
| } | ||
| // Retry only on server (5xx) errors | ||
| if (response.status >= 500 && attempt < retries) { | ||
| console.warn(`Retrying translateText (attempt ${attempt + 1})`); | ||
| continue; | ||
| } | ||
|
|
||
| return translatedText; | ||
| } catch (error) { | ||
| console.error("Translation error:", error); | ||
| throw error; | ||
| throw new Error( | ||
| errorData.error?.message || `API error: ${response.status}` | ||
| ); | ||
| } | ||
|
|
||
| const data = await response.json(); | ||
| const translatedText = data.choices[0].message.content.trim(); | ||
|
|
||
| if (!translatedText) { | ||
| throw new Error("Empty translation received"); | ||
| } | ||
|
|
||
| return translatedText; | ||
|
|
||
| } catch (error) { | ||
| if (attempt === retries) { | ||
| throw error; | ||
| } | ||
| console.warn(`translateText failed on attempt ${attempt + 1}: ${error.message}`); | ||
| } | ||
| } |
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.
🛠️ Refactor suggestion
Implement exponential backoff and handle network errors.
The retry logic correctly handles 5xx server errors, but could be enhanced for better resilience:
- Missing exponential backoff: Rapid successive retries may overwhelm the server or hit rate limits
- Network errors not handled: Fetch exceptions (network timeouts, connection issues) don't trigger retries
Consider this enhanced implementation:
for (let attempt = 0; attempt <= retries; attempt++) {
try {
+ // Add exponential backoff delay (except for first attempt)
+ if (attempt > 0) {
+ const delay = Math.min(1000 * Math.pow(2, attempt - 1), 5000);
+ await new Promise(resolve => setTimeout(resolve, delay));
+ }
+
const response = await fetch(
"https://api.groq.com/openai/v1/chat/completions",
{
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${groqApiKey}`,
},
body: JSON.stringify(payload),
}
);
if (!response.ok) {
const errorData = await response.json().catch(() => ({}));
// Retry only on server (5xx) errors
if (response.status >= 500 && attempt < retries) {
console.warn(`Retrying translateText (attempt ${attempt + 1})`);
continue;
}
throw new Error(
errorData.error?.message || `API error: ${response.status}`
);
}
const data = await response.json();
const translatedText = data.choices[0].message.content.trim();
if (!translatedText) {
throw new Error("Empty translation received");
}
return translatedText;
} catch (error) {
+ // Handle network errors (fetch exceptions) for retries
+ const isNetworkError = error.name === 'TypeError' ||
+ error.message.includes('fetch') ||
+ error.message.includes('network');
+
+ if ((isNetworkError || error.message.includes('5')) && attempt < retries) {
+ console.warn(`translateText failed on attempt ${attempt + 1}: ${error.message}`);
+ continue;
+ }
+
if (attempt === retries) {
throw error;
}
- console.warn(`translateText failed on attempt ${attempt + 1}: ${error.message}`);
}
}📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| for (let attempt = 0; attempt <= retries; attempt++) { | |
| try { | |
| const response = await fetch( | |
| "https://api.groq.com/openai/v1/chat/completions", | |
| { | |
| method: "POST", | |
| headers: { | |
| "Content-Type": "application/json", | |
| Authorization: `Bearer ${groqApiKey}`, | |
| }, | |
| body: JSON.stringify(payload), | |
| } | |
| ); | |
| } | |
| const data = await response.json(); | |
| const translatedText = data.choices[0].message.content.trim(); | |
| if (!response.ok) { | |
| const errorData = await response.json().catch(() => ({})); | |
| if (!translatedText) { | |
| throw new Error("Empty translation received"); | |
| } | |
| // Retry only on server (5xx) errors | |
| if (response.status >= 500 && attempt < retries) { | |
| console.warn(`Retrying translateText (attempt ${attempt + 1})`); | |
| continue; | |
| } | |
| return translatedText; | |
| } catch (error) { | |
| console.error("Translation error:", error); | |
| throw error; | |
| throw new Error( | |
| errorData.error?.message || `API error: ${response.status}` | |
| ); | |
| } | |
| const data = await response.json(); | |
| const translatedText = data.choices[0].message.content.trim(); | |
| if (!translatedText) { | |
| throw new Error("Empty translation received"); | |
| } | |
| return translatedText; | |
| } catch (error) { | |
| if (attempt === retries) { | |
| throw error; | |
| } | |
| console.warn(`translateText failed on attempt ${attempt + 1}: ${error.message}`); | |
| } | |
| } | |
| for (let attempt = 0; attempt <= retries; attempt++) { | |
| try { | |
| // Add exponential backoff delay (except for first attempt) | |
| if (attempt > 0) { | |
| const delay = Math.min(1000 * Math.pow(2, attempt - 1), 5000); | |
| await new Promise(resolve => setTimeout(resolve, delay)); | |
| } | |
| const response = await fetch( | |
| "https://api.groq.com/openai/v1/chat/completions", | |
| { | |
| method: "POST", | |
| headers: { | |
| "Content-Type": "application/json", | |
| Authorization: `Bearer ${groqApiKey}`, | |
| }, | |
| body: JSON.stringify(payload), | |
| } | |
| ); | |
| if (!response.ok) { | |
| const errorData = await response.json().catch(() => ({})); | |
| // Retry only on server (5xx) errors | |
| if (response.status >= 500 && attempt < retries) { | |
| console.warn(`Retrying translateText (attempt ${attempt + 1})`); | |
| continue; | |
| } | |
| throw new Error( | |
| errorData.error?.message || `API error: ${response.status}` | |
| ); | |
| } | |
| const data = await response.json(); | |
| const translatedText = data.choices[0].message.content.trim(); | |
| if (!translatedText) { | |
| throw new Error("Empty translation received"); | |
| } | |
| return translatedText; | |
| } catch (error) { | |
| // Handle network errors (fetch exceptions) for retries | |
| const isNetworkError = | |
| error.name === 'TypeError' || | |
| error.message.includes('fetch') || | |
| error.message.includes('network'); | |
| if ((isNetworkError || error.message.includes('5')) && attempt < retries) { | |
| console.warn(`translateText failed on attempt ${attempt + 1}: ${error.message}`); | |
| continue; | |
| } | |
| if (attempt === retries) { | |
| throw error; | |
| } | |
| } | |
| } |
🤖 Prompt for AI Agents
In background.js between lines 202 and 245, the retry logic for the fetch call
lacks exponential backoff and does not handle network errors properly. To fix
this, implement an exponential backoff delay before each retry attempt to space
out retries progressively. Also, ensure that any fetch exceptions (network
errors) are caught and trigger a retry, not just server 5xx responses. Add a
delay function and call it with an increasing timeout before continuing retries,
and wrap the fetch call in a try-catch that retries on both network errors and
server errors.
🔧 Overview
This PR introduces a retry mechanism for API requests made to the Groq endpoint (
translateTextandexplainTextfunctions in background.js). This addresses the problem where transient failures like network issues or 5xx server errors caused immediate failures and poor UX.✅ What’s Changed
console.warn()💡 Why This Matters
Without retry logic, temporary network issues or Groq server downtime causes immediate user-facing failures. Now, the extension gracefully retries in the background, improving overall reliability and user trust.
🔗 Linked Issue
Fixes #12
🧪 Testing
Summary by CodeRabbit
New Features
Bug Fixes