Skip to main content

Python SDK for CognitiveAI API

Project description

CognitiveAI Python SDK

PyPI version Python 3.8+ License: MIT

A comprehensive Python SDK for the Neural Multi-Level Reasoning (CognitiveAI) API. Provides async support, error handling, and easy integration with Python applications.

Features

  • 🚀 Async First: Built with asyncio for high-performance async operations
  • 🔄 Auto Retry: Intelligent retry logic with exponential backoff
  • 🛡️ Error Handling: Comprehensive error handling with custom exceptions
  • 📊 Job Management: Full support for async job monitoring and cancellation
  • 🔑 API Key Management: Create, list, and manage API keys programmatically
  • 📈 Grid Search: Efficient parameter optimization across beam/step combinations
  • 🧪 Well Tested: Comprehensive test suite with high coverage

Installation

pip install cognitiveai-sdk

Or install from source:

git clone https://github.com/cognitiveai/cognitiveai-python-sdk.git
cd cognitiveai-python-sdk
pip install -e .

Quick Start

Basic Search Reasoning

import asyncio
from cognitiveai import CognitiveAIClient, CognitiveAIConfig

async def main():
    # Configure the client
    config = CognitiveAIConfig(api_key="your-api-key-here")
    # Use local development server
    config.base_url = "http://localhost:8000"

    async with CognitiveAIClient(config) as client:
        # Perform search reasoning
        result = await client.search("What are the three laws of thermodynamics?")

        print(f"Response: {result.response}")
        print(f"Tokens used: {result.tokens_used}")
        print(f"Cost: ${result.cost}")

asyncio.run(main())

Grid Search for Parameter Optimization

import asyncio
from cognitiveai import CognitiveAIClient, CognitiveAIConfig, GridRequest

async def optimize_parameters():
    config = CognitiveAIConfig(api_key="your-api-key-here")
    config.base_url = "http://localhost:8000"

    async with CognitiveAIClient(config) as client:
        # Test multiple beam/step combinations
        request = GridRequest(
            beams=[2, 3, 4],
            steps=[1, 2, 3],
            prompt="Solve this complex reasoning problem...",
            provider="mock"  # Use mock for testing
        )

        result = await client.grid_search(request)

        print(f"Best result: {result.best_result}")
        print(f"Total cost: ${result.total_cost}")
        print(f"Total tokens: {result.total_tokens_used}")

asyncio.run(optimize_parameters())

Quick Functions for Simple Use Cases

import asyncio
from cognitiveai import search, grid_search

async def quick_examples():
    # Simple search
    result = await search(
        prompt="Explain quantum entanglement",
        api_key="your-api-key",
        provider="mock",
        beam=3,
        steps=2
    )
    print(result.response)

    # Simple grid search
    result = await grid_search(
        beams=[2, 3],
        steps=[1, 2],
        api_key="your-api-key",
        prompt="What is the meaning of life?",
        provider="mock"
    )
    print(result.best_result)

asyncio.run(quick_examples())

Advanced Usage

Custom Configuration

from cognitiveai import CognitiveAIClient, CognitiveAIConfig

# Custom configuration
config = CognitiveAIConfig(
    api_key="your-api-key",
    base_url="https://cognitiveai-api.fly.dev",  # Production API
    timeout=600.0,  # 10 minutes timeout
    max_retries=5,
    retry_delay=2.0
)

async with CognitiveAIClient(config) as client:
    # Use client...
    pass

Job Management

import asyncio
from cognitiveai import CognitiveAIClient, CognitiveAIConfig

async def manage_jobs():
    config = CognitiveAIConfig(api_key="your-api-key")
    async with CognitiveAIClient(config) as client:
        # Start a long-running job
        search_request = SearchRequest(
            prompt="Complex reasoning task...",
            beam=4,
            steps=3,
            provider="openai"
        )

        # This will return immediately with job_id for async jobs
        result = await client.search(search_request)
        job_id = result.job_id

        # Monitor job progress
        while True:
            status = await client.get_job_status(job_id)
            print(f"Status: {status.status}, Progress: {status.progress}")

            if status.status == "completed":
                print("Job completed!")
                break
            elif status.status == "failed":
                print(f"Job failed: {status.error}")
                break

            await asyncio.sleep(5)

        # Cancel a job if needed
        # await client.cancel_job(job_id)

asyncio.run(manage_jobs())

API Key Management

import asyncio
from cognitiveai import CognitiveAIClient, CognitiveAIConfig

