Spaces:
Paused

yaz / src /core /intelligence /models.py
anaselamr's picture
fix(collaboration): production-ready collaboration fixes — all 19 engines
0743ddc
Raw History Blame Contribute Delete
16.2 kB
"""
YAZ Intelligence Registry — Creator Profiles & Intelligence Classification
Extends the Tool Registry to support the "Intelligence" concept:
- Intelligence = Domain expertise encoded as a composable tool
- Creator = Practitioner who builds intelligences from their practice
- Dual Licensing = Open (free) for learning/public, Licensed for profit
Architecture:
Creator builds Intelligence → Publishes to Marketplace
→ Learners/Public get it free (AGPL)
→ Private entities license it (Commercial)
→ Anyone can fork it to build their own variant
First Creator: Dr. Anass Elamrani — Surgio (Surgical Intelligence)
Version: 1.0.0
Sprint: 40
Standards: AGPL-3.0 (open), Commercial (licensed)
"""
from datetime import UTC, datetime, timezone
from decimal import Decimal
from enum import Enum
from typing import Any, Dict, List, Optional
from uuid import UUID, uuid4
from pydantic import BaseModel, ConfigDict
from pydantic import Field as PydanticField
from sqlmodel import JSON, Column, Field, SQLModel
# ============================================================================
# ENUMERATIONS
# ============================================================================
class IntelligenceClass(str, Enum):
"""
Classification of intelligence by domain expertise.
An intelligence is a tool that encodes deep domain knowledge
into structured workflows, protocols, and decision support.
"""
SURGICAL = "surgical" # Surgical workflows, OR management
CLINICAL = "clinical" # Patient care, diagnosis, treatment
LABORATORY = "laboratory" # Lab workflows, QC, analysis
PHARMACEUTICAL = "pharmaceutical" # Drug management, interactions
EMERGENCY = "emergency" # Emergency protocols, triage
RADIOLOGY = "radiology" # Imaging workflows
ANESTHESIA = "anesthesia" # Anesthesia protocols
NURSING = "nursing" # Nursing workflows
ADMINISTRATIVE = "administrative" # Hospital operations
EDUCATIONAL = "educational" # Training, competency
LOGISTICS = "logistics" # Supply chain, inventory
FINANCIAL = "financial" # Billing, insurance
RESEARCH = "research" # Clinical research
FIELD_OPS = "field_ops" # Community health, field clinics
CUSTOM = "custom" # User-defined
class IntelligenceLevel(str, Enum):
"""
Depth of domain expertise encoded in the intelligence.
"""
STARTER = "starter" # Basic workflows, simple checklists
PRACTITIONER = "practitioner" # Standard clinical workflows
EXPERT = "expert" # Advanced protocols, analytics, decision support
SPECIALIST = "specialist" # Sub-specialty depth, research-grade
class CreatorVerification(str, Enum):
"""Creator verification levels"""
UNVERIFIED = "unverified"
EMAIL_VERIFIED = "email_verified"
CREDENTIAL_VERIFIED = "credential_verified" # Medical license confirmed
PLATFORM_VERIFIED = "platform_verified" # YAZ team verified
class LicenseModel(str, Enum):
"""Dual licensing models for intelligences"""
OPEN_ONLY = "open_only" # Free for everyone, no commercial tier
DUAL = "dual" # Open for public, licensed for profit
COMMERCIAL_ONLY = "commercial_only" # Paid only
CUSTOM = "custom" # Custom licensing arrangement
# ============================================================================
# CREATOR PROFILE
# ============================================================================
class CreatorProfile(SQLModel, table=True):
"""
Creator profile — practitioners who build intelligences.
A Creator is a domain expert (surgeon, pharmacist, lab scientist, etc.)
who encodes their expertise into tools on the YAZ platform.
First Creator: Dr. Anass Elamrani (Surgio — Surgical Intelligence)
Creators can:
- Build intelligences from their practice
- Publish them free for learners and public institutions
- License them for private/for-profit entities
- Fork existing intelligences to create variants
- Earn revenue from commercial licenses
Security: No PHI stored. Public profile data only.
"""
__tablename__ = "creator_profiles"
__table_args__ = {"schema": "platform", "extend_existing": True}
# Identity
id: UUID = Field(default_factory=uuid4, primary_key=True)
user_id: UUID = Field(unique=True, index=True, description="Platform user ID")
tenant_id: UUID = Field(index=True, description="Creator's home tenant")
# Public Identity
slug: str = Field(max_length=100, unique=True, index=True)
display_name: str = Field(max_length=200)
title: str | None = Field(default=None, max_length=300)
bio: str | None = Field(default=None, max_length=3000)
philosophy: str | None = Field(default=None, max_length=2000)
# Professional Info
specialties: list[str] = Field(default_factory=list, sa_column=Column(JSON))
credentials: str | None = Field(default=None, max_length=500)
institution: str | None = Field(default=None, max_length=300)
country: str | None = Field(default=None, max_length=100)
language: str = Field(default="en", max_length=10)
# Contact & Links
contact_email: str | None = Field(default=None, max_length=300)
website: str | None = Field(default=None, max_length=500)
profile_image_url: str | None = Field(default=None, max_length=500)
# Verification
verification_level: CreatorVerification = Field(default=CreatorVerification.UNVERIFIED)
verified_at: datetime | None = Field(default=None)
verified_by: UUID | None = Field(default=None)
# Portfolio Stats (aggregated)
intelligence_count: int = Field(default=0)
total_installs: int = Field(default=0)
total_forks: int = Field(default=0)
total_cases_powered: int = Field(default=0)
average_rating: Decimal = Field(default=Decimal("0.0"))
# Revenue (from licensed intelligences)
total_earnings: Decimal = Field(default=Decimal("0.0"))
pending_payout: Decimal = Field(default=Decimal("0.0"))
payout_method: str | None = Field(default=None, max_length=50)
# Timestamps
created_at: datetime = Field(default_factory=lambda: datetime.now(UTC))
updated_at: datetime = Field(default_factory=lambda: datetime.now(UTC))
def to_dict_public(self) -> dict[str, Any]:
"""Public-facing creator profile (no revenue details)."""
return {
"id": str(self.id),
"slug": self.slug,
"display_name": self.display_name,
"title": self.title,
"bio": self.bio,
"philosophy": self.philosophy,
"specialties": self.specialties,
"credentials": self.credentials,
"institution": self.institution,
"country": self.country,
"language": self.language,
"website": self.website,
"profile_image_url": self.profile_image_url,
"verification_level": self.verification_level.value,
"intelligence_count": self.intelligence_count,
"total_installs": self.total_installs,
"total_forks": self.total_forks,
"average_rating": float(self.average_rating),
}
def to_dict_owner(self) -> dict[str, Any]:
"""Full profile for the creator themselves (includes revenue)."""
data = self.to_dict_public()
data.update(
{
"total_cases_powered": self.total_cases_powered,
"total_earnings": float(self.total_earnings),
"pending_payout": float(self.pending_payout),
"payout_method": self.payout_method,
}
)
return data
# ============================================================================
# INTELLIGENCE METADATA (extends Tool)
# ============================================================================
class IntelligenceMetadata(SQLModel, table=True):
"""
Intelligence metadata — extends a Tool with intelligence classification.
This is a 1:1 extension of the Tool entity in core.tools.models.
When a Tool is classified as an "intelligence", this metadata defines
its expertise level, knowledge base, and licensing model.
Architecture:
Tool (core.tools.models) ← base entity
IntelligenceMetadata ← intelligence-specific extension
An Intelligence is more than a tool:
- It encodes domain expertise (not just UI/workflows)
- It has a creator with verified credentials
- It follows dual licensing (open + commercial)
- It can be forked, extended, and specialized
"""
__tablename__ = "intelligence_metadata"
__table_args__ = {"schema": "platform", "extend_existing": True}
id: UUID = Field(default_factory=uuid4, primary_key=True)
slug: str = Field(max_length=100, index=True, default="", description="URL-friendly identifier")
name: str = Field(max_length=200, default="", description="Human-readable name")
tool_id: UUID = Field(unique=True, index=True, description="FK to platform.tools")
creator_id: UUID = Field(index=True, description="FK to creator_profiles")
# Intelligence Classification
intelligence_class: IntelligenceClass = Field(index=True)
intelligence_level: IntelligenceLevel = Field(default=IntelligenceLevel.PRACTITIONER)
# Knowledge Base
knowledge_domains: list[str] = Field(
default_factory=list,
sa_column=Column(JSON),
description="Specific knowledge areas (e.g., 'visceral_surgery', 'laparoscopy')",
)
clinical_standards: list[str] = Field(
default_factory=list,
sa_column=Column(JSON),
description="Standards implemented (e.g., 'WHO SSC 2.0', 'ASA Classification')",
)
protocols_count: int = Field(default=0)
checklists_count: int = Field(default=0)
algorithms_count: int = Field(default=0)
# Licensing Model
license_model: LicenseModel = Field(default=LicenseModel.DUAL)
open_license: str = Field(default="AGPL-3.0", max_length=50)
commercial_license: str | None = Field(default="Commercial License", max_length=100)
# Open License Details
open_eligible: list[str] = Field(
default_factory=lambda: [
"Residents and trainees",
"Medical students",
"Public hospitals",
"University hospitals",
"Non-profit organizations",
"NGOs and humanitarian missions",
"Academic research institutions",
],
sa_column=Column(JSON),
)
# Fork & Derivative Info
is_fork: bool = Field(default=False)
forked_from_id: UUID | None = Field(default=None)
fork_count: int = Field(default=0)
allows_forking: bool = Field(default=True)
# Quality & Validation
peer_reviewed: bool = Field(default=False)
clinically_validated: bool = Field(default=False)
validation_notes: str | None = Field(default=None, max_length=2000)
# Timestamps
created_at: datetime = Field(default_factory=lambda: datetime.now(UTC))
updated_at: datetime = Field(default_factory=lambda: datetime.now(UTC))
def to_dict(self) -> dict[str, Any]:
return {
"id": str(self.id),
"slug": self.slug,
"name": self.name,
"tool_id": str(self.tool_id),
"creator_id": str(self.creator_id),
"intelligence_class": self.intelligence_class.value,
"intelligence_level": self.intelligence_level.value,
"knowledge_domains": self.knowledge_domains,
"clinical_standards": self.clinical_standards,
"license_model": self.license_model.value,
"open_license": self.open_license,
"is_fork": self.is_fork,
"fork_count": self.fork_count,
"peer_reviewed": self.peer_reviewed,
"clinically_validated": self.clinically_validated,
}
# ============================================================================
# PYDANTIC SCHEMAS
# ============================================================================
class CreatorProfileCreate(BaseModel):
"""Create a new creator profile."""
slug: str = PydanticField(..., min_length=3, max_length=100)
display_name: str = PydanticField(..., min_length=2, max_length=200)
title: str | None = PydanticField(None, max_length=300)
bio: str | None = PydanticField(None, max_length=3000)
philosophy: str | None = PydanticField(None, max_length=2000)
specialties: list[str] = PydanticField(default_factory=list)
credentials: str | None = PydanticField(None, max_length=500)
institution: str | None = PydanticField(None, max_length=300)
country: str | None = PydanticField(None, max_length=100)
language: str = PydanticField("en", max_length=10)
contact_email: str | None = PydanticField(None, max_length=300)
website: str | None = PydanticField(None, max_length=500)
model_config = ConfigDict(
json_schema_extra={
"examples": [
{
"slug": "dr-anass-elamrani",
"display_name": "Dr. Anass Elamrani",
"title": "Chirurgien Viscéral & Digestif",
"specialties": ["Visceral Surgery", "Digestive Surgery", "Laparoscopy"],
"country": "Morocco",
"language": "fr",
}
]
}
)
class CreatorProfileResponse(BaseModel):
"""Public creator profile response."""
id: UUID
slug: str
display_name: str
title: str | None
bio: str | None
philosophy: str | None
specialties: list[str]
credentials: str | None
institution: str | None
country: str | None
language: str
website: str | None
profile_image_url: str | None
verification_level: CreatorVerification
intelligence_count: int
total_installs: int
total_forks: int
average_rating: float
created_at: datetime
model_config = ConfigDict(from_attributes=True)
class IntelligenceCreate(BaseModel):
"""Register a tool as an intelligence."""
tool_id: UUID
intelligence_class: IntelligenceClass
intelligence_level: IntelligenceLevel = IntelligenceLevel.PRACTITIONER
knowledge_domains: list[str] = PydanticField(default_factory=list)
clinical_standards: list[str] = PydanticField(default_factory=list)
license_model: LicenseModel = LicenseModel.DUAL
open_license: str = PydanticField("AGPL-3.0", max_length=50)
allows_forking: bool = True
model_config = ConfigDict(
json_schema_extra={
"examples": [
{
"tool_id": "00000000-0000-0000-0000-000000000001",
"intelligence_class": "surgical",
"intelligence_level": "expert",
"knowledge_domains": ["visceral_surgery", "digestive_surgery", "laparoscopy"],
"clinical_standards": ["WHO SSC 2.0", "ASA Classification", "ERAS"],
"license_model": "dual",
}
]
}
)
class IntelligenceResponse(BaseModel):
"""Intelligence metadata response."""
id: UUID
tool_id: UUID
creator_id: UUID
intelligence_class: IntelligenceClass
intelligence_level: IntelligenceLevel
knowledge_domains: list[str]
clinical_standards: list[str]
license_model: LicenseModel
open_license: str
is_fork: bool
fork_count: int
allows_forking: bool
peer_reviewed: bool
clinically_validated: bool
created_at: datetime
model_config = ConfigDict(from_attributes=True)
# ============================================================================
# EXPORTS
# ============================================================================
__all__ = [
# Enums
"IntelligenceClass",
"IntelligenceLevel",
"CreatorVerification",
"LicenseModel",
# Models
"CreatorProfile",
"IntelligenceMetadata",
# Schemas
"CreatorProfileCreate",
"CreatorProfileResponse",
"IntelligenceCreate",
"IntelligenceResponse",
]