|
| 1 | +"""Synapse Layer — Python Basic Example |
| 2 | +Store a memory and recall it with semantic search. |
| 3 | +""" |
| 4 | +import os |
| 5 | +import requests |
| 6 | +from dotenv import load_dotenv |
| 7 | + |
| 8 | +load_dotenv() |
| 9 | + |
| 10 | +TOKEN = os.getenv("SYNAPSE_TOKEN", "") |
| 11 | +BASE_URL = os.getenv("SYNAPSE_BASE_URL", "https://forge.synapselayer.org") |
| 12 | + |
| 13 | +if not TOKEN or TOKEN == "sk_connect_xxx": |
| 14 | + print("ERROR: Set SYNAPSE_TOKEN in .env") |
| 15 | + print("Get yours at: https://forge.synapselayer.org/dashboard/connect") |
| 16 | + exit(1) |
| 17 | + |
| 18 | +HEADERS = {"Content-Type": "application/json", "Authorization": f"Bearer {TOKEN}"} |
| 19 | +AGENT = "python-example" |
| 20 | + |
| 21 | + |
| 22 | +def store_memory(): |
| 23 | + """Store a memory via the Forge API.""" |
| 24 | + print("[store] Saving memory...") |
| 25 | + resp = requests.post(f"{BASE_URL}/api/forge", headers=HEADERS, json={ |
| 26 | + "action": "store", |
| 27 | + "agent": AGENT, |
| 28 | + "content": "The user prefers dark mode and communicates in Portuguese.", |
| 29 | + "intent": "user_preference", |
| 30 | + }) |
| 31 | + resp.raise_for_status() |
| 32 | + print("[store] Done.\n") |
| 33 | + |
| 34 | + |
| 35 | +def recall_memory(): |
| 36 | + """Recall memories with a semantic query (cross-agent).""" |
| 37 | + print("[recall] Searching for user preferences...") |
| 38 | + resp = requests.post(f"{BASE_URL}/api/forge", headers=HEADERS, json={ |
| 39 | + "action": "recall", |
| 40 | + "query": "What are the user preferences?", |
| 41 | + "topK": 5, |
| 42 | + }) |
| 43 | + resp.raise_for_status() |
| 44 | + data = resp.json() |
| 45 | + memories = data.get("memories", []) |
| 46 | + if memories: |
| 47 | + for i, mem in enumerate(memories): |
| 48 | + print(f" [{i}] content: {mem.get('content', 'N/A')}") |
| 49 | + print(f" tq_score: {mem.get('trustQuotient', 'N/A')}") |
| 50 | + print(f"\n[recall] {len(memories)} memories found.") |
| 51 | + else: |
| 52 | + print("[recall] No memories found yet.") |
| 53 | + |
| 54 | + |
| 55 | +if __name__ == "__main__": |
| 56 | + try: |
| 57 | + store_memory() |
| 58 | + recall_memory() |
| 59 | + except requests.exceptions.HTTPError as e: |
| 60 | + print(f"API Error: {e.response.status_code} — {e.response.text[:200]}") |
| 61 | + except Exception as e: |
| 62 | + print(f"Error: {e}") |
0 commit comments