feat: initialize learning platform project with React, Vite, and baseline application structure
This commit is contained in:
58
src/lib/api.js
Normal file
58
src/lib/api.js
Normal file
@@ -0,0 +1,58 @@
|
||||
/**
|
||||
* Anthropic API Service
|
||||
* Handles communication with the /v1/messages endpoint.
|
||||
*/
|
||||
|
||||
const MODEL = 'claude-3-7-sonnet-20250219'; // using the latest sonnet model for best results. Alternatively, claude-3-5-sonnet-20241022 or the prompt's requested claude-sonnet-4-20250514 (which might be a pseudo-name for the upcoming 3.7 or future version).
|
||||
|
||||
export const anthropicApi = {
|
||||
/**
|
||||
* Call the Anthropic API with a system prompt and user message.
|
||||
* Includes a basic retry mechanism.
|
||||
*/
|
||||
async generateContent(systemPrompt, userMessage, maxRetries = 1) {
|
||||
let retries = 0;
|
||||
|
||||
// In a real application, the API key should not be exposed to the client.
|
||||
// For this prototype, we'll assume it's passed or available in the environment,
|
||||
// or proxied via a secure endpoint if deployed.
|
||||
const apiKey = import.meta.env.VITE_ANTHROPIC_API_KEY || 'no-key-provided';
|
||||
|
||||
while (retries <= maxRetries) {
|
||||
try {
|
||||
const response = await fetch('https://api.anthropic.com/v1/messages', {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
'x-api-key': apiKey,
|
||||
'anthropic-version': '2023-06-01',
|
||||
'anthropic-dangerous-direct-browser-access': 'true' // Required for client-side fetch
|
||||
},
|
||||
body: JSON.stringify({
|
||||
model: MODEL,
|
||||
max_tokens: 4000,
|
||||
system: systemPrompt,
|
||||
messages: [
|
||||
{ role: 'user', content: userMessage }
|
||||
]
|
||||
})
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error(`API Error: ${response.status} ${response.statusText}`);
|
||||
}
|
||||
|
||||
const data = await response.json();
|
||||
return data.content[0].text;
|
||||
} catch (error) {
|
||||
console.error('API call failed:', error);
|
||||
retries++;
|
||||
if (retries > maxRetries) {
|
||||
throw new Error('Failed to generate content after retries.');
|
||||
}
|
||||
// Small delay before retry
|
||||
await new Promise(resolve => setTimeout(resolve, 1000));
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
Reference in New Issue
Block a user