@moontra/moonui-pro
Version:
Premium React components for MoonUI - Advanced UI library with 50+ pro components including performance, interactive, and gesture components
377 lines (320 loc) • 13.9 kB
text/typescript
// AI Provider Interfaces and Implementations
export interface AIResponse {
text: string;
error?: string;
}
export interface AIProvider {
generateText(prompt: string): Promise<string>;
rewrite(text: string): Promise<string>;
expand(text: string): Promise<string>;
summarize(text: string): Promise<string>;
fixGrammar(text: string): Promise<string>;
translate(text: string, targetLang: string): Promise<string>;
changeTone(text: string, tone: string): Promise<string>;
continueWriting(text: string): Promise<string>;
improveWriting(text: string): Promise<string>;
generateIdeas(text: string): Promise<string>;
complete(text: string): Promise<string>;
}
export interface AIProviderConfig {
apiKey: string;
model?: string;
temperature?: number;
maxTokens?: number;
}
// Gemini Provider Implementation
export class GeminiProvider implements AIProvider {
private apiKey: string;
private model: string;
private apiUrl = 'https://generativelanguage.googleapis.com/v1beta/models';
constructor(config: AIProviderConfig) {
this.apiKey = config.apiKey;
// Use gemini-2.0-flash as shown in the curl example
this.model = config.model || 'gemini-2.0-flash';
}
private async callGeminiAPI(prompt: string): Promise<string> {
try {
const response = await fetch(`${this.apiUrl}/${this.model}:generateContent`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-goog-api-key': this.apiKey
},
body: JSON.stringify({
contents: [{
parts: [{
text: prompt
}]
}]
})
});
if (!response.ok) {
const errorData = await response.text();
console.error('Gemini API error response:', errorData);
throw new Error(`Gemini API error: ${response.status} ${response.statusText} - ${errorData}`);
}
const data = await response.json();
// Check for API errors in response
if (data.error) {
throw new Error(`Gemini API error: ${data.error.message || JSON.stringify(data.error)}`);
}
// Check if content was blocked
if (data.candidates?.[0]?.finishReason === 'SAFETY') {
throw new Error('Content was blocked by safety filters');
}
const text = data.candidates?.[0]?.content?.parts?.[0]?.text;
if (!text) {
console.error('Gemini API response:', JSON.stringify(data, null, 2));
throw new Error('No text content in Gemini API response');
}
return text.trim();
} catch (error) {
console.error('Gemini API error details:', error);
if (error instanceof Error) {
throw error;
}
throw new Error('Unknown error occurred while calling Gemini API');
}
}
async generateText(prompt: string): Promise<string> {
return this.callGeminiAPI(prompt);
}
async rewrite(text: string): Promise<string> {
const prompt = `Rewrite the following text to make it clearer, more engaging, and better structured while maintaining the original meaning. Respond in the same language:\n\n${text}`;
return this.callGeminiAPI(prompt);
}
async expand(text: string): Promise<string> {
const prompt = `Expand this text with more details, specific examples, explanations, and supporting information while keeping the same structure and tone. Respond in the same language:\n\n${text}`;
return this.callGeminiAPI(prompt);
}
async summarize(text: string): Promise<string> {
const prompt = `Create a comprehensive summary that captures all key points, main arguments, important details, and significant examples from the text. The summary should be thorough enough to understand the core message. Respond in the same language:\n\n${text}`;
return this.callGeminiAPI(prompt);
}
async fixGrammar(text: string): Promise<string> {
const prompt = `Fix grammar and spelling errors. Respond in the same language:\n\n${text}`;
return this.callGeminiAPI(prompt);
}
async translate(text: string, targetLang: string): Promise<string> {
const prompt = `Translate to ${targetLang}:\n\n${text}`;
return this.callGeminiAPI(prompt);
}
async changeTone(text: string, tone: string): Promise<string> {
const toneDescriptions: Record<string, string> = {
professional: 'professional and business-appropriate',
casual: 'casual and conversational',
friendly: 'warm and friendly',
formal: 'formal and academic'
};
const toneDesc = toneDescriptions[tone] || tone;
const prompt = `Rewrite the following text in a ${toneDesc} tone. IMPORTANT: Respond in the SAME LANGUAGE as the input text. Only return the rewritten text, nothing else:\n\n${text}`;
return this.callGeminiAPI(prompt);
}
async continueWriting(text: string): Promise<string> {
const prompt = `Continue writing from where this text ends. IMPORTANT: Respond in the SAME LANGUAGE as the input text. Only return the continuation, nothing else:\n\n${text}`;
return this.callGeminiAPI(prompt);
}
async improveWriting(text: string): Promise<string> {
const prompt = `Improve the following text by making it more compelling, clear, and well-structured. IMPORTANT: Respond in the SAME LANGUAGE as the input text. Only return the improved text, nothing else:\n\n${text}`;
return this.callGeminiAPI(prompt);
}
async generateIdeas(text: string): Promise<string> {
const prompt = `Generate creative ideas and suggestions based on this topic. IMPORTANT: Respond in the SAME LANGUAGE as the input text. Format as a bullet list:\n\n${text}`;
return this.callGeminiAPI(prompt);
}
async complete(text: string): Promise<string> {
const prompt = `Complete this text naturally. IMPORTANT: Respond in the SAME LANGUAGE as the input text. Only return the completion, nothing else:\n\n${text}`;
return this.callGeminiAPI(prompt);
}
}
// OpenAI Provider Implementation
export class OpenAIProvider implements AIProvider {
private apiKey: string;
private model: string;
private temperature: number;
private maxTokens: number;
private apiUrl = 'https://api.openai.com/v1/chat/completions';
constructor(config: AIProviderConfig) {
this.apiKey = config.apiKey;
this.model = config.model || 'gpt-3.5-turbo';
this.temperature = config.temperature || 0.7;
this.maxTokens = config.maxTokens || 1000;
}
private async callOpenAI(systemPrompt: string, userPrompt: string): Promise<string> {
try {
const response = await fetch(this.apiUrl, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${this.apiKey}`
},
body: JSON.stringify({
model: this.model,
messages: [
{ role: 'system', content: systemPrompt },
{ role: 'user', content: userPrompt }
],
temperature: this.temperature,
max_tokens: this.maxTokens
})
});
if (!response.ok) {
throw new Error(`OpenAI API error: ${response.statusText}`);
}
const data = await response.json();
return data.choices?.[0]?.message?.content || '';
} catch (error) {
console.error('OpenAI API error:', error);
throw error;
}
}
async generateText(prompt: string): Promise<string> {
return this.callOpenAI('You are a helpful writing assistant. Always respond in the same language as the input text.', prompt);
}
async rewrite(text: string): Promise<string> {
return this.callOpenAI(
'Rewrite the text to be clearer, more engaging, and better structured while maintaining the original meaning. Respond in the same language as the input.',
text
);
}
async expand(text: string): Promise<string> {
return this.callOpenAI(
'Expand the text with more details, specific examples, explanations, and supporting information while keeping the same structure and tone. Respond in the same language as the input.',
text
);
}
async summarize(text: string): Promise<string> {
return this.callOpenAI(
'Create a comprehensive summary that captures all key points, main arguments, important details, and significant examples. The summary should be thorough enough to understand the core message. Respond in the same language as the input.',
text
);
}
async fixGrammar(text: string): Promise<string> {
return this.callOpenAI(
'You are a grammar expert. Fix all grammar and spelling errors. Always respond in the same language as the input text.',
text
);
}
async translate(text: string, targetLang: string): Promise<string> {
return this.callOpenAI(
`You are a professional translator. Translate to ${targetLang}.`,
text
);
}
async changeTone(text: string, tone: string): Promise<string> {
return this.callOpenAI(
`You are a writing expert. Rewrite the text in a ${tone} tone. Always respond in the same language as the input text.`,
text
);
}
async continueWriting(text: string): Promise<string> {
return this.callOpenAI(
'You are a creative writer. Continue writing from where the text ends. Always respond in the same language as the input text.',
text
);
}
async improveWriting(text: string): Promise<string> {
return this.callOpenAI(
'You are a professional editor. Improve the text quality. Always respond in the same language as the input text.',
text
);
}
async generateIdeas(text: string): Promise<string> {
return this.callOpenAI(
'You are a creative consultant. Generate ideas based on the topic. Always respond in the same language as the input text.',
text
);
}
async complete(text: string): Promise<string> {
return this.callOpenAI(
'You are a writing assistant. Complete the text naturally. Always respond in the same language as the input text.',
text
);
}
}
// Claude Provider Implementation
export class ClaudeProvider implements AIProvider {
private apiKey: string;
private model: string;
private apiUrl = 'https://api.anthropic.com/v1/messages';
constructor(config: AIProviderConfig) {
this.apiKey = config.apiKey;
this.model = config.model || 'claude-3-sonnet-20240229';
}
private async callClaude(prompt: string): Promise<string> {
try {
const response = await fetch(this.apiUrl, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'x-api-key': this.apiKey,
'anthropic-version': '2023-06-01'
},
body: JSON.stringify({
model: this.model,
max_tokens: 1000,
messages: [
{ role: 'user', content: prompt }
]
})
});
if (!response.ok) {
throw new Error(`Claude API error: ${response.statusText}`);
}
const data = await response.json();
return data.content?.[0]?.text || '';
} catch (error) {
console.error('Claude API error:', error);
throw error;
}
}
async generateText(prompt: string): Promise<string> {
return this.callClaude(`${prompt}\n\nIMPORTANT: Respond in the SAME LANGUAGE as the input text.`);
}
async rewrite(text: string): Promise<string> {
return this.callClaude(`Rewrite this text to be clearer and more engaging. IMPORTANT: Respond in the SAME LANGUAGE as the input text:\n\n${text}`);
}
async expand(text: string): Promise<string> {
return this.callClaude(`Expand this text with more details, specific examples, explanations, and supporting information while keeping the same structure and tone. Respond in the same language as the input:\n\n${text}`);
}
async summarize(text: string): Promise<string> {
return this.callClaude(`Create a comprehensive summary that captures all key points, main arguments, important details, and significant examples. The summary should be thorough enough to understand the core message. Respond in the same language as the input:\n\n${text}`);
}
async fixGrammar(text: string): Promise<string> {
return this.callClaude(`Fix grammar and spelling errors. IMPORTANT: Respond in the SAME LANGUAGE as the input text:\n\n${text}`);
}
async translate(text: string, targetLang: string): Promise<string> {
return this.callClaude(`Translate to ${targetLang}:\n\n${text}`);
}
async changeTone(text: string, tone: string): Promise<string> {
return this.callClaude(`Rewrite in a ${tone} tone. IMPORTANT: Respond in the SAME LANGUAGE as the input text:\n\n${text}`);
}
async continueWriting(text: string): Promise<string> {
return this.callClaude(`Continue writing from where this text ends. IMPORTANT: Respond in the SAME LANGUAGE as the input text:\n\n${text}`);
}
async improveWriting(text: string): Promise<string> {
return this.callClaude(`Improve this text. IMPORTANT: Respond in the SAME LANGUAGE as the input text:\n\n${text}`);
}
async generateIdeas(text: string): Promise<string> {
return this.callClaude(`Generate ideas for this topic. IMPORTANT: Respond in the SAME LANGUAGE as the input text:\n\n${text}`);
}
async complete(text: string): Promise<string> {
return this.callClaude(`Complete this text naturally. IMPORTANT: Respond in the SAME LANGUAGE as the input text:\n\n${text}`);
}
}
// Factory function to create AI provider instances
export function createAIProvider(
provider: 'openai' | 'gemini' | 'claude',
config: AIProviderConfig
): AIProvider {
switch (provider) {
case 'gemini':
return new GeminiProvider(config);
case 'openai':
return new OpenAIProvider(config);
case 'claude':
return new ClaudeProvider(config);
default:
throw new Error(`Unsupported AI provider: ${provider}`);
}
}