Update geminiService.ts

This commit is contained in:
fcarraUniSa
2026-02-17 00:48:29 +01:00
committed by GitHub
parent 4b48ed359c
commit acf7ddbc53

View File

@@ -1,32 +1,23 @@
import { GoogleGenAI } from "@google/genai";
import { KBArticle, Ticket, TicketStatus } from "../types";
// The API key must be obtained exclusively from the environment variable process.env.API_KEY.
const apiKey = process.env.API_KEY || '';
// Initialize AI only if key exists to prevent immediate instantiation errors
let ai: GoogleGenAI | null = null;
if (apiKey) {
try {
ai = new GoogleGenAI({ apiKey });
} catch (e) {
console.warn("Failed to initialize GoogleGenAI", e);
}
}
/**
* Agent 1: Customer Support Chat
* Uses the KB to answer questions.
*/
export const getSupportResponse = async (
apiKey: string,
userQuery: string,
chatHistory: string[],
knowledgeBase: KBArticle[]
): Promise<string> => {
if (!ai || !apiKey) {
return "L'assistente AI non è configurato o la chiave API è mancante. Contatta l'amministratore.";
if (!apiKey) {
return "L'assistente AI non è configurato (API Key mancante). Contatta l'amministratore.";
}
try {
const ai = new GoogleGenAI({ apiKey });
// Prepare Context from KB
const kbContext = knowledgeBase.map(a => {
if (a.type === 'url') {
@@ -55,7 +46,6 @@ export const getSupportResponse = async (
4. Sii cortese, professionale e sintetico.
`;
try {
const response = await ai.models.generateContent({
model: 'gemini-3-flash-preview',
contents: [
@@ -71,7 +61,7 @@ export const getSupportResponse = async (
return response.text || "Mi dispiace, non riesco a generare una risposta al momento.";
} catch (error) {
console.error("Gemini Error:", error);
return "Si è verificato un errore nel servizio AI.";
return "Si è verificato un errore nel servizio AI (Verifica API Key o connessione).";
}
};
@@ -79,10 +69,14 @@ export const getSupportResponse = async (
* Agent 2: Knowledge Extraction
*/
export const generateNewKBArticle = async (
apiKey: string,
resolvedTickets: Ticket[],
existingArticles: KBArticle[]
): Promise<{ title: string; content: string; category: string } | null> => {
if (!ai || !apiKey) return null;
if (!apiKey) return null;
try {
const ai = new GoogleGenAI({ apiKey });
// Filter only resolved tickets
const relevantTickets = resolvedTickets.filter(t => t.status === TicketStatus.RESOLVED);
@@ -120,7 +114,6 @@ export const generateNewKBArticle = async (
}
`;
try {
const response = await ai.models.generateContent({
model: 'gemini-3-pro-preview',
contents: prompt,