Skip to main content

Python SDK for Context OS — Memory, Search, Crawl, Knowledge

Project description

Context AI — Python SDK

A Python client library for the Context OS API. Provides memory, search, crawl, and knowledge graph operations for AI agents.

Installation

pip install context-ai

Or install from source:

git clone https://github.com/AmanSagar0607/Context-OS.git
cd Context-OS/sdk/python
pip install -e .

Quick Start

from context_ai import ContextAI

# Initialize client
client = ContextAI(
    base_url="http://localhost:8000",
    api_key="your-api-key",  # or set CONTEXT_API_KEY env var
)

# Check health
print(client.health())

Memory Operations

from context_ai import MemoryCreate, MemoryType, ImportanceLevel

# Add a memory
memory = client.memory.add(MemoryCreate(
    content="User prefers dark mode and compact layouts",
    memory_type=MemoryType.SEMANTIC,
    importance=ImportanceLevel.HIGH,
    tags=["preferences", "ui"],
))
print(f"Created memory: {memory.id}")

# Search memories
results = client.memory.search(query="dark mode preferences")
for result in results:
    print(f"Score: {result.score:.2f} - {result.memory.content}")

# Get context window for a query
context = client.memory.context(
    query="What UI settings does the user prefer?",
    max_tokens=2000,
)
print(f"Context has {len(context['memories'])} memories")

# List memories
memories = client.memory.list(memory_type="semantic", limit=10)

# Get related memories
related = client.memory.related(memory_id=memory.id, limit=5)

Web Search

from context_ai import SearchRequest

# Web search
results = client.search.web(SearchRequest(
    query="latest AI agent frameworks 2025",
    max_results=5,
))
for result in results:
    print(f"{result.title}: {result.url}")

Web Crawl

# Scrape a single page
page = client.crawl.scrape(url="https://docs.example.com/api")
print(f"Title: {page.title}")
print(f"Content length: {len(page.content)} chars")

# Crawl a website
from context_ai import CrawlRequest

results = client.crawl.crawl(CrawlRequest(
    url="https://docs.example.com",
    max_pages=20,
    extract_content=True,
))
print(f"Crawled {len(results)} pages")

# Map a website (get all URLs)
urls = client.crawl.map(url="https://example.com", max_pages=100)
print(f"Found {len(urls)} URLs")

Knowledge Graph

from context_ai import EntityCreate, RelationshipCreate

# Create entities
entity = client.knowledge.create_entity(EntityCreate(
    name="GPT-4",
    entity_type="model",
    description="OpenAI's large language model",
    properties={"provider": "OpenAI", "parameters": "1.7T"},
))

# Create relationships
client.knowledge.create_relationship(RelationshipCreate(
    source_id=entity.id,
    target_id="other-entity-id",
    relationship_type="related_to",
    weight=0.9,
))

# Get entity graph
graph = client.knowledge.get_graph(entity.id, depth=2)
print(f"Graph has {len(graph['nodes'])} nodes")

# Search entities
entities = client.knowledge.search(query="language models", entity_type="model")

Async Support

All methods have async equivalents:

import asyncio
from context_ai import ContextAI, MemoryCreate

async def main():
    async with ContextAI() as client:
        # Async memory add
        memory = await client.memory.aadd(MemoryCreate(
            content="Async memory",
        ))

        # Async search
        results = await client.memory.asearch(query="async")

asyncio.run(main())

Configuration

Environment Variables

Variable Description Default
CONTEXT_API_KEY API key for authentication None
CONTEXT_API_URL API server URL http://localhost:8000
CONTEXT_OS_URL Alias for CONTEXT_API_URL http://localhost:8000
CONTEXT_OS_API_KEY Alias for CONTEXT_API_KEY None

Constructor Parameters

client = ContextAI(
    base_url="http://localhost:8000",  # API server URL
    api_key="your-key",                # API key
    timeout=30.0,                      # Request timeout (seconds)
)

Error Handling

from httpx import HTTPStatusError

try:
    memory = client.memory.get("nonexistent-id")
except HTTPStatusError as e:
    if e.response.status_code == 404:
        print("Memory not found")
    elif e.response.status_code == 401:
        print("Authentication failed")

License

MIT License — see LICENSE for details.

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

contextos_sdk-0.1.0.tar.gz (8.9 kB view details)

Uploaded Source

Built Distribution

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

contextos_sdk-0.1.0-py3-none-any.whl (11.2 kB view details)

Uploaded Python 3

File details

Details for the file contextos_sdk-0.1.0.tar.gz.

File metadata

  • Download URL: contextos_sdk-0.1.0.tar.gz
  • Upload date:
  • Size: 8.9 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.13.14

File hashes

Hashes for contextos_sdk-0.1.0.tar.gz
Algorithm Hash digest
SHA256 d62b3f72f0e2cdab1caf085408d8b78ca7173609ebf1cbd66b6825c0faf47d96
MD5 b8000e866f95f1b04dcd463413756de8
BLAKE2b-256 f4ccb4cee1b7ee84219653b29f31528bfe212f0caeee156dac75051b197f8e4a

See more details on using hashes here.

File details

Details for the file contextos_sdk-0.1.0-py3-none-any.whl.

File metadata

  • Download URL: contextos_sdk-0.1.0-py3-none-any.whl
  • Upload date:
  • Size: 11.2 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.13.14

File hashes

Hashes for contextos_sdk-0.1.0-py3-none-any.whl
Algorithm Hash digest
SHA256 b480aab19e16ad5f9f3730b982ebdadc9cd88e3720d419158139cdf45416d1a3
MD5 811d3f616c7e47f2cf9b0a3c3e7d1897
BLAKE2b-256 958a165d1b911ec658c2a975c731bfa9a91d645e678b1ce2e4e0409039331cbc

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