Skip to main content

A three-layer intelligence engine with ONNX integration for Open Agent Spec

Project description

Cortex Intelligence Engine ๐Ÿง โšก

Python 3.8+ License: MIT Tests

A three-layer intelligence engine designed for integration with Open Agent Spec, providing advanced sensory processing, interpretation, and reasoning capabilities with intelligent filtering and cost optimization.

๐ŸŽฏ What is Cortex?

Cortex acts as an intelligent filtering layer between your OAS agents and expensive external LLMs. Instead of routing every request directly to external LLMs, Cortex:

  1. Processes input through Layer 1 (sensory processing)
  2. Analyzes with Layer 2 (internal intelligence - rule-based or ONNX models)
  3. Decides whether to trigger Layer 3 (external LLM) based on complexity and importance
  4. Provides intelligent responses with suggested actions

Result: 60-80% cost reduction while maintaining intelligence! ๐Ÿ’ฐ๐Ÿง 

๐Ÿ—๏ธ Architecture

Cortex implements a three-layer architecture:

OAS Agent โ†’ Cortex Intelligence Engine โ†’ External LLM (if needed)
                โ†“
            Layer 1: Sensory Processing (Text, Image, Audio)
                โ†“
            Layer 2: Internal Intelligence (Rule-based/ONNX/Local LLM)
                โ†“
            Layer 3: External LLM (OpenAI, Claude, etc.)

Layer Breakdown

  1. Layer 1 - Sensory Processing: Raw data processing for vision, audio, and text inputs
  2. Layer 2 - Interpretation: Onboard ONNX/LLM for base-level data interpretation and reaction decisions
  3. Layer 3 - Reasoning: External LLM vendor integration (OpenAI, Claude, etc.) for complex reasoning

โœจ Features

  • ๐Ÿง  Intelligent Filtering: Automatically decides when to use expensive external LLMs
  • ๐Ÿค– ONNX Integration: Local neural network models for intelligent decision-making
  • ๐Ÿ’ฐ Cost Optimization: 60-80% reduction in external API calls
  • โšก Performance: Sub-second responses for simple queries
  • ๐Ÿ”„ Multi-modal Processing: Handles text, images, and audio data
  • ๐ŸŽฏ Smart Routing: Determines when complex reasoning is needed
  • ๐Ÿ”Œ Flexible LLM Integration: Supports multiple LLM providers with fallback mechanisms
  • ๐Ÿค– Open Agent Spec Compatible: Drop-in replacement for standard OAS intelligence engines
  • ๐Ÿ“Š Performance Monitoring: Built-in metrics and status tracking
  • ๐Ÿ“ฆ Batch Processing: Efficient processing of multiple inputs
  • โš™๏ธ Configurable Processing Modes: Reactive, proactive, and selective processing

๐Ÿš€ Installation

# Clone the repository
git clone https://github.com/yourusername/cortex.git
cd cortex

# Install in development mode
pip install -e .

๐Ÿ“‹ Dependencies

  • Python 3.8+
  • numpy - Numerical computing
  • Pillow - Image processing
  • onnxruntime - Layer 2 ONNX models
  • aiohttp - Async HTTP requests
  • pydantic - Data validation

โšก Quick Start

Basic Usage

import asyncio
from cortex import create_simple_cortex, create_cortex_function

async def main():
    # Create a basic Cortex instance
    cortex = create_simple_cortex(
        openai_api_key="your_openai_key",  # Optional
        claude_api_key="your_claude_key",  # Optional
        enable_layer3=True
    )
    
    # Process some input
    result = await cortex.process_input(
        data="Analyze this urgent system alert!",
        context="System monitoring detected anomaly"
    )
    
    print(f"Response: {result.final_response}")
    print(f"Suggested actions: {result.suggested_actions}")

asyncio.run(main())

๐Ÿค– Open Agent Spec Integration

from cortex import create_cortex_oas_intelligence, create_cortex_oas_function

# Configure like standard OAS intelligence
config = {
    "type": "cortex",
    "config": {
        "processing_mode": "reactive",
        "layer2_threshold": 0.6,
        "enable_layer3": True,
        "external_engine": "openai",
        "external_model": "gpt-4"
    }
}

# Create OAS-compatible intelligence engine
intelligence = create_cortex_oas_intelligence(config)
oas_function = create_cortex_oas_function(intelligence)

# Use in your OAS agent
response = await oas_function(
    prompt="URGENT: System failure detected!",
    context={"user_id": "123", "session_id": "456"}
)

print(f"Triggered Layer 3: {response['metadata']['triggered_layer3']}")

๐Ÿ“– For detailed OAS integration guide, see docs/OAS_INTEGRATION.md

๐Ÿง  ONNX Integration

from cortex import create_cortex_oas_intelligence, CortexOASConfig

