Skip to content

Instantly share code, notes, and snippets.

@WomB0ComB0
Last active February 14, 2025 22:38
Show Gist options
  • Save WomB0ComB0/eba64fb29611c712e08251683caff931 to your computer and use it in GitHub Desktop.
Save WomB0ComB0/eba64fb29611c712e08251683caff931 to your computer and use it in GitHub Desktop.
Local LLM powered error handler.
import { GoogleGenerativeAI } from '@google/generative-ai';
// Initialize the Google Generative AI client
const genAI = new GoogleGenerativeAI('your-google-api-key'); // Replace with your actual API key
const model = genAI.getGenerativeModel({ model: 'gemini-pro' });
// Example function that might throw an error
function riskyOperation(input: string): string {
if (input.length < 5) {
throw new Error('Input is too short!');
}
return `Processed: ${input}`;
}
// Function to handle errors and attempt to fix them using Google's Generative AI
async function handleErrorAndFix(error: Error, context: string): Promise<string> {
try {
const prompt = `Fix for: ${error.message}. Context: ${context}`;
const result = await model.generateContent(prompt);
const response = await result.response;
const text = response.text(); // Extract the generated text
return text.trim(); // Return the LLM-generated fix
} catch (err) {
console.error('Failed to fix error using Generative AI:', err);
throw error; // Re-throw the original error if the LLM fix fails
}
}
// Main function to execute the risky operation and handle errors
async function executeWithErrorHandling(input: string): Promise<string> {
try {
return riskyOperation(input); // Execute the risky operation
} catch (error) {
if (error instanceof Error) {
console.error('Error caught:', error.message);
try {
const fixedResult = await handleErrorAndFix(error, `Input: ${input}`);
return `Error occurred but fixed: ${fixedResult}`;
} catch (fixError) {
console.error('Failed to fix error:', fixError);
throw error; // Return the original error if the LLM fix fails
}
} else {
throw new Error('An unknown error occurred.'); // Handle non-Error types
}
}
}
// Example usage
(async () => {
try {
const result = await executeWithErrorHandling('abc'); // Input that will cause an error
console.log(result);
} catch (error) {
console.error('Final error:', error.message); // Original error is returned if LLM fix fails
}
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment