Workflow

LangGraph Search Memory Pipeline

LangGraph agent pipeline that refreshes session memory with live search data, preventing stale facts from persisting across turns.

Overview

This workflow integrates Scavio search into a LangGraph agent's memory update cycle. Before the agent uses any memorized fact with a time dimension (prices, availability, rankings), it verifies the fact with a live search and updates memory if the data has changed. This prevents stale memory from causing confidently wrong answers across multi-session conversations.

Trigger

Agent turn (before citing time-sensitive memorized facts)

Schedule

Triggered per agent turn when citing time-sensitive facts

Workflow Steps

1

Detect time-sensitive claims

Identify memorized facts that have a time dimension: prices, stock levels, dates, rankings.

2

Generate verification query

Construct a search query designed to verify or update the specific claim.

3

Execute live search

Call Scavio with the verification query and retrieve fresh data.

4

Compare against memory

Check if the fresh data contradicts or confirms the memorized claim.

5

Update memory if stale

Replace the stale memorized fact with the fresh data and timestamp.

6

Respond with fresh data

Use the verified or updated fact in the agent's response with a freshness citation.

Python Implementation

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']}")

JavaScript Implementation

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)}`);

Platforms Used

Google

Web search with knowledge graph, PAA, and AI overviews

Amazon

Product search with prices, ratings, and reviews

Walmart

Product search with pricing and fulfillment data

Frequently Asked Questions

This workflow integrates Scavio search into a LangGraph agent's memory update cycle. Before the agent uses any memorized fact with a time dimension (prices, availability, rankings), it verifies the fact with a live search and updates memory if the data has changed. This prevents stale memory from causing confidently wrong answers across multi-session conversations.

This workflow uses a agent turn (before citing time-sensitive memorized facts). Triggered per agent turn when citing time-sensitive facts.

This workflow uses the following Scavio platforms: google, amazon, walmart. Each platform is called via the same unified API endpoint.

Yes. Scavio's free tier includes 250 credits per month with no credit card required. That is enough to test and validate this workflow before scaling it.

LangGraph Search Memory Pipeline

LangGraph agent pipeline that refreshes session memory with live search data, preventing stale facts from persisting across turns.