Skip to content
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

Add a recursion limit to prevent infinite loops. #350

Open
AndlerRL opened this issue Jan 25, 2025 · 0 comments
Open

Add a recursion limit to prevent infinite loops. #350

AndlerRL opened this issue Jan 25, 2025 · 0 comments

Comments

@AndlerRL
Copy link
Member

⚠️ Potential issue

Add a recursion limit to prevent infinite loops.

The recursive call in improveMessage lacks a base case or maximum retry limit, which could lead to infinite recursion if the AI consistently returns invalid results.

Consider adding a retry limit:

 export async function improveMessage(
   content: string,
   clientType: AiClientType,
   model: string,
+  retryCount: number = 0,
 ): Promise<CleanPromptResult> {
+  const MAX_RETRIES = 3;
+  if (retryCount >= MAX_RETRIES) {
+    return setDefaultPrompt(content);
+  }
   // ... existing code ...
-      return await improveMessage(content, clientType, model)
+      return await improveMessage(content, clientType, model, retryCount + 1)
   // ... rest of the function ...
 }
📝 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.

// * This function improves the message using the AI
export async function improveMessage(
  content: string,
  clientType: AiClientType,
  model: string,
  retryCount: number = 0,
): Promise<CleanPromptResult> {
  const MAX_RETRIES = 3;
  if (retryCount >= MAX_RETRIES) {
    return setDefaultPrompt(content);
  }
  const messageImprovementPrompt = createImprovementPrompt(content)

  try {
    const result = await processWithAi(messageImprovementPrompt, clientType, model)
    const cleanedResult = cleanResult(result)

    if (
      isInvalidResult(cleanedResult.translatedText || cleanedResult.improvedText, content) &&
      cleanedResult.improved
    ) {
      console.warn(
        'AI did not modify the text or returned invalid result. Recursively executing improved prompt.',
      )
      return await improveMessage(content, clientType, model, retryCount + 1)
    }

    return cleanedResult
  } catch (error) {
    const originalText = handleImprovementError(error, content, clientType, model)
    return setDefaultPrompt(originalText)
  }
}

Originally posted by @coderabbitai[bot] in #344 (comment)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant