Integrate Claude AI (#36)

* Added Claude AI

* Reverted explicit type annotation

* Explicit handling for claude ai

* Ensures consistent behavior

---------

Co-authored-by: Devashish Nayak <m_891815@AMBUS001458.local>
Co-authored-by: Devashish Nayak <m_891815@MacBookPro.attlocal.net>
main
Devashish Nayak 2 years ago committed by GitHub
parent a65c2a858d
commit 0ada479235
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194

@ -7,7 +7,7 @@ import { OpenAI } from "openai"
interface Config {
apiKey: string;
apiProvider: "openai" | "gemini"; // Added provider selection
apiProvider: "openai" | "gemini" | "anthropic"; // Added provider selection
extractionModel: string;
solutionModel: string;
debuggingModel: string;
@ -58,7 +58,7 @@ export class ConfigHelper extends EventEmitter {
/**
* Validate and sanitize model selection to ensure only allowed models are used
*/
private sanitizeModelSelection(model: string, provider: "openai" | "gemini"): string {
private sanitizeModelSelection(model: string, provider: "openai" | "gemini" | "anthropic"): string {
if (provider === "openai") {
// Only allow gpt-4o and gpt-4o-mini for OpenAI
const allowedModels = ['gpt-4o', 'gpt-4o-mini'];
@ -67,7 +67,7 @@ export class ConfigHelper extends EventEmitter {
return 'gpt-4o';
}
return model;
} else {
} else if (provider === "gemini") {
// Only allow gemini-1.5-pro and gemini-2.0-flash for Gemini
const allowedModels = ['gemini-1.5-pro', 'gemini-2.0-flash'];
if (!allowedModels.includes(model)) {
@ -75,7 +75,17 @@ export class ConfigHelper extends EventEmitter {
return 'gemini-2.0-flash'; // Changed default to flash
}
return model;
} else if (provider === "anthropic") {
// Only allow Claude models
const allowedModels = ['claude-3-opus-20240229', 'claude-3-sonnet-20240229', 'claude-3-haiku-20240307'];
if (!allowedModels.includes(model)) {
console.warn(`Invalid Anthropic model specified: ${model}. Using default model: claude-3-opus-20240229`);
return 'claude-3-opus-20240229';
}
return model;
}
// Default fallback
return model;
}
public loadConfig(): Config {
@ -85,7 +95,7 @@ export class ConfigHelper extends EventEmitter {
const config = JSON.parse(configData);
// Ensure apiProvider is a valid value
if (config.apiProvider !== "openai" && config.apiProvider !== "gemini") {
if (config.apiProvider !== "openai" && config.apiProvider !== "gemini" && config.apiProvider !== "anthropic") {
config.apiProvider = "gemini"; // Default to Gemini if invalid
}
@ -146,6 +156,9 @@ export class ConfigHelper extends EventEmitter {
if (updates.apiKey.trim().startsWith('sk-')) {
provider = "openai";
console.log("Auto-detected OpenAI API key format");
} else if (updates.apiKey.trim().startsWith('sk-ant-')) {
provider = "anthropic";
console.log("Auto-detected Anthropic API key format");
} else {
provider = "gemini";
console.log("Using Gemini API key format (default)");
@ -161,6 +174,10 @@ export class ConfigHelper extends EventEmitter {
updates.extractionModel = "gpt-4o";
updates.solutionModel = "gpt-4o";
updates.debuggingModel = "gpt-4o";
} else if (updates.apiProvider === "anthropic") {
updates.extractionModel = "claude-3-opus-20240229";
updates.solutionModel = "claude-3-opus-20240229";
updates.debuggingModel = "claude-3-opus-20240229";
} else {
updates.extractionModel = "gemini-2.0-flash";
updates.solutionModel = "gemini-2.0-flash";
@ -208,11 +225,15 @@ export class ConfigHelper extends EventEmitter {
/**
* Validate the API key format
*/
public isValidApiKeyFormat(apiKey: string, provider?: "openai" | "gemini"): boolean {
public isValidApiKeyFormat(apiKey: string, provider?: "openai" | "gemini" | "anthropic" ): boolean {
// If provider is not specified, attempt to auto-detect
if (!provider) {
if (apiKey.trim().startsWith('sk-')) {
provider = "openai";
if (apiKey.trim().startsWith('sk-ant-')) {
provider = "anthropic";
} else {
provider = "openai";
}
} else {
provider = "gemini";
}
@ -224,6 +245,9 @@ export class ConfigHelper extends EventEmitter {
} else if (provider === "gemini") {
// Basic format validation for Gemini API keys (usually alphanumeric with no specific prefix)
return apiKey.trim().length >= 10; // Assuming Gemini keys are at least 10 chars
} else if (provider === "anthropic") {
// Basic format validation for Anthropic API keys
return /^sk-ant-[a-zA-Z0-9]{32,}$/.test(apiKey.trim());
}
return false;
@ -264,12 +288,17 @@ export class ConfigHelper extends EventEmitter {
/**
* Test API key with the selected provider
*/
public async testApiKey(apiKey: string, provider?: "openai" | "gemini"): Promise<{valid: boolean, error?: string}> {
public async testApiKey(apiKey: string, provider?: "openai" | "gemini" | "anthropic"): Promise<{valid: boolean, error?: string}> {
// Auto-detect provider based on key format if not specified
if (!provider) {
if (apiKey.trim().startsWith('sk-')) {
provider = "openai";
console.log("Auto-detected OpenAI API key format for testing");
if (apiKey.trim().startsWith('sk-ant-')) {
provider = "anthropic";
console.log("Auto-detected Anthropic API key format for testing");
} else {
provider = "openai";
console.log("Auto-detected OpenAI API key format for testing");
}
} else {
provider = "gemini";
console.log("Using Gemini API key format for testing (default)");
@ -280,6 +309,8 @@ export class ConfigHelper extends EventEmitter {
return this.testOpenAIKey(apiKey);
} else if (provider === "gemini") {
return this.testGeminiKey(apiKey);
} else if (provider === "anthropic") {
return this.testAnthropicKey(apiKey);
}
return { valid: false, error: "Unknown API provider" };
@ -338,6 +369,31 @@ export class ConfigHelper extends EventEmitter {
return { valid: false, error: errorMessage };
}
}
/**
* Test Anthropic API key
* Note: This is a simplified implementation since we don't have the actual Anthropic client
*/
private async testAnthropicKey(apiKey: string): Promise<{valid: boolean, error?: string}> {
try {
// For now, we'll just do a basic check to ensure the key exists and has valid format
// In production, you would connect to the Anthropic API and validate the key
if (apiKey && /^sk-ant-[a-zA-Z0-9]{32,}$/.test(apiKey.trim())) {
// Here you would actually validate the key with an Anthropic API call
return { valid: true };
}
return { valid: false, error: 'Invalid Anthropic API key format.' };
} catch (error: any) {
console.error('Anthropic API key test failed:', error);
let errorMessage = 'Unknown error validating Anthropic API key';
if (error.message) {
errorMessage = `Error: ${error.message}`;
}
return { valid: false, error: errorMessage };
}
}
}
// Export a singleton instance

@ -7,6 +7,7 @@ import * as axios from "axios"
import { app, BrowserWindow, dialog } from "electron"
import { OpenAI } from "openai"
import { configHelper } from "./ConfigHelper"
import Anthropic from '@anthropic-ai/sdk';
// Interface for Gemini API requests
interface GeminiMessage {
@ -30,12 +31,24 @@ interface GeminiResponse {
finishReason: string;
}>;
}
interface AnthropicMessage {
role: 'user' | 'assistant';
content: Array<{
type: 'text' | 'image';
text?: string;
source?: {
type: 'base64';
media_type: string;
data: string;
};
}>;
}
export class ProcessingHelper {
private deps: IProcessingHelperDeps
private screenshotHelper: ScreenshotHelper
private openaiClient: OpenAI | null = null
private geminiApiKey: string | null = null
private anthropicClient: Anthropic | null = null
// AbortControllers for API requests
private currentProcessingAbortController: AbortController | null = null
@ -69,27 +82,50 @@ export class ProcessingHelper {
maxRetries: 2 // Retry up to 2 times
});
this.geminiApiKey = null;
this.anthropicClient = null;
console.log("OpenAI client initialized successfully");
} else {
this.openaiClient = null;
this.geminiApiKey = null;
this.anthropicClient = null;
console.warn("No API key available, OpenAI client not initialized");
}
} else {
} else if (config.apiProvider === "gemini"){
// Gemini client initialization
this.openaiClient = null;
this.anthropicClient = null;
if (config.apiKey) {
this.geminiApiKey = config.apiKey;
console.log("Gemini API key set successfully");
} else {
this.openaiClient = null;
this.geminiApiKey = null;
this.anthropicClient = null;
console.warn("No API key available, Gemini client not initialized");
}
} else if (config.apiProvider === "anthropic") {
// Reset other clients
this.openaiClient = null;
this.geminiApiKey = null;
if (config.apiKey) {
this.anthropicClient = new Anthropic({
apiKey: config.apiKey,
timeout: 60000,
maxRetries: 2
});
console.log("Anthropic client initialized successfully");
} else {
this.openaiClient = null;
this.geminiApiKey = null;
this.anthropicClient = null;
console.warn("No API key available, Anthropic client not initialized");
}
}
} catch (error) {
console.error("Failed to initialize AI client:", error);
this.openaiClient = null;
this.geminiApiKey = null;
this.anthropicClient = null;
}
}
@ -187,6 +223,17 @@ export class ProcessingHelper {
);
return;
}
} else if (config.apiProvider === "anthropic" && !this.anthropicClient) {
// Add check for Anthropic client
this.initializeAIClient();
if (!this.anthropicClient) {
console.error("Anthropic client not initialized");
mainWindow.webContents.send(
this.deps.PROCESSING_EVENTS.API_KEY_INVALID
);
return;
}
}
const view = this.deps.getView()
@ -502,7 +549,7 @@ export class ProcessingHelper {
error: "Failed to parse problem information. Please try again or use clearer screenshots."
};
}
} else {
} else if (config.apiProvider === "gemini") {
// Use Gemini API
if (!this.geminiApiKey) {
return {
@ -561,6 +608,66 @@ export class ProcessingHelper {
error: "Failed to process with Gemini API. Please check your API key or try again later."
};
}
} else if (config.apiProvider === "anthropic") {
if (!this.anthropicClient) {
return {
success: false,
error: "Anthropic API key not configured. Please check your settings."
};
}
try {
const messages = [
{
role: "user" as const,
content: [
{
type: "text" as const,
text: `Extract the coding problem details from these screenshots. Return in JSON format with these fields: problem_statement, constraints, example_input, example_output. Preferred coding language is ${language}.`
},
...imageDataList.map(data => ({
type: "image" as const,
source: {
type: "base64" as const,
media_type: "image/png" as const,
data: data
}
}))
]
}
];
const response = await this.anthropicClient.messages.create({
model: config.extractionModel || "claude-3-opus-20240229",
max_tokens: 4000,
messages: messages,
temperature: 0.2
});
const responseText = (response.content[0] as { type: 'text', text: string }).text;
const jsonText = responseText.replace(/```json|```/g, '').trim();
problemInfo = JSON.parse(jsonText);
} catch (error: any) {
console.error("Error using Anthropic API:", error);
// Add specific handling for Claude's limitations
if (error.status === 429) {
return {
success: false,
error: "Claude API rate limit exceeded. Please wait a few minutes before trying again."
};
} else if (error.status === 413 || (error.message && error.message.includes("token"))) {
return {
success: false,
error: "Your screenshots contain too much information for Claude to process. Switch to OpenAI or Gemini in settings which can handle larger inputs."
};
}
return {
success: false,
error: "Failed to process with Anthropic API. Please check your API key or try again later."
};
}
}
// Update the user on progress
@ -712,7 +819,7 @@ Your solution should be efficient, well-commented, and handle edge cases.
});
responseContent = solutionResponse.choices[0].message.content;
} else {
} else if (config.apiProvider === "gemini") {
// Gemini processing
if (!this.geminiApiKey) {
return {
@ -761,6 +868,58 @@ Your solution should be efficient, well-commented, and handle edge cases.
error: "Failed to generate solution with Gemini API. Please check your API key or try again later."
};
}
} else if (config.apiProvider === "anthropic") {
// Anthropic processing
if (!this.anthropicClient) {
return {
success: false,
error: "Anthropic API key not configured. Please check your settings."
};
}
try {
const messages = [
{
role: "user" as const,
content: [
{
type: "text" as const,
text: `You are an expert coding interview assistant. Provide a clear, optimal solution with detailed explanations for this problem:\n\n${promptText}`
}
]
}
];
// Send to Anthropic API
const response = await this.anthropicClient.messages.create({
model: config.solutionModel || "claude-3-opus-20240229",
max_tokens: 4000,
messages: messages,
temperature: 0.2
});
responseContent = (response.content[0] as { type: 'text', text: string }).text;
} catch (error: any) {
console.error("Error using Anthropic API for solution:", error);
// Add specific handling for Claude's limitations
if (error.status === 429) {
return {
success: false,
error: "Claude API rate limit exceeded. Please wait a few minutes before trying again."
};
} else if (error.status === 413 || (error.message && error.message.includes("token"))) {
return {
success: false,
error: "Your screenshots contain too much information for Claude to process. Switch to OpenAI or Gemini in settings which can handle larger inputs."
};
}
return {
success: false,
error: "Failed to generate solution with Anthropic API. Please check your API key or try again later."
};
}
}
// Extract parts from the response
@ -782,7 +941,7 @@ Your solution should be efficient, well-commented, and handle edge cases.
} else {
// If no bullet points found, split by newlines and filter empty lines
thoughts = thoughtsMatch[1].split('\n')
.map(line => line.trim())
.map((line) => line.trim())
.filter(Boolean);
}
}
@ -949,7 +1108,7 @@ If you include code examples, use proper markdown code blocks with language spec
});
debugContent = debugResponse.choices[0].message.content;
} else {
} else if (config.apiProvider === "gemini") {
if (!this.geminiApiKey) {
return {
success: false,
@ -1030,8 +1189,98 @@ If you include code examples, use proper markdown code blocks with language spec
error: "Failed to process debug request with Gemini API. Please check your API key or try again later."
};
}
} else if (config.apiProvider === "anthropic") {
if (!this.anthropicClient) {
return {
success: false,
error: "Anthropic API key not configured. Please check your settings."
};
}
try {
const debugPrompt = `
You are a coding interview assistant helping debug and improve solutions. Analyze these screenshots which include either error messages, incorrect outputs, or test cases, and provide detailed debugging help.
I'm solving this coding problem: "${problemInfo.problem_statement}" in ${language}. I need help with debugging or improving my solution.
YOUR RESPONSE MUST FOLLOW THIS EXACT STRUCTURE WITH THESE SECTION HEADERS:
### Issues Identified
- List each issue as a bullet point with clear explanation
### Specific Improvements and Corrections
- List specific code changes needed as bullet points
### Optimizations
- List any performance optimizations if applicable
### Explanation of Changes Needed
Here provide a clear explanation of why the changes are needed
### Key Points
- Summary bullet points of the most important takeaways
If you include code examples, use proper markdown code blocks with language specification.
`;
const messages = [
{
role: "user" as const,
content: [
{
type: "text" as const,
text: debugPrompt
},
...imageDataList.map(data => ({
type: "image" as const,
source: {
type: "base64" as const,
media_type: "image/png" as const,
data: data
}
}))
]
}
];
if (mainWindow) {
mainWindow.webContents.send("processing-status", {
message: "Analyzing code and generating debug feedback with Claude...",
progress: 60
});
}
const response = await this.anthropicClient.messages.create({
model: config.debuggingModel || "claude-3-opus-20240229",
max_tokens: 4000,
messages: messages,
temperature: 0.2
});
debugContent = (response.content[0] as { type: 'text', text: string }).text;
} catch (error: any) {
console.error("Error using Anthropic API for debugging:", error);
// Add specific handling for Claude's limitations
if (error.status === 429) {
return {
success: false,
error: "Claude API rate limit exceeded. Please wait a few minutes before trying again."
};
} else if (error.status === 413 || (error.message && error.message.includes("token"))) {
return {
success: false,
error: "Your screenshots contain too much information for Claude to process. Switch to OpenAI or Gemini in settings which can handle larger inputs."
};
}
return {
success: false,
error: "Failed to process debug request with Anthropic API. Please check your API key or try again later."
};
}
}
if (mainWindow) {
mainWindow.webContents.send("processing-status", {
message: "Debug analysis complete",

@ -120,6 +120,7 @@
"license": "AGPL-3.0-or-later",
"description": "An invisible desktop application to help you pass your technical interviews.",
"dependencies": {
"@anthropic-ai/sdk": "^0.39.0",
"@electron/notarize": "^2.3.0",
"@emotion/react": "^11.11.0",
"@emotion/styled": "^11.11.0",

@ -13,7 +13,7 @@ import { Button } from "../ui/button";
import { Settings } from "lucide-react";
import { useToast } from "../../contexts/toast";
type APIProvider = "openai" | "gemini";
type APIProvider = "openai" | "gemini" | "anthropic";
type AIModel = {
id: string;
@ -27,6 +27,7 @@ type ModelCategory = {
description: string;
openaiModels: AIModel[];
geminiModels: AIModel[];
anthropicModels: AIModel[];
};
// Define available models for each category
@ -58,6 +59,23 @@ const modelCategories: ModelCategory[] = [
name: "Gemini 2.0 Flash",
description: "Faster, more cost-effective option"
}
],
anthropicModels: [
{
id: "claude-3-opus-20240229",
name: "Claude 3 Opus",
description: "Best overall performance for problem extraction"
},
{
id: "claude-3-sonnet-20240229",
name: "Claude 3 Sonnet",
description: "Balanced performance and speed"
},
{
id: "claude-3-haiku-20240307",
name: "Claude 3 Haiku",
description: "Fastest, most cost-effective option"
}
]
},
{
@ -87,6 +105,23 @@ const modelCategories: ModelCategory[] = [
name: "Gemini 2.0 Flash",
description: "Faster, more cost-effective option"
}
],
anthropicModels: [
{
id: "claude-3-opus-20240229",
name: "Claude 3 Opus",
description: "Strong overall performance for coding tasks"
},
{
id: "claude-3-sonnet-20240229",
name: "Claude 3 Sonnet",
description: "Balanced performance and speed"
},
{
id: "claude-3-haiku-20240307",
name: "Claude 3 Haiku",
description: "Faster, more cost-effective option"
}
]
},
{
@ -116,6 +151,23 @@ const modelCategories: ModelCategory[] = [
name: "Gemini 2.0 Flash",
description: "Faster, more cost-effective option"
}
],
anthropicModels: [
{
id: "claude-3-opus-20240229",
name: "Claude 3 Opus",
description: "Best for analyzing code and error messages"
},
{
id: "claude-3-sonnet-20240229",
name: "Claude 3 Sonnet",
description: "Balanced performance and speed"
},
{
id: "claude-3-haiku-20240307",
name: "Claude 3 Haiku",
description: "Faster, more cost-effective option"
}
]
}
];
@ -191,10 +243,14 @@ export function SettingsDialog({ open: externalOpen, onOpenChange }: SettingsDia
setExtractionModel("gpt-4o");
setSolutionModel("gpt-4o");
setDebuggingModel("gpt-4o");
} else {
} else if (provider === "gemini") {
setExtractionModel("gemini-1.5-pro");
setSolutionModel("gemini-1.5-pro");
setDebuggingModel("gemini-1.5-pro");
} else if (provider === "anthropic") {
setExtractionModel("claude-3-opus-20240229");
setSolutionModel("claude-3-opus-20240229");
setDebuggingModel("claude-3-opus-20240229");
}
};
@ -310,19 +366,45 @@ export function SettingsDialog({ open: externalOpen, onOpenChange }: SettingsDia
</div>
</div>
</div>
<div
className={`flex-1 p-2 rounded-lg cursor-pointer transition-colors ${
apiProvider === "anthropic"
? "bg-white/10 border border-white/20"
: "bg-black/30 border border-white/5 hover:bg-white/5"
}`}
onClick={() => handleProviderChange("anthropic")}
>
<div className="flex items-center gap-2">
<div
className={`w-3 h-3 rounded-full ${
apiProvider === "anthropic" ? "bg-white" : "bg-white/20"
}`}
/>
<div className="flex flex-col">
<p className="font-medium text-white text-sm">Claude</p>
<p className="text-xs text-white/60">Claude 3 models</p>
</div>
</div>
</div>
</div>
</div>
<div className="space-y-2">
<label className="text-sm font-medium text-white" htmlFor="apiKey">
{apiProvider === "openai" ? "OpenAI API Key" : "Gemini API Key"}
{apiProvider === "openai" ? "OpenAI API Key" :
apiProvider === "gemini" ? "Gemini API Key" :
"Anthropic API Key"}
</label>
<Input
id="apiKey"
type="password"
value={apiKey}
onChange={(e) => setApiKey(e.target.value)}
placeholder={apiProvider === "openai" ? "sk-..." : "Enter your Gemini API key"}
placeholder={
apiProvider === "openai" ? "sk-..." :
apiProvider === "gemini" ? "Enter your Gemini API key" :
"sk-ant-..."
}
className="bg-black/50 border-white/10 text-white"
/>
{apiKey && (
@ -347,7 +429,7 @@ export function SettingsDialog({ open: externalOpen, onOpenChange }: SettingsDia
</p>
<p className="text-xs text-white/60">3. Create a new secret key and paste it here</p>
</>
) : (
) : apiProvider === "gemini" ? (
<>
<p className="text-xs text-white/60 mb-1">1. Create an account at <button
onClick={() => openExternalLink('https://aistudio.google.com/')}
@ -359,6 +441,18 @@ export function SettingsDialog({ open: externalOpen, onOpenChange }: SettingsDia
</p>
<p className="text-xs text-white/60">3. Create a new API key and paste it here</p>
</>
) : (
<>
<p className="text-xs text-white/60 mb-1">1. Create an account at <button
onClick={() => openExternalLink('https://console.anthropic.com/signup')}
className="text-blue-400 hover:underline cursor-pointer">Anthropic</button>
</p>
<p className="text-xs text-white/60 mb-1">2. Go to the <button
onClick={() => openExternalLink('https://console.anthropic.com/settings/keys')}
className="text-blue-400 hover:underline cursor-pointer">API Keys</button> section
</p>
<p className="text-xs text-white/60">3. Create a new API key and paste it here</p>
</>
)}
</div>
</div>
@ -414,7 +508,10 @@ export function SettingsDialog({ open: externalOpen, onOpenChange }: SettingsDia
{modelCategories.map((category) => {
// Get the appropriate model list based on selected provider
const models = apiProvider === "openai" ? category.openaiModels : category.geminiModels;
const models =
apiProvider === "openai" ? category.openaiModels :
apiProvider === "gemini" ? category.geminiModels :
category.anthropicModels;
return (
<div key={category.key} className="mb-4">

Loading…
Cancel
Save