# Configure with ONNX models for intelligent filtering
config = CortexOASConfig(
    layer2_engine="onnx",  # Enable ONNX models
    layer2_threshold=0.6,  # Confidence threshold
    enable_layer3=True,    # Allow external LLM calls
    external_engine="openai",
    external_model="gpt-4"
)

# Create intelligence engine with ONNX-powered Layer 2
intelligence = create_cortex_oas_intelligence(config)

# Process input - ONNX models will decide if Layer 3 is needed
response = await intelligence.process("URGENT: System failure detected!")
print(f"Triggered Layer 3: {response['metadata']['triggered_layer3']}")

๐Ÿ“– For detailed ONNX integration guide, see docs/ONNX_INTEGRATION.md

๐Ÿ“š Usage Examples

๐Ÿ“ Text Processing

result = await cortex.process_input(
    data="Emergency: Database server is down!",
    sense_type="text",
    task_type="incident_response"
)

๐Ÿ–ผ๏ธ Image Processing

from PIL import Image

image = Image.open("photo.jpg")
result = await cortex.process_input(
    data=image,
    sense_type="vision",
    context="Security camera feed analysis"
)

๐ŸŽต Audio Processing

import numpy as np

# Audio data as numpy array
audio_data = np.load("audio_sample.npy")
result = await cortex.process_input(
    data=audio_data,
    sense_type="audio",
    task_type="sound_classification"
)

๐Ÿ“ฆ Batch Processing

inputs = [
    {"data": "Message 1", "task_type": "general"},
    {"data": "URGENT: Alert message", "task_type": "alert"},
    {"data": image_data, "sense_type": "vision"}
]

results = await cortex.batch_process(inputs)

โš™๏ธ Configuration

๐Ÿ”„ Processing Modes

Mode Behavior Use Case
REACTIVE Only Layer 3 when Layer 2 decides Cost-effective, intelligent filtering
PROACTIVE Always use all layers Maximum intelligence, higher cost
SELECTIVE Custom logic for Layer 3 Custom filtering rules
from cortex.core import CortexConfig, ProcessingMode

config = CortexConfig(
    processing_mode=ProcessingMode.REACTIVE,
    layer2_threshold=0.6,
    enable_layer3=True,
    max_processing_time=30.0
)

cortex = Cortex(config)

๐Ÿค– LLM Provider Configuration

from cortex.layers.layer3 import LLMConfig, LLMProvider

# OpenAI Configuration
openai_config = LLMConfig(
    provider=LLMProvider.OPENAI,
    api_key="your_key",
    model="gpt-3.5-turbo",
    max_tokens=1000,
    temperature=0.7
)

# Claude Configuration
claude_config = LLMConfig(
    provider=LLMProvider.CLAUDE,
    api_key="your_key",
    model="claude-3-sonnet-20240229",
    max_tokens=1000,
    temperature=0.7
)

cortex.add_llm_provider(openai_config, is_primary=True)
cortex.add_llm_provider(claude_config, is_primary=False)  # Fallback

๐Ÿค– Open Agent Spec Integration

Cortex is designed as a drop-in replacement for standard OAS intelligence engines:

Basic OAS Configuration

name: "my_cortex_agent"
intelligence:
  type: "cortex"
  engine: "cortex-hybrid"
  config:
    processing_mode: "reactive"
    layer2_threshold: 0.6
    enable_layer3: true
    external_engine: "openai"
    external_model: "gpt-4"
    external_endpoint: "https://api.openai.com/v1"
    temperature: 0.7
    max_tokens: 150
    trigger_keywords: ["help", "urgent", "error", "assist"]

Response Format

Cortex returns OAS-compatible responses:

{
  "success": true,
  "response": "Analysis and response from Cortex",
  "actions": ["suggested_action_1", "suggested_action_2"],
  "metadata": {
    "layers_used": ["layer1", "layer2", "layer3"],
    "processing_time": 1.23,
    "confidence": 0.85,
    "cortex_stats": {
      "total_requests": 100,
      "layer2_only": 70,
      "layer3_triggered": 30,
      "average_response_time": 0.5
    },
    "triggered_layer3": true
  },
  "error": null
}

๐Ÿ“– For comprehensive OAS integration guide, see docs/OAS_INTEGRATION.md

๐Ÿ“Š Monitoring and Metrics

Performance Statistics

# Get current status
status = cortex.get_status()
print(f"Performance metrics: {status['cortex']['performance_metrics']}")

# Get processing history
history = cortex.get_recent_history(limit=10)

# Reset metrics
cortex.reset_metrics()

๐Ÿ“ˆ Example Output

Performance Statistics:
  Total Requests: 100
  Layer 2 Only: 70 (70.0%)
  Layer 3 Triggered: 30 (30.0%)
  Average Response Time: 0.5s

๐Ÿ”” Callback System

async def on_high_priority(data):
    print(f"High priority reaction detected: {data}")

