Add Notification Backend Protocol (#24)
All checks were successful
CI / ci (push) Successful in 21s

Reviewed-on: #24
This commit was merged in pull request #24.
This commit is contained in:
2026-03-09 07:36:47 +00:00
parent ba6fde1b15
commit 1803d011d0
11 changed files with 676 additions and 189 deletions

View File

@@ -1,5 +1,7 @@
"""ADK agent with vector search RAG tool."""
from functools import partial
from google import genai
from google.adk.agents.llm_agent import Agent
from google.adk.runners import Runner
@@ -10,8 +12,9 @@ from google.genai.types import Content, Part
from va_agent.auth import auth_headers_provider
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 FirestoreNotificationBackend
from va_agent.session import FirestoreSessionService
# MCP Toolset for RAG knowledge search
@@ -32,10 +35,11 @@ session_service = FirestoreSessionService(
)
# Notification service
notification_service = NotificationService(
notification_service = FirestoreNotificationBackend(
db=firestore_db,
collection_path=settings.notifications_collection_path,
max_to_notify=settings.notifications_max_to_notify,
window_hours=settings.notifications_window_hours,
)
# Agent with static and dynamic instructions
@@ -43,11 +47,11 @@ governance = GovernancePlugin()
agent = Agent(
model=settings.agent_model,
name=settings.agent_name,
instruction=partial(provide_dynamic_instruction, notification_service),
static_instruction=Content(
role="user",
parts=[Part(text=settings.agent_instructions)],
),
instruction=settings.agent_instructions,
tools=[toolset],
after_model_callback=governance.after_model_callback,
)

View File

@@ -31,6 +31,7 @@ class AgentSettings(BaseSettings):
"artifacts/bnt-orquestador-cognitivo-dev/notifications"
)
notifications_max_to_notify: int = 5
notifications_window_hours: float = 48
# MCP configuration
mcp_audience: str

View File

@@ -3,27 +3,49 @@
from __future__ import annotations
import logging
import time
from typing import TYPE_CHECKING
if TYPE_CHECKING:
from google.adk.agents.readonly_context import ReadonlyContext
from va_agent.notifications import NotificationService
from va_agent.notifications import NotificationBackend
logger = logging.getLogger(__name__)
_SECONDS_PER_MINUTE = 60
_SECONDS_PER_HOUR = 3600
_MINUTES_PER_HOUR = 60
_HOURS_PER_DAY = 24
def _format_time_ago(now: float, ts: float) -> str:
"""Return a human-readable Spanish label like 'hace 3 horas'."""
diff = max(now - ts, 0)
minutes = int(diff // _SECONDS_PER_MINUTE)
hours = int(diff // _SECONDS_PER_HOUR)
if minutes < 1:
return "justo ahora"
if minutes < _MINUTES_PER_HOUR:
return f"hace {minutes} min"
if hours < _HOURS_PER_DAY:
return f"hace {hours}h"
days = hours // _HOURS_PER_DAY
return f"hace {days}d"
async def provide_dynamic_instruction(
notification_service: NotificationService,
notification_service: NotificationBackend,
ctx: ReadonlyContext | None = None,
) -> str:
"""Provide dynamic instructions based on pending notifications.
"""Provide dynamic instructions based on recent notifications.
This function is called by the ADK agent on each message. It:
1. Checks if this is the first message in the session (< 2 events)
2. Queries Firestore for pending notifications
3. Marks them as notified
4. Returns a dynamic instruction for the agent to mention them
1. Queries Firestore for recent notifications
2. Marks them as notified
3. Returns a dynamic instruction for the agent to mention them
Args:
notification_service: Service for fetching/marking notifications
@@ -43,71 +65,54 @@ async def provide_dynamic_instruction(
logger.debug("No session available for dynamic instruction")
return ""
# FOR TESTING: Always check for notifications
# (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
# event_count = len(session.events) if session.events else 0
#
# if event_count >= 2:
# logger.debug(
# "Skipping notification check: not first message (event_count=%d)",
# event_count,
# )
# return ""
# Extract phone number from user_id (they are the same in this implementation)
phone_number = session.user_id
logger.info(
"First message detected for user %s, checking for pending notifications",
"Checking recent notifications for user %s",
phone_number,
)
try:
# Fetch pending notifications
pending_notifications = await notification_service.get_pending_notifications(
# Fetch recent notifications
recent_notifications = await notification_service.get_recent_notifications(
phone_number
)
if not pending_notifications:
logger.info("No pending notifications for user %s", phone_number)
if not recent_notifications:
logger.info("No recent notifications for user %s", phone_number)
return ""
# Build dynamic instruction with notification details
notification_ids = [
nid
for n in pending_notifications
for n in recent_notifications
if (nid := n.get("id_notificacion")) is not None
]
count = len(pending_notifications)
count = len(recent_notifications)
# Format notification details for the agent
# Format notification details for the agent (most recent first)
now = time.time()
notification_details = []
for notif in pending_notifications:
for i, notif in enumerate(recent_notifications, 1):
evento = notif.get("nombre_evento_dialogflow", "notificacion")
texto = notif.get("texto", "Sin texto")
notification_details.append(f" - Evento: {evento} | Texto: {texto}")
ts = notif.get("timestamp_creacion", notif.get("timestampCreacion", 0))
ago = _format_time_ago(now, ts)
notification_details.append(
f" {i}. [{ago}] Evento: {evento} | Texto: {texto}"
)
details_text = "\n".join(notification_details)
header = (
f"Estas son {count} notificación(es) reciente(s)"
" de las cuales el usuario podría preguntar más:"
)
instruction = f"""
IMPORTANTE - NOTIFICACIONES PENDIENTES:
El usuario tiene {count} notificación(es) sin leer:
{header}
{details_text}
INSTRUCCIONES:
- Menciona estas notificaciones de forma natural en tu respuesta inicial
- No necesitas leerlas todas literalmente, solo hazle saber que las tiene
- 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
Ejemplo: "¡Hola! 👋 Tienes {count} notificación(es)\
pendiente(s). ¿Te gustaría revisarlas?"
"""
# Mark notifications as notified in Firestore

View File

@@ -4,7 +4,7 @@ from __future__ import annotations
import logging
import time
from typing import TYPE_CHECKING, Any
from typing import TYPE_CHECKING, Any, Protocol, runtime_checkable
if TYPE_CHECKING:
from google.cloud.firestore_v1.async_client import AsyncClient
@@ -12,8 +12,28 @@ if TYPE_CHECKING:
logger = logging.getLogger(__name__)
class NotificationService:
"""Service for fetching and managing user notifications from Firestore."""
@runtime_checkable
class NotificationBackend(Protocol):
"""Backend-agnostic interface for notification storage."""
async def get_recent_notifications(self, phone_number: str) -> list[dict[str, Any]]:
"""Return recent notifications for *phone_number*."""
...
async def mark_as_notified(
self, phone_number: str, notification_ids: list[str]
) -> bool:
"""Mark the given notification IDs as notified. Return success."""
...
class FirestoreNotificationBackend:
"""Firestore-backed notification backend (read-only).
Reads notifications from a Firestore document keyed by phone number.
Filters by a configurable time window instead of tracking read/unread
state — the agent is awareness-only; delivery happens in the app.
"""
def __init__(
self,
@@ -21,25 +41,18 @@ class NotificationService:
db: AsyncClient,
collection_path: str,
max_to_notify: int = 5,
window_hours: float = 48,
) -> None:
"""Initialize NotificationService.
Args:
db: Firestore async client
collection_path: Path to notifications collection
max_to_notify: Maximum number of notifications to return
"""
"""Initialize with Firestore client and collection path."""
self._db = db
self._collection_path = collection_path
self._max_to_notify = max_to_notify
self._window_hours = window_hours
async def get_pending_notifications(
self, phone_number: str
) -> list[dict[str, Any]]:
"""Get pending notifications for a user.
async def get_recent_notifications(self, phone_number: str) -> list[dict[str, Any]]:
"""Get recent notifications for a user.
Retrieves notifications that have not been notified by the agent yet,
Retrieves notifications created within the configured time window,
ordered by timestamp (most recent first), limited to max_to_notify.
Args:
@@ -57,7 +70,6 @@ class NotificationService:
"""
try:
# Query Firestore document by phone number
doc_ref = self._db.collection(self._collection_path).document(phone_number)
doc = await doc_ref.get()
@@ -74,26 +86,31 @@ class NotificationService:
logger.info("No notifications in array for phone: %s", phone_number)
return []
# Filter notifications that have NOT been notified by the agent
pending = [
n for n in all_notifications if not n.get("notified_by_agent", False)
]
cutoff = time.time() - (self._window_hours * 3600)
if not pending:
def _ts(n: dict[str, Any]) -> Any:
return n.get(
"timestamp_creacion",
n.get("timestampCreacion", 0),
)
recent = [n for n in all_notifications if _ts(n) >= cutoff]
if not recent:
logger.info(
"All notifications already notified for phone: %s", phone_number
"No notifications within the last %.0fh for phone: %s",
self._window_hours,
phone_number,
)
return []
# Sort by timestamp_creacion (most recent first)
pending.sort(key=lambda n: n.get("timestamp_creacion", 0), reverse=True)
recent.sort(key=_ts, reverse=True)
# Return top N most recent
result = pending[: self._max_to_notify]
result = recent[: self._max_to_notify]
logger.info(
"Found %d pending notifications for phone: %s (returning top %d)",
len(pending),
"Found %d recent notifications for phone: %s (returning top %d)",
len(recent),
phone_number,
len(result),
)
@@ -107,114 +124,109 @@ class NotificationService:
return result
async def mark_as_notified(
self, phone_number: str, notification_ids: list[str]
self,
phone_number: str, # noqa: ARG002
notification_ids: list[str], # noqa: ARG002
) -> bool:
"""Mark notifications as notified by the agent.
"""No-op — the agent is not the delivery mechanism."""
return True
Updates the notifications in Firestore by adding:
- notified_by_agent: true
- notified_at: current timestamp
Args:
phone_number: User's phone number (document ID)
notification_ids: List of id_notificacion values to mark
class RedisNotificationBackend:
"""Redis-backed notification backend (read-only)."""
Returns:
True if update was successful, False otherwise
def __init__(
self,
*,
host: str = "127.0.0.1",
port: int = 6379,
max_to_notify: int = 5,
window_hours: float = 48,
) -> None:
"""Initialize with Redis connection parameters."""
import redis.asyncio as aioredis # noqa: PLC0415
self._client = aioredis.Redis(
host=host,
port=port,
decode_responses=True,
socket_connect_timeout=5,
)
self._max_to_notify = max_to_notify
self._window_hours = window_hours
async def get_recent_notifications(self, phone_number: str) -> list[dict[str, Any]]:
"""Get recent notifications for a user from Redis.
Reads from the ``notification:{phone}`` key, parses the JSON
payload, and returns notifications created within the configured
time window, sorted by creation timestamp (most recent first),
limited to *max_to_notify*.
"""
if not notification_ids:
return True
import json # noqa: PLC0415
try:
doc_ref = self._db.collection(self._collection_path).document(phone_number)
doc = await doc_ref.get()
raw = await self._client.get(f"notification:{phone_number}")
if not doc.exists:
logger.warning(
"Cannot mark notifications as notified: document not found for %s",
if not raw:
logger.info(
"No notification data in Redis for phone: %s",
phone_number,
)
return False
return []
data = doc.to_dict() or {}
notificaciones = data.get("notificaciones", [])
data = json.loads(raw)
all_notifications: list[dict[str, Any]] = data.get("notificaciones", [])
if not notificaciones:
logger.warning(
"Cannot mark notifications: empty array for %s", phone_number
if not all_notifications:
logger.info(
"No notifications in array for phone: %s",
phone_number,
)
return False
return []
# Update matching notifications
now = time.time()
updated_count = 0
cutoff = time.time() - (self._window_hours * 3600)
for notif in notificaciones:
if notif.get("id_notificacion") in notification_ids:
notif["notified_by_agent"] = True
notif["notified_at"] = now
updated_count += 1
if updated_count == 0:
logger.warning(
"No notifications matched IDs for phone: %s", phone_number
def _ts(n: dict[str, Any]) -> Any:
return n.get(
"timestamp_creacion",
n.get("timestampCreacion", 0),
)
return False
# Save back to Firestore
await doc_ref.update(
{
"notificaciones": notificaciones,
"ultima_actualizacion": now,
}
)
recent = [n for n in all_notifications if _ts(n) >= cutoff]
if not recent:
logger.info(
"No notifications within the last %.0fh for phone: %s",
self._window_hours,
phone_number,
)
return []
recent.sort(key=_ts, reverse=True)
result = recent[: self._max_to_notify]
logger.info(
"Marked %d notification(s) as notified for phone: %s",
updated_count,
"Found %d recent notifications for phone: %s (returning top %d)",
len(recent),
phone_number,
len(result),
)
except Exception:
logger.exception(
"Failed to mark notifications as notified for phone: %s",
"Failed to fetch notifications from Redis for phone: %s",
phone_number,
)
return False
return []
else:
return True
return result
def format_notification_summary(self, notifications: list[dict[str, Any]]) -> str:
"""Format notifications into a human-readable summary.
Args:
notifications: List of notification dictionaries
Returns:
Formatted string summarizing the notifications
"""
if not notifications:
return ""
count = len(notifications)
summary_lines = [f"El usuario tiene {count} notificación(es) pendiente(s):"]
for i, notif in enumerate(notifications, 1):
texto = notif.get("texto", "Sin texto")
params = notif.get("parametros", {})
# Extract key parameters if available
amount = params.get("notification_po_amount")
tx_id = params.get("notification_po_transaction_id")
line = f"{i}. {texto}"
if amount:
line += f" (monto: ${amount})"
if tx_id:
line += f" [ID: {tx_id}]"
summary_lines.append(line)
return "\n".join(summary_lines)
async def mark_as_notified(
self,
phone_number: str, # noqa: ARG002
notification_ids: list[str], # noqa: ARG002
) -> bool:
"""No-op — the agent is not the delivery mechanism."""
return True

View File

@@ -22,20 +22,11 @@ app = FastAPI(title="Vaia Agent")
# ---------------------------------------------------------------------------
class NotificationPayload(BaseModel):
"""Notification context sent alongside a user query."""
text: str | None = None
parameters: dict[str, Any] = Field(default_factory=dict)
class QueryRequest(BaseModel):
"""Incoming query request from the integration layer."""
phone_number: str
text: str
type: str = "conversation"
notification: NotificationPayload | None = None
language_code: str = "es"
@@ -56,26 +47,6 @@ class ErrorResponse(BaseModel):
status: int
# ---------------------------------------------------------------------------
# Helpers
# ---------------------------------------------------------------------------
def _build_user_message(request: QueryRequest) -> str:
"""Compose the text sent to the agent, including notification context."""
if request.type == "notification" and request.notification:
parts = [request.text]
if request.notification.text:
parts.append(f"\n[Notificación recibida]: {request.notification.text}")
if request.notification.parameters:
formatted = ", ".join(
f"{k}: {v}" for k, v in request.notification.parameters.items()
)
parts.append(f"[Parámetros de notificación]: {formatted}")
return "\n".join(parts)
return request.text
# ---------------------------------------------------------------------------
# Endpoints
# ---------------------------------------------------------------------------
@@ -92,13 +63,12 @@ def _build_user_message(request: QueryRequest) -> str:
)
async def query(request: QueryRequest) -> QueryResponse:
"""Process a user message and return a generated response."""
user_message = _build_user_message(request)
session_id = request.phone_number
user_id = request.phone_number
new_message = Content(
role="user",
parts=[Part(text=user_message)],
parts=[Part(text=request.text)],
)
try: