|
| 1 | +"""Scenario: Memory reconciliation — duplicate merging and contradiction resolution. |
| 2 | +
|
| 3 | +Demonstrates how `reconcile_memories` collapses paraphrased facts and resolves |
| 4 | +semantic contradictions in a single LLM pass: |
| 5 | +
|
| 6 | +1. Seed paraphrased facts about a user (will be merged). |
| 7 | +2. Seed contradicting facts about the same subject (one will win, one will lose). |
| 8 | +3. Run reconcile() and print the {kept, merged, contradicted} stats. |
| 9 | +4. Show the live state — paraphrased duplicates collapsed, contradiction loser hidden. |
| 10 | +5. Show the audit trail (include_superseded=True) — soft-deleted records carry |
| 11 | + supersede_reason, superseded_at, and superseded_by pointing at the survivor. |
| 12 | +
|
| 13 | +Requirements: |
| 14 | + - Azure Cosmos DB account with vector-search enabled. |
| 15 | + - Azure AI Foundry endpoint with chat + embeddings deployments. |
| 16 | + - Environment variables (.env supported via python-dotenv): |
| 17 | + COSMOS_DB_ENDPOINT |
| 18 | + COSMOS_DB_KEY (optional, falls back to DefaultAzureCredential) |
| 19 | + AI_FOUNDRY_ENDPOINT |
| 20 | + AI_FOUNDRY_EMBEDDING_DEPLOYMENT_NAME |
| 21 | + AI_FOUNDRY_CHAT_DEPLOYMENT_NAME |
| 22 | +""" |
| 23 | + |
| 24 | +from __future__ import annotations |
| 25 | + |
| 26 | +import os |
| 27 | +import sys |
| 28 | +import uuid |
| 29 | + |
| 30 | +from dotenv import load_dotenv |
| 31 | + |
| 32 | +from agent_memory_toolkit import CosmosMemoryClient |
| 33 | + |
| 34 | +load_dotenv() |
| 35 | + |
| 36 | +# --------------------------------------------------------------------------- |
| 37 | +# Helpers |
| 38 | +# --------------------------------------------------------------------------- |
| 39 | + |
| 40 | +DIVIDER = "-" * 60 |
| 41 | + |
| 42 | + |
| 43 | +def banner(title: str) -> None: |
| 44 | + """Print a section banner.""" |
| 45 | + print(f"\n{DIVIDER}") |
| 46 | + print(f" {title}") |
| 47 | + print(DIVIDER) |
| 48 | + |
| 49 | + |
| 50 | +def print_facts(facts: list[dict]) -> None: |
| 51 | + """Pretty-print fact records (id + content).""" |
| 52 | + if not facts: |
| 53 | + print(" (none)") |
| 54 | + return |
| 55 | + for f in facts: |
| 56 | + print(f" id={f['id']} content: {f.get('content', '')}") |
| 57 | + |
| 58 | + |
| 59 | +# --------------------------------------------------------------------------- |
| 60 | +# Main |
| 61 | +# --------------------------------------------------------------------------- |
| 62 | + |
| 63 | +PARAPHRASED_FACTS = [ |
| 64 | + "User prefers aisle seats on flights.", |
| 65 | + "User likes aisle seats when flying.", |
| 66 | + "User always picks aisle when booking flights.", |
| 67 | +] |
| 68 | + |
| 69 | +CONTRADICTING_FACTS = [ |
| 70 | + "User is strictly vegetarian and avoids all meat.", |
| 71 | + "User loves a good ribeye steak.", |
| 72 | +] |
| 73 | + |
| 74 | + |
| 75 | +def main() -> None: |
| 76 | + required = ["COSMOS_DB_ENDPOINT", "AI_FOUNDRY_ENDPOINT"] |
| 77 | + missing = [v for v in required if not os.environ.get(v)] |
| 78 | + if missing: |
| 79 | + print(f"ERROR: missing env vars: {', '.join(missing)}") |
| 80 | + sys.exit(1) |
| 81 | + |
| 82 | + mem = CosmosMemoryClient( |
| 83 | + cosmos_endpoint=os.environ["COSMOS_DB_ENDPOINT"], |
| 84 | + cosmos_key=os.environ.get("COSMOS_DB_KEY") or None, |
| 85 | + cosmos_database=os.environ.get("COSMOS_DB_DATABASE", "ai_memory"), |
| 86 | + cosmos_container=os.environ.get("COSMOS_DB_CONTAINER", "memories"), |
| 87 | + ai_foundry_endpoint=os.environ["AI_FOUNDRY_ENDPOINT"], |
| 88 | + ai_foundry_api_key=os.environ.get("AI_FOUNDRY_API_KEY") or None, |
| 89 | + embedding_deployment_name=os.environ.get("AI_FOUNDRY_EMBEDDING_DEPLOYMENT_NAME", "text-embedding-3-large"), |
| 90 | + chat_deployment_name=os.environ.get("AI_FOUNDRY_CHAT_DEPLOYMENT_NAME", "gpt-4o-mini"), |
| 91 | + use_default_credential=True, |
| 92 | + ) |
| 93 | + print("Connected to Cosmos DB.") |
| 94 | + |
| 95 | + unique_user_id = f"reconcile-demo-{uuid.uuid4().hex[:8]}" |
| 96 | + unique_thread_id = f"reconcile-demo-thread-{uuid.uuid4().hex[:8]}" |
| 97 | + print(f"User ID: {unique_user_id}") |
| 98 | + print(f"Thread ID: {unique_thread_id}") |
| 99 | + |
| 100 | + try: |
| 101 | + banner("1. Seeding paraphrased facts (duplicates)") |
| 102 | + for content in PARAPHRASED_FACTS: |
| 103 | + mem.add_cosmos( |
| 104 | + user_id=unique_user_id, |
| 105 | + role="user", |
| 106 | + content=content, |
| 107 | + memory_type="fact", |
| 108 | + thread_id=unique_thread_id, |
| 109 | + salience=0.7, |
| 110 | + ) |
| 111 | + print(f" + {content}") |
| 112 | + |
| 113 | + banner("2. Seeding contradicting facts") |
| 114 | + for content in CONTRADICTING_FACTS: |
| 115 | + mem.add_cosmos( |
| 116 | + user_id=unique_user_id, |
| 117 | + role="user", |
| 118 | + content=content, |
| 119 | + memory_type="fact", |
| 120 | + thread_id=unique_thread_id, |
| 121 | + salience=0.7, |
| 122 | + ) |
| 123 | + print(f" + {content}") |
| 124 | + |
| 125 | + banner("3. Active facts before reconcile") |
| 126 | + before = mem.get_memories(user_id=unique_user_id, memory_type="fact") |
| 127 | + print_facts(before) |
| 128 | + |
| 129 | + banner("4. Running reconcile_memories") |
| 130 | + stats = mem.reconcile(user_id=unique_user_id) |
| 131 | + print(f" stats: {dict(stats)}") |
| 132 | + |
| 133 | + banner("5. Active facts after reconcile (duplicates merged, contradictions resolved)") |
| 134 | + after = mem.get_memories(user_id=unique_user_id, memory_type="fact") |
| 135 | + print_facts(after) |
| 136 | + |
| 137 | + banner("6. Audit trail (soft-deleted records)") |
| 138 | + all_facts = mem.get_memories( |
| 139 | + user_id=unique_user_id, |
| 140 | + memory_type="fact", |
| 141 | + include_superseded=True, |
| 142 | + ) |
| 143 | + soft_deleted = [f for f in all_facts if f.get("supersede_reason")] |
| 144 | + if not soft_deleted: |
| 145 | + print(" (no soft-deleted records)") |
| 146 | + for f in soft_deleted: |
| 147 | + print( |
| 148 | + f" id={f['id']} reason={f.get('supersede_reason')} " |
| 149 | + f"superseded_at={f.get('superseded_at')} " |
| 150 | + f"superseded_by={f.get('superseded_by')}" |
| 151 | + ) |
| 152 | + print(f" content: {f.get('content', '')}") |
| 153 | + |
| 154 | + finally: |
| 155 | + banner("7. Cleanup") |
| 156 | + try: |
| 157 | + all_records = mem.get_memories( |
| 158 | + user_id=unique_user_id, |
| 159 | + include_superseded=True, |
| 160 | + ) |
| 161 | + deleted = 0 |
| 162 | + for rec in all_records: |
| 163 | + try: |
| 164 | + mem.delete_cosmos( |
| 165 | + memory_id=rec["id"], |
| 166 | + thread_id=rec.get("thread_id", unique_thread_id), |
| 167 | + user_id=unique_user_id, |
| 168 | + ) |
| 169 | + deleted += 1 |
| 170 | + except Exception as exc: # pragma: no cover - best effort cleanup |
| 171 | + print(f" WARN: failed to delete {rec.get('id')}: {exc}") |
| 172 | + print(f" Deleted {deleted} record(s) for user {unique_user_id}") |
| 173 | + except Exception as exc: # pragma: no cover - best effort cleanup |
| 174 | + print(f" WARN: cleanup failed: {exc}") |
| 175 | + |
| 176 | + |
| 177 | +if __name__ == "__main__": |
| 178 | + main() |
0 commit comments