|
| 1 | +# Copyright 2025 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 | +import markdown |
| 16 | +import re |
| 17 | +from google_workspace import create_message, update_message, download_chat_attachment |
| 18 | +from vertex_ai import IAiAgentHandler, IAiAgentUiRender |
| 19 | +from typing import Any |
| 20 | + |
| 21 | +# Error message to display when something goes wrong |
| 22 | +ERROR_MESSAGE = "❌ Something went wrong" |
| 23 | + |
| 24 | +def snake_to_user_readable(snake_case_string="") -> str: |
| 25 | + """Converts a snake_case_string to a user-readable Title Case string.""" |
| 26 | + return snake_case_string.replace('_', ' ').title() |
| 27 | + |
| 28 | +class AgentCommon(IAiAgentHandler): |
| 29 | + """AI Agent handler implementation for non-Chat host apps.""" |
| 30 | + |
| 31 | + # ----- IAiAgentHandler interface implementation |
| 32 | + |
| 33 | + def __init__(self, ui_render: IAiAgentUiRender): |
| 34 | + super().__init__(ui_render) |
| 35 | + self.turn_card_sections = [] |
| 36 | + |
| 37 | + def extract_content_from_input(self, input) -> dict: |
| 38 | + # For non-Chat host apps, the input is a simple text string |
| 39 | + return { "role": "user", "parts": [{ "text": input }] } |
| 40 | + |
| 41 | + def final_answer(self, author: str, text: str, success: bool, failure: bool): |
| 42 | + """Adds the final answer section to the turn card sections.""" |
| 43 | + self.add_section(section=self.build_section(author=author, text=text, widgets=[], success=success, failure=failure)) |
| 44 | + |
| 45 | + def function_calling_initiation(self, author: str, name: str) -> Any: |
| 46 | + """Adds a function calling initiation section to the turn card sections.""" |
| 47 | + return self.add_section(section=self.build_section( |
| 48 | + author=name, |
| 49 | + text=f"Working on **{snake_to_user_readable(author)}**'s request...", |
| 50 | + widgets=[], |
| 51 | + success=False, |
| 52 | + failure=False |
| 53 | + )) |
| 54 | + |
| 55 | + def function_calling_completion(self, author: str, name: str, response, output_id): |
| 56 | + """Updates the function calling section with the completion response.""" |
| 57 | + self.update_section( |
| 58 | + index=output_id, |
| 59 | + section=self.build_section( |
| 60 | + author=name, |
| 61 | + text="", |
| 62 | + widgets=self.ui_render.get_agent_response_widgets(name=name, response=response), |
| 63 | + success=True, |
| 64 | + failure=False |
| 65 | + ) |
| 66 | + ) |
| 67 | + |
| 68 | + def function_calling_failure(self, name: str, output_id: str): |
| 69 | + """Updates the function calling section with a failure status.""" |
| 70 | + self.update_section( |
| 71 | + index=output_id, |
| 72 | + section=self.build_section( |
| 73 | + author=name, |
| 74 | + text=ERROR_MESSAGE, |
| 75 | + widgets=[], |
| 76 | + success=False, |
| 77 | + failure=True |
| 78 | + ) |
| 79 | + ) |
| 80 | + |
| 81 | + # ------ Utility functions |
| 82 | + |
| 83 | + def add_section(self, section) -> int: |
| 84 | + """Adds a new section to the turn card sections and returns its index.""" |
| 85 | + print(f"Adding section in stack...") |
| 86 | + self.turn_card_sections.append(section) |
| 87 | + return len(self.turn_card_sections) - 1 |
| 88 | + |
| 89 | + def update_section(self, index: int, section): |
| 90 | + """Updates an existing section in the turn card sections.""" |
| 91 | + print(f"Updating section in stack...") |
| 92 | + self.turn_card_sections[index] = section |
| 93 | + |
| 94 | + def get_answer_sections(self) -> list: |
| 95 | + """Returns the turn card sections in reverse order for display.""" |
| 96 | + return self.turn_card_sections[::-1] |
| 97 | + |
| 98 | + def build_section(self, author, text, widgets, success: bool, failure: bool) -> dict: |
| 99 | + """Builds a card section for the given author, text, and widgets.""" |
| 100 | + displayedText = f"{self.ui_render.get_author_emoji(author)} **{snake_to_user_readable(author)}**{f' ✅' if success else ''}{f'\n\n{text}' if text else ''}" |
| 101 | + textWidgets = [{ "text_paragraph": { "text": markdown.markdown(self.substitute_listings_from_markdown(displayedText)).replace('\n', '\n\n') }}] |
| 102 | + return { "widgets": textWidgets + widgets + ([] if success or failure else self.ui_render.create_status_accessory_widgets(text="In progress...", material_icon_name="progress_activity")) } |
| 103 | + |
| 104 | + def substitute_listings_from_markdown(self, markdown: str) -> str: |
| 105 | + """Removes markdown listings (bulleted and numbered) from the given markdown text.""" |
| 106 | + pattern = re.compile(r'^\s*([*-+]|\d+\.)\s+', re.MULTILINE) |
| 107 | + return pattern.sub('-> ', markdown) |
| 108 | + |
| 109 | +class AgentChat(IAiAgentHandler): |
| 110 | + """AI Agent handler implementation for Chat apps.""" |
| 111 | + |
| 112 | + # ----- IAiAgentHandler interface implementation |
| 113 | + |
| 114 | + def extract_content_from_input(self, input) -> dict: |
| 115 | + # For Chat host apps, the input can contain text and attachments |
| 116 | + parts = [{ "text": input.get("text") }] |
| 117 | + if "attachment" in input: |
| 118 | + for attachment in input.get("attachment"): |
| 119 | + attachmentBase64Data = download_chat_attachment(attachment.get("attachmentDataRef").get("resourceName")) |
| 120 | + inline_data_part = { "inline_data": { |
| 121 | + "mime_type": attachment.get("contentType"), |
| 122 | + "data": attachmentBase64Data |
| 123 | + }} |
| 124 | + parts.append(inline_data_part) |
| 125 | + return { "role": "user", "parts": parts } |
| 126 | + |
| 127 | + def final_answer(self, author: str, text: str, success: bool, failure: bool): |
| 128 | + """Sends the final answer as a Chat message.""" |
| 129 | + create_message(message=self.build_message(author=author, text=text, cards_v2=[], success=success, failure=failure)) |
| 130 | + |
| 131 | + def function_calling_initiation(self, author: str, name: str) -> Any: |
| 132 | + """Sends a function calling initiation message in Chat and returns the message name as output ID.""" |
| 133 | + return create_message(message=self.build_message( |
| 134 | + author=name, |
| 135 | + text=f"Working on **{snake_to_user_readable(author)}**'s request...", |
| 136 | + cards_v2=[], |
| 137 | + success=False, |
| 138 | + failure=False |
| 139 | + )) |
| 140 | + |
| 141 | + def function_calling_completion(self, author: str, name: str, response, output_id): |
| 142 | + """Updates the function calling message in Chat with the completion response.""" |
| 143 | + widgets = self.ui_render.get_agent_response_widgets(name=name, response=response) |
| 144 | + update_message( |
| 145 | + name=output_id, |
| 146 | + message=self.build_message( |
| 147 | + author=name, |
| 148 | + text="", |
| 149 | + cards_v2=self.wrap_widgets_in_cards_v2(widgets) if len(widgets) > 0 else [], |
| 150 | + success=True, |
| 151 | + failure=False |
| 152 | + ) |
| 153 | + ) |
| 154 | + |
| 155 | + def function_calling_failure(self, name: str, output_id: str): |
| 156 | + """Updates the function calling section with a failure status.""" |
| 157 | + update_message( |
| 158 | + name=output_id, |
| 159 | + message=self.build_message( |
| 160 | + author=name, |
| 161 | + text=ERROR_MESSAGE, |
| 162 | + cards_v2=[], |
| 163 | + success=False, |
| 164 | + failure=True |
| 165 | + ) |
| 166 | + ) |
| 167 | + |
| 168 | + # ------ Utility functions |
| 169 | + |
| 170 | + def build_message(self, author, text, cards_v2, success: bool, failure: bool) -> dict: |
| 171 | + """Builds a Chat message for the given author, text, and cards_v2.""" |
| 172 | + if text: |
| 173 | + cards_v2.insert(0, { "card": { "sections": [{ "widgets": [{ "text_paragraph": { "text": text.replace('\n', '\n\n'), "text_syntax": "MARKDOWN" }}]}]}}) |
| 174 | + return { |
| 175 | + "text": f"{self.ui_render.get_author_emoji(author)} *{snake_to_user_readable(author)}*{f' ✅' if success else ''}", |
| 176 | + "cards_v2": cards_v2, |
| 177 | + "accessory_widgets": [] if success or failure else self.ui_render.create_status_accessory_widgets(text="In progress...", material_icon_name="progress_activity") |
| 178 | + } |
| 179 | + |
| 180 | + def wrap_widgets_in_cards_v2(self, widgets=[]) -> list: |
| 181 | + """Wraps the given widgets in Chat cards_v2 structure.""" |
| 182 | + return [{ "card": { "sections": [{ "widgets": widgets }]}}] |
0 commit comments