UNPKG

field-service-agent

Version:

Field Service AI Agent - NPM package for integrating AI-powered field service management into mobile apps

319 lines 13.7 kB
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; import { EnhancedAgent } from './agent/enhancedAgent'; export class FieldServiceAgent { constructor(config) { this.context = null; this.isInitialized = false; this.conversationHistory = []; this.config = config; this.sdk = config.sdk; const mockNavigation = { navigateToJob: () => { }, navigateToClient: () => { }, navigateToInvoice: () => { }, navigateToEstimate: () => { } }; const mockUser = { id: 'agent-user', name: 'Agent User', email: 'agent@fieldservice.com' }; this.agent = new EnhancedAgent({ sdk: this.sdk, navigation: mockNavigation, user: mockUser, debugMode: config.enableDebugLogging, googlePlacesApiKey: config.googlePlacesApiKey, chatHistory: this.conversationHistory, language: config.language, voiceName: config.voiceName }); } initialize() { return __awaiter(this, void 0, void 0, function* () { if (this.isInitialized) { return; } try { this.context = { timeZone: this.config.timezone || Intl.DateTimeFormat().resolvedOptions().timeZone, currentScreenType: undefined, currentRecordId: undefined, }; this.isInitialized = true; } catch (error) { throw new Error(`Failed to initialize Field Service Agent: ${error instanceof Error ? error.message : 'Unknown error'}`); } }); } processCommand(command, context) { return __awaiter(this, void 0, void 0, function* () { var _a, _b; if (!this.isInitialized) { yield this.initialize(); } if (context) { if (this.context) { this.context = Object.assign(Object.assign({}, this.context), context); } if (context.currentScreenType !== undefined || context.currentRecordId !== undefined) { this.agent.setCurrentScreen(context.currentScreenType, context.currentRecordId); } } console.log('context', this.context); try { const isAudioInput = typeof command === 'object' && 'audioContent' in command; if (!isAudioInput) { const lowerCommand = command.toLowerCase().trim(); if (lowerCommand === 'start new conversation' || lowerCommand === 'clear history' || lowerCommand === 'new conversation' || lowerCommand === 'start over' || lowerCommand === 'clear conversation') { this.clearConversationHistory(); return { success: true, message: 'Starting a new conversation. How can I help you today?' }; } const userMessageId = `msg_${Date.now()}_user`; this.conversationHistory.push({ id: userMessageId, text: command, isUser: true }); } else { const userMessageId = `msg_${Date.now()}_user`; this.conversationHistory.push({ id: userMessageId, text: '🎤 [Audio message]', isUser: true }); } this.agent.updateChatHistory(this.conversationHistory); const result = yield this.agent.processCommand(command); const response = this.transformAgentResponse(result); const agentMessageId = `msg_${Date.now()}_agent`; this.conversationHistory.push({ id: agentMessageId, text: result.message, isUser: false, action: (_a = response.result) === null || _a === void 0 ? void 0 : _a.action }); if ((_b = response.result) === null || _b === void 0 ? void 0 : _b.action) { if (response.result.action.type === 'navigation' && this.config.onNavigationRequest) { this.config.onNavigationRequest(response.result.action); } else if (response.result.action.type === 'communication' && this.config.onCommunicationRequest) { this.config.onCommunicationRequest(response.result.action); } if (response.result.navigationActions && this.config.onNavigationRequest) { const firstNavigationAction = response.result.navigationActions[0]; this.config.onNavigationRequest(firstNavigationAction); } } return Object.assign(Object.assign({}, response), { transcribedText: result.transcribedText }); } catch (error) { return { success: false, message: `Error processing command: ${error instanceof Error ? error.message : 'Unknown error'}`, error: error instanceof Error ? error.message : 'Unknown error' }; } }); } transformAgentResponse(internalResponse) { const response = { audioContent: internalResponse.audioContent || '', success: internalResponse.success || false, message: internalResponse.message || '', followUpQuestion: internalResponse.followUpQuestion || false, navigationActions: internalResponse.navigationActions || [] }; if (internalResponse.action) { response.result = { success: internalResponse.success, message: internalResponse.message, data: internalResponse.data, action: internalResponse.action, requiresUserAction: true, followUpQuestion: internalResponse.followUpQuestion || false }; } else if (internalResponse.data) { response.result = { success: internalResponse.success, message: internalResponse.message, data: internalResponse.data, requiresUserAction: false, followUpQuestion: internalResponse.followUpQuestion || false }; } if (this.config.enableDebugLogging) { response.debugInfo = { internalResponse, context: this.context }; } return response; } updateContext(context) { if (!this.context) { throw new Error('Agent not initialized. Call initialize() first.'); } this.context = Object.assign(Object.assign({}, this.context), context); if (context.currentScreenType !== undefined || context.currentRecordId !== undefined) { this.agent.setCurrentScreen(context.currentScreenType, context.currentRecordId); } } setCurrentScreen(screenType, recordId) { this.updateContext({ currentScreenType: screenType, currentRecordId: recordId }); } setCurrentRecordId(recordId) { this.updateContext({ currentRecordId: recordId }); } setLanguage(language) { this.config.language = language; this.agent.setLanguage(language); } setVoiceName(voiceName) { this.config.voiceName = voiceName; this.agent.setVoiceName(voiceName); } getContext() { return this.context; } updateSDK(sdk) { console.log('[FieldServiceAgent] Updating SDK instance'); this.sdk = sdk; this.config.sdk = sdk; if (this.agent) { this.agent.updateSDK(this.sdk); } } clearConversationHistory() { console.log('clearing conversation history'); this.conversationHistory = []; this.agent.updateChatHistory([]); } getConversationHistory() { return [...this.conversationHistory]; } getRecentMessages(count = 10) { return this.conversationHistory.slice(-count); } clearContext() { this.clearConversationHistory(); this.setCurrentScreen(undefined, undefined); this.agent.setCurrentScreen(undefined, undefined); } processVoiceCommand(command, context) { return __awaiter(this, void 0, void 0, function* () { const response = yield this.processCommand(command, context); let speechText = response.message; if (speechText.length > 200) { if (response.message.toLowerCase().includes('created') || response.message.toLowerCase().includes('added')) { speechText = 'I created that for you.'; } else if (response.message.toLowerCase().includes('updated')) { speechText = 'I updated that for you.'; } else if (response.message.toLowerCase().includes('text message') || response.message.toLowerCase().includes('sent')) { speechText = 'I sent the text message.'; } else if (response.message.toLowerCase().includes('email')) { speechText = 'I prepared the email.'; } else if (response.message.toLowerCase().includes('opening')) { speechText = 'Opening that now.'; } } console.log('speechText', speechText); console.log('response', response); return Object.assign(Object.assign({}, response), { speechText }); }); } processVoiceInput(audioContent_1) { return __awaiter(this, arguments, void 0, function* (audioContent, inputEncoding = 'WEBM_OPUS', inputSampleRate = 48000, context) { var _a, _b; if (!this.isInitialized) { yield this.initialize(); } if (context) { if (this.context) { this.context = Object.assign(Object.assign({}, this.context), context); } if (context.currentScreenType !== undefined || context.currentRecordId !== undefined) { this.agent.setCurrentScreen(context.currentScreenType, context.currentRecordId); } } try { this.agent.updateChatHistory(this.conversationHistory); const result = yield this.agent.processCommand({ audioContent, inputEncoding, inputSampleRate }); const response = this.transformAgentResponse(result); const agentMessageId = `msg_${Date.now()}_agent`; this.conversationHistory.push({ id: agentMessageId, text: result.message, isUser: false, action: (_a = response.result) === null || _a === void 0 ? void 0 : _a.action }); if ((_b = response.result) === null || _b === void 0 ? void 0 : _b.action) { if (response.result.action.type === 'navigation' && this.config.onNavigationRequest) { this.config.onNavigationRequest(response.result.action); } else if (response.result.action.type === 'communication' && this.config.onCommunicationRequest) { this.config.onCommunicationRequest(response.result.action); } } return response; } catch (error) { return { success: false, message: `Error processing voice input: ${error instanceof Error ? error.message : 'Unknown error'}`, error: error instanceof Error ? error.message : 'Unknown error' }; } }); } refreshData() { return __awaiter(this, void 0, void 0, function* () { yield this.initialize(); }); } getTextToSpeechAudio(text, language) { return __awaiter(this, void 0, void 0, function* () { return new ArrayBuffer(0); }); } getAvailableLanguages() { return [ 'en-US', 'es-ES', 'fr-FR', 'de-DE', 'he-IL' ]; } isReady() { return this.isInitialized; } } //# sourceMappingURL=FieldServiceAgent.js.map