Spaces:
Runtime error
Runtime error
feat(agent): asistente RAG con function calling + memoria (Fase 5)
Browse files- backend/services/tools.py: 3 herramientas tipadas (tendencia NDVI, contexto
climático, densidad [en desarrollo]) + TOOLS_SCHEMA + dispatch.
- backend/services/agent.py: orquestación Groq/Llama 3 (OpenAI-compatible vía httpx),
bucle de tool-calling y memoria en chat_messages.
- backend/api/chat.py: POST /api/chat (no-streaming; SSE diferido).
- repositories.get_field_by_name (con centroide para el clima).
- Tests: unit (schema, _describe_trend) + integración en vivo (Groq llama la
herramienta NDVI end-to-end). 58 passed, ruff limpio.
- backend/api/chat.py +57 -0
- backend/db/repositories.py +18 -0
- backend/main.py +2 -0
- backend/services/agent.py +131 -0
- backend/services/tools.py +178 -0
- tests/integration/test_agent.py +90 -0
- tests/unit/test_tools.py +61 -0
backend/api/chat.py
ADDED
|
@@ -0,0 +1,57 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Archivo: chat.py
|
| 3 |
+
Fecha de modificación: 03/06/2026
|
| 4 |
+
Autor: Equipo AgroVisión
|
| 5 |
+
|
| 6 |
+
Descripción:
|
| 7 |
+
Router del Asistente Agéntico (RAG). `POST /api/chat` recibe un turno del usuario, lo
|
| 8 |
+
procesa con el agente (function calling sobre las parcelas) y devuelve la respuesta más
|
| 9 |
+
la traza de herramientas usadas. La memoria vive en `chat_messages`. La llave de Groq es
|
| 10 |
+
efímera (cabecera `X-User-Groq-Key` o `DEV_GROQ_API_KEY` en local).
|
| 11 |
+
|
| 12 |
+
Nota: versión **no-streaming** (request/response). El streaming SSE queda como mejora
|
| 13 |
+
futura; la respuesta sincrónica encaja bien con la UI Shiny.
|
| 14 |
+
|
| 15 |
+
Estructura Interna:
|
| 16 |
+
- `POST /api/chat`.
|
| 17 |
+
|
| 18 |
+
Entradas / Dependencias:
|
| 19 |
+
- `backend.services.agent`, `backend.db.repositories`, `backend.api.deps`.
|
| 20 |
+
|
| 21 |
+
Ejemplo de Integración:
|
| 22 |
+
from backend.api.chat import router
|
| 23 |
+
"""
|
| 24 |
+
|
| 25 |
+
from __future__ import annotations
|
| 26 |
+
|
| 27 |
+
from fastapi import APIRouter, Depends, HTTPException
|
| 28 |
+
from pydantic import BaseModel, Field
|
| 29 |
+
from sqlalchemy.ext.asyncio import AsyncSession
|
| 30 |
+
|
| 31 |
+
from backend.api.deps import UserKeys, get_db, get_user_keys
|
| 32 |
+
from backend.db import repositories as repo
|
| 33 |
+
from backend.services import agent
|
| 34 |
+
|
| 35 |
+
router = APIRouter(prefix="/api/chat", tags=["asistente"])
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
class ChatRequest(BaseModel):
|
| 39 |
+
"""Turno del usuario hacia el agente."""
|
| 40 |
+
|
| 41 |
+
session_id: str = Field(min_length=1, description="Hilo conversacional")
|
| 42 |
+
message: str = Field(min_length=1, description="Mensaje del usuario")
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
@router.post("")
|
| 46 |
+
async def chat(
|
| 47 |
+
body: ChatRequest,
|
| 48 |
+
keys: UserKeys = Depends(get_user_keys),
|
| 49 |
+
session: AsyncSession = Depends(get_db),
|
| 50 |
+
) -> dict:
|
| 51 |
+
"""Procesa un turno con el agente RAG y devuelve respuesta + traza de herramientas."""
|
| 52 |
+
if not keys.groq:
|
| 53 |
+
raise HTTPException(
|
| 54 |
+
status_code=400, detail="Falta la llave de Groq (pestaña Credenciales)."
|
| 55 |
+
)
|
| 56 |
+
field_names = [row.name for row in await repo.list_fields(session)]
|
| 57 |
+
return await agent.run_agent(session, body.message, body.session_id, keys.groq, field_names)
|
backend/db/repositories.py
CHANGED
|
@@ -88,6 +88,24 @@ async def get_field(session: AsyncSession, field_id: Any) -> Row | None:
|
|
| 88 |
return result.first()
|
| 89 |
|
| 90 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 91 |
async def list_fields(session: AsyncSession, user_id: str | None = None) -> list[Row]:
|
| 92 |
"""Lista las parcelas (filtradas por usuario si se indica), ordenadas por nombre."""
|
| 93 |
if user_id is None:
|
|
|
|
| 88 |
return result.first()
|
| 89 |
|
| 90 |
|
| 91 |
+
async def get_field_by_name(session: AsyncSession, name: str) -> Row | None:
|
| 92 |
+
"""
|
| 93 |
+
Busca una parcela por nombre (case-insensitive) y devuelve id, nombre, área y centroide.
|
| 94 |
+
|
| 95 |
+
Returns:
|
| 96 |
+
Row | None: Fila con `id`, `name`, `area_ha`, `lon`, `lat` (centroide), o None.
|
| 97 |
+
"""
|
| 98 |
+
result = await session.execute(
|
| 99 |
+
text(
|
| 100 |
+
"select id, name, (ST_Area(geom::geography) / 10000.0) as area_ha, "
|
| 101 |
+
"ST_X(ST_Centroid(geom)) as lon, ST_Y(ST_Centroid(geom)) as lat "
|
| 102 |
+
"from fields where lower(name) = lower(:name) order by created_at desc limit 1"
|
| 103 |
+
),
|
| 104 |
+
{"name": name},
|
| 105 |
+
)
|
| 106 |
+
return result.first()
|
| 107 |
+
|
| 108 |
+
|
| 109 |
async def list_fields(session: AsyncSession, user_id: str | None = None) -> list[Row]:
|
| 110 |
"""Lista las parcelas (filtradas por usuario si se indica), ordenadas por nombre."""
|
| 111 |
if user_id is None:
|
backend/main.py
CHANGED
|
@@ -39,6 +39,7 @@ from contextlib import asynccontextmanager
|
|
| 39 |
from fastapi import FastAPI
|
| 40 |
from fastapi.middleware.cors import CORSMiddleware
|
| 41 |
|
|
|
|
| 42 |
from backend.api.count import router as count_router
|
| 43 |
from backend.api.fields import router as fields_router
|
| 44 |
from backend.api.ndvi import router as ndvi_router
|
|
@@ -103,6 +104,7 @@ def create_app() -> FastAPI:
|
|
| 103 |
app.include_router(fields_router) # Creación de Parcelas
|
| 104 |
app.include_router(ndvi_router) # Teledetección NDVI
|
| 105 |
app.include_router(weather_router) # Clima
|
|
|
|
| 106 |
app.include_router(count_router) # Conteo (en desarrollo / standby)
|
| 107 |
return app
|
| 108 |
|
|
|
|
| 39 |
from fastapi import FastAPI
|
| 40 |
from fastapi.middleware.cors import CORSMiddleware
|
| 41 |
|
| 42 |
+
from backend.api.chat import router as chat_router
|
| 43 |
from backend.api.count import router as count_router
|
| 44 |
from backend.api.fields import router as fields_router
|
| 45 |
from backend.api.ndvi import router as ndvi_router
|
|
|
|
| 104 |
app.include_router(fields_router) # Creación de Parcelas
|
| 105 |
app.include_router(ndvi_router) # Teledetección NDVI
|
| 106 |
app.include_router(weather_router) # Clima
|
| 107 |
+
app.include_router(chat_router) # Asistente Agéntico (RAG)
|
| 108 |
app.include_router(count_router) # Conteo (en desarrollo / standby)
|
| 109 |
return app
|
| 110 |
|
backend/services/agent.py
ADDED
|
@@ -0,0 +1,131 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Archivo: agent.py
|
| 3 |
+
Fecha de modificación: 03/06/2026
|
| 4 |
+
Autor: Equipo AgroVisión
|
| 5 |
+
|
| 6 |
+
Descripción:
|
| 7 |
+
Orquestador del agente conversacional (RAG con function calling) sobre Groq/Llama 3.
|
| 8 |
+
Construye la conversación (sistema + memoria + turno), deja que el modelo decida qué
|
| 9 |
+
herramienta tipada invocar, ejecuta las herramientas reales (NDVI/clima/densidad) y
|
| 10 |
+
devuelve la respuesta final con la traza de herramientas usadas. Persiste los turnos
|
| 11 |
+
(user/assistant) en `chat_messages`. Usa la API OpenAI-compatible de Groq vía httpx
|
| 12 |
+
(async) — sin SDK extra.
|
| 13 |
+
|
| 14 |
+
Acciones Principales:
|
| 15 |
+
- `run_agent`: ciclo de tool-calling + memoria + respuesta final.
|
| 16 |
+
|
| 17 |
+
Estructura Interna:
|
| 18 |
+
- `_system_prompt`: instrucciones + parcelas disponibles.
|
| 19 |
+
- `_groq_chat`: llamada HTTP a Groq (con/sin herramientas).
|
| 20 |
+
- `run_agent`: bucle de orquestación.
|
| 21 |
+
|
| 22 |
+
Entradas / Dependencias:
|
| 23 |
+
- `httpx`; `backend.services.tools`, `backend.db.repositories`.
|
| 24 |
+
|
| 25 |
+
Salidas / Efectos:
|
| 26 |
+
- Lecturas/escrituras en `chat_messages`; llamadas a Groq y a las herramientas.
|
| 27 |
+
|
| 28 |
+
Ejemplo de Integración:
|
| 29 |
+
from backend.services.agent import run_agent
|
| 30 |
+
out = await run_agent(session, "¿cómo va el NDVI de Lote A?", "sess-1", keys, ["Lote A"])
|
| 31 |
+
"""
|
| 32 |
+
|
| 33 |
+
from __future__ import annotations
|
| 34 |
+
|
| 35 |
+
import json
|
| 36 |
+
|
| 37 |
+
import httpx
|
| 38 |
+
from sqlalchemy.ext.asyncio import AsyncSession
|
| 39 |
+
|
| 40 |
+
from backend.db import repositories as repo
|
| 41 |
+
from backend.services.tools import TOOL_DISPATCH, TOOLS_SCHEMA
|
| 42 |
+
|
| 43 |
+
_GROQ_URL = "https://api.groq.com/openai/v1/chat/completions"
|
| 44 |
+
_MODEL = "llama-3.3-70b-versatile"
|
| 45 |
+
_MAX_TOOL_ROUNDS = 4
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
def _system_prompt(field_names: list[str]) -> str:
|
| 49 |
+
"""Construye el prompt de sistema con las parcelas disponibles."""
|
| 50 |
+
parcelas = ", ".join(field_names) if field_names else "(ninguna registrada todavía)"
|
| 51 |
+
return (
|
| 52 |
+
"Eres el asistente agronómico de AgroVisión. Respondes en español, de forma "
|
| 53 |
+
"concisa y técnica. Dispones de herramientas para consultar el NDVI, el clima y "
|
| 54 |
+
"la densidad de las parcelas del usuario; úsalas en vez de inventar datos. Si una "
|
| 55 |
+
"herramienta indica que algo está 'en desarrollo', acláralo. "
|
| 56 |
+
f"Parcelas disponibles: {parcelas}."
|
| 57 |
+
)
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
async def _groq_chat(api_key: str, messages: list[dict], use_tools: bool) -> dict:
|
| 61 |
+
"""Llama al endpoint de chat de Groq (con herramientas si `use_tools`)."""
|
| 62 |
+
payload: dict = {"model": _MODEL, "messages": messages, "temperature": 0.2}
|
| 63 |
+
if use_tools:
|
| 64 |
+
payload["tools"] = TOOLS_SCHEMA
|
| 65 |
+
payload["tool_choice"] = "auto"
|
| 66 |
+
async with httpx.AsyncClient() as client:
|
| 67 |
+
response = await client.post(
|
| 68 |
+
_GROQ_URL, headers={"Authorization": f"Bearer {api_key}"}, json=payload, timeout=60
|
| 69 |
+
)
|
| 70 |
+
response.raise_for_status()
|
| 71 |
+
return response.json()
|
| 72 |
+
|
| 73 |
+
|
| 74 |
+
async def run_agent(
|
| 75 |
+
session: AsyncSession,
|
| 76 |
+
message: str,
|
| 77 |
+
session_id: str,
|
| 78 |
+
api_key: str,
|
| 79 |
+
field_names: list[str],
|
| 80 |
+
) -> dict:
|
| 81 |
+
"""
|
| 82 |
+
Ejecuta el agente: memoria + tool-calling + respuesta, y persiste los turnos.
|
| 83 |
+
|
| 84 |
+
Args:
|
| 85 |
+
session (AsyncSession): Sesión de BD.
|
| 86 |
+
message (str): Mensaje del usuario.
|
| 87 |
+
session_id (str): Hilo conversacional.
|
| 88 |
+
api_key (str): Llave de Groq (efímera).
|
| 89 |
+
field_names (list[str]): Parcelas disponibles (para el prompt de sistema).
|
| 90 |
+
|
| 91 |
+
Returns:
|
| 92 |
+
dict: {reply, tool_logs, session_id}.
|
| 93 |
+
"""
|
| 94 |
+
await repo.save_chat_message(session, session_id=session_id, role="user", content=message)
|
| 95 |
+
history = await repo.get_chat_history(session, session_id)
|
| 96 |
+
messages: list[dict] = [{"role": "system", "content": _system_prompt(field_names)}]
|
| 97 |
+
messages += [{"role": row.role, "content": row.content} for row in history]
|
| 98 |
+
|
| 99 |
+
tool_logs: list[dict] = []
|
| 100 |
+
for _ in range(_MAX_TOOL_ROUNDS):
|
| 101 |
+
data = await _groq_chat(api_key, messages, use_tools=True)
|
| 102 |
+
choice = data["choices"][0]["message"]
|
| 103 |
+
tool_calls = choice.get("tool_calls")
|
| 104 |
+
if not tool_calls:
|
| 105 |
+
reply = choice.get("content") or ""
|
| 106 |
+
await repo.save_chat_message(
|
| 107 |
+
session, session_id=session_id, role="assistant", content=reply
|
| 108 |
+
)
|
| 109 |
+
return {"reply": reply, "tool_logs": tool_logs, "session_id": session_id}
|
| 110 |
+
|
| 111 |
+
messages.append(choice) # mensaje del asistente con las tool_calls
|
| 112 |
+
for call in tool_calls:
|
| 113 |
+
name = call["function"]["name"]
|
| 114 |
+
try:
|
| 115 |
+
args = json.loads(call["function"].get("arguments") or "{}")
|
| 116 |
+
except json.JSONDecodeError:
|
| 117 |
+
args = {}
|
| 118 |
+
tool = TOOL_DISPATCH.get(name)
|
| 119 |
+
result = (
|
| 120 |
+
await tool(session, **args)
|
| 121 |
+
if tool
|
| 122 |
+
else f"Herramienta desconocida: {name}."
|
| 123 |
+
)
|
| 124 |
+
tool_logs.append({"tool": name, "args": args})
|
| 125 |
+
messages.append({"role": "tool", "tool_call_id": call["id"], "content": result})
|
| 126 |
+
|
| 127 |
+
# Si se agotaron las rondas de herramientas, pide una respuesta final sin tools.
|
| 128 |
+
data = await _groq_chat(api_key, messages, use_tools=False)
|
| 129 |
+
reply = data["choices"][0]["message"].get("content") or "(sin respuesta)"
|
| 130 |
+
await repo.save_chat_message(session, session_id=session_id, role="assistant", content=reply)
|
| 131 |
+
return {"reply": reply, "tool_logs": tool_logs, "session_id": session_id}
|
backend/services/tools.py
ADDED
|
@@ -0,0 +1,178 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Archivo: tools.py
|
| 3 |
+
Fecha de modificación: 03/06/2026
|
| 4 |
+
Autor: Equipo AgroVisión
|
| 5 |
+
|
| 6 |
+
Descripción:
|
| 7 |
+
Herramientas tipadas del agente RAG (function calling). El LLM no inventa datos: decide
|
| 8 |
+
qué función llamar y nuestro código la ejecuta contra la BD / clima real y devuelve el
|
| 9 |
+
resultado para que redacte. Tres herramientas: tendencia NDVI, contexto climático y
|
| 10 |
+
densidad de siembra (esta última, en desarrollo mientras el Conteo esté inactivo).
|
| 11 |
+
|
| 12 |
+
Acciones Principales:
|
| 13 |
+
- Define `TOOLS_SCHEMA` (JSON-Schema) y `TOOL_DISPATCH` (name -> coroutine).
|
| 14 |
+
|
| 15 |
+
Estructura Interna:
|
| 16 |
+
- `_describe_trend`: formateo puro de la tendencia NDVI (testeable sin BD).
|
| 17 |
+
- `get_vegetation_index_trend` / `get_weather_context` / `get_field_planting_density`.
|
| 18 |
+
|
| 19 |
+
Entradas / Dependencias:
|
| 20 |
+
- `backend.db.repositories`, `backend.services.weather`.
|
| 21 |
+
|
| 22 |
+
Salidas / Efectos:
|
| 23 |
+
- Lecturas a la BD del usuario y a Open-Meteo.
|
| 24 |
+
|
| 25 |
+
Ejemplo de Integración:
|
| 26 |
+
from backend.services.tools import TOOLS_SCHEMA, TOOL_DISPATCH
|
| 27 |
+
"""
|
| 28 |
+
|
| 29 |
+
from __future__ import annotations
|
| 30 |
+
|
| 31 |
+
import datetime as dt
|
| 32 |
+
|
| 33 |
+
from dateutil.relativedelta import relativedelta
|
| 34 |
+
from sqlalchemy.ext.asyncio import AsyncSession
|
| 35 |
+
|
| 36 |
+
from backend.db import repositories as repo
|
| 37 |
+
from backend.services import weather
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
def _in_range(date_value: object, start: str | None, end: str | None) -> bool:
|
| 41 |
+
"""Indica si una fecha (date o str) cae dentro de [start, end] (ISO) si se dan."""
|
| 42 |
+
day = str(date_value)[:10]
|
| 43 |
+
if start and day < start[:10]:
|
| 44 |
+
return False
|
| 45 |
+
return not (end and day > end[:10])
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
def _describe_trend(field_name: str, series: list[dict]) -> str:
|
| 49 |
+
"""
|
| 50 |
+
Redacta la tendencia NDVI de una serie (función pura).
|
| 51 |
+
|
| 52 |
+
Args:
|
| 53 |
+
field_name (str): Nombre de la parcela.
|
| 54 |
+
series (list[dict]): Puntos con 'date' y 'mean_ndvi' ordenados por fecha.
|
| 55 |
+
|
| 56 |
+
Returns:
|
| 57 |
+
str: Texto con la tendencia (descenso/incremento/estable) y los extremos.
|
| 58 |
+
"""
|
| 59 |
+
valid = [p for p in series if p.get("mean_ndvi") is not None]
|
| 60 |
+
if len(valid) < 2:
|
| 61 |
+
return f"Datos insuficientes de NDVI para '{field_name}' (se necesitan ≥2 observaciones)."
|
| 62 |
+
first, last = valid[0], valid[-1]
|
| 63 |
+
delta = last["mean_ndvi"] - first["mean_ndvi"]
|
| 64 |
+
trend = "estable" if abs(delta) < 0.02 else ("descenso" if delta < 0 else "incremento")
|
| 65 |
+
return (
|
| 66 |
+
f"NDVI de '{field_name}': {trend} de {delta:+.2f} entre {str(first['date'])[:10]} "
|
| 67 |
+
f"({first['mean_ndvi']:.2f}) y {str(last['date'])[:10]} ({last['mean_ndvi']:.2f}). "
|
| 68 |
+
f"Observaciones: {len(valid)}."
|
| 69 |
+
)
|
| 70 |
+
|
| 71 |
+
|
| 72 |
+
async def get_vegetation_index_trend(
|
| 73 |
+
session: AsyncSession,
|
| 74 |
+
field_name: str,
|
| 75 |
+
start_date: str | None = None,
|
| 76 |
+
end_date: str | None = None,
|
| 77 |
+
) -> str:
|
| 78 |
+
"""Tendencia de NDVI de una parcela entre dos fechas (usa la serie persistida)."""
|
| 79 |
+
field = await repo.get_field_by_name(session, field_name)
|
| 80 |
+
if field is None:
|
| 81 |
+
return f"No encontré la parcela '{field_name}'."
|
| 82 |
+
series = await repo.get_ndvi_series(session, field.id)
|
| 83 |
+
in_range = [p for p in series if _in_range(p["date"], start_date, end_date)]
|
| 84 |
+
return _describe_trend(field_name, in_range)
|
| 85 |
+
|
| 86 |
+
|
| 87 |
+
async def get_weather_context(
|
| 88 |
+
session: AsyncSession,
|
| 89 |
+
field_name: str,
|
| 90 |
+
start_date: str | None = None,
|
| 91 |
+
end_date: str | None = None,
|
| 92 |
+
) -> str:
|
| 93 |
+
"""Resumen agroclimático de una parcela (clima de Open-Meteo en su centroide)."""
|
| 94 |
+
field = await repo.get_field_by_name(session, field_name)
|
| 95 |
+
if field is None:
|
| 96 |
+
return f"No encontré la parcela '{field_name}'."
|
| 97 |
+
if not start_date or not end_date:
|
| 98 |
+
end = dt.date.today()
|
| 99 |
+
start = end - relativedelta(months=12)
|
| 100 |
+
start_date, end_date = start.isoformat(), end.isoformat()
|
| 101 |
+
series = await weather.weather_series(field.lat, field.lon, start_date, end_date)
|
| 102 |
+
if not series:
|
| 103 |
+
return f"Sin datos climáticos para '{field_name}' en el rango."
|
| 104 |
+
total_precip = round(sum(p["precip_mm"] for p in series), 1)
|
| 105 |
+
temps = [p["temp_mean_c"] for p in series if p["temp_mean_c"] is not None]
|
| 106 |
+
avg_temp = round(sum(temps) / len(temps), 1) if temps else None
|
| 107 |
+
return (
|
| 108 |
+
f"Clima de '{field_name}' ({start_date} a {end_date}): precipitación acumulada "
|
| 109 |
+
f"{total_precip} mm, temperatura media {avg_temp} °C sobre {len(series)} meses."
|
| 110 |
+
)
|
| 111 |
+
|
| 112 |
+
|
| 113 |
+
async def get_field_planting_density(session: AsyncSession, field_name: str) -> str:
|
| 114 |
+
"""Densidad de siembra de una parcela (en desarrollo: depende del módulo de Conteo)."""
|
| 115 |
+
field = await repo.get_field_by_name(session, field_name)
|
| 116 |
+
if field is None:
|
| 117 |
+
return f"No encontré la parcela '{field_name}'."
|
| 118 |
+
area = f"{field.area_ha:.2f} ha" if field.area_ha else "área desconocida"
|
| 119 |
+
return (
|
| 120 |
+
f"La parcela '{field_name}' mide {area}. La densidad de plantas aún no está "
|
| 121 |
+
"disponible: el módulo de conteo por dron está en desarrollo."
|
| 122 |
+
)
|
| 123 |
+
|
| 124 |
+
|
| 125 |
+
TOOLS_SCHEMA: list[dict] = [
|
| 126 |
+
{
|
| 127 |
+
"type": "function",
|
| 128 |
+
"function": {
|
| 129 |
+
"name": "get_vegetation_index_trend",
|
| 130 |
+
"description": "Tendencia del NDVI (vigor vegetal) de una parcela entre dos fechas.",
|
| 131 |
+
"parameters": {
|
| 132 |
+
"type": "object",
|
| 133 |
+
"properties": {
|
| 134 |
+
"field_name": {"type": "string", "description": "Nombre de la parcela"},
|
| 135 |
+
"start_date": {"type": "string", "description": "Inicio YYYY-MM-DD (opcional)"},
|
| 136 |
+
"end_date": {"type": "string", "description": "Fin YYYY-MM-DD (opcional)"},
|
| 137 |
+
},
|
| 138 |
+
"required": ["field_name"],
|
| 139 |
+
},
|
| 140 |
+
},
|
| 141 |
+
},
|
| 142 |
+
{
|
| 143 |
+
"type": "function",
|
| 144 |
+
"function": {
|
| 145 |
+
"name": "get_weather_context",
|
| 146 |
+
"description": "Resumen agroclimático (precipitación y temperatura) de una parcela.",
|
| 147 |
+
"parameters": {
|
| 148 |
+
"type": "object",
|
| 149 |
+
"properties": {
|
| 150 |
+
"field_name": {"type": "string", "description": "Nombre de la parcela"},
|
| 151 |
+
"start_date": {"type": "string", "description": "Inicio YYYY-MM-DD (opcional)"},
|
| 152 |
+
"end_date": {"type": "string", "description": "Fin YYYY-MM-DD (opcional)"},
|
| 153 |
+
},
|
| 154 |
+
"required": ["field_name"],
|
| 155 |
+
},
|
| 156 |
+
},
|
| 157 |
+
},
|
| 158 |
+
{
|
| 159 |
+
"type": "function",
|
| 160 |
+
"function": {
|
| 161 |
+
"name": "get_field_planting_density",
|
| 162 |
+
"description": "Densidad de siembra (pl/Ha) de una parcela. En desarrollo.",
|
| 163 |
+
"parameters": {
|
| 164 |
+
"type": "object",
|
| 165 |
+
"properties": {
|
| 166 |
+
"field_name": {"type": "string", "description": "Nombre de la parcela"},
|
| 167 |
+
},
|
| 168 |
+
"required": ["field_name"],
|
| 169 |
+
},
|
| 170 |
+
},
|
| 171 |
+
},
|
| 172 |
+
]
|
| 173 |
+
|
| 174 |
+
TOOL_DISPATCH = {
|
| 175 |
+
"get_vegetation_index_trend": get_vegetation_index_trend,
|
| 176 |
+
"get_weather_context": get_weather_context,
|
| 177 |
+
"get_field_planting_density": get_field_planting_density,
|
| 178 |
+
}
|
tests/integration/test_agent.py
ADDED
|
@@ -0,0 +1,90 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Archivo: test_agent.py
|
| 3 |
+
Fecha de modificación: 03/06/2026
|
| 4 |
+
Autor: Equipo AgroVisión
|
| 5 |
+
|
| 6 |
+
Descripción:
|
| 7 |
+
Prueba de integración del agente RAG (Fase 5): con una parcela y serie NDVI sembradas,
|
| 8 |
+
una consulta de tendencia debe disparar la herramienta `get_vegetation_index_trend` y
|
| 9 |
+
producir una respuesta. Verifica function calling + memoria end-to-end. Se omite si
|
| 10 |
+
faltan la llave de Groq o `DATABASE_URL`.
|
| 11 |
+
|
| 12 |
+
Ejecución:
|
| 13 |
+
uv run python -m pytest tests/integration/test_agent.py -v
|
| 14 |
+
"""
|
| 15 |
+
|
| 16 |
+
from __future__ import annotations
|
| 17 |
+
|
| 18 |
+
import asyncio
|
| 19 |
+
import contextlib
|
| 20 |
+
import os
|
| 21 |
+
import uuid
|
| 22 |
+
|
| 23 |
+
import pytest
|
| 24 |
+
from dotenv import load_dotenv
|
| 25 |
+
|
| 26 |
+
load_dotenv()
|
| 27 |
+
|
| 28 |
+
_HAS_GROQ = bool(os.getenv("DEV_GROQ_API_KEY"))
|
| 29 |
+
_HAS_DB = bool(os.getenv("DATABASE_URL"))
|
| 30 |
+
|
| 31 |
+
from backend.db import repositories as repo # noqa: E402
|
| 32 |
+
from backend.db.session import get_engine, get_sessionmaker # noqa: E402
|
| 33 |
+
from backend.services.agent import run_agent # noqa: E402
|
| 34 |
+
|
| 35 |
+
_SQUARE = {
|
| 36 |
+
"type": "Polygon",
|
| 37 |
+
"coordinates": [
|
| 38 |
+
[[-58.0, -34.0], [-58.0, -34.1], [-57.9, -34.1], [-57.9, -34.0], [-58.0, -34.0]]
|
| 39 |
+
],
|
| 40 |
+
}
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
@contextlib.asynccontextmanager
|
| 44 |
+
async def _engine_scope():
|
| 45 |
+
get_engine.cache_clear()
|
| 46 |
+
get_sessionmaker.cache_clear()
|
| 47 |
+
try:
|
| 48 |
+
yield get_sessionmaker()
|
| 49 |
+
finally:
|
| 50 |
+
await get_engine().dispose()
|
| 51 |
+
get_engine.cache_clear()
|
| 52 |
+
get_sessionmaker.cache_clear()
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
@pytest.mark.skipif(not (_HAS_GROQ and _HAS_DB), reason="Faltan Groq o DATABASE_URL")
|
| 56 |
+
def test_agente_llama_herramienta_ndvi() -> None:
|
| 57 |
+
"""Una consulta de NDVI dispara la herramienta de tendencia y devuelve respuesta."""
|
| 58 |
+
user_id = str(uuid.uuid4())
|
| 59 |
+
field_name = f"Lote Test {uuid.uuid4().hex[:6]}"
|
| 60 |
+
session_id = f"sess-{uuid.uuid4()}"
|
| 61 |
+
|
| 62 |
+
async def _run() -> None:
|
| 63 |
+
async with _engine_scope() as sm, sm() as session:
|
| 64 |
+
try:
|
| 65 |
+
field = await repo.create_field(
|
| 66 |
+
session, name=field_name, geojson=_SQUARE, user_id=user_id
|
| 67 |
+
)
|
| 68 |
+
await repo.upsert_ndvi_points(
|
| 69 |
+
session,
|
| 70 |
+
field.id,
|
| 71 |
+
[
|
| 72 |
+
{"date": "2026-01-01", "mean_ndvi": 0.80, "cloud_cover": 5},
|
| 73 |
+
{"date": "2026-03-01", "mean_ndvi": 0.68, "cloud_cover": 7},
|
| 74 |
+
],
|
| 75 |
+
)
|
| 76 |
+
out = await run_agent(
|
| 77 |
+
session,
|
| 78 |
+
f"¿Cómo evolucionó el NDVI de {field_name}?",
|
| 79 |
+
session_id,
|
| 80 |
+
os.environ["DEV_GROQ_API_KEY"],
|
| 81 |
+
[field_name],
|
| 82 |
+
)
|
| 83 |
+
assert out["reply"]
|
| 84 |
+
tools_used = {log["tool"] for log in out["tool_logs"]}
|
| 85 |
+
assert "get_vegetation_index_trend" in tools_used
|
| 86 |
+
finally:
|
| 87 |
+
await repo.delete_chat_for_session(session, session_id)
|
| 88 |
+
await repo.delete_fields_for_user(session, user_id)
|
| 89 |
+
|
| 90 |
+
asyncio.run(_run())
|
tests/unit/test_tools.py
ADDED
|
@@ -0,0 +1,61 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Archivo: test_tools.py
|
| 3 |
+
Fecha de modificación: 03/06/2026
|
| 4 |
+
Autor: Equipo AgroVisión
|
| 5 |
+
|
| 6 |
+
Descripción:
|
| 7 |
+
Pruebas unitarias de las herramientas del agente: el esquema de function calling y el
|
| 8 |
+
formateo puro de la tendencia NDVI.
|
| 9 |
+
|
| 10 |
+
Ejecución:
|
| 11 |
+
uv run python -m pytest tests/unit/test_tools.py
|
| 12 |
+
"""
|
| 13 |
+
|
| 14 |
+
from __future__ import annotations
|
| 15 |
+
|
| 16 |
+
from backend.services.tools import TOOLS_SCHEMA, _describe_trend, _in_range
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
def test_tools_schema_define_tres_herramientas() -> None:
|
| 20 |
+
"""El esquema declara las 3 herramientas con `field_name` requerido."""
|
| 21 |
+
names = {t["function"]["name"] for t in TOOLS_SCHEMA}
|
| 22 |
+
assert names == {
|
| 23 |
+
"get_vegetation_index_trend",
|
| 24 |
+
"get_weather_context",
|
| 25 |
+
"get_field_planting_density",
|
| 26 |
+
}
|
| 27 |
+
for tool in TOOLS_SCHEMA:
|
| 28 |
+
assert "field_name" in tool["function"]["parameters"]["required"]
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
def test_describe_trend_descenso() -> None:
|
| 32 |
+
"""Una serie que baja se describe como 'descenso' con el delta correcto."""
|
| 33 |
+
series = [
|
| 34 |
+
{"date": "2026-01-01", "mean_ndvi": 0.80},
|
| 35 |
+
{"date": "2026-03-01", "mean_ndvi": 0.70},
|
| 36 |
+
]
|
| 37 |
+
out = _describe_trend("Lote A", series)
|
| 38 |
+
assert "descenso" in out
|
| 39 |
+
assert "Lote A" in out
|
| 40 |
+
assert "-0.10" in out
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
def test_describe_trend_estable() -> None:
|
| 44 |
+
"""Un cambio menor a 0.02 se considera 'estable'."""
|
| 45 |
+
series = [
|
| 46 |
+
{"date": "2026-01-01", "mean_ndvi": 0.70},
|
| 47 |
+
{"date": "2026-03-01", "mean_ndvi": 0.71},
|
| 48 |
+
]
|
| 49 |
+
assert "estable" in _describe_trend("Lote A", series)
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
def test_describe_trend_insuficiente() -> None:
|
| 53 |
+
"""Con menos de 2 observaciones se reporta datos insuficientes."""
|
| 54 |
+
assert "insuficientes" in _describe_trend("Lote A", [{"date": "2026-01-01", "mean_ndvi": 0.7}])
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
def test_in_range() -> None:
|
| 58 |
+
"""El filtro de rango respeta los límites ISO."""
|
| 59 |
+
assert _in_range("2026-03-01", "2026-01-01", "2026-12-31")
|
| 60 |
+
assert not _in_range("2025-12-01", "2026-01-01", None)
|
| 61 |
+
assert _in_range("2026-03-01", None, None)
|