async def manage_api_keys():
    config = CognitiveAIConfig(api_key="your-master-api-key")
    async with CognitiveAIClient(config) as client:
        # List existing keys
        keys = await client.get_api_keys()
        for key in keys:
            print(f"Key: {key['name']} - {key['id']}")

        # Create a new key
        new_key = await client.create_api_key(
            name="My New Key",
            permissions=["read", "write"]
        )
        print(f"Created key: {new_key['key']}")

        # Delete a key
        # await client.delete_api_key(key_id)

asyncio.run(manage_api_keys())

Error Handling

import asyncio
from cognitiveai import CognitiveAIClient, CognitiveAIConfig, CognitiveAIError, CognitiveAIAuthenticationError, CognitiveAIRateLimitError

async def handle_errors():
    config = CognitiveAIConfig(api_key="invalid-key")
    async with CognitiveAIClient(config) as client:
        try:
            result = await client.search("Test prompt")
        except CognitiveAIAuthenticationError:
            print("Invalid API key")
        except CognitiveAIRateLimitError:
            print("Rate limit exceeded, please wait")
        except CognitiveAIError as e:
            print(f"CognitiveAI error: {e}")
        except Exception as e:
            print(f"Unexpected error: {e}")

asyncio.run(handle_errors())

Data Classes

SearchRequest

@dataclass
class SearchRequest:
    prompt: str
    provider: str = "mock"
    beam: int = 2
    steps: int = 1
    temperature: Optional[float] = None
    max_tokens: Optional[int] = None
    model: Optional[str] = None

GridRequest

@dataclass
class GridRequest:
    beams: List[int]
    steps: List[int]
    provider: str = "mock"
    prompt: Optional[str] = None
    temperature: Optional[float] = None
    max_tokens: Optional[int] = None
    model: Optional[str] = None

SearchResult

@dataclass
class SearchResult:
    job_id: str
    prompt: str
    response: str
    reasoning_trace: List[Dict[str, Any]]
    provider: str
    beam: int
    steps: int
    tokens_used: int
    cost: float
    created_at: datetime

GridResult

@dataclass
class GridResult:
    job_id: str
    prompt: Optional[str]
    results: List[Dict[str, Any]]
    best_result: Dict[str, Any]
    provider: str
    beams: List[int]
    steps: List[int]
    total_tokens_used: int
    total_cost: float
    created_at: datetime

Exception Hierarchy

  • CognitiveAIError: Base exception for all CognitiveAI errors
    • CognitiveAIAuthenticationError: Invalid API key or authentication failure
    • CognitiveAIRateLimitError: API rate limit exceeded
    • CognitiveAIServerError: Server-side errors (5xx responses)

Development

Setup Development Environment

git clone https://github.com/cognitiveai/cognitiveai-python-sdk.git
cd cognitiveai-python-sdk
pip install -e ".[dev]"

Run Tests

pytest

Code Quality

# Format code
black cognitiveai/
isort cognitiveai/

# Type checking
mypy cognitiveai/

# Linting
flake8 cognitiveai/

Build Documentation

cd docs
make html

Contributing

We welcome contributions! Please see our Contributing Guide for details.

  1. Fork the repository
  2. Create a feature branch
  3. Make your changes
  4. Add tests for new functionality
  5. Ensure all tests pass
  6. Submit a pull request

License

This project is licensed under the MIT License - see the LICENSE file for details.

Support

Changelog

See CHANGELOG.md for version history and updates.

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

cognitiveai_sdk-0.1.0.tar.gz (15.1 kB view details)

Uploaded Source

Built Distribution

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

cognitiveai_sdk-0.1.0-py3-none-any.whl (8.6 kB view details)

Uploaded Python 3

File details

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

File metadata

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

File hashes

Hashes for cognitiveai_sdk-0.1.0.tar.gz
Algorithm Hash digest
SHA256 238a18e96ae0e797f11f12bcec608a17d72af00303c8f22b79062e397815145b
MD5 111f25bc4dbf6aec5f7f2924aadead1c
BLAKE2b-256 0d85d941b5f929cc9a2e259db2d6378470b9d99e3d28e1c3b6d6d3d78d8097fe

See more details on using hashes here.

File details

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

File metadata

File hashes

Hashes for cognitiveai_sdk-0.1.0-py3-none-any.whl
Algorithm Hash digest
SHA256 5209eb2fec8ff340dab16a875376b0d33d2a3740dc901aebfb44f11c56eae0a0
MD5 f854b58abc3566fffb8a86634c100345
BLAKE2b-256 fff0cba0c43c6912140b8d0cdba8cf8e588f1d5c4087c63032af5ac1c86b943d

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