aibanking.dev / services /geminiService.ts
admin08077's picture
Upload 4 files
262ab3a verified
import { GoogleGenAI } from "@google/genai";
import { SimulationResult, AIInsight } from "../types/index";
export const TTS_VOICES = [
{ name: 'Puck', style: 'Energetic' },
{ name: 'Charon', style: 'Calm' },
{ name: 'Kore', style: 'Professional' },
{ name: 'Fenrir', style: 'Deep' },
{ name: 'Zephyr', style: 'Friendly' }
];
export const TTS_LANGUAGES = [
{ code: 'en', name: 'English (US)' },
{ code: 'es', name: 'Spanish' },
{ code: 'fr', name: 'French' },
{ code: 'de', name: 'German' },
{ code: 'it', name: 'Italian' },
{ code: 'ja', name: 'Japanese' },
{ code: 'ko', name: 'Korean' },
{ code: 'zh', name: 'Chinese' }
];
const TEXT_MODEL = 'gemini-3-flash-preview';
/**
* Direct call to Gemini 3 Flash.
* SDK rule: Fresh instantiation within the call captures the most recent process.env.API_KEY.
*/
export const callGemini = async (model: string, contents: any, config: any = {}) => {
const ai = new GoogleGenAI({ apiKey: process.env.API_KEY });
const response = await ai.models.generateContent({
model: model || TEXT_MODEL,
contents: typeof contents === 'string' ? [{ parts: [{ text: contents }] }] : contents,
config: config,
});
return response;
};
export const speakText = async (text: string) => {
return new Promise((resolve) => {
if (!('speechSynthesis' in window)) {
console.warn("Synthesis unsupported.");
resolve(false);
return;
}
window.speechSynthesis.cancel();
const utterance = new SpeechSynthesisUtterance(text);
utterance.rate = 1.0;
utterance.pitch = 0.9;
utterance.onend = () => resolve(true);
window.speechSynthesis.speak(utterance);
});
};
export const synthesizeSpeech = async (params: {
text: string;
voiceName: string;
directorNotes?: string;
multiSpeaker?: any;
}) => {
return speakText(params.text);
};
export const processVoiceCommand = async (command: string) => {
try {
const ai = new GoogleGenAI({ apiKey: process.env.API_KEY });
const response = await ai.models.generateContent({
model: TEXT_MODEL,
contents: [{ parts: [{ text: `You are an institutional treasury AI. Analyze: "${command}". Return ONLY JSON: { "action": "SEND_MONEY" | "QUERY", "amount": number, "recipient": string, "category": string, "narration": string }.` }] }],
config: { responseMimeType: "application/json" }
});
return JSON.parse(response.text || '{}');
} catch (error) {
console.error("Neural Signal Loss.");
return { action: "ERROR", narration: "Registry parity error." };
}
};
export const getFinancialAdviceStream = async (query: string, context: any) => {
const ai = new GoogleGenAI({ apiKey: process.env.API_KEY });
const response = await ai.models.generateContent({
model: TEXT_MODEL,
contents: [{ parts: [{ text: `System Context: ${JSON.stringify(context)}. User Query: ${query}` }] }],
});
return [{ text: response.text }];
};
export const getSystemIntelligenceFeed = async (): Promise<AIInsight[]> => {
try {
const ai = new GoogleGenAI({ apiKey: process.env.API_KEY });
const response = await ai.models.generateContent({
model: TEXT_MODEL,
contents: [{ parts: [{ text: "Generate 4 corporate treasury alerts. Return ONLY JSON: [{title, description, severity: 'INFO'|'CRITICAL'}]" }] }],
config: { responseMimeType: "application/json" }
});
return JSON.parse(response.text || '[]');
} catch {
return [{ id: '1', title: "Mesh Parity Stable", description: "All nodes performing within 0.001ms delta.", severity: "INFO" }];
}
};
export const runSimulationForecast = async (prompt: string): Promise<SimulationResult> => {
try {
const ai = new GoogleGenAI({ apiKey: process.env.API_KEY });
const response = await ai.models.generateContent({
model: TEXT_MODEL,
contents: [{ parts: [{ text: `Simulate: "${prompt}". Return ONLY JSON: { "outcomeNarrative": string, "projectedValue": number, "confidenceScore": number, "status": string, "simulationId": string, "keyRisks": string[] }.` }] }],
config: { responseMimeType: "application/json" }
});
const result = JSON.parse(response.text || '{}');
return {
simulationId: `SIM-${Math.floor(Math.random() * 9000) + 1000}`,
status: 'SUCCESS',
...result
};
} catch (error) {
return { outcomeNarrative: "Forecast link failed.", projectedValue: 0, confidenceScore: 0, status: 'ERROR', simulationId: 'ERR-01' };
}
};
export const getPortfolioSuggestions = async (context: any) => {
try {
const ai = new GoogleGenAI({ apiKey: process.env.API_KEY });
const response = await ai.models.generateContent({
model: TEXT_MODEL,
contents: [{ parts: [{ text: `Suggest 3 actions: ${JSON.stringify(context)}. Return ONLY JSON: [{type: 'ALPHA'|'RISK'|'LIQUIDITY', title, description}]` }] }],
config: { responseMimeType: "application/json" }
});
return JSON.parse(response.text || '[]');
} catch {
return [];
}
};