Skip to main content

Python SDK for Cogniz Memory Platform - Persistent memory for AI applications

Project description

Cogniz Python SDK

PyPI version Python versions License: MIT

Official Python SDK for Cogniz Memory Platform. Build AI applications with persistent, searchable memory.

Features

  • Persistent Memory - Store and recall information across sessions
  • Semantic Search - Natural language memory retrieval
  • Confidence Scoring - Filter memories by reliability
  • Auto-Expiration - Automatic cleanup of stale data
  • Agent Scoping - Separate AI personality from user data
  • Async Support - Native asyncio for concurrent operations
  • Prompt Optimizer - AI-powered prompt enhancement
  • Playbooks - Automation workflows
  • Self-Hosted - Run on your own infrastructure
  • Multi-Client - Works with Browser Extension, VS Code, MCP

Installation

pip install cogniz

Quick Start

from cogniz import Client

# Initialize client
client = Client(api_key="mp_your_api_key_here")

# Store a memory
client.store(
    "User prefers Python for backend development",
    user_id="alice",
    category="preferences"
)

# Search memories
results = client.search("programming languages", user_id="alice")
for memory in results.get("results", []):
    print(f"- {memory['content']}")

# Get usage stats
stats = client.get_stats()
print(f"Plan: {stats['plan']}, Memories: {stats['total_memories']}")

Environment Variables

Set these in your .env file:

COGNIZ_API_KEY=mp_your_api_key_here
COGNIZ_PROJECT_ID=123  # Optional default project
COGNIZ_BASE_URL=https://cogniz.online  # Optional custom host

Then use without parameters:

from cogniz import Client

# Automatically reads from environment
client = Client()

Core Operations

Store Memories

# Simple storage
result = client.store(
    "User completed Python course",
    user_id="alice"
)

# With metadata and category
result = client.store(
    "User allergic to penicillin",
    user_id="patient_123",
    category="medical",
    metadata={"severity": "high", "verified": True},
    confidence=1.0
)

# With expiration
result = client.store(
    "User browsing electronics section",
    user_id="bob",
    category="session",
    auto_expire=True  # Expires based on category
)

Search Memories

# Basic search
results = client.search(
    "What programming languages does the user know?",
    user_id="alice"
)

# With filtering
results = client.search(
    "medical conditions",
    user_id="patient_123",
    threshold=0.8,  # High confidence only
    limit=5
)

# With agent context
results = client.search(
    "fitness goals",
    user_id="alice",
    agent_id="fitness_coach_v1"
)

Manage Memories

# Get all memories
memories = client.get_all(user_id="alice", limit=50)

# Update memory
client.update(
    memory_id="mem_123",
    content="Updated information",
    metadata={"verified": True}
)

# Delete memory
client.delete("mem_123")

# Delete all for user
client.delete_all(user_id="alice")

Advanced Features

Agent Memory Scoping

Store AI personality once, share across all users:

# Store agent personality (shared)
client.store(
    "You are a motivational fitness coach who celebrates wins",
    agent_id="fitness_coach_v1"
)

# Store user progress (private)
client.store(
    "User completed 5K run in 28 minutes",
    user_id="alice"
)

# Search combines both contexts
results = client.search(
    "my running progress",
    user_id="alice",
    agent_id="fitness_coach_v1"
)

Prompt Optimization

# Optimize your prompts with AI
result = client.optimize_prompt(
    "Write code to sort a list",
    preset="technical"  # or "comprehensive", "concise"
)

print(result["optimized"])
# Output: "Write production-ready, well-commented Python code..."

Automation Playbooks

# List available playbooks
playbooks = client.list_playbooks()

# Run a playbook
result = client.run_playbook(
    "web_scraper_v1",
    input_data={"url": "https://example.com"}
)

Knowledge Graph

# Extract entities from text
entities = client.extract_entities(
    "Emma works with David at Cogniz on the Python SDK"
)

# Get graph statistics
stats = client.get_graph_stats()
print(f"Entities: {stats['entity_count']}")

Async Usage

import asyncio
from cogniz import AsyncClient

async def main():
    async with AsyncClient(api_key="mp_...") as client:
        # Store memory
        await client.store(
            "User loves async Python",
            user_id="alice"
        )

        # Search memories
        results = await client.search(
            "async programming",
            user_id="alice"
        )

        print(results)

