Text Generation
Transformers
Safetensors
French
English
Chinese
deepseek_v4
cortex
code-generation
web-development
software-engineering
Mixture of Experts
8-bit precision
fp8
Instructions to use Frankenstein-Labs/cortex.6.sol with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- Transformers
How to use Frankenstein-Labs/cortex.6.sol with Transformers:
# Use a pipeline as a high-level helper from transformers import pipeline pipe = pipeline("text-generation", model="Frankenstein-Labs/cortex.6.sol")# pip install -U transformers accelerate # Load model directly from transformers import AutoTokenizer, AutoModelForCausalLM tokenizer = AutoTokenizer.from_pretrained("Frankenstein-Labs/cortex.6.sol") model = AutoModelForCausalLM.from_pretrained("Frankenstein-Labs/cortex.6.sol", device_map="auto") - Notebooks
- Google Colab
- Kaggle
- Local Apps Settings
- vLLM
How to use Frankenstein-Labs/cortex.6.sol with vLLM:
Install from pip and serve model
# Install vLLM from pip: pip install vllm # Start the vLLM server: vllm serve "Frankenstein-Labs/cortex.6.sol" # Call the server using curl (OpenAI-compatible API): curl -X POST "http://localhost:8000/v1/completions" \ -H "Content-Type: application/json" \ --data '{ "model": "Frankenstein-Labs/cortex.6.sol", "prompt": "Once upon a time,", "max_tokens": 512, "temperature": 0.5 }'Use Docker
docker model run hf.co/Frankenstein-Labs/cortex.6.sol
- SGLang
How to use Frankenstein-Labs/cortex.6.sol with SGLang:
Install from pip and serve model
# Install SGLang from pip: pip install sglang # Start the SGLang server: python3 -m sglang.launch_server \ --model-path "Frankenstein-Labs/cortex.6.sol" \ --host 0.0.0.0 \ --port 30000 # Call the server using curl (OpenAI-compatible API): curl -X POST "http://localhost:30000/v1/completions" \ -H "Content-Type: application/json" \ --data '{ "model": "Frankenstein-Labs/cortex.6.sol", "prompt": "Once upon a time,", "max_tokens": 512, "temperature": 0.5 }'Use Docker images
docker run --gpus all \ --shm-size 32g \ -p 30000:30000 \ -v ~/.cache/huggingface:/root/.cache/huggingface \ --env "HF_TOKEN=<secret>" \ --ipc=host \ lmsysorg/sglang:latest \ python3 -m sglang.launch_server \ --model-path "Frankenstein-Labs/cortex.6.sol" \ --host 0.0.0.0 \ --port 30000 # Call the server using curl (OpenAI-compatible API): curl -X POST "http://localhost:30000/v1/completions" \ -H "Content-Type: application/json" \ --data '{ "model": "Frankenstein-Labs/cortex.6.sol", "prompt": "Once upon a time,", "max_tokens": 512, "temperature": 0.5 }' - Docker Model Runner
How to use Frankenstein-Labs/cortex.6.sol with Docker Model Runner:
docker model run hf.co/Frankenstein-Labs/cortex.6.sol
Commit ·
91c4b21
1
Parent(s): c63bc31
feat: add extensible orchestration foundation
Browse files- cortex_ai/orchestration/__init__.py +18 -0
- cortex_ai/orchestration/engine.py +28 -0
- cortex_ai/orchestration/errors.py +25 -0
- cortex_ai/orchestration/finance.py +22 -0
- cortex_ai/orchestration/gateway.py +31 -0
- cortex_ai/orchestration/jobs.py +37 -0
- cortex_ai/orchestration/policy.py +20 -0
- cortex_ai/orchestration/providers.py +51 -0
- cortex_ai/orchestration/router.py +38 -0
- cortex_ai/orchestration/schemas.py +78 -0
- cortex_ai/orchestration/tooling.py +19 -0
- docs/orchestration.fr.md +34 -0
- tests/test_orchestration.py +42 -0
- tests/test_training.py +3 -2
cortex_ai/orchestration/__init__.py
ADDED
|
@@ -0,0 +1,18 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from .errors import *
|
| 2 |
+
from .finance import Money, add, subtract, multiply, percentage, convert
|
| 3 |
+
from .gateway import ApiGateway
|
| 4 |
+
from .jobs import JobManager
|
| 5 |
+
from .policy import Policy
|
| 6 |
+
from .providers import Provider, ProviderRegistry, ProviderResult
|
| 7 |
+
from .router import CapabilityRouter
|
| 8 |
+
from .engine import OrchestrationEngine
|
| 9 |
+
from .tooling import ToolExecutor
|
| 10 |
+
from .schemas import Capability, CapabilityRequest, Job, JobStatus, PrivacyMode, ToolSpec, UnifiedResult
|
| 11 |
+
|
| 12 |
+
__all__ = [
|
| 13 |
+
"ApiGateway", "Capability", "CapabilityRequest", "CapabilityRouter", "Job", "JobManager", "JobStatus", "OrchestrationEngine", "ToolExecutor",
|
| 14 |
+
"Money", "Policy", "PrivacyMode", "Provider", "ProviderRegistry", "ProviderResult", "ToolSpec", "UnifiedResult",
|
| 15 |
+
"add", "subtract", "multiply", "percentage", "convert",
|
| 16 |
+
"CapabilityUnavailable", "InvalidProviderResponse", "InvalidToolInput", "JobCancelled", "JobNotFound",
|
| 17 |
+
"PolicyDenied", "ProviderAuthenticationError", "ProviderRateLimited", "ProviderTimeout", "ProviderUnavailable",
|
| 18 |
+
]
|
cortex_ai/orchestration/engine.py
ADDED
|
@@ -0,0 +1,28 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""CORTEX Engine integration boundary; the model remains owned by CORTEX AI."""
|
| 2 |
+
from __future__ import annotations
|
| 3 |
+
from dataclasses import dataclass
|
| 4 |
+
from typing import Any
|
| 5 |
+
from .jobs import JobManager
|
| 6 |
+
from .policy import Policy
|
| 7 |
+
from .providers import ProviderRegistry
|
| 8 |
+
from .router import CapabilityRouter
|
| 9 |
+
from .schemas import Capability, UnifiedResult
|
| 10 |
+
|
| 11 |
+
@dataclass
|
| 12 |
+
class OrchestrationEngine:
|
| 13 |
+
router: CapabilityRouter
|
| 14 |
+
providers: ProviderRegistry
|
| 15 |
+
policy: Policy
|
| 16 |
+
jobs: JobManager
|
| 17 |
+
def plan(self, text: str, hints=()): return self.router.route(text, hints)
|
| 18 |
+
def execute(self, text: str, *, hints=(), preferred_provider: str | None = None, payload: dict[str, Any] | None = None) -> UnifiedResult | Any:
|
| 19 |
+
request = self.plan(text, hints)
|
| 20 |
+
if request.capabilities == (Capability.TEXT_GENERATION,): return UnifiedResult(text=text, provenance=[{"component": "cortex_ai", "mode": "model"}])
|
| 21 |
+
cap = next((c for c in request.capabilities if c not in (Capability.REASONING, Capability.STRUCTURED_DATA)), request.capabilities[0])
|
| 22 |
+
provider = self.providers.select(cap, preferred_provider)
|
| 23 |
+
self.policy.check_provider(provider.id, local=provider.local)
|
| 24 |
+
body = {"text": text, **(payload or {})}
|
| 25 |
+
if request.requires_async:
|
| 26 |
+
return self.jobs.submit(provider.id, cap.value, provider.generate, body)
|
| 27 |
+
result = provider.generate(body)
|
| 28 |
+
return UnifiedResult(text=result.output if isinstance(result.output, str) else "", structured_data=result.output if isinstance(result.output, dict) else None, provenance=[{"provider": result.provider, **result.metadata}])
|
cortex_ai/orchestration/errors.py
ADDED
|
@@ -0,0 +1,25 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Structured errors for CORTEX orchestration and provider boundaries."""
|
| 2 |
+
class CortexOrchestrationError(Exception):
|
| 3 |
+
category = "system_error"
|
| 4 |
+
class ProviderUnavailable(CortexOrchestrationError):
|
| 5 |
+
category = "provider_error"
|
| 6 |
+
class ProviderTimeout(CortexOrchestrationError):
|
| 7 |
+
category = "provider_error"
|
| 8 |
+
class ProviderAuthenticationError(CortexOrchestrationError):
|
| 9 |
+
category = "provider_error"
|
| 10 |
+
class ProviderRateLimited(CortexOrchestrationError):
|
| 11 |
+
category = "provider_error"
|
| 12 |
+
class InvalidToolInput(CortexOrchestrationError):
|
| 13 |
+
category = "user_error"
|
| 14 |
+
class InvalidProviderResponse(CortexOrchestrationError):
|
| 15 |
+
category = "provider_error"
|
| 16 |
+
class JobNotFound(CortexOrchestrationError):
|
| 17 |
+
category = "user_error"
|
| 18 |
+
class JobCancelled(CortexOrchestrationError):
|
| 19 |
+
category = "system_error"
|
| 20 |
+
class PolicyDenied(CortexOrchestrationError):
|
| 21 |
+
category = "policy_error"
|
| 22 |
+
class CapabilityUnavailable(CortexOrchestrationError):
|
| 23 |
+
category = "configuration_error"
|
| 24 |
+
|
| 25 |
+
__all__ = [name for name in globals() if not name.startswith("_")]
|
cortex_ai/orchestration/finance.py
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Deterministic financial tools; LLMs may explain results but never perform them."""
|
| 2 |
+
from __future__ import annotations
|
| 3 |
+
from decimal import Decimal, ROUND_HALF_UP
|
| 4 |
+
from dataclasses import dataclass
|
| 5 |
+
|
| 6 |
+
@dataclass(frozen=True)
|
| 7 |
+
class Money:
|
| 8 |
+
amount: Decimal
|
| 9 |
+
currency: str
|
| 10 |
+
def __post_init__(self):
|
| 11 |
+
if len(self.currency) != 3 or not self.currency.isalpha(): raise ValueError("currency must be a 3-letter ISO code")
|
| 12 |
+
def quantized(self) -> "Money": return Money(self.amount.quantize(Decimal("0.01"), rounding=ROUND_HALF_UP), self.currency.upper())
|
| 13 |
+
|
| 14 |
+
def add(a: Money, b: Money) -> Money:
|
| 15 |
+
if a.currency.upper() != b.currency.upper(): raise ValueError("currency mismatch; convert before arithmetic")
|
| 16 |
+
return Money(a.amount + b.amount, a.currency.upper()).quantized()
|
| 17 |
+
def subtract(a: Money, b: Money) -> Money:
|
| 18 |
+
if a.currency.upper() != b.currency.upper(): raise ValueError("currency mismatch; convert before arithmetic")
|
| 19 |
+
return Money(a.amount - b.amount, a.currency.upper()).quantized()
|
| 20 |
+
def multiply(a: Money, factor: Decimal | int | str) -> Money: return Money(a.amount * Decimal(str(factor)), a.currency.upper()).quantized()
|
| 21 |
+
def percentage(a: Money, rate: Decimal | int | str) -> Money: return multiply(a, Decimal(str(rate)) / 100)
|
| 22 |
+
def convert(a: Money, target_currency: str, rate: Decimal | int | str) -> Money: return Money(a.amount * Decimal(str(rate)), target_currency.upper()).quantized()
|
cortex_ai/orchestration/gateway.py
ADDED
|
@@ -0,0 +1,31 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Common external API gateway; secrets are read from environment, never logged."""
|
| 2 |
+
from __future__ import annotations
|
| 3 |
+
import os, time
|
| 4 |
+
from typing import Any
|
| 5 |
+
import httpx
|
| 6 |
+
from .errors import ProviderAuthenticationError, ProviderRateLimited, ProviderTimeout
|
| 7 |
+
|
| 8 |
+
class ApiGateway:
|
| 9 |
+
def __init__(self, *, timeout: float = 30.0, retries: int = 2, client: httpx.Client | None = None) -> None:
|
| 10 |
+
self.timeout, self.retries = timeout, retries
|
| 11 |
+
self.client = client or httpx.Client(timeout=timeout)
|
| 12 |
+
def bearer_headers(self, env_name: str) -> dict[str, str]:
|
| 13 |
+
token = os.getenv(env_name)
|
| 14 |
+
if not token: raise ProviderAuthenticationError(f"missing credential environment variable {env_name}")
|
| 15 |
+
return {"Authorization": f"Bearer {token}"}
|
| 16 |
+
def request(self, method: str, url: str, *, headers: dict[str, str] | None = None, **kwargs: Any) -> httpx.Response:
|
| 17 |
+
last: Exception | None = None
|
| 18 |
+
for attempt in range(self.retries + 1):
|
| 19 |
+
try:
|
| 20 |
+
response = self.client.request(method, url, headers=headers, **kwargs)
|
| 21 |
+
if response.status_code in (401, 403): raise ProviderAuthenticationError(f"provider authentication failed ({response.status_code})")
|
| 22 |
+
if response.status_code == 429: raise ProviderRateLimited("provider rate limit reached")
|
| 23 |
+
response.raise_for_status(); return response
|
| 24 |
+
except httpx.TimeoutException as exc:
|
| 25 |
+
last = ProviderTimeout("provider request timed out")
|
| 26 |
+
except (ProviderAuthenticationError, ProviderRateLimited): raise
|
| 27 |
+
except httpx.HTTPError as exc:
|
| 28 |
+
last = exc
|
| 29 |
+
if attempt < self.retries: time.sleep(0.2 * (2 ** attempt))
|
| 30 |
+
if isinstance(last, ProviderTimeout): raise last
|
| 31 |
+
raise RuntimeError("provider request failed after retries") from last
|
cortex_ai/orchestration/jobs.py
ADDED
|
@@ -0,0 +1,37 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Async job lifecycle abstraction for long-running multimodal operations."""
|
| 2 |
+
from __future__ import annotations
|
| 3 |
+
from concurrent.futures import Future, ThreadPoolExecutor
|
| 4 |
+
from dataclasses import replace
|
| 5 |
+
from uuid import uuid4
|
| 6 |
+
from .errors import JobCancelled, JobNotFound
|
| 7 |
+
from .schemas import Job, JobStatus, utcnow
|
| 8 |
+
|
| 9 |
+
class JobManager:
|
| 10 |
+
def __init__(self, max_workers: int = 4) -> None:
|
| 11 |
+
self._jobs: dict[str, Job] = {}
|
| 12 |
+
self._futures: dict[str, Future] = {}
|
| 13 |
+
self._executor = ThreadPoolExecutor(max_workers=max_workers, thread_name_prefix="cortex-job")
|
| 14 |
+
def submit(self, provider: str, job_type: str, fn, *args, **kwargs) -> Job:
|
| 15 |
+
job = Job(id=f"job_{uuid4().hex}", provider=provider, type=job_type)
|
| 16 |
+
self._jobs[job.id] = job
|
| 17 |
+
self._futures[job.id] = self._executor.submit(self._run, job.id, fn, args, kwargs)
|
| 18 |
+
return replace(job)
|
| 19 |
+
def _run(self, job_id, fn, args, kwargs):
|
| 20 |
+
job = self._jobs[job_id]; job.status = JobStatus.RUNNING; job.started_at = utcnow(); job.progress = 0.1
|
| 21 |
+
try:
|
| 22 |
+
job.result = fn(*args, **kwargs); job.progress = 1.0; job.status = JobStatus.COMPLETED
|
| 23 |
+
except Exception as exc:
|
| 24 |
+
job.error = f"{type(exc).__name__}: {exc}"; job.status = JobStatus.FAILED
|
| 25 |
+
finally: job.completed_at = utcnow()
|
| 26 |
+
def get(self, job_id: str) -> Job:
|
| 27 |
+
if job_id not in self._jobs: raise JobNotFound(f"job {job_id!r} not found")
|
| 28 |
+
return replace(self._jobs[job_id])
|
| 29 |
+
def cancel(self, job_id: str) -> Job:
|
| 30 |
+
job = self._jobs.get(job_id)
|
| 31 |
+
if job is None: raise JobNotFound(f"job {job_id!r} not found")
|
| 32 |
+
future = self._futures[job_id]
|
| 33 |
+
if job.status in (JobStatus.COMPLETED, JobStatus.FAILED): return replace(job)
|
| 34 |
+
if future.cancel(): job.status = JobStatus.CANCELLED; job.completed_at = utcnow()
|
| 35 |
+
else: raise JobCancelled(f"job {job_id!r} is already running")
|
| 36 |
+
return replace(job)
|
| 37 |
+
def shutdown(self) -> None: self._executor.shutdown(wait=False, cancel_futures=True)
|
cortex_ai/orchestration/policy.py
ADDED
|
@@ -0,0 +1,20 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Explicit privacy and permission policies for orchestration."""
|
| 2 |
+
from __future__ import annotations
|
| 3 |
+
from dataclasses import dataclass
|
| 4 |
+
from .errors import PolicyDenied
|
| 5 |
+
from .schemas import PrivacyMode, ToolSpec
|
| 6 |
+
|
| 7 |
+
@dataclass(frozen=True)
|
| 8 |
+
class Policy:
|
| 9 |
+
privacy_mode: PrivacyMode = PrivacyMode.APPROVED_EXTERNAL
|
| 10 |
+
approved_providers: frozenset[str] = frozenset()
|
| 11 |
+
permissions: frozenset[str] = frozenset({"read"})
|
| 12 |
+
def check_provider(self, provider_id: str, *, local: bool = False) -> None:
|
| 13 |
+
if self.privacy_mode == PrivacyMode.LOCAL_ONLY and not local:
|
| 14 |
+
raise PolicyDenied("external provider denied by local_only privacy mode")
|
| 15 |
+
if self.privacy_mode == PrivacyMode.APPROVED_EXTERNAL and self.approved_providers and provider_id not in self.approved_providers and not local:
|
| 16 |
+
raise PolicyDenied(f"provider {provider_id!r} is not approved")
|
| 17 |
+
def check_tool(self, spec: ToolSpec) -> None:
|
| 18 |
+
missing = spec.permissions - self.permissions
|
| 19 |
+
if missing:
|
| 20 |
+
raise PolicyDenied(f"tool {spec.name!r} requires permissions: {sorted(missing)}")
|
cortex_ai/orchestration/providers.py
ADDED
|
@@ -0,0 +1,51 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Provider contracts and registry; providers are optional and explicitly configured."""
|
| 2 |
+
from __future__ import annotations
|
| 3 |
+
from abc import ABC, abstractmethod
|
| 4 |
+
from dataclasses import dataclass, field
|
| 5 |
+
from typing import Any, Iterable
|
| 6 |
+
from .errors import CapabilityUnavailable, ProviderUnavailable
|
| 7 |
+
from .schemas import Capability
|
| 8 |
+
|
| 9 |
+
@dataclass(frozen=True)
|
| 10 |
+
class ProviderResult:
|
| 11 |
+
output: Any
|
| 12 |
+
provider: str
|
| 13 |
+
metadata: dict[str, Any] = field(default_factory=dict)
|
| 14 |
+
|
| 15 |
+
class Provider(ABC):
|
| 16 |
+
id: str
|
| 17 |
+
capabilities: frozenset[Capability]
|
| 18 |
+
local: bool = False
|
| 19 |
+
@abstractmethod
|
| 20 |
+
def health(self) -> bool: ...
|
| 21 |
+
@abstractmethod
|
| 22 |
+
def generate(self, request: dict[str, Any]) -> ProviderResult: ...
|
| 23 |
+
def submit(self, request: dict[str, Any]) -> str:
|
| 24 |
+
raise NotImplementedError(f"provider {self.id} does not support async jobs")
|
| 25 |
+
def get_status(self, job_id: str) -> dict[str, Any]:
|
| 26 |
+
raise NotImplementedError
|
| 27 |
+
def cancel(self, job_id: str) -> None:
|
| 28 |
+
raise NotImplementedError
|
| 29 |
+
|
| 30 |
+
class ProviderRegistry:
|
| 31 |
+
def __init__(self, providers: Iterable[Provider] = ()) -> None:
|
| 32 |
+
self._providers: dict[str, Provider] = {}
|
| 33 |
+
for provider in providers: self.register(provider)
|
| 34 |
+
def register(self, provider: Provider) -> None:
|
| 35 |
+
if not provider.id: raise ValueError("provider id is required")
|
| 36 |
+
self._providers[provider.id] = provider
|
| 37 |
+
def get(self, provider_id: str) -> Provider:
|
| 38 |
+
try: return self._providers[provider_id]
|
| 39 |
+
except KeyError: raise ProviderUnavailable(f"unknown provider {provider_id!r}") from None
|
| 40 |
+
def available(self, capability: Capability) -> list[Provider]:
|
| 41 |
+
return [p for p in self._providers.values() if capability in p.capabilities and p.health()]
|
| 42 |
+
def select(self, capability: Capability, preferred: str | None = None) -> Provider:
|
| 43 |
+
if preferred:
|
| 44 |
+
provider = self.get(preferred)
|
| 45 |
+
if capability not in provider.capabilities or not provider.health(): raise CapabilityUnavailable(f"provider {preferred!r} cannot serve {capability.value}")
|
| 46 |
+
return provider
|
| 47 |
+
candidates = self.available(capability)
|
| 48 |
+
if not candidates: raise CapabilityUnavailable(f"no healthy provider for {capability.value}")
|
| 49 |
+
return candidates[0]
|
| 50 |
+
def health(self) -> dict[str, bool]: return {p.id: p.health() for p in self._providers.values()}
|
| 51 |
+
def ids(self) -> list[str]: return sorted(self._providers)
|
cortex_ai/orchestration/router.py
ADDED
|
@@ -0,0 +1,38 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Capability detection for CORTEX requests."""
|
| 2 |
+
from __future__ import annotations
|
| 3 |
+
import re
|
| 4 |
+
from typing import Iterable
|
| 5 |
+
from .schemas import Capability, CapabilityRequest, PrivacyMode
|
| 6 |
+
|
| 7 |
+
class CapabilityRouter:
|
| 8 |
+
"""Small deterministic router; applications can extend keyword rules or pass hints."""
|
| 9 |
+
def __init__(self, rules: dict[Capability, Iterable[str]] | None = None) -> None:
|
| 10 |
+
self.rules = rules or {
|
| 11 |
+
Capability.VISION: ("image", "photo", "picture", "image", "photo"),
|
| 12 |
+
Capability.DOCUMENT_ANALYSIS: ("document", "pdf", "invoice", "facture"),
|
| 13 |
+
Capability.IMAGE_GENERATION: ("generate an image", "create an image", "génère une image"),
|
| 14 |
+
Capability.VIDEO_GENERATION: ("generate a video", "create a video", "génère une vidéo"),
|
| 15 |
+
Capability.AUDIO: ("audio", "voice", "speech", "son"),
|
| 16 |
+
Capability.WEB_SEARCH: ("search the web", "web search", "recherche sur le web"),
|
| 17 |
+
Capability.FILE_ANALYSIS: ("file", "attachment", "fichier", "pièce jointe"),
|
| 18 |
+
Capability.CALCULATION: ("calculate", "compute", "combien", "calcul", "total", "montant"),
|
| 19 |
+
Capability.CODE_GENERATION: ("code", "python", "javascript", "program", "fonction"),
|
| 20 |
+
Capability.STRUCTURED_DATA: ("json", "table", "structured", "tableau"),
|
| 21 |
+
Capability.REASONING: ("reason", "explain why", "analyse", "pourquoi"),
|
| 22 |
+
}
|
| 23 |
+
def route(self, text: str, hints: Iterable[str | Capability] = ()) -> CapabilityRequest:
|
| 24 |
+
lowered = text.lower()
|
| 25 |
+
found: list[Capability] = []
|
| 26 |
+
for hint in hints:
|
| 27 |
+
cap = hint if isinstance(hint, Capability) else Capability(hint)
|
| 28 |
+
if cap not in found: found.append(cap)
|
| 29 |
+
for cap, terms in self.rules.items():
|
| 30 |
+
if any(term.lower() in lowered for term in terms) and cap not in found:
|
| 31 |
+
found.append(cap)
|
| 32 |
+
if not found: found.append(Capability.TEXT_GENERATION)
|
| 33 |
+
if Capability.VISION in found and Capability.DOCUMENT_ANALYSIS not in found and any(x in lowered for x in ("document", "invoice", "facture")):
|
| 34 |
+
found.append(Capability.DOCUMENT_ANALYSIS)
|
| 35 |
+
requires_tool = any(c in found for c in (Capability.CALCULATION, Capability.WEB_SEARCH, Capability.FILE_ANALYSIS, Capability.VISION, Capability.DOCUMENT_ANALYSIS))
|
| 36 |
+
requires_async = any(c in found for c in (Capability.VIDEO_GENERATION, Capability.IMAGE_GENERATION, Capability.AUDIO))
|
| 37 |
+
privacy = PrivacyMode.LOCAL_ONLY if re.search(r"\b(secret|private|confidential|confidentielle?|sensible|sensible)\b", lowered) else PrivacyMode.APPROVED_EXTERNAL
|
| 38 |
+
return CapabilityRequest(tuple(found), requires_tool, requires_async, privacy)
|
cortex_ai/orchestration/schemas.py
ADDED
|
@@ -0,0 +1,78 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Typed contracts shared by routers, tools, providers, and API adapters."""
|
| 2 |
+
from __future__ import annotations
|
| 3 |
+
from dataclasses import dataclass, field
|
| 4 |
+
from datetime import datetime, timezone
|
| 5 |
+
from enum import Enum
|
| 6 |
+
from typing import Any, Mapping
|
| 7 |
+
|
| 8 |
+
class Capability(str, Enum):
|
| 9 |
+
TEXT_GENERATION = "text_generation"
|
| 10 |
+
REASONING = "reasoning"
|
| 11 |
+
CODE_GENERATION = "code_generation"
|
| 12 |
+
CALCULATION = "calculation"
|
| 13 |
+
WEB_SEARCH = "web_search"
|
| 14 |
+
FILE_ANALYSIS = "file_analysis"
|
| 15 |
+
VISION = "vision"
|
| 16 |
+
IMAGE_GENERATION = "image_generation"
|
| 17 |
+
VIDEO_GENERATION = "video_generation"
|
| 18 |
+
AUDIO = "audio"
|
| 19 |
+
DOCUMENT_ANALYSIS = "document_analysis"
|
| 20 |
+
STRUCTURED_DATA = "structured_data"
|
| 21 |
+
|
| 22 |
+
class PrivacyMode(str, Enum):
|
| 23 |
+
LOCAL_ONLY = "local_only"
|
| 24 |
+
APPROVED_EXTERNAL = "approved_external"
|
| 25 |
+
UNRESTRICTED = "unrestricted"
|
| 26 |
+
|
| 27 |
+
class JobStatus(str, Enum):
|
| 28 |
+
QUEUED = "queued"
|
| 29 |
+
RUNNING = "running"
|
| 30 |
+
COMPLETED = "completed"
|
| 31 |
+
FAILED = "failed"
|
| 32 |
+
CANCELLED = "cancelled"
|
| 33 |
+
|
| 34 |
+
def utcnow() -> datetime:
|
| 35 |
+
return datetime.now(timezone.utc)
|
| 36 |
+
|
| 37 |
+
@dataclass(frozen=True)
|
| 38 |
+
class CapabilityRequest:
|
| 39 |
+
capabilities: tuple[Capability, ...]
|
| 40 |
+
requires_tool: bool = False
|
| 41 |
+
requires_async_job: bool = False
|
| 42 |
+
privacy_mode: PrivacyMode = PrivacyMode.APPROVED_EXTERNAL
|
| 43 |
+
@property
|
| 44 |
+
def requires_async(self) -> bool:
|
| 45 |
+
"""Compatibility alias for early orchestration callers."""
|
| 46 |
+
return self.requires_async_job
|
| 47 |
+
|
| 48 |
+
@dataclass
|
| 49 |
+
class ToolSpec:
|
| 50 |
+
name: str
|
| 51 |
+
description: str
|
| 52 |
+
input_schema: dict[str, Any]
|
| 53 |
+
output_schema: dict[str, Any] = field(default_factory=lambda: {"type": "string"})
|
| 54 |
+
permissions: frozenset[str] = frozenset()
|
| 55 |
+
execution_mode: str = "sync"
|
| 56 |
+
timeout_seconds: float = 30.0
|
| 57 |
+
provider: str = "native"
|
| 58 |
+
|
| 59 |
+
@dataclass
|
| 60 |
+
class Job:
|
| 61 |
+
id: str
|
| 62 |
+
provider: str
|
| 63 |
+
type: str
|
| 64 |
+
status: JobStatus = JobStatus.QUEUED
|
| 65 |
+
created_at: datetime = field(default_factory=utcnow)
|
| 66 |
+
started_at: datetime | None = None
|
| 67 |
+
completed_at: datetime | None = None
|
| 68 |
+
progress: float = 0.0
|
| 69 |
+
result: Any = None
|
| 70 |
+
error: str | None = None
|
| 71 |
+
|
| 72 |
+
@dataclass
|
| 73 |
+
class UnifiedResult:
|
| 74 |
+
text: str = ""
|
| 75 |
+
structured_data: Mapping[str, Any] | None = None
|
| 76 |
+
calculations: list[Mapping[str, Any]] = field(default_factory=list)
|
| 77 |
+
artifacts: list[Mapping[str, Any]] = field(default_factory=list)
|
| 78 |
+
provenance: list[Mapping[str, Any]] = field(default_factory=list)
|
cortex_ai/orchestration/tooling.py
ADDED
|
@@ -0,0 +1,19 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Policy-aware wrapper around the existing CORTEX ToolRegistry."""
|
| 2 |
+
from __future__ import annotations
|
| 3 |
+
from typing import Any
|
| 4 |
+
from ..tools.registry import ToolRegistry, ToolError
|
| 5 |
+
from .errors import InvalidToolInput
|
| 6 |
+
from .policy import Policy
|
| 7 |
+
from .schemas import ToolSpec
|
| 8 |
+
|
| 9 |
+
class ToolExecutor:
|
| 10 |
+
def __init__(self, registry: ToolRegistry, policy: Policy | None = None) -> None:
|
| 11 |
+
self.registry, self.policy = registry, policy or Policy()
|
| 12 |
+
def spec(self, name: str) -> ToolSpec:
|
| 13 |
+
tool = self.registry.get(name)
|
| 14 |
+
return ToolSpec(name=tool.name, description=tool.description, input_schema=tool.parameters)
|
| 15 |
+
def execute(self, name: str, arguments: dict[str, Any] | str) -> str:
|
| 16 |
+
spec = self.spec(name)
|
| 17 |
+
self.policy.check_tool(spec)
|
| 18 |
+
try: return self.registry.call(name, arguments)
|
| 19 |
+
except ToolError as exc: raise InvalidToolInput(str(exc)) from exc
|
docs/orchestration.fr.md
ADDED
|
@@ -0,0 +1,34 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Fondation d'orchestration CORTEX
|
| 2 |
+
|
| 3 |
+
Cette couche complète le dépôt **CORTEX AI** sans le transformer en CORTEX Engine, IDE ou Cloud. Le modèle reste exposé par les adaptateurs existants ; l'orchestration fournit des contrats réutilisables pour l'intégration future.
|
| 4 |
+
|
| 5 |
+
## Composants
|
| 6 |
+
|
| 7 |
+
| Composant | Module | Responsabilité |
|
| 8 |
+
| --- | --- | --- |
|
| 9 |
+
| Capability Router | `cortex_ai/orchestration/router.py` | Détecte les capacités requises et le mode de confidentialité. |
|
| 10 |
+
| Provider Registry | `providers.py` | Enregistre, vérifie et sélectionne des providers interchangeables. |
|
| 11 |
+
| Policy | `policy.py` | Applique les modes `local_only`, `approved_external` et `unrestricted`, ainsi que les permissions d'outils. |
|
| 12 |
+
| Job Manager | `jobs.py` | Exécute les tâches longues dans un pool contrôlé et expose les états `queued`, `running`, `completed`, `failed` et `cancelled`. |
|
| 13 |
+
| API Gateway | `gateway.py` | Centralise les timeouts, retries, backoff et erreurs HTTP ; les identifiants viennent exclusivement de l'environnement. |
|
| 14 |
+
| Finance | `finance.py` | Effectue les calculs avec `Decimal`, notamment pour USD et GNF, sans dépendre du modèle. |
|
| 15 |
+
| Tool Executor | `tooling.py` | Réutilise le `ToolRegistry` existant après validation et contrôle de permissions. |
|
| 16 |
+
|
| 17 |
+
## Exemple
|
| 18 |
+
|
| 19 |
+
```python
|
| 20 |
+
from cortex_ai.orchestration import CapabilityRouter
|
| 21 |
+
|
| 22 |
+
request = CapabilityRouter().route(
|
| 23 |
+
"Analyse cette facture confidentielle et génère une vidéo"
|
| 24 |
+
)
|
| 25 |
+
print(request.capabilities)
|
| 26 |
+
print(request.requires_async_job)
|
| 27 |
+
print(request.privacy_mode)
|
| 28 |
+
```
|
| 29 |
+
|
| 30 |
+
Les providers externes ne sont pas activés implicitement. Une application doit les enregistrer dans `ProviderRegistry`, configurer les secrets par variables d'environnement, puis appliquer une `Policy` adaptée avant exécution.
|
| 31 |
+
|
| 32 |
+
## Limites actuelles
|
| 33 |
+
|
| 34 |
+
La fondation ne branche aucun fournisseur d'image, de vidéo, d'audio ou de recherche web concret : ces intégrations dépendent de choix de produit, de credentials et de contrats externes. Le checkpoint complet n'est pas chargé pendant les tests, car il pèse environ 893 Go et nécessite une infrastructure spécialisée. Les contrats sont donc testés avec des providers déterministes et locaux, sans prétendre mesurer les performances du modèle.
|
tests/test_orchestration.py
ADDED
|
@@ -0,0 +1,42 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from decimal import Decimal
|
| 2 |
+
import time
|
| 3 |
+
import pytest
|
| 4 |
+
from cortex_ai.orchestration import *
|
| 5 |
+
from cortex_ai.orchestration.errors import PolicyDenied
|
| 6 |
+
|
| 7 |
+
class EchoProvider(Provider):
|
| 8 |
+
id = "echo"
|
| 9 |
+
capabilities = frozenset({Capability.VISION, Capability.VIDEO_GENERATION})
|
| 10 |
+
local = True
|
| 11 |
+
def health(self): return True
|
| 12 |
+
def generate(self, request): return ProviderResult({"echo": request["text"]}, self.id, {"test": True})
|
| 13 |
+
|
| 14 |
+
def test_router_detects_mixed_request_and_privacy():
|
| 15 |
+
req = CapabilityRouter().route("Analyse cette facture confidentielle et génère une vidéo")
|
| 16 |
+
assert Capability.DOCUMENT_ANALYSIS in req.capabilities
|
| 17 |
+
assert Capability.VIDEO_GENERATION in req.capabilities
|
| 18 |
+
assert req.requires_async_job is True
|
| 19 |
+
assert req.requires_async is True
|
| 20 |
+
assert req.privacy_mode == PrivacyMode.LOCAL_ONLY
|
| 21 |
+
|
| 22 |
+
def test_registry_selects_provider_and_engine_returns_job_for_long_task():
|
| 23 |
+
jobs = JobManager()
|
| 24 |
+
engine = OrchestrationEngine(CapabilityRouter(), ProviderRegistry([EchoProvider()]), Policy(), jobs)
|
| 25 |
+
job = engine.execute("generate a video", preferred_provider="echo")
|
| 26 |
+
assert job.provider == "echo"
|
| 27 |
+
for _ in range(20):
|
| 28 |
+
if jobs.get(job.id).status == JobStatus.COMPLETED: break
|
| 29 |
+
time.sleep(0.01)
|
| 30 |
+
assert jobs.get(job.id).result.output["echo"] == "generate a video"
|
| 31 |
+
jobs.shutdown()
|
| 32 |
+
|
| 33 |
+
def test_local_only_policy_denies_external_provider():
|
| 34 |
+
class External(EchoProvider):
|
| 35 |
+
id = "external"; local = False
|
| 36 |
+
with pytest.raises(PolicyDenied):
|
| 37 |
+
OrchestrationEngine(CapabilityRouter(), ProviderRegistry([External()]), Policy(PrivacyMode.LOCAL_ONLY), JobManager()).execute("describe this image", preferred_provider="external")
|
| 38 |
+
|
| 39 |
+
def test_money_is_decimal_and_supports_gnf():
|
| 40 |
+
total = add(Money(Decimal("10.005"), "USD"), Money(Decimal("2.00"), "USD"))
|
| 41 |
+
assert total == Money(Decimal("12.01"), "USD")
|
| 42 |
+
assert convert(Money(Decimal("100"), "USD"), "GNF", Decimal("8500")).amount == Decimal("850000.00")
|
tests/test_training.py
CHANGED
|
@@ -1,6 +1,7 @@
|
|
| 1 |
"""Tests for the fine-tuning dataset pipeline and configuration."""
|
| 2 |
|
| 3 |
import json
|
|
|
|
| 4 |
|
| 5 |
import pytest
|
| 6 |
|
|
@@ -72,7 +73,7 @@ def test_load_jsonl_reports_bad_json(tmp_path):
|
|
| 72 |
|
| 73 |
|
| 74 |
def test_dataset_stats():
|
| 75 |
-
examples = load_jsonl(
|
| 76 |
stats = dataset_stats(examples)
|
| 77 |
assert stats["exemples"] == 10
|
| 78 |
assert stats["repartition_roles"]["assistant"] == 10
|
|
@@ -80,7 +81,7 @@ def test_dataset_stats():
|
|
| 80 |
|
| 81 |
|
| 82 |
def test_encoding_uses_the_real_encoder():
|
| 83 |
-
examples = load_jsonl(
|
| 84 |
prompts = list(iter_encoded(examples, thinking_mode="chat"))
|
| 85 |
assert len(prompts) == len(examples)
|
| 86 |
assert all(isinstance(p, str) and p for p in prompts)
|
|
|
|
| 1 |
"""Tests for the fine-tuning dataset pipeline and configuration."""
|
| 2 |
|
| 3 |
import json
|
| 4 |
+
from pathlib import Path
|
| 5 |
|
| 6 |
import pytest
|
| 7 |
|
|
|
|
| 73 |
|
| 74 |
|
| 75 |
def test_dataset_stats():
|
| 76 |
+
examples = load_jsonl(Path(__file__).parents[1] / "data" / "cortex_sft.jsonl")
|
| 77 |
stats = dataset_stats(examples)
|
| 78 |
assert stats["exemples"] == 10
|
| 79 |
assert stats["repartition_roles"]["assistant"] == 10
|
|
|
|
| 81 |
|
| 82 |
|
| 83 |
def test_encoding_uses_the_real_encoder():
|
| 84 |
+
examples = load_jsonl(Path(__file__).parents[1] / "data" / "cortex_sft.jsonl")
|
| 85 |
prompts = list(iter_encoded(examples, thinking_mode="chat"))
|
| 86 |
assert len(prompts) == len(examples)
|
| 87 |
assert all(isinstance(p, str) and p for p in prompts)
|