omninexus-ai / geminiService.ts
aditya9708's picture
Auto-deploy from AI Studio
e4c7604 verified
Raw History Blame Contribute Delete
5.13 kB
import { GoogleGenAI } from "@google/genai";
export interface ChatHistoryItem {
role: 'user' | 'model';
parts: { text: string }[];
}
export class GeminiService {
static getAI() {
// @ts-ignore
let apiKey = (typeof process !== 'undefined' && (process.env?.API_KEY || process.env?.GEMINI_API_KEY)) || import.meta.env.VITE_GEMINI_API_KEY || '';
// Fallback for Docker runtime replacement
if (!apiKey || apiKey.includes('__GEMINI_API_KEY__')) {
apiKey = 'AIzaSyAyVva5wY2g6kmoG3bafrwf4dzM8xLrqDk'; // Hardcoded fallback as requested for "automatic" setup
}
return new GoogleGenAI({ apiKey });
}
/**
* General Text Chat using Gemini 3 Flash.
* Includes Google Search Grounding for up-to-date info.
*/
static async chat(prompt: string, history: ChatHistoryItem[] = []) {
const ai = this.getAI();
try {
const contents = [
...history,
{ role: 'user', parts: [{ text: prompt }] }
];
const response = await ai.models.generateContent({
model: 'gemini-3-flash-preview',
contents: contents,
config: {
tools: [{ googleSearch: {} }],
temperature: 0.7,
}
});
const text = response.text || "Bhai, model ne koi response nahi diya.";
// Extracting grounding chunks for search transparency
const grounding = response.candidates?.[0]?.groundingMetadata?.groundingChunks?.map((chunk: any) => ({
title: chunk.web?.title || 'Verified Source',
uri: chunk.web?.uri || ''
})).filter((c: any) => c.uri) || [];
return { text, grounding };
} catch (error) {
console.error("Chat Error:", error);
return { text: "Network error! Please check your connection or API key.", grounding: [] };
}
}
/**
* High-Quality Image Generation using Gemini 3 Pro Image.
* Mandates API key selection check as per guidelines.
*/
static async generateImage(prompt: string) {
if (typeof window !== 'undefined' && (window as any).aistudio) {
const hasKey = await (window as any).aistudio.hasSelectedApiKey();
if (!hasKey) {
await (window as any).aistudio.openSelectKey();
}
}
const ai = this.getAI();
try {
const response = await ai.models.generateContent({
model: 'gemini-3-pro-image-preview',
contents: { parts: [{ text: prompt }] },
config: {
imageConfig: {
aspectRatio: "1:1",
imageSize: "1K"
}
}
});
// Find the image part in the parts array
if (response.candidates?.[0]?.content?.parts) {
for (const part of response.candidates[0].content.parts) {
if (part.inlineData) {
return `data:image/png;base64,${part.inlineData.data}`;
}
}
}
throw new Error("No image data in response.");
} catch (error) {
console.error("Image Gen Error:", error);
throw error;
}
}
/**
* Cinematic Video Generation using Veo.
* Includes operation polling and API key attachment to fetch.
*/
static async generateVideo(prompt: string) {
if (typeof window !== 'undefined' && (window as any).aistudio) {
const hasKey = await (window as any).aistudio.hasSelectedApiKey();
if (!hasKey) {
await (window as any).aistudio.openSelectKey();
}
}
const ai = this.getAI();
try {
let operation = await ai.models.generateVideos({
model: 'veo-3.1-fast-generate-preview',
prompt: prompt,
config: {
numberOfVideos: 1,
resolution: '720p',
aspectRatio: '16:9'
}
});
// Poll for completion
while (!operation.done) {
await new Promise(resolve => setTimeout(resolve, 10000));
operation = await ai.operations.getVideosOperation({ operation: operation });
}
const downloadLink = operation.response?.generatedVideos?.[0]?.video?.uri;
if (!downloadLink) throw new Error("Video generation failed.");
// Fetch video bytes using the key
// @ts-ignore
const apiKey = ai.apiKey;
const response = await fetch(`${downloadLink}&key=${apiKey}`);
const blob = await response.blob();
return URL.createObjectURL(blob);
} catch (error) {
console.error("Video Gen Error:", error);
throw error;
}
}
/**
* Multimodal Vision using Gemini 3 Flash.
*/
static async vision(prompt: string, base64Data: string, mimeType: string) {
const ai = this.getAI();
try {
const response = await ai.models.generateContent({
model: 'gemini-3-flash-preview',
contents: {
parts: [
{ inlineData: { data: base64Data, mimeType: mimeType } },
{ text: prompt }
]
}
});
const text = response.text || "Bhai, model ne image dekh kar koi response nahi diya.";
return { text };
} catch (error) {
console.error("Vision Error:", error);
return { text: "Error analyzing image! Please check your connection." };
}
}
}