{"id":"47af3003-c46b-4d27-9b3b-8f94b11c6aa1","slug":"piyapi","kind":"mcp","name":"Piyapi","summary":"Give any AI application enterprise-grade, persistent memory through a simple API.","owner":"Negentro-ai","repoUrl":"https://github.com/Negentro-ai/Piyapi","license":"Apache-2.0","licenseTier":"permissive","trust":"community","stars":0,"match":null,"fewStars":true,"format":"mcp","createdAt":"2026-09-02T21:05:52.000Z","addedAt":"2026-10-21T05:04:57.769Z","logoUrl":"https://avatars.githubusercontent.com/u/323351984?v=4","linkOnly":false,"collection":null,"skillPath":null,"categories":["memory-knowledge","search","cloud-infra"],"tags":["agent-memory","ai-agents","ai-architecture","aimemory","cognitive-ai","knowledge-graph","llm-agents","python"],"runtime":"binary","local":true,"cloudCapable":false,"cloudCapability":"unknown","cloudReadyOnPlatform":false,"needsApiKey":false,"reviewed":false,"syncedAt":"2026-10-23T02:28:12.094Z","sample":false,"url":"https://conduits.dev/tools/piyapi","language":"HTML","transports":["stdio"],"install":{},"requirements":{"env":[],"upstreamMayCharge":false},"tools":null,"readme":"<p align=\"center\">\n  <img src=\"piyapi.png\" width=\"400\" alt=\"PiyAPI by Negentro\"/>\n</p> \n\n<p align=\"center\">\n  <b>The cognitive memory API for AI agents. Persistent memory, knowledge graphs, bitemporal time-travel, and hybrid search — one API.</b>\n</p>\n\n<p align=\"center\">\n  <a href=\"https://piyapi.cloud/docs\">Docs</a> ·\n  <a href=\"https://piyapi.cloud/docs/quickstart\">Quickstart</a> ·\n  <a href=\"https://piyapi.cloud/\">Dashboard</a>\n</p>\n\n<div align=\"center\">\n<details><summary><b>Read this in other languages</b></summary>\n\n🇺🇸 <a href=\"README.md\">English</a> | 🇨🇳 <a href=\"README.zh-CN.md\">简体中文</a>\n\n</details>\n</div>\n\n<p align=\"center\">\n  <a href=\"https://www.npmjs.com/package/@piyapi/sdk\"><img src=\"https://img.shields.io/npm/v/@piyapi/sdk?style=for-the-badge&color=2563eb&logo=npm\" alt=\"npm\"/></a>\n  <a href=\"https://pypi.org/project/piyapi-memory/\"><img src=\"https://img.shields.io/pypi/v/piyapi-memory?style=for-the-badge&color=3776ab&logo=python&logoColor=white\" alt=\"PyPI\"/></a>\n  <a href=\"LICENSE\"><img src=\"https://img.shields.io/badge/License-Apache%202.0-8b5cf6?style=for-the-badge\" alt=\"License\"/></a>\n  <a href=\"https://api.piyapi.cloud/health\"><img src=\"https://img.shields.io/badge/Status-Operational-10b981?style=for-the-badge&logo=statuspage&logoColor=white\" alt=\"System Status\"/></a>\n  <a href=\"#categorized-mcp-tools\"><img src=\"https://img.shields.io/badge/MCP_Tools-40%2B-f97316?style=for-the-badge&logo=anthropic&logoColor=white\" alt=\"MCP Tools\"/></a>\n  <a href=\"#-testing--verification\"><img src=\"https://img.shields.io/badge/Tests-9258%20Passed-10b981?style=for-the-badge&logo=jest&logoColor=white\" alt=\"Tests\"/></a>\n</p>\n\n---\n\n## 📈 [Benchmarks (August 2026)](benchmark.md)\n\n**#1 on LongMemEval, LoCoMo, and ConvoMem** · 95% Recall@15 · 99.4% context reduction · ~50ms user profiles\n\n| Benchmark | Score | Tokens | Latency |\n|---|---|---|---|\n| LoCoMo | **96.5** | 8.0K | 0.81s |\n| LongMemEval | **95.4** | 7.2K | 1.02s |\n| ConvoMem | **94.8** | 6.5K | 0.95s |\n\n<p align=\"center\">\n  <a href=\"benchmark.md\"><img src=\"https://img.shields.io/badge/Full%20Benchmark%20Report-View%20Details-6366f1?style=for-the-badge&logo=databricks&logoColor=white\" alt=\"Full Benchmark Report\"/></a>\n</p>\n\n---\n\n## What is PiyAPI?\n\n**PiyAPI** is the first **Neuro-Symbolic, Self-Correcting, and Sovereign Cognitive Memory Operating System** for AI agents, built by [Negentro](https://www.negentro.tech/). We replace fragmented vector stacks with an integrated cognitive engine featuring **Active Inference**, a **Bayesian Truth Engine**, **Bitemporal Knowledge Graphs (`PiyGraph`)**, **Dual-Process Cognition**, **Offline Sleep Consolidation**, **6-Strategy PRM Scoring**, and **20+ Jurisdiction PHI Compliance**.\n\nYour AI forgets everything between conversations. PiyAPI fixes that — with a 426,524+ LOC cognitive engine that goes far beyond simple RAG.\n\n| | |\n|---|---|\n| 🧠 **Memory Engine** | 8-operator unified surface — store, retrieve, update, delete, merge, summarize, pin, verify. Handles temporal changes, contradictions, and automatic forgetting. |\n| 🔍 **Hybrid Search** | Dense vector similarity + BM25 keyword search in a single query. Tunable alpha blending. |\n| 🤖 **Cognitive RAG** | Context-aware Q&A with auto-citations. Not just retrieval — reasoning over your memory graph. |\n| 🕰️ **Bitemporal Time Travel** | PiyGraph knowledge graph with `valid_at` vs `system_at` reasoning. Query your data as it was at any point in time. |\n| 🔌 **12 Data Connectors** | Google Drive · Gmail · Notion · OneDrive · GitHub · Slack · Salesforce · HubSpot · Jira · Confluence · Linear · Web Crawler — auto-sync with real-time CDC webhooks. |\n| 📄 **Multi-modal Processing** | PDFs, images (OCR), videos (transcription), code (AST-aware chunking). Upload and it works. |\n| 🔐 **Privacy & Compliance** | PHI/PII redaction, tokenization, SAML 2.0 & OIDC SSO, legal hold, data residency, geo-fencing. |\n| 🌿 **Speculative Branching** | Create memory branches, diff them, and merge — like Git for your AI's knowledge. |\n| 🧩 **40+ MCP Tools** | Full Model Context Protocol integration for Cursor, Windsurf, Claude Desktop, and VS Code. |\n| 🔑 **BYOK** | Bring Your Own Key — multi-provider routing with automatic failover across OpenAI, Anthropic, Google, and more. |\n\n---\n\n## Use PiyAPI\n\n### 🧑‍💻 I use AI tools\n\nGive your AI assistant persistent memory across every conversation. PiyAPI remembers your preferences, projects, and past discussions — and gets smarter over time.\n\n**[→ Jump to MCP setup](#give-your-ai-memory--mcp-setup)**\n\n### 🔧 I'm building AI products\n\nAdd memory, RAG, user profiles, knowledge graphs, and connectors to your agents and apps with **a single API**.\n\nNo vector DB config. No embedding pipelines. No chunking strategies.\n\n**[→ Jump to developer quickstart](#build-with-piyapi)**\n\n### 🖥️ I want to run it myself\n\nEnterprise-grade cognitive memory, on your machine. **One binary. Zero config.** Bring any model — or run fully offline.\n\n```bash\ncurl -fsSL https://piyapi.cloud/install | bash\n```\n\n**[→ Jump to self-hosting](#piyapi-local--run-it-yourself)**\n\n---\n\n## Give Your AI Memory — MCP Setup\n\nPiyAPI ships with a full Model Context Protocol server exposing 40+ tools, 3 resources, and 3 prompts.\n\nAdd to your `claude_desktop_config.json` or `mcp_config.json`:\n\n```json\n{\n  \"mcpServers\": {\n    \"piyapi\": {\n      \"command\": \"npx\",\n      \"args\": [\"-y\", \"@piyapi/mcp-server\"],\n      \"env\": {\n        \"PIYAPI_API_KEY\": \"your_piyapi_api_key_here\",\n        \"PIYAPI_BASE_URL\": \"https://api.piyapi.cloud\"\n      }\n    }\n  }\n}\n```\n\nOr use the remote MCP server directly:\n\n```json\n{\n  \"mcpServers\": {\n    \"piyapi\": {\n      \"url\": \"https://mcp.piyapi.cloud/mcp\"\n    }\n  }\n}\n```\n\n**Supported clients:** Claude Desktop · Cursor · Windsurf · VS Code · Claude Code · OpenCode\n\n### What your AI gets\n\n| Tool | What it does |\n|---|---|\n| `memory` | Store, update, merge, or forget information. 8 operators in one unified surface. |\n| `recall` | Hybrid search across memories — vector similarity + keyword matching with tunable alpha. |\n| `context` | Injects your full profile, preferences, and recent activity into the conversation. |\n| `ask` | Cognitive RAG — answers questions with auto-generated citations from your memory graph. |\n| `graph` | Traverse the PiyGraph knowledge graph with bitemporal time-travel queries. |\n\n---\n\n## Build with PiyAPI\n\nIf you're building AI agents or apps, PiyAPI gives you the entire context stack through one API — memory, cognitive RAG, knowledge graphs, user profiles, connectors, and file processing.\n\n### Install\n\n```bash\nnpm install @piyapi/sdk    # or: pip install piyapi-memory\n```\n\n### Quickstart\n\n<details>\n<summary><b>TypeScript / Node.js</b></summary>\n\n```typescript\nimport { PiyAPIClient } from '@piyapi/sdk';\n\nconst client = new PiyAPIClient({\n  apiKey: process.env.PIYAPI_API_KEY!,\n  baseUrl: 'https://api.piyapi.cloud',\n});\n\n// 1. Store a memory\nawait client.memories.create({\n  content: 'User prefers dark mode UI and works primarily with React and TypeScript.',\n  metadata: { source: 'onboarding_chat', user_id: 'usr_9918' },\n});\n\n// 2. Hybrid search — vector + keyword in one call\nconst results = await client.search({\n  query: 'What frontend framework does the user prefer?',\n  limit: 5,\n  alpha: 0.7, // 0 = pure keyword, 1 = pure vector\n});\n\n// 3. Cognitive RAG with citations\nconst answer = await client.ask({\n  query: 'Summarize the user\\'s code preferences and UI choices.',\n  temperature: 0.2,\n});\n// answer.response → Natural language answer\n// answer.citations → Source memories used\n\n// 4. Bitemporal time-travel query (unique feature)\nconst snapshot = await client.graph.query({\n  valid_at: '2026-01-15T00:00:00Z',   // When the fact was true\n  system_at: '2026-03-01T00:00:00Z',  // When the system recorded it\n  query: \"What was the user's role?\",\n});\n\n// 5. Memory branching (unique feature)\nconst branch = await client.branches.create({ name: 'experiment-a', base: 'main' });\nconst diff = await client.branches.diff('main', 'experiment-a');\nawait client.branches.merge('experiment-a', 'main');\n```\n</details>\n\n<details>\n<summary><b>Python</b></summary>\n\n```python\nfrom piyapi_memory import PiyAPIClient\n\nclient = PiyAPIClient(api_key=\"sk_live_...\")\n\n# 1. Store a memory\nclient.memories.create(\n    content=\"User prefers dark mode UI and works primarily with React and TypeScript.\",\n    metadata={\"source\": \"onboarding_chat\", \"user_id\": \"usr_9918\"}\n)\n\n# 2. Hybrid search\nresults = client.search(query=\"frontend framework preference\", limit=5, alpha=0.7)\n\n# 3. Cognitive RAG\nanswer = client.ask(query=\"Summarize user preferences\", temperature=0.2)\nprint(answer.response)\nprint(answer.citations)\n\n# 4. Bitemporal time-travel query (unique feature)\nhistorical_facts = client.graph.time_travel(\n    query=\"What was the user's role?\",\n    as_of_date=\"2026-01-15T00:00:00Z\"\n)\n\n# 5. Memory branching (unique feature)\nbranch = client.branches.create(name=\"experiment-a\", base=\"main\")\ndiff = client.branches.diff(\"main\", \"experiment-a\")\nclient.branches.merge(\"experiment-a\", \"main\")\n```\n</details>\n\n<details>\n<summary><b>LangChain Adapter</b></summary>\n\n```python\nfrom piyapi_langchain import PiyAPIMemoryRetriever\n\nretriever = PiyAPIMemoryRetriever(api_key=\"sk_live_your_key_here\")\ndocs = retriever.get_relevant_documents(\"user database preferences\")\n```\n</details>\n\n### API at a glance\n\n| Method | Purpose |\n|---|---|\n| `POST /api/v1/memories` | Store content — text, conversations, documents |\n| `POST /api/v1/memories/batch` | Bulk store multiple memories |\n| `POST /api/v1/memory/op` | Unified 8-operator surface |\n| `POST /api/v1/search` | Hybrid vector + keyword search |\n| `POST /api/v1/ask` | Cognitive RAG with citations |\n| `GET /api/v1/context` | Context retrieval & summarization |\n| `POST /api/v1/kg/*` | PiyGraph knowledge graph queries |\n| `POST /api/v1/branches` | Speculative memory branching |\n| `POST /api/v1/connectors` | Data connector management |\n| `POST /api/v1/documents` | Document processing & upload |\n| `POST /api/v1/feedback` | Adaptive learning feedback |\n\nFull API reference → [piyapi.cloud/docs](https://piyapi.cloud/docs) · OpenAPI Spec → [api.piyapi.cloud/docs/raw/openapi.json](https://api.piyapi.cloud/docs/raw/openapi.json)\n\n---\n\n## Architecture\n\n### System Architecture\n\n```mermaid\nflowchart TD\n    CLIENT[\"CLIENT LAYER\\nTypeScript SDK  |  Python SDK  |  MCP Server  |  cURL\"]\n    GATEWAY[\"PIYAPI REST GATEWAY (api.piyapi.cloud)\\nNamespace Scoping  |  Rate Limiter  |  Auth & BYOK Guard\"]\n    MEMORY[\"MEMORY ENGINE\\n• 8-Operators\\n• Bitemporal\\n• Branching\"]\n    COGNITIVE[\"COGNITIVE ENGINE\\n• Hybrid RAG\\n• PiyGraph KG\\n• Active Infer\"]\n    INTEGRATIONS[\"INTEGRATIONS\\n• BYOK Manager\\n• 12 Connectors\\n• 30 MCP Tools\"]\n    DATA[\"DATA & VECTOR SUBSTRATE\\nPostgreSQL + pgvector  |  Bitemporal KG  |  Redis Cache\"]\n\n    CLIENT --> GATEWAY\n    GATEWAY --> MEMORY\n    GATEWAY --> COGNITIVE\n    GATEWAY --> INTEGRATIONS\n    MEMORY --> DATA\n    COGNITIVE --> DATA\n    INTEGRATIONS --> DATA\n```\n\n### Cognitive Request Flow\n\n```mermaid\nflowchart LR\n    AGENT([\"🤖 AI Agent\"])\n    AUTH{\"Auth &\\nNamespace\\nGuard\"}\n    INFER[\"Active\\nInference\\nEngine\"]\n    HYBRID[\"Hybrid Search\\nVector + BM25\\n(alpha blend)\"]\n    PRM[\"6-Strategy\\nPRM Scorer\"]\n    GRAPH[\"PiyGraph\\nBitemporal KG\"]\n    SLEEP[\"Sleep\\nConsolidation\"]\n    RESP([\"📦 Context\\nResponse +\\nCitations\"])\n\n    AGENT -->|API call| AUTH\n    AUTH -->|authorized| INFER\n    INFER --> HYBRID\n    INFER --> GRAPH\n    HYBRID --> PRM\n    GRAPH --> PRM\n    PRM -->|scored memories| SLEEP\n    SLEEP -->|consolidated context| RESP\n    RESP -->|answer + citations| AGENT\n```\n\n\n---\n\n## Works with\n\n**OpenAI** · **Anthropic** · **Google Gemini** · **LangChain** · **LlamaIndex** · **OpenAI Agents SDK** · **Mastra** · **Vercel AI SDK** · **CrewAI** · **Cursor** · **Claude Code** · **Claude Desktop** · **Windsurf** · **VS Code** · **Ollama** · **Groq**\n\n---\n\n## PiyAPI local — run it yourself\n\nEnterprise-grade cognitive memory, on your machine. One binary. Zero config.\n\n```bash\ncurl -fsSL https://piyapi.cloud/install | bash\npiyapi-server\n```\n\nFirst boot sets up the embedded PiyGraph engine, local embeddings, vector store, and your credentials, then prints an API key. The full API — memories, search, RAG, knowledge graph, connectors — runs against `http://localhost:6767`.\n\n```typescript\nconst client = new PiyAPIClient({\n  apiKey: 'sk_live_...',\n  baseUrl: 'http://localhost:6767', // that's the only change\n});\n```\n\n- **Bring any model** — OpenAI, Anthropic, Google Gemini, Groq, or any OpenAI-compatible endpoint.\n- **BYOK multi-provider routing** — automatic failover across providers.\n- **Fully offline** — point it at Ollama and nothing leaves your machine.\n- **Your data, one directory** — everything lives in `./.piyapi`, easy to back up or move.\n- **Same API as the cloud** — prototype locally, ship on the hosted platform by changing `baseURL`.\n\n---\n\n## Enterprise Features\n\n| Feature | Description |\n|---|---|\n| **SAML 2.0 & OIDC SSO** | Enterprise single sign-on with any identity provider |\n| **Data Residency & Geo-Fencing** | Control where your data lives |\n| **Legal Hold & Litigation Blocks** | Dual-custody breakglass for compliance |\n| **PHI/PII Redaction** | Automatic tokenization and privacy filtering |\n| **Namespace Isolation** | Strict tenant separation for multi-tenant deployments |\n| **Prometheus Metrics** | Full observability with `/metrics` endpoint |\n| **Admin Console** | User management, impersonation, plan overrides, cache controls |\n| **On-Prem Licensing** | Run PiyAPI entirely within your infrastructure |\n\n**Enterprise & BAA inquiries:** `care.piyapi@outlook.com`\n\n---\n\n## SDKs & Integrations\n\n| Platform | Package |\n|---|---|\n| **TypeScript / Node.js** | `@piyapi/sdk` |\n| **Python** | `piyapi-memory` |\n| **LangChain** | `packages/langchain-adapter` |\n| **MCP Server** | 40+ tools, 3 resources, 3 prompts |\n\n---\n\n## Categorized MCP Tools\n\n| Category | Tools | Description |\n| :--- | :--- | :--- |\n| **Memory Lifecycle** | `store_memory`, `update_memory`, `get_memory`, `delete_memory`, `list_memories`, `batch_create`, `pin_memory` | Complete CRUD and bulk ingestion with auto-embedding and graph extraction. |\n| **Search & Retrieval** | `search_memories`, `fuzzy_search`, `get_context`, `create_context_session`, `ask_memory` | Hybrid search, trigram typo tolerance, and token-aware context packing for LLM prompts. |\n| **Knowledge Graph** | `get_graph`, `graph_traverse`, `create_relationship`, `delete_relationship`, `get_clusters`, `kg_search`, `kg_entities`, `kg_ingest`, `kg_stats` | Interactive relationship graphs, multi-hop traversals, entity lookup, and cluster extraction. |\n| **Temporal & Time Travel** | `kg_time_travel`, `version_history`, `rollback_memory` | Reconstruct memory state as of any historical timestamp; inspect and rollback diffs. |\n| **Cognitive & Quality** | `session_mine`, `session_propose`, `deduplicate`, `find_contradictions`, `memory_audit`, `feedback_positive`, `feedback_negative` | Extract candidate memories from transcripts, resolve contradictions, and train adaptive decay. |\n| **Data Connectors** | `list_connectors`, `trigger_connector_sync`, `clip_web_page`, `get_connector_logs` | Trigger manual CDC syncs for Google Drive/Notion/GitHub and clip web articles into memory. |\n| **Security & Privacy** | `check_phi`, `export_all` | Verify text for Protected Health Information (PHI) and generate GDPR export bundles. |\n\n---\n\n## Verified Engine Metrics (Audit: August 2026)\n\n| Metric | Live Production Value |\n|---|---|\n| **Production Substrate** | **426,524+ LOC** across **1,239** TypeScript modules |\n| **Test Suites** | **9,258** test cases across **673** test files (100% Jest) |\n| **Property-Based Tests** | **1,329** `fc.property()` mathematical correctness assertions |\n| **Client-Facing API Endpoints** | **16** endpoints (516 total internal) |\n| **MCP Tools** | **40 core tools / 52 registrations** in `@piyapi/mcp-server` v2.0.0 |\n| **Database Migrations** | **298** SQL migration files with **90** RLS security policies |\n| **CDC Data Connectors** | **12** built-in providers |\n| **Cognitive Subsystems** | **51** specialized service modules |\n| **Hard Benchmark Pass Rate** | **93.8%** (75/80) |\n| **Adversarial Security Rate** | **82.6%** (71/86) |\n\n---\n\n## 🧪 Testing & Verification\n\n```bash\nnpm test           # Run all 9,258 test cases under Jest\nnpm run test:props # Run 1,329 property-based tests (fast-check)\nnpm run test:chaos # Run chaos & resilience test suites\n```\n\n---\n\n## How it works under the hood\n\n```\nYour app / AI tool\n        ↓\n     PiyAPI\n        │\n        ├── Memory Engine        8-operator unified surface, bitemporal storage,\n        │                        contradiction resolution, automatic forgetting\n        ├── Cognitive RAG        Context-aware Q&A with auto-citations\n        ├── PiyGraph KG          Bitemporal knowledge graph with time-travel queries\n        ├── Hybrid Search        Dense vector + BM25 keyword, tunable alpha blending\n        ├── Speculative Branches Git-like branching for memory experimentation\n        ├── BYOK Router          Multi-provider key routing with automatic failover\n        ├── Connectors           12 real-time CDC connectors with webhook sync\n        ├── Privacy Engine       PHI/PII redaction, tokenization, compliance\n        └── File Processing      PDFs, images, videos, code → searchable chunks\n```\n\n**Memory is not RAG.** RAG retrieves document chunks — stateless, same results for everyone. Memory extracts and tracks *facts about users* over time, resolving contradictions and forgetting expired information. PiyAPI runs both together by default.\n\n**Bitemporal reasoning.** Every memory has two time dimensions: when the fact was true in the real world (`valid_at`) and when the system recorded it (`system_at`). This enables time-travel queries and audit trails that traditional memory systems can't provide.\n\n**Active inference.** PiyAPI's cognitive engine uses the Friston Free Energy Principle framework for intelligent memory formation — not just storing what you tell it, but actively modeling and predicting what context will be needed.\n\n---\n\n## Legal & Compliance Disclaimer\n\n> ⚠️ PiyAPI provides technical controls (e.g., PHI/PII redaction, field-level encryption, audit logging) designed to assist in meeting compliance requirements. Full compliance with regulations such as HIPAA, GDPR, or SOC 2 requires appropriate infrastructure configuration, organizational governance, and a signed Business Associate Agreement (BAA) where applicable.\n\n**Security disclosures:** `negentroai@gmail.com` — do NOT open a public GitHub issue for security vulnerabilities.\n\n---\n\n## 🤝 Community & Support\n\n<p align=\"center\">\n  <a href=\"https://www.negentro.tech/\"><img src=\"negentro.jpeg\" width=\"80\" alt=\"Negentro\"/></a>\n</p>\n\n<p align=\"center\">\n  <a href=\"https://www.linkedin.com/company/negentroai/\"><img src=\"https://img.shields.io/badge/LinkedIn-negentroai-0077B5?style=flat&logo=linkedin&logoColor=white\" alt=\"LinkedIn\"/></a>\n  <a href=\"https://x.com/negentroai?s=11\"><img src=\"https://img.shields.io/badge/X-negentroai-000000?style=flat&logo=x&logoColor=white\" alt=\"X\"/></a>\n  <a href=\"https://www.instagram.com/negentro_ai\"><img src=\"https://img.shields.io/badge/Instagram-negentro__ai-E4405F?style=flat&logo=instagram&logoColor=white\" alt=\"Instagram\"/></a>\n  <a href=\"https://www.reddit.com/u/Negentro_AI\"><img src=\"https://img.shields.io/badge/Reddit-u%2FNegentro__AI-FF4500?style=flat&logo=reddit&logoColor=white\" alt=\"Reddit\"/></a>\n  <img src=\"https://img.shields.io/badge/Telegram-Coming%20Soon-26A5E4?style=flat&logo=telegram&logoColor=white\" alt=\"Telegram (channel link coming soon)\"/>\n</p>\n\n- 🐛 **Issues:** [GitHub Issues](https://github.com/Negentro-ai/Piyapi/issues)\n- 💬 **Discussions:** [GitHub Discussions](https://github.com/Negentro-ai/Piyapi/discussions)\n- 📖 **Documentation:** [piyapi.cloud/docs](https://piyapi.cloud/docs)\n- 🔒 **Security:** `negentroai@gmail.com`\n\n---\n\n---\n\n## 🛠️ Developer Setup Manual\n\n> **Every code snippet in this guide has been tested against the live API on Sept 3, 2026.**\n> Nothing is assumed. Everything works.\n\n### What is PiyAPI?\n\nA **cloud API** that gives your AI app persistent memory. Store conversations, search them semantically, and retrieve context — all through REST calls or MCP.\n\n**Base URL:** `https://api.piyapi.cloud/api/v1`\n\n---\n\n### Step 1 — Get Your API Key\n\n1. Go to [piyapi.cloud/register](https://piyapi.cloud/register)\n2. Create an account\n3. Dashboard → copy your API key (`sk_live_...`)\n\nSave it:\n\n```bash\nexport PIYAPI_API_KEY=\"sk_live_your_key_here\"\n```\n\n---\n\n### Step 2 — Verify It Works (30 seconds)\n\n```bash\n# Health check (no auth needed)\ncurl https://api.piyapi.cloud/health\n# → {\"status\":\"ok\",\"timestamp\":\"...\"}\n\n# Auth check\ncurl -H \"Authorization: Bearer $PIYAPI_API_KEY\" \\\n  https://api.piyapi.cloud/api/v1\n# → {\"name\":\"PiyAPI Memory API\",\"status\":\"operational\",...}\n```\n\nIf both return 200, you're good. Skip to whichever path fits your stack.\n\n---\n\n### Path A — REST API (Python)\n\nNo SDK needed. Pure `urllib` — works everywhere.\n\n#### Store a memory\n\n```python\nimport json, os, urllib.request\n\nAPI_KEY = os.environ[\"PIYAPI_API_KEY\"]\nBASE = \"https://api.piyapi.cloud/api/v1\"\nHEADERS = {\n    \"Authorization\": f\"Bearer {API_KEY}\",\n    \"Content-Type\": \"application/json\",\n}\n\ndef piy_post(endpoint, payload):\n    \"\"\"POST to PiyAPI. Returns (status_code, response_dict).\"\"\"\n    req = urllib.request.Request(\n        f\"{BASE}/{endpoint}\",\n        data=json.dumps(payload).encode(),\n        headers=HEADERS,\n        method=\"POST\",\n    )\n    with urllib.request.urlopen(req, timeout=30) as r:\n        return r.status, json.loads(r.read())\n\ndef piy_get(endpoint):\n    \"\"\"GET from PiyAPI.\"\"\"\n    req = urllib.request.Request(f\"{BASE}/{endpoint}\", headers=HEADERS)\n    with urllib.request.urlopen(req, timeout=30) as r:\n        return r.status, json.loads(r.read())\n\n# Store a memory\nstatus, result = piy_post(\"memories\", {\n    \"content\": \"User prefers dark mode and works with React and TypeScript.\",\n    \"namespace\": \"my-app\",   # isolates data per project/user\n    \"tags\": [\"preferences\"], # optional, for filtering\n    \"metadata\": {\"user_id\": \"u_123\"}, # optional, your custom fields\n})\nmemory_id = result[\"memory\"][\"id\"]\nprint(f\"Stored: {memory_id}\")\n# → Stored: 2a11b4c6-8049-4071-aaea-237dd5cd5c7f\n```\n\n**Response includes auto-generated fields:**\n- `importance_score` — how significant PiyAPI thinks this memory is\n- `type_tag` — auto-classified category (e.g. \"Discussion\", \"Fact\")\n- `emotional_tag` — detected sentiment\n- `entity_count` — number of entities extracted for the knowledge graph\n\n#### Search memories\n\nPiyAPI has **3 search modes**. All are free to call. Use these instead of `/ask`.\n\n**1. Hybrid Search (recommended — semantic + keyword)**\n\n```python\nstatus, result = piy_post(\"search/hybrid\", {\n    \"query\": \"What frontend framework does the user prefer?\",\n    \"namespace\": \"my-app\",\n    \"limit\": 10,\n})\nfor hit in result[\"results\"]:\n    mem = hit[\"memory\"]\n    score = hit.get(\"similarity\", 0)\n    print(f\"  [{score:.3f}] {mem['content']}\")\n\n# Response also includes:\n# result[\"count\"]   → total corpus size\n# result[\"weights\"] → how semantic vs keyword was balanced\n# result[\"facets\"]  → tag/metadata distribution\n# result[\"metrics\"] → latency breakdown\n```\n\n**2. Basic Search (semantic only)**\n\n```python\nstatus, result = piy_post(\"search\", {\n    \"query\": \"deployment platform\",\n    \"namespace\": \"my-app\",\n    \"limit\": 10,\n})\nfor hit in result[\"results\"]:\n    print(f\"  [{hit.get('similarity', 0):.3f}] {hit['memory']['content']}\")\n# Response keys: results, query, count, metrics\n```\n\n**3. Fuzzy Search (MCP only — typo-tolerant)**\n\nAvailable through the MCP server's `fuzzy_search` tool. Uses trigram similarity — great for handling user typos.\n\n#### Get Context (best for injecting into LLM prompts)\n\nThis is the **smartest retrieval endpoint**. It packs relevant memories into a token-budgeted context block, ready to inject into your LLM prompt.\n\n```python\nstatus, result = piy_post(\"context/retrieve\", {\n    \"query\": \"What does the user work with?\",\n    \"namespace\": \"my-app\",\n})\n# result[\"content\"]         → formatted context string, ready for prompt injection\n# result[\"tokenCount\"]      → how many tokens the context uses\n# result[\"user_profile\"]    → auto-built user profile from stored memories\n# result[\"header\"]          → metadata about the retrieval\n# result[\"scoring_reasons\"] → why each memory was selected\n\n# Inject into your LLM prompt:\ncontext = result[\"content\"]\nprompt = f\"\"\"You are a helpful assistant. Use this context about the user:\n\n{context}\n\nUser question: How should I set up my project?\"\"\"\n```\n\n> [!TIP]\n> **Use `context/retrieve` instead of `/ask`.** It gives you the retrieved memories formatted and token-counted, so you can feed them into your own LLM (OpenAI, Anthropic, Gemini, local models — anything). The `/ask` endpoint runs our built-in RAG pipeline which costs us compute. During our pre-funding phase, please use search + context endpoints and bring your own LLM for the generation step.\n\n#### List memories\n\n```python\nstatus, result = piy_get(\"memories?namespace=my-app&limit=20\")\nfor mem in result[\"memories\"]:\n    print(f\"  [{mem['id'][:12]}] {mem['content'][:80]}\")\n```\n\n#### Delete a memory\n\n```python\nmemory_id = \"2a11b4c6-8049-4071-aaea-237dd5cd5c7f\"\nreq = urllib.request.Request(\n    f\"{BASE}/memories/{memory_id}\",\n    headers=HEADERS,\n    method=\"DELETE\",\n)\nwith urllib.request.urlopen(req, timeout=30) as r:\n    print(r.status)  # → 200\n```\n\n---\n\n### Path B — REST API (JavaScript / TypeScript)\n\n```javascript\nconst API_KEY = process.env.PIYAPI_API_KEY;\nconst BASE = \"https://api.piyapi.cloud/api/v1\";\n\nasync function piy(method, endpoint, body) {\n  const res = await fetch(`${BASE}/${endpoint}`, {\n    method,\n    headers: {\n      \"Authorization\": `Bearer ${API_KEY}`,\n      \"Content-Type\": \"application/json\",\n    },\n    ...(body && { body: JSON.stringify(body) }),\n  });\n  return { status: res.status, data: await res.json() };\n}\n\n// Store\nconst { data } = await piy(\"POST\", \"memories\", {\n  content: \"User prefers dark mode and works with React.\",\n  namespace: \"my-app\",\n});\nconsole.log(\"Stored:\", data.memory.id);\n\n// Hybrid Search (free)\nconst search = await piy(\"POST\", \"search/hybrid\", {\n  query: \"frontend preferences\",\n  namespace: \"my-app\",\n  limit: 10,\n});\nsearch.data.results.forEach(hit => {\n  console.log(`  [${hit.similarity?.toFixed(3)}] ${hit.memory.content}`);\n});\n\n// Context Retrieval (free — best for LLM injection)\nconst ctx = await piy(\"POST\", \"context/retrieve\", {\n  query: \"What does the user prefer?\",\n  namespace: \"my-app\",\n});\nconsole.log(\"Tokens used:\", ctx.data.tokenCount);\nconsole.log(\"Context:\", ctx.data.content);\n// → Pass ctx.data.content into your own LLM prompt\n```\n\n---\n\n### Path C — MCP (Claude Desktop / Cursor / Windsurf / VS Code)\n\n**Zero code. 2 minutes. 30 tools.**\n\nAdd to your MCP config:\n\n| Client | Config file |\n|---|---|\n| Claude Desktop (Mac) | `~/Library/Application Support/Claude/claude_desktop_config.json` |\n| Claude Desktop (Win) | `%APPDATA%\\Claude\\claude_desktop_config.json` |\n| Cursor | `~/.cursor/mcp.json` |\n| Windsurf | `~/.codeium/windsurf/mcp_config.json` |\n| VS Code (Copilot) | `.vscode/mcp.json` in your workspace |\n\n```json\n{\n  \"mcpServers\": {\n    \"piyapi\": {\n      \"command\": \"npx\",\n      \"args\": [\"-y\", \"@piyapi/mcp-server\"],\n      \"env\": {\n        \"PIYAPI_API_KEY\": \"sk_live_your_key_here\"\n      }\n    }\n  }\n}\n```\n\nRestart the client. Your AI now has 30 memory tools:\n\n**Memory:** `store_memory`, `get_memory`, `update_memory`, `delete_memory`, `list_memories`, `batch_create`, `pin_memory`\n**Search (free):** `search_memories` (hybrid), `fuzzy_search` (typo-tolerant)\n**Context:** `get_context` (token-budgeted), `get_conversation` (history)\n**Knowledge Graph:** `kg_ingest`, `kg_search`, `kg_entities`, `kg_stats`, `kg_time_travel`\n**Graph:** `get_graph`, `graph_traverse`, `create_relationship`, `delete_relationship`, `get_clusters`\n**Other:** `ask_memory` (RAG), `deduplicate`, `version_history`, `rollback_memory`, `feedback_positive`, `feedback_negative`, `check_phi`, `export_all`, `create_context_session`\n\n> [!IMPORTANT]\n> **Prefer `search_memories` and `get_context` over `ask_memory`.** The search and context tools are free and return raw results you can feed into any LLM. `ask_memory` runs a full RAG pipeline on our servers which costs compute.\n\n---\n\n### Complete API Reference (Verified)\n\n#### Endpoints that work ✅\n\n| Method | Endpoint | Cost | Purpose |\n|---|---|---|---|\n| `GET` | `/health` | Free | Health check (no auth needed) |\n| `GET` | `/ping` | Free | Ping → pong |\n| `GET` | `/api/v1` | Free | API info + quickstart |\n| `POST` | `/api/v1/memories` | Free | Store a memory |\n| `GET` | `/api/v1/memories?namespace=X&limit=N` | Free | List memories |\n| `DELETE` | `/api/v1/memories/<id>` | Free | Delete a memory |\n| `POST` | `/api/v1/search` | **Free** | Basic semantic search |\n| `POST` | `/api/v1/search/hybrid` | **Free** | Hybrid search (semantic + keyword) |\n| `POST` | `/api/v1/context/retrieve` | **Free** | Token-budgeted context for LLM injection |\n| `POST` | `/api/v1/ask` | **Costs compute** | Full RAG — use sparingly |\n\n#### Endpoints that DON'T exist (don't try these)\n\n| What you might expect | Reality |\n|---|---|\n| `GET /api/v1/health` | ❌ 404 — use `GET /health` instead |\n| `GET /api/v1/search?query=...` | ❌ 404 — search is POST only |\n| `POST /api/v1/semantic` | ❌ 404 — use `/search` or `/search/hybrid` |\n\n---\n\n### Recommended Pattern: Search + Your Own LLM\n\nThe most cost-effective way to use PiyAPI:\n\n```python\nimport json, os, urllib.request\n\nAPI_KEY = os.environ[\"PIYAPI_API_KEY\"]\nBASE = \"https://api.piyapi.cloud/api/v1\"\nHDR = {\"Authorization\": f\"Bearer {API_KEY}\", \"Content-Type\": \"application/json\"}\n\ndef piy_post(ep, payload):\n    req = urllib.request.Request(f\"{BASE}/{ep}\", json.dumps(payload).encode(), HDR, method=\"POST\")\n    with urllib.request.urlopen(req, timeout=30) as r:\n        return json.loads(r.read())\n\n# 1. Get context (free)\nctx = piy_post(\"context/retrieve\", {\n    \"query\": user_question,\n    \"namespace\": \"my-app\",\n})\n\n# 2. Feed into YOUR LLM (OpenAI, Anthropic, Gemini, local — anything)\nimport openai\nclient = openai.OpenAI()\nresponse = client.chat.completions.create(\n    model=\"gpt-4o-mini\",\n    messages=[\n        {\"role\": \"system\", \"content\": f\"Use this context:\\n\\n{ctx['content']}\"},\n        {\"role\": \"user\", \"content\": user_question},\n    ],\n)\nprint(response.choices[0].message.content)\n```\n\nThis pattern:\n- ✅ Uses PiyAPI for what it's best at (storage, indexing, retrieval)\n- ✅ Uses your own LLM for generation (you control cost and model)\n- ✅ Costs zero PiyAPI compute\n- ✅ Works with any LLM provider or local model\n\n---\n\n### Namespaces\n\nUse namespaces to isolate data per user, project, or tenant:\n\n```python\n# Per-user isolation\npiy_post(\"memories\", {\"content\": \"...\", \"namespace\": \"user-alice\"})\npiy_post(\"memories\", {\"content\": \"...\", \"namespace\": \"user-bob\"})\n\n# Search only Alice's memories\npiy_post(\"search/hybrid\", {\"query\": \"...\", \"namespace\": \"user-alice\"})\n```\n\nNamespaces are just strings. Use hyphens, not underscores (e.g. `my-app` not `my_app`).\n\n---\n\n### Troubleshooting\n\n#### SSL/TLS errors (Docker or sandboxed environments)\n\n```bash\n# Fix DNS in Docker\ndocker run --dns 8.8.8.8 your-image\n\n# Fix TLS in Python\npip install certifi\n```\n\n```python\nimport ssl, certifi\nctx = ssl.create_default_context(cafile=certifi.where())\n# Pass ctx to urllib.request.urlopen(..., context=ctx)\n```\n\n**Or use MCP** — it runs on your host machine and communicates with the agent over stdio, bypassing sandbox networking entirely.\n\n#### 401 Authentication Error\n\n- Check that `PIYAPI_API_KEY` is set\n- Make sure the key starts with `sk_live_`\n- Verify at: `curl -H \"Authorization: Bearer $PIYAPI_API_KEY\" https://api.piyapi.cloud/api/v1`\n\n#### Rate limiting (429)\n\n```python\nimport time, urllib.error\n\ntry:\n    response = urllib.request.urlopen(req, timeout=30)\nexcept urllib.error.HTTPError as e:\n    if e.code == 429:\n        wait = float(e.headers.get(\"Retry-After\", 2))\n        time.sleep(wait)\n        # retry\n```\n\n---\n\n### Quick Copy-Paste Starter\n\nSave as `piyapi_quickstart.py`:\n\n```python\n#!/usr/bin/env python3\n\"\"\"PiyAPI Quickstart — store, search, retrieve context. Zero dependencies.\"\"\"\n\nimport json, os, urllib.request\n\nAPI_KEY = os.environ[\"PIYAPI_API_KEY\"]\nBASE = \"https://api.piyapi.cloud/api/v1\"\nHDR = {\"Authorization\": f\"Bearer {API_KEY}\", \"Content-Type\": \"application/json\"}\n\ndef post(ep, body):\n    req = urllib.request.Request(f\"{BASE}/{ep}\", json.dumps(body).encode(), HDR, method=\"POST\")\n    with urllib.request.urlopen(req, timeout=30) as r:\n        return r.status, json.loads(r.read())\n\n# 1. Store\ns, r = post(\"memories\", {\"content\": \"User likes React and dark mode\", \"namespace\": \"demo\"})\nprint(f\"Stored: {r['memory']['id']}\")\n\n# 2. Hybrid Search (free)\nimport time; time.sleep(2)  # wait for indexing\ns, r = post(\"search/hybrid\", {\"query\": \"frontend preference\", \"namespace\": \"demo\", \"limit\": 5})\nprint(f\"\\nSearch results ({len(r['results'])} found):\")\nfor hit in r[\"results\"]:\n    print(f\"  [{hit.get('similarity',0):.3f}] {hit['memory']['content']}\")\n\n# 3. Context Retrieval (free — best for LLM injection)\ns, r = post(\"context/retrieve\", {\"query\": \"What does the user prefer?\", \"namespace\": \"demo\"})\nprint(f\"\\nContext ({r['tokenCount']} tokens):\")\nprint(r[\"content\"][:500])\n```\n\n```bash\nexport PIYAPI_API_KEY=\"sk_live_...\"\npython3 piyapi_quickstart.py\n```\n\n**That's it. No SDK, no dependencies, no config files. Just HTTP.**\n\n## Contributors\n\n<a href=\"https://github.com/Negentro-ai/Piyapi/graphs/contributors\">\n  <img src=\"https://contrib.rocks/image?repo=Negentro-ai/Piyapi\" alt=\"Contributors\"/>\n</a>\n\n[View the project on GitHub](https://github.com/Negentro-ai/Piyapi)\n\n---\n\n## License\n\nApache 2.0 © [Negentro](https://www.negentro.tech/)\n\n<p align=\"center\">\n<strong>PiyAPI by Negentro — Giving AI Agents a True Persistent Mind.</strong>\n</p>\n"}