Resumen
Este flujo de trabajo integrates Scavio search en un LangGraph agent's memory actualizacion cycle. Before el agent usa cualquier memorized fact con un time dimension (prices, disponibilidad, posicionamientos), it verifies el fact con un live search y actualiza memory if el datos tiene changed. Este prevents stale memory de causing confidently wrong answers a traves de multi-session conversations.
Desencadenador
Agent convertir (antes de citing time-sensitive memorized facts)
Programación
Activado per agent convertir cuando citing time-sensitive facts
Pasos del flujo de trabajo
Detectar time-sensitive claims
Identificar memorized facts ese tienen un time dimension: prices, stock levels, dates, posicionamientos.
Generar verification consulta
Construct un consulta de busqueda designed to verify o actualizacion el especifico claim.
Ejecutar live search
Call Scavio con el verification consulta y retrieve fresh datos.
Comparar contra memory
Verificar if el fresh datos contradicts o confirms el memorized claim.
Actualizar memory if stale
Replace el stale memorized fact con el fresh datos y marca de tiempo.
Respond con fresh datos
Use el verified o actualizado fact in el agent's respuesta con un freshness citacion.
Implementacion en Python
import requests
import json
from datetime import datetime
from pathlib import Path
from langgraph.graph import StateGraph, END
from typing import TypedDict
API_KEY = "your_scavio_api_key"
class MemoryState(TypedDict):
query: str
claim_key: str
memorized_value: str
verified: bool
fresh_value: str
source_url: str
updated_at: str
MEMORY_STORE = Path("agent_memory.json")
def load_memory() -> dict:
if MEMORY_STORE.exists():
return json.loads(MEMORY_STORE.read_text())
return {}
def save_memory(memory: dict):
MEMORY_STORE.write_text(json.dumps(memory, indent=2))
def verify_claim(state: MemoryState) -> MemoryState:
res = requests.post(
"https://api.scavio.dev/api/v1/search",
headers={"x-api-key": API_KEY},
json={"platform": "google", "query": state["query"]},
timeout=10,
)
res.raise_for_status()
data = res.json()
top_results = data.get("organic", [])[:3]
fresh_snippets = " ".join(r.get("snippet", "") for r in top_results)
source_url = top_results[0].get("link", "") if top_results else ""
return {
**state,
"verified": True,
"fresh_value": fresh_snippets[:500],
"source_url": source_url,
"updated_at": datetime.utcnow().isoformat(),
}
def update_memory(state: MemoryState) -> MemoryState:
memory = load_memory()
memory[state["claim_key"]] = {
"value": state["fresh_value"],
"source": state["source_url"],
"updated_at": state["updated_at"],
}
save_memory(memory)
return state
def should_update(state: MemoryState) -> str:
if state["memorized_value"].lower() not in state["fresh_value"].lower():
return "update"
return "skip"
# Build the graph
graph = StateGraph(MemoryState)
graph.add_node("verify", verify_claim)
graph.add_node("update", update_memory)
graph.add_node("done", lambda s: s)
graph.set_entry_point("verify")
graph.add_conditional_edges("verify", should_update, {"update": "update", "skip": "done"})
graph.add_edge("update", "done")
graph.add_edge("done", END)
app = graph.compile()
# Example: agent verifies a memorized price
result = app.invoke({
"query": "macbook pro m4 max price 2026",
"claim_key": "macbook_pro_m4_max_price",
"memorized_value": "$3499",
"verified": False,
"fresh_value": "",
"source_url": "",
"updated_at": "",
})
print(f"Verified: {result['verified']}")
print(f"Fresh data: {result['fresh_value'][:200]}")
print(f"Source: {result['source_url']}")Implementacion en JavaScript
const API_KEY = "your_scavio_api_key";
async function verifyClaim(query) {
const res = await fetch("https://api.scavio.dev/api/v1/search", {
method: "POST",
headers: { "x-api-key": API_KEY, "content-type": "application/json" },
body: JSON.stringify({ platform: "google", query }),
});
if (!res.ok) throw new Error(`scavio ${res.status}`);
const data = await res.json();
const topResults = (data.organic ?? []).slice(0, 3);
return {
freshValue: topResults.map((r) => r.snippet ?? "").join(" ").slice(0, 500),
sourceUrl: topResults[0]?.link ?? "",
updatedAt: new Date().toISOString(),
};
}
async function refreshMemory(claimKey, memorizedValue, verificationQuery) {
const fs = await import("fs/promises");
let memory = {};
try { memory = JSON.parse(await fs.readFile("agent_memory.json", "utf8")); } catch {}
const verification = await verifyClaim(verificationQuery);
const isStale = !verification.freshValue.toLowerCase().includes(
memorizedValue.toLowerCase().replace("$", "")
);
if (isStale) {
memory[claimKey] = {
value: verification.freshValue,
source: verification.sourceUrl,
updatedAt: verification.updatedAt,
};
await fs.writeFile("agent_memory.json", JSON.stringify(memory, null, 2));
console.log(`Memory updated for ${claimKey}`);
} else {
console.log(`Memory confirmed fresh for ${claimKey}`);
}
return {
claimKey,
wasStale: isStale,
freshValue: verification.freshValue,
source: verification.sourceUrl,
};
}
// Example: verify a memorized price
const result = await refreshMemory(
"macbook_pro_m4_max_price",
"$3499",
"macbook pro m4 max price 2026"
);
console.log(`Was stale: ${result.wasStale}`);
console.log(`Fresh: ${result.freshValue.slice(0, 200)}`);Plataformas utilizadas
Búsqueda web con grafo de conocimiento, PAA y resúmenes de IA
Amazon
Búsqueda de productos con precios, calificaciones y reseñas
Walmart
Búsqueda de productos con precios y datos de cumplimiento