cortex.add_callback("on_reaction_decision", on_high_priority)

๐Ÿ› ๏ธ Development

๐Ÿงช Running Tests

pip install pytest pytest-asyncio
python -m pytest tests/ -v

๐Ÿš€ Running Examples

# Basic usage examples
python examples/basic_usage.py

# OAS integration examples
python examples/oas_integration_example.py

๐Ÿ“ Project Structure

cortex/
โ”œโ”€โ”€ cortex/
โ”‚   โ”œโ”€โ”€ __init__.py
โ”‚   โ”œโ”€โ”€ core.py              # Main Cortex class
โ”‚   โ”œโ”€โ”€ oas_integration.py   # OAS integration module
โ”‚   โ””โ”€โ”€ layers/
โ”‚       โ”œโ”€โ”€ __init__.py
โ”‚       โ”œโ”€โ”€ layer1.py        # Sensory processing
โ”‚       โ”œโ”€โ”€ layer2.py        # Interpretation and reaction decisions
โ”‚       โ””โ”€โ”€ layer3.py        # External LLM reasoning
โ”œโ”€โ”€ examples/
โ”‚   โ”œโ”€โ”€ basic_usage.py       # Basic usage examples
โ”‚   โ””โ”€โ”€ oas_integration_example.py  # OAS integration examples
โ”œโ”€โ”€ docs/
โ”‚   โ””โ”€โ”€ OAS_INTEGRATION.md   # Detailed OAS integration guide
โ”œโ”€โ”€ tests/
โ”‚   โ””โ”€โ”€ test_basic.py        # Test suite
โ”œโ”€โ”€ pyproject.toml           # Project configuration
โ””โ”€โ”€ README.md

๐Ÿค Contributing

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

๐Ÿ“„ License

MIT License - see LICENSE file for details.

๐Ÿ“š API Reference

๐Ÿง  Core Classes

  • Cortex: Main intelligence engine
  • SenseLayer: Layer 1 sensory processing
  • InterpretationLayer: Layer 2 interpretation and reaction decisions
  • ReasoningLayer: Layer 3 external LLM reasoning

๐Ÿ› ๏ธ Utility Functions

  • create_simple_cortex(): Quick Cortex setup
  • create_cortex_function(): Create Open Agent Spec compatible function
  • create_cortex_oas_intelligence(): Create OAS intelligence engine
  • create_cortex_oas_function(): Create OAS-compatible function

โš™๏ธ Configuration Classes

  • CortexConfig: Main configuration
  • CortexOASConfig: OAS-specific configuration
  • LLMConfig: LLM provider configuration
  • ProcessingMode: Processing mode enumeration

๐ŸŽฏ Use Cases

๐Ÿ’ฐ Cost Optimization

  • Problem: High LLM API costs for simple queries
  • Solution: Cortex filters out simple requests
  • Result: 60-80% cost reduction

โšก Response Speed

  • Problem: Slow responses for simple questions
  • Solution: Layer 2 handles simple queries instantly
  • Result: Sub-second responses for basic requests

๐Ÿง  Intelligent Routing

  • Problem: All requests treated equally
  • Solution: Cortex analyzes complexity and urgency
  • Result: Appropriate resource allocation

๐Ÿ”„ Multi-modal Support

  • Problem: Text-only intelligence engines
  • Solution: Cortex handles text, images, and audio
  • Result: Rich multi-modal interactions

Cortex - Intelligent filtering for Open Agent Spec agents. ๐Ÿง โšก

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

cortex_intelligence-0.1.0.tar.gz (51.2 kB view details)

Uploaded Source

Built Distribution

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

cortex_intelligence-0.1.0-py3-none-any.whl (31.5 kB view details)

Uploaded Python 3

File details

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

File metadata

  • Download URL: cortex_intelligence-0.1.0.tar.gz
  • Upload date:
  • Size: 51.2 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.0.1 CPython/3.12.5

File hashes

Hashes for cortex_intelligence-0.1.0.tar.gz
Algorithm Hash digest
SHA256 35a8b71619c3ccf383689e592e5f016a3396622d73e5213b6613363544636b72
MD5 455af14c835fe7e733cf9f60614d8b27
BLAKE2b-256 84e882fef2814c54e78f01ecf1e2b6fd32aeaf196b4d9b5eb08661e06b76eb9d

See more details on using hashes here.

File details

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

File metadata

File hashes

Hashes for cortex_intelligence-0.1.0-py3-none-any.whl
Algorithm Hash digest
SHA256 be7bf2f3af3d1910fb9223ad78d129df7b267f3c60b60f2147b7933bf51c8c1b
MD5 31b118b19616f07cc89096c09316576c
BLAKE2b-256 e907b746c10383daea7cf2311de24d838aa4102ecd71a5079c2b0fbab8c34862

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