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 { GoogleGenAI } from "@google/genai";
import { KBArticle, Ticket, TicketStatus } from "../types"; 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 * Agent 1: Customer Support Chat
* Uses the KB to answer questions. * Uses the KB to answer questions.
*/ */
export const getSupportResponse = async ( export const getSupportResponse = async (
apiKey: string,
userQuery: string, userQuery: string,
chatHistory: string[], chatHistory: string[],
knowledgeBase: KBArticle[] knowledgeBase: KBArticle[]
): Promise<string> => { ): Promise<string> => {
if (!ai || !apiKey) { if (!apiKey) {
return "L'assistente AI non è configurato o la chiave API è mancante. Contatta l'amministratore."; return "L'assistente AI non è configurato (API Key mancante). Contatta l'amministratore.";
} }
try {
const ai = new GoogleGenAI({ apiKey });
// Prepare Context from KB // Prepare Context from KB
const kbContext = knowledgeBase.map(a => { const kbContext = knowledgeBase.map(a => {
if (a.type === 'url') { if (a.type === 'url') {
@@ -55,7 +46,6 @@ export const getSupportResponse = async (
4. Sii cortese, professionale e sintetico. 4. Sii cortese, professionale e sintetico.
`; `;
try {
const response = await ai.models.generateContent({ const response = await ai.models.generateContent({
model: 'gemini-3-flash-preview', model: 'gemini-3-flash-preview',
contents: [ contents: [
@@ -71,7 +61,7 @@ export const getSupportResponse = async (
return response.text || "Mi dispiace, non riesco a generare una risposta al momento."; return response.text || "Mi dispiace, non riesco a generare una risposta al momento.";
} catch (error) { } catch (error) {
console.error("Gemini Error:", 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 * Agent 2: Knowledge Extraction
*/ */
export const generateNewKBArticle = async ( export const generateNewKBArticle = async (
apiKey: string,
resolvedTickets: Ticket[], resolvedTickets: Ticket[],
existingArticles: KBArticle[] existingArticles: KBArticle[]
): Promise<{ title: string; content: string; category: string } | null> => { ): 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 // Filter only resolved tickets
const relevantTickets = resolvedTickets.filter(t => t.status === TicketStatus.RESOLVED); const relevantTickets = resolvedTickets.filter(t => t.status === TicketStatus.RESOLVED);
@@ -120,7 +114,6 @@ export const generateNewKBArticle = async (
} }
`; `;
try {
const response = await ai.models.generateContent({ const response = await ai.models.generateContent({
model: 'gemini-3-pro-preview', model: 'gemini-3-pro-preview',
contents: prompt, contents: prompt,