Format/Lint

This commit is contained in:
2026-03-05 06:06:01 +00:00
parent 5941c41296
commit db879cee9f
6 changed files with 102 additions and 57 deletions

View File

@@ -1,3 +1,4 @@
Use `uv` for project management. Use `uv` for project management.
Use `uv run ruff check` for linting, and `uv run ty check` for type checking Use `uv run ruff check` for linting
Use `uv run ty check` for type checking
Use `uv run pytest` for testing. Use `uv run pytest` for testing.

View File

@@ -1,7 +1,5 @@
"""ADK agent with vector search RAG tool.""" """ADK agent with vector search RAG tool."""
from functools import partial
from google import genai from google import genai
from google.adk.agents.llm_agent import Agent from google.adk.agents.llm_agent import Agent
from google.adk.runners import Runner from google.adk.runners import Runner
@@ -12,10 +10,9 @@ from google.genai.types import Content, Part
from va_agent.auth import auth_headers_provider from va_agent.auth import auth_headers_provider
from va_agent.config import settings from va_agent.config import settings
from va_agent.dynamic_instruction import provide_dynamic_instruction from va_agent.governance import GovernancePlugin
from va_agent.notifications import NotificationService from va_agent.notifications import NotificationService
from va_agent.session import FirestoreSessionService from va_agent.session import FirestoreSessionService
from va_agent.governance import GovernancePlugin
# MCP Toolset for RAG knowledge search # MCP Toolset for RAG knowledge search
toolset = McpToolset( toolset = McpToolset(

View File

@@ -39,7 +39,7 @@ class AgentSettings(BaseSettings):
model_config = SettingsConfigDict( model_config = SettingsConfigDict(
yaml_file=CONFIG_FILE_PATH, yaml_file=CONFIG_FILE_PATH,
extra="ignore", # Ignore extra fields from config.yaml extra="ignore", # Ignore extra fields from config.yaml
env_file=".env" env_file=".env",
) )
@classmethod @classmethod

View File

@@ -34,17 +34,19 @@ async def provide_dynamic_instruction(
""" """
# Only check notifications on the first message # Only check notifications on the first message
if not ctx or not ctx._invocation_context: if not ctx:
logger.debug("No context available for dynamic instruction") logger.debug("No context available for dynamic instruction")
return "" return ""
session = ctx._invocation_context.session session = ctx.session
if not session: if not session:
logger.debug("No session available for dynamic instruction") logger.debug("No session available for dynamic instruction")
return "" return ""
# FOR TESTING: Always check for notifications (comment out to enable first-message-only) # FOR TESTING: Always check for notifications
# Only check on first message (when events list is empty or has only 1-2 events) # (comment out to enable first-message-only)
# Only check on first message (when events list is empty
# or has only 1-2 events)
# Events include both user and agent messages, so < 2 means first interaction # Events include both user and agent messages, so < 2 means first interaction
# event_count = len(session.events) if session.events else 0 # event_count = len(session.events) if session.events else 0
# #
@@ -74,7 +76,11 @@ async def provide_dynamic_instruction(
return "" return ""
# Build dynamic instruction with notification details # Build dynamic instruction with notification details
notification_ids = [n.get("id_notificacion") for n in pending_notifications] notification_ids = [
nid
for n in pending_notifications
if (nid := n.get("id_notificacion")) is not None
]
count = len(pending_notifications) count = len(pending_notifications)
# Format notification details for the agent # Format notification details for the agent
@@ -97,9 +103,11 @@ INSTRUCCIONES:
- Menciona estas notificaciones de forma natural en tu respuesta inicial - Menciona estas notificaciones de forma natural en tu respuesta inicial
- No necesitas leerlas todas literalmente, solo hazle saber que las tiene - No necesitas leerlas todas literalmente, solo hazle saber que las tiene
- Sé breve y directo según tu personalidad (directo y cálido) - Sé breve y directo según tu personalidad (directo y cálido)
- Si el usuario pregunta algo específico, prioriza responder eso primero y luego menciona las notificaciones - Si el usuario pregunta algo específico, prioriza responder eso primero\
y luego menciona las notificaciones
Ejemplo: "¡Hola! 👋 Antes de empezar, veo que tienes {count} notificación(es) pendiente(s) en tu cuenta. ¿Te gustaría revisarlas o prefieres que te ayude con algo más?" Ejemplo: "¡Hola! 👋 Tienes {count} notificación(es)\
pendiente(s). ¿Te gustaría revisarlas?"
""" """
# Mark notifications as notified in Firestore # Mark notifications as notified in Firestore
@@ -111,10 +119,11 @@ Ejemplo: "¡Hola! 👋 Antes de empezar, veo que tienes {count} notificación(es
phone_number, phone_number,
) )
return instruction
except Exception: except Exception:
logger.exception( logger.exception(
"Error building dynamic instruction for user %s", phone_number "Error building dynamic instruction for user %s",
phone_number,
) )
return "" return ""
else:
return instruction

View File

@@ -1,4 +1,5 @@
"""GovernancePlugin: Guardrails for VAia, the virtual assistant for VA.""" """GovernancePlugin: Guardrails for VAia, the virtual assistant for VA."""
import logging import logging
import re import re
@@ -9,10 +10,57 @@ logger = logging.getLogger(__name__)
FORBIDDEN_EMOJIS = [ FORBIDDEN_EMOJIS = [
"🥵","🔪","🎰","🎲","🃏","😤","🤬","😡","😠","🩸","🧨","🪓","☠️","💀", "🥵",
"💣","🔫","👗","💦","🍑","🍆","👄","👅","🫦","💩","⚖️","⚔️","✝️","🕍", "🔪",
"🕌","","🍻","🍸","🥃","🍷","🍺","🚬","👹","👺","👿","😈","🤡","🧙", "🎰",
"🧙‍♀️", "🧙‍♂️", "🧛", "🧛‍♀️", "🧛‍♂️", "🔞","🧿","💊", "💏" "🎲",
"🃏",
"😤",
"🤬",
"😡",
"😠",
"🩸",
"🧨",
"🪓",
"☠️",
"💀",
"💣",
"🔫",
"👗",
"💦",
"🍑",
"🍆",
"👄",
"👅",
"🫦",
"💩",
"⚖️",
"⚔️",
"✝️",
"🕍",
"🕌",
"",
"🍻",
"🍸",
"🥃",
"🍷",
"🍺",
"🚬",
"👹",
"👺",
"👿",
"😈",
"🤡",
"🧙",
"🧙‍♀️",
"🧙‍♂️",
"🧛",
"🧛‍♀️",
"🧛‍♂️",
"🔞",
"🧿",
"💊",
"💏",
] ]
@@ -20,29 +68,31 @@ class GovernancePlugin:
"""Guardrail executor for VAia requests as a Agent engine callbacks.""" """Guardrail executor for VAia requests as a Agent engine callbacks."""
def __init__(self) -> None: def __init__(self) -> None:
"""Initialize guardrail model (structured output), prompt and emojis patterns.""" """Initialize guardrail model, prompt and emojis patterns."""
self._combined_pattern = self._get_combined_pattern() self._combined_pattern = self._get_combined_pattern()
def _get_combined_pattern(self): def _get_combined_pattern(self) -> re.Pattern[str]:
person_pattern = r"(?:🧑|👩|👨)" person = r"(?:🧑|👩|👨)"
tone_pattern = r"[\U0001F3FB-\U0001F3FF]?" tone = r"[\U0001F3FB-\U0001F3FF]?"
simple = "|".join(
# Unique pattern that combines all forbidden emojis, including complex ones with skin tones map(re.escape, sorted(FORBIDDEN_EMOJIS, key=len, reverse=True))
combined_pattern = re.compile(
rf"{person_pattern}{tone_pattern}\u200d❤?\u200d💋\u200d{person_pattern}{tone_pattern}" # kiss
rf"|{person_pattern}{tone_pattern}\u200d❤?\u200d{person_pattern}{tone_pattern}" # lovers
rf"|🖕{tone_pattern}" # middle finger with all skin tone variations
rf"|{'|'.join(map(re.escape, sorted(FORBIDDEN_EMOJIS, key=len, reverse=True)))}" # simple emojis
rf"|\u200d|\uFE0F" # residual ZWJ and variation selectors
) )
return combined_pattern
# Combines all forbidden emojis, including complex
# ones with skin tones
return re.compile(
rf"{person}{tone}\u200d❤?\u200d💋\u200d{person}{tone}"
rf"|{person}{tone}\u200d❤?\u200d{person}{tone}"
rf"|🖕{tone}"
rf"|{simple}"
rf"|\u200d|\uFE0F"
)
def _remove_emojis(self, text: str) -> tuple[str, list[str]]: def _remove_emojis(self, text: str) -> tuple[str, list[str]]:
removed = self._combined_pattern.findall(text) removed = self._combined_pattern.findall(text)
text = self._combined_pattern.sub("", text) text = self._combined_pattern.sub("", text)
return text.strip(), removed return text.strip(), removed
def after_model_callback( def after_model_callback(
self, self,
callback_context: CallbackContext | None = None, callback_context: CallbackContext | None = None,

View File

@@ -58,9 +58,7 @@ class NotificationService:
""" """
try: try:
# Query Firestore document by phone number # Query Firestore document by phone number
doc_ref = self._db.collection(self._collection_path).document( doc_ref = self._db.collection(self._collection_path).document(phone_number)
phone_number
)
doc = await doc_ref.get() doc = await doc_ref.get()
if not doc.exists: if not doc.exists:
@@ -78,9 +76,7 @@ class NotificationService:
# Filter notifications that have NOT been notified by the agent # Filter notifications that have NOT been notified by the agent
pending = [ pending = [
n n for n in all_notifications if not n.get("notified_by_agent", False)
for n in all_notifications
if not n.get("notified_by_agent", False)
] ]
if not pending: if not pending:
@@ -90,9 +86,7 @@ class NotificationService:
return [] return []
# Sort by timestamp_creacion (most recent first) # Sort by timestamp_creacion (most recent first)
pending.sort( pending.sort(key=lambda n: n.get("timestamp_creacion", 0), reverse=True)
key=lambda n: n.get("timestamp_creacion", 0), reverse=True
)
# Return top N most recent # Return top N most recent
result = pending[: self._max_to_notify] result = pending[: self._max_to_notify]
@@ -104,13 +98,13 @@ class NotificationService:
len(result), len(result),
) )
return result
except Exception: except Exception:
logger.exception( logger.exception(
"Failed to fetch notifications for phone: %s", phone_number "Failed to fetch notifications for phone: %s", phone_number
) )
return [] return []
else:
return result
async def mark_as_notified( async def mark_as_notified(
self, phone_number: str, notification_ids: list[str] self, phone_number: str, notification_ids: list[str]
@@ -133,9 +127,7 @@ class NotificationService:
return True return True
try: try:
doc_ref = self._db.collection(self._collection_path).document( doc_ref = self._db.collection(self._collection_path).document(phone_number)
phone_number
)
doc = await doc_ref.get() doc = await doc_ref.get()
if not doc.exists: if not doc.exists:
@@ -184,18 +176,16 @@ class NotificationService:
phone_number, phone_number,
) )
return True
except Exception: except Exception:
logger.exception( logger.exception(
"Failed to mark notifications as notified for phone: %s", "Failed to mark notifications as notified for phone: %s",
phone_number, phone_number,
) )
return False return False
else:
return True
def format_notification_summary( def format_notification_summary(self, notifications: list[dict[str, Any]]) -> str:
self, notifications: list[dict[str, Any]]
) -> str:
"""Format notifications into a human-readable summary. """Format notifications into a human-readable summary.
Args: Args:
@@ -209,9 +199,7 @@ class NotificationService:
return "" return ""
count = len(notifications) count = len(notifications)
summary_lines = [ summary_lines = [f"El usuario tiene {count} notificación(es) pendiente(s):"]
f"El usuario tiene {count} notificación(es) pendiente(s):"
]
for i, notif in enumerate(notifications, 1): for i, notif in enumerate(notifications, 1):
texto = notif.get("texto", "Sin texto") texto = notif.get("texto", "Sin texto")