|
| 1 | +// Copyright 2026 Google LLC. All Rights Reserved. |
| 2 | +// |
| 3 | +// Licensed under the Apache License, Version 2.0 (the 'License'); |
| 4 | +// you may not use this file except in compliance with the License. |
| 5 | +// You may obtain a copy of the License at |
| 6 | +// |
| 7 | +// https://www.apache.org/licenses/LICENSE-2.0 |
| 8 | +// |
| 9 | +// Unless required by applicable law or agreed to in writing, software |
| 10 | +// distributed under the License is distributed on an 'AS IS' BASIS, |
| 11 | +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | +// See the License for the specific language governing permissions and |
| 13 | +// limitations under the License. |
| 14 | + |
| 15 | +// Service that handles Vertex AI Agent operations. |
| 16 | + |
| 17 | +// Submits a query to the AI agent and returns the response string synchronously |
| 18 | +function queryAgent(input) { |
| 19 | + let systemPrompt = "SYSTEM PROMPT START Do not respond with tables but use bullet points instead." + |
| 20 | + " Do not ask the user follow-up questions or converse with them as history is not kept in this interface." + |
| 21 | + " SYSTEM PROMPT END\n\n"; |
| 22 | + |
| 23 | + const requestPayload = { |
| 24 | + "class_method": "async_stream_query", |
| 25 | + "input": { |
| 26 | + "user_id": "vertex_ai_add_on", |
| 27 | + "message": { "role": "user", "parts": [{ "text": systemPrompt + input.text }] }, |
| 28 | + "state_delta": { |
| 29 | + "enterprise-ai_999": `${ScriptApp.getOAuthToken()}` |
| 30 | + } |
| 31 | + } |
| 32 | + }; |
| 33 | + |
| 34 | + const responseContentText = UrlFetchApp.fetch( |
| 35 | + `https://${getLocation()}-aiplatform.googleapis.com/v1/${getReasoningEngine()}:streamQuery?alt=sse`, |
| 36 | + { |
| 37 | + method: 'post', |
| 38 | + headers: { 'Authorization': `Bearer ${ScriptApp.getOAuthToken()}` }, |
| 39 | + contentType: 'application/json', |
| 40 | + payload: JSON.stringify(requestPayload), |
| 41 | + muteHttpExceptions: true |
| 42 | + } |
| 43 | + ).getContentText(); |
| 44 | + |
| 45 | + if (isInDebugMode()) { |
| 46 | + console.log(`Response: ${responseContentText}`); |
| 47 | + } |
| 48 | + |
| 49 | + const events = responseContentText.split('\n').map(s => s.replace(/^data:\s*/, '')).filter(s => s.trim().length > 0); |
| 50 | + console.log(`Received ${events.length} agent events.`); |
| 51 | + |
| 52 | + let author = "default"; |
| 53 | + let answerText = ""; |
| 54 | + for (const eventJson of events) { |
| 55 | + if (isInDebugMode()) { |
| 56 | + console.log("Event: " + eventJson); |
| 57 | + } |
| 58 | + const event = JSON.parse(eventJson); |
| 59 | + |
| 60 | + // Retrieve the agent responsible for generating the content |
| 61 | + author = event.author; |
| 62 | + |
| 63 | + // Ignore events that are not useful for the end-user |
| 64 | + if (!event.content) { |
| 65 | + console.log(`${author}: internal event`); |
| 66 | + continue; |
| 67 | + } |
| 68 | + |
| 69 | + // Handle text answers |
| 70 | + const parts = event.content.parts || []; |
| 71 | + const textPart = parts.find(p => p.text); |
| 72 | + if (textPart) { |
| 73 | + answerText += textPart.text; |
| 74 | + } |
| 75 | + } |
| 76 | + return { author: author, text: answerText }; |
| 77 | +} |
| 78 | + |
| 79 | +// --- UI Management --- |
| 80 | + |
| 81 | +// Sends an answer as a Chat message. |
| 82 | +function answer(author, text, success) { |
| 83 | + const widgets = createMarkdownWidgets(text); |
| 84 | + createMessage(buildMessage(author, [wrapWidgetsInCardsV2(widgets)], success)); |
| 85 | +} |
| 86 | + |
| 87 | +// Sends a request to the AI agent and processes the response for Chat UI |
| 88 | +function requestAgent(input) { |
| 89 | + try { |
| 90 | + const response = queryAgent(input); |
| 91 | + if (response.text) { |
| 92 | + answer(response.author, response.text, true); |
| 93 | + } |
| 94 | + } catch (err) { |
| 95 | + answer(response.author, err.message, false); |
| 96 | + } |
| 97 | +} |
| 98 | + |
| 99 | +// Builds a Chat message for the given author, state, and cards_v2. |
| 100 | +function buildMessage(author, cardsV2, success = true) { |
| 101 | + const messageBuilder = CardService.newChatResponseBuilder(); |
| 102 | + messageBuilder.setText(`${getAuthorEmoji(author)} *${snakeToUserReadable(author)}* ${success ? '✅' : '❌'}`); |
| 103 | + cardsV2.forEach(cardV2 => { messageBuilder.addCardsV2(cardV2) }); |
| 104 | + let message = JSON.parse(messageBuilder.build().printJson()); |
| 105 | + |
| 106 | + if (isInDebugMode()) { |
| 107 | + console.log(`Built message: ${JSON.stringify(message)}`); |
| 108 | + } |
| 109 | + |
| 110 | + return message; |
| 111 | +} |
| 112 | + |
| 113 | +// Converts a snake_case_string to a user-readable Title Case string. |
| 114 | +function snakeToUserReadable(snakeCaseString = "") { |
| 115 | + return snakeCaseString.replace(/_/g, ' ').split(' ').map(word => { |
| 116 | + if (!word) return ''; |
| 117 | + return word.charAt(0).toUpperCase() + word.slice(1).toLowerCase(); |
| 118 | + }).join(' '); |
| 119 | +} |
| 120 | + |
| 121 | +// Wraps the given widgets in Chat cards_v2 structure. |
| 122 | +function wrapWidgetsInCardsV2(widgets = []) { |
| 123 | + const section = CardService.newCardSection(); |
| 124 | + widgets.forEach(widget => { section.addWidget(widget) }); |
| 125 | + return CardService.newCardWithId().setCard(CardService.newCardBuilder().addSection(section).build()); |
| 126 | +} |
| 127 | + |
| 128 | +// Returns an emoji representing the author. |
| 129 | +function getAuthorEmoji(author) { |
| 130 | + switch (author) { |
| 131 | + case "enterprise_ai": return "ℹ️"; |
| 132 | + default: return "🤖"; |
| 133 | + } |
| 134 | +} |
| 135 | + |
| 136 | +// Creates widgets for markdown text response. |
| 137 | +function createMarkdownWidgets(markdown) { |
| 138 | + if (!markdown) return []; |
| 139 | + const textParagraph = CardService.newTextParagraph(); |
| 140 | + textParagraph.setText(new showdown.Converter().makeHtml(markdown)); |
| 141 | + return [textParagraph]; |
| 142 | +} |
0 commit comments