asyncio.run(main())

Project Management

# List all projects
projects = client.list_projects()
for project in projects:
    print(f"{project['id']}: {project['name']}")

# Use specific project
client = Client(api_key="mp_...", project_id=456)

Error Handling

from cogniz import (
    Client,
    AuthenticationError,
    NotFoundError,
    RateLimitError,
    ValidationError,
    QuotaExceededError
)

client = Client(api_key="mp_...")

try:
    result = client.store("User data", user_id="alice")
except AuthenticationError:
    print("Invalid API key")
except RateLimitError:
    print("Rate limit exceeded, please wait")
except QuotaExceededError:
    print("Storage quota exceeded, upgrade plan")
except ValidationError as e:
    print(f"Invalid input: {e}")

Context Manager

# Automatically closes HTTP connections
with Client(api_key="mp_...") as client:
    client.store("User data", user_id="alice")
    results = client.search("query", user_id="alice")
# Connection closed automatically

Compatibility

Works seamlessly with:

  • Cogniz Browser Extension - Chrome/Firefox extension for web memory
  • Cogniz VS Code Extension - IDE integration
  • Cogniz MCP Server - Claude Desktop integration
  • Self-Hosted Platform - Your own WordPress installation

All clients use the same API, so memories are synced across all surfaces.

API Reference

Client(api_key, base_url, project_id, config, client)

Main synchronous client.

Core Methods:

  • store(content, **kwargs) - Store a memory
  • search(query, **kwargs) - Search memories
  • get_all(**kwargs) - Get all memories
  • update(memory_id, **kwargs) - Update memory
  • delete(memory_id) - Delete memory
  • delete_all(**kwargs) - Bulk delete

Project Methods:

  • list_projects() - List all projects

Cogniz Features:

  • optimize_prompt(prompt, **kwargs) - Optimize prompts
  • run_playbook(playbook_id, input_data, **kwargs) - Run automation
  • list_playbooks(**kwargs) - List playbooks
  • get_stats() - Get usage statistics
  • get_debug_settings() - Get platform info

Knowledge Graph:

  • extract_entities(text, **kwargs) - Extract entities
  • get_graph_stats(**kwargs) - Get graph statistics

AsyncClient

Async version with same API using async/await.

Config(api_key, base_url, project_id, timeout)

Configuration object.

Get API Key

  1. Sign up at cogniz.online
  2. Go to Dashboard → API Keys
  3. Create new API key
  4. Copy key (starts with mp_)

Documentation

Support

Contributing

Contributions welcome! Please read CONTRIBUTING.md for guidelines.

License

MIT License - see LICENSE file for details.

Credits

Built by the Cogniz team. Powered by WordPress and httpx.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

cogniz-1.0.1.tar.gz (16.0 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

cogniz-1.0.1-py3-none-any.whl (12.6 kB view details)

Uploaded Python 3

File details

Details for the file cogniz-1.0.1.tar.gz.

File metadata

  • Download URL: cogniz-1.0.1.tar.gz
  • Upload date:
  • Size: 16.0 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.11.9

File hashes

Hashes for cogniz-1.0.1.tar.gz
Algorithm Hash digest
SHA256 6da8f6855d5800afd8d42b2b27029561d1ac5caca95ae7cbb123cc2e24d50b4e
MD5 02c7b6d446b411d80b0f5ff646b6aebb
BLAKE2b-256 e90e525d93cdad3ab198fd18ea0dc54c94748de4a9ad89ba9012a7f8513b6c2b

See more details on using hashes here.

File details

Details for the file cogniz-1.0.1-py3-none-any.whl.

File metadata

  • Download URL: cogniz-1.0.1-py3-none-any.whl
  • Upload date:
  • Size: 12.6 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.11.9

File hashes

Hashes for cogniz-1.0.1-py3-none-any.whl
Algorithm Hash digest
SHA256 9ff98fb3893261e833aff0c4d3bc257f8d1d8a78aaf242d3aafedeb25c0827ef
MD5 007670c4fc9ca5782eab909c629a2c53
BLAKE2b-256 bb20c794735e444bd997219cf15f291c4501223d51fb354d1e144d56cef9d140

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page