Download scripts/generators/create_tool.py from anaselamr/yaz: direct link, hf CLI and curl.
- Browser
- Download file 19.8 kB
-
https://huggingface.co/spaces/anaselamr/yaz/resolve/main/scripts/generators/create_tool.py
- Command line
-
hf download hf://spaces/anaselamr/yaz/scripts/generators/create_tool.py
-
curl -L -o create_tool.py https://huggingface.co/spaces/anaselamr/yaz/resolve/main/scripts/generators/create_tool.py
19.8 kB
| #!/usr/bin/env python3 | |
| """ | |
| Tool Generator - Create standardized tool structure | |
| This script generates a complete tool structure with: | |
| - Models (SQLModel with TenantMixin, TimestampMixin) | |
| - Schemas (Pydantic with OpenAPI examples) | |
| - Routes (FastAPI with RBAC, rate limiting) | |
| - Services (Business logic with BaseService inheritance) | |
| - Adapters (Event-driven wrappers) | |
| - Events (Domain event definitions) | |
| - Tests (85%+ coverage scaffolding) | |
| Usage: | |
| python scripts/generators/create_tool.py \\ | |
| --name mednote \\ | |
| --display-name "MedNote (Clinical Documentation)" \\ | |
| --category clinical \\ | |
| --standards "HL7 FHIR,21 CFR Part 11" \\ | |
| --description "Electronic clinical documentation" | |
| Author: Platform Architecture Team | |
| Date: December 28, 2025 | |
| Version: 2.0 | |
| """ | |
| import os | |
| import argparse | |
| from pathlib import Path | |
| from datetime import datetime | |
| from typing import List | |
| # ============================================================================ | |
| # TEMPLATES | |
| # ============================================================================ | |
| INIT_TEMPLATE = '''""" | |
| {display_name} Tool Module | |
| Auto-generated on {timestamp} | |
| Category: {category} | |
| Standards: {standards} | |
| This module provides {description}. | |
| """ | |
| from .routes import router | |
| from .models import * | |
| from .schemas import * | |
| __all__ = ["router"] | |
| ''' | |
| MODELS_TEMPLATE = '''""" | |
| {display_name} - Domain Models | |
| Clinical Context: {description} | |
| Standards: {standards} | |
| Performance: <100ms CRUD operations (p95) | |
| """ | |
| from __future__ import annotations | |
| from datetime import datetime | |
| from typing import Optional, List | |
| from uuid import UUID, uuid4 | |
| from sqlmodel import SQLModel, Field, Relationship | |
| from sqlalchemy import String, Text, JSON | |
| from sqlalchemy.dialects.postgresql import UUID as PGUUID | |
| from core.database.mixins import TenantMixin, TimestampMixin, SoftDeleteMixin | |
| class {entity_class}(TenantMixin, TimestampMixin, SoftDeleteMixin, table=True): | |
| """ | |
| {entity_class} domain model | |
| Clinical Context: | |
| {description} | |
| Standards Compliance: | |
| {standards_list} | |
| Performance Targets: | |
| - CREATE: <100ms p95 | |
| - READ: <50ms p95 | |
| - UPDATE: <100ms p95 | |
| - DELETE: <50ms p95 (soft delete) | |
| Security: | |
| - PHI: {phi_protected} | |
| - Audit: YES (all operations logged) | |
| - Encryption: AES-256 at rest | |
| Multi-Tenancy: | |
| - Schema: {name}.{table_name} | |
| - Isolation: STRICT (tenant_id required on all queries) | |
| """ | |
| __tablename__ = "{table_name}" | |
| __table_args__ = {{ | |
| "schema": "{name}", | |
| "comment": "{entity_class} records" | |
| }} | |
| # Primary Key | |
| id: UUID = Field( | |
| default_factory=uuid4, | |
| primary_key=True, | |
| sa_column_kwargs={{"type_": PGUUID(as_uuid=True)}}, | |
| description="Unique identifier" | |
| ) | |
| # Domain Fields (customize these) | |
| name: str = Field( | |
| ..., | |
| min_length=1, | |
| max_length=255, | |
| sa_column_kwargs={{"nullable": False}}, | |
| description="{entity_class} name" | |
| ) | |
| category: Optional[str] = Field( | |
| default=None, | |
| max_length=100, | |
| description="Category for grouping" | |
| ) | |
| metadata_: dict = Field( | |
| default_factory=dict, | |
| sa_column=JSON, | |
| description="Flexible metadata storage" | |
| ) | |
| def to_dict_safe(self) -> dict: | |
| """Convert to dictionary without PHI fields.""" | |
| return {{ | |
| "id": str(self.id), | |
| "tenant_id": str(self.tenant_id), | |
| "category": self.category, | |
| "created_at": self.created_at.isoformat(), | |
| "updated_at": self.updated_at.isoformat() | |
| }} | |
| def __repr__(self) -> str: | |
| """String representation without PHI.""" | |
| return f"<{{self.__class__.__name__}}(id={{self.id}}, tenant={{self.tenant_id}})>" | |
| ''' | |
| SCHEMAS_TEMPLATE = '''""" | |
| {display_name} - API Schemas | |
| Request/response models for {name} API endpoints. | |
| """ | |
| from __future__ import annotations | |
| from datetime import datetime | |
| from typing import Optional, List | |
| from uuid import UUID | |
| from pydantic import BaseModel, Field, ConfigDict, field_validator | |
| class Create{entity_class}Request(BaseModel): | |
| """ | |
| Create {entity_class} request | |
| Clinical Context: {description} | |
| Standards: {standards} | |
| Performance: <200ms p95 (API endpoint) | |
| Security: RBAC role:CLINICIAN, audit_logging:yes, PHI:{phi_protected} | |
| """ | |
| name: str = Field( | |
| ..., | |
| min_length=1, | |
| max_length=255, | |
| description="{entity_class} name with clinical context" | |
| ) | |
| category: Optional[str] = Field( | |
| default=None, | |
| max_length=100, | |
| description="Category for grouping" | |
| ) | |
| metadata_: dict = Field( | |
| default_factory=dict, | |
| description="Additional metadata" | |
| ) | |
| model_config = ConfigDict( | |
| json_schema_extra={{ | |
| "examples": [{{ | |
| "name": "Example {entity_class}", | |
| "category": "clinical", | |
| "metadata_": {{"key": "value"}} | |
| }}] | |
| }} | |
| ) | |
| class {entity_class}Response(BaseModel): | |
| """ | |
| {entity_class} response model | |
| """ | |
| id: UUID | |
| tenant_id: UUID | |
| name: str | |
| category: Optional[str] | |
| metadata_: dict | |
| created_at: datetime | |
| updated_at: datetime | |
| created_by: Optional[UUID] | |
| updated_by: Optional[UUID] | |
| model_config = ConfigDict(from_attributes=True) | |
| class Update{entity_class}Request(BaseModel): | |
| """ | |
| Update {entity_class} request (partial update) | |
| """ | |
| name: Optional[str] = Field( | |
| default=None, | |
| min_length=1, | |
| max_length=255 | |
| ) | |
| category: Optional[str] = Field( | |
| default=None, | |
| max_length=100 | |
| ) | |
| metadata_: Optional[dict] = None | |
| class List{entity_class}Response(BaseModel): | |
| """ | |
| Paginated list of {entity_class} records | |
| """ | |
| items: List[{entity_class}Response] | |
| total: int | |
| page: int | |
| page_size: int | |
| has_more: bool | |
| ''' | |
| ROUTES_TEMPLATE = '''""" | |
| {display_name} - API Routes | |
| RESTful API endpoints for {name} tool. | |
| """ | |
| from __future__ import annotations | |
| from typing import Optional, List | |
| from uuid import UUID | |
| from fastapi import APIRouter, Depends, HTTPException, Query | |
| from sqlalchemy.ext.asyncio import AsyncSession | |
| from core.database import get_db_session | |
| from core.auth.dependencies import get_current_user, require_permission | |
| from core.multitenancy.tenant import tenant_context | |
| from core.models.user import User | |
| from .schemas import ( | |
| Create{entity_class}Request, | |
| {entity_class}Response, | |
| Update{entity_class}Request, | |
| List{entity_class}Response | |
| ) | |
| from .services.{name}_service import {entity_class}Service | |
| router = APIRouter( | |
| prefix="/api/v1/{name}", | |
| tags=["{display_name}"] | |
| ) | |
| @router.post("/{plural}", response_model={entity_class}Response, status_code=201) | |
| async def create_{name}( | |
| data: Create{entity_class}Request, | |
| session: AsyncSession = Depends(get_session), | |
| current_user: User = Depends(get_current_user), | |
| _: None = Depends(require_permission("{name}:{plural}:create")) | |
| ): | |
| """ | |
| Create new {entity_class} | |
| Clinical Context: {description} | |
| Performance: <200ms p95 | |
| Security: RBAC role:CLINICIAN | |
| """ | |
| service = {entity_class}Service(session) | |
| result = await service.create( | |
| data=data.model_dump(), | |
| tenant_id=tenant_context.tenant_id, | |
| user_id=current_user.id | |
| ) | |
| return result | |
| @router.get("/{plural}", response_model=List{entity_class}Response) | |
| async def list_{plural}( | |
| page: int = Query(1, ge=1, description="Page number"), | |
| page_size: int = Query(50, ge=1, le=1000, description="Items per page"), | |
| category: Optional[str] = Query(None, description="Filter by category"), | |
| session: AsyncSession = Depends(get_session), | |
| current_user: User = Depends(get_current_user), | |
| _: None = Depends(require_permission("{name}:{plural}:read")) | |
| ): | |
| """ | |
| List {entity_class} records with pagination | |
| Performance: <200ms p95 for 100 records | |
| """ | |
| service = {entity_class}Service(session) | |
| result = await service.list_paginated( | |
| tenant_id=tenant_context.tenant_id, | |
| page=page, | |
| page_size=page_size, | |
| category=category | |
| ) | |
| return result | |
| @router.get("/{plural}/{{item_id}}", response_model={entity_class}Response) | |
| async def get_{name}( | |
| item_id: UUID, | |
| session: AsyncSession = Depends(get_session), | |
| current_user: User = Depends(get_current_user), | |
| _: None = Depends(require_permission("{name}:{plural}:read")) | |
| ): | |
| """ | |
| Get {entity_class} by ID | |
| Performance: <100ms p95 | |
| """ | |
| service = {entity_class}Service(session) | |
| result = await service.get_by_id( | |
| item_id=item_id, | |
| tenant_id=tenant_context.tenant_id | |
| ) | |
| if not result: | |
| raise HTTPException(status_code=404, detail="{entity_class} not found") | |
| return result | |
| @router.patch("/{plural}/{{item_id}}", response_model={entity_class}Response) | |
| async def update_{name}( | |
| item_id: UUID, | |
| data: Update{entity_class}Request, | |
| session: AsyncSession = Depends(get_session), | |
| current_user: User = Depends(get_current_user), | |
| _: None = Depends(require_permission("{name}:{plural}:update")) | |
| ): | |
| """ | |
| Update {entity_class} | |
| Performance: <200ms p95 | |
| """ | |
| service = {entity_class}Service(session) | |
| result = await service.update( | |
| item_id=item_id, | |
| data=data.model_dump(exclude_unset=True), | |
| tenant_id=tenant_context.tenant_id, | |
| user_id=current_user.id | |
| ) | |
| if not result: | |
| raise HTTPException(status_code=404, detail="{entity_class} not found") | |
| return result | |
| @router.delete("/{plural}/{{item_id}}", status_code=204) | |
| async def delete_{name}( | |
| item_id: UUID, | |
| session: AsyncSession = Depends(get_session), | |
| current_user: User = Depends(get_current_user), | |
| _: None = Depends(require_permission("{name}:{plural}:delete")) | |
| ): | |
| """ | |
| Delete {entity_class} (soft delete) | |
| Performance: <100ms p95 | |
| """ | |
| service = {entity_class}Service(session) | |
| await service.delete( | |
| item_id=item_id, | |
| tenant_id=tenant_context.tenant_id, | |
| user_id=current_user.id | |
| ) | |
| return None | |
| ''' | |
| SERVICE_TEMPLATE = '''""" | |
| {display_name} - Business Logic Service | |
| Core business logic for {name} tool. | |
| """ | |
| from __future__ import annotations | |
| from typing import Optional, List, Dict, Any | |
| from uuid import UUID | |
| from sqlalchemy.ext.asyncio import AsyncSession | |
| from sqlalchemy import select, and_ | |
| from sqlalchemy.sql import func | |
| import structlog | |
| from core.services.base import BaseService | |
| from ..models import {entity_class} | |
| logger = structlog.get_logger() | |
| class {entity_class}Service(BaseService): | |
| """ | |
| {entity_class} business logic service | |
| Inherits from BaseService: | |
| - Structured logging (OpenTelemetry) | |
| - Error handling (StandardErrorResponse) | |
| - Caching (4-tier strategy) | |
| - Tracing (distributed traces) | |
| - Metrics (Prometheus) | |
| """ | |
| def __init__(self, session: AsyncSession): | |
| super().__init__(session) | |
| self.model = {entity_class} | |
| async def create( | |
| self, | |
| data: Dict[str, Any], | |
| tenant_id: UUID, | |
| user_id: UUID | |
| ) -> {entity_class}: | |
| """ | |
| Create {entity_class} | |
| Performance: <100ms p95 | |
| """ | |
| entity = self.model( | |
| **data, | |
| tenant_id=tenant_id, | |
| created_by=user_id | |
| ) | |
| self.session.add(entity) | |
| await self.session.commit() | |
| await self.session.refresh(entity) | |
| logger.info( | |
| "{name}_created", | |
| entity_id=str(entity.id), | |
| tenant_id=str(tenant_id), | |
| user_id=str(user_id) | |
| ) | |
| return entity | |
| async def get_by_id( | |
| self, | |
| item_id: UUID, | |
| tenant_id: UUID | |
| ) -> Optional[{entity_class}]: | |
| """ | |
| Get {entity_class} by ID | |
| Performance: <50ms p95 | |
| """ | |
| result = await self.session.execute( | |
| select(self.model).where( | |
| and_( | |
| self.model.id == item_id, | |
| self.model.tenant_id == tenant_id, | |
| self.model.deleted_at.is_(None) # Exclude soft-deleted | |
| ) | |
| ) | |
| ) | |
| return result.scalars().first() | |
| async def list_paginated( | |
| self, | |
| tenant_id: UUID, | |
| page: int = 1, | |
| page_size: int = 50, | |
| category: Optional[str] = None | |
| ) -> Dict[str, Any]: | |
| """ | |
| List {entity_class} records with pagination | |
| Performance: <200ms p95 for 100 records | |
| """ | |
| # Build query | |
| query = select(self.model).where( | |
| and_( | |
| self.model.tenant_id == tenant_id, | |
| self.model.deleted_at.is_(None) | |
| ) | |
| ) | |
| # Add filters | |
| if category: | |
| query = query.where(self.model.category == category) | |
| # Count total | |
| count_query = select(func.count()).select_from(query.subquery()) | |
| total_result = await self.session.execute(count_query) | |
| total = total_result.scalar() | |
| # Paginate | |
| offset = (page - 1) * page_size | |
| query = query.offset(offset).limit(page_size) | |
| # Execute | |
| result = await self.session.execute(query) | |
| items = result.scalars().all() | |
| return {{ | |
| "items": items, | |
| "total": total, | |
| "page": page, | |
| "page_size": page_size, | |
| "has_more": (offset + page_size) < total | |
| }} | |
| async def update( | |
| self, | |
| item_id: UUID, | |
| data: Dict[str, Any], | |
| tenant_id: UUID, | |
| user_id: UUID | |
| ) -> Optional[{entity_class}]: | |
| """ | |
| Update {entity_class} | |
| Performance: <100ms p95 | |
| """ | |
| entity = await self.get_by_id(item_id, tenant_id) | |
| if not entity: | |
| return None | |
| # Update fields | |
| for field, value in data.items(): | |
| if value is not None: | |
| setattr(entity, field, value) | |
| entity.updated_by = user_id | |
| await self.session.commit() | |
| await self.session.refresh(entity) | |
| logger.info( | |
| "{name}_updated", | |
| entity_id=str(entity.id), | |
| tenant_id=str(tenant_id), | |
| user_id=str(user_id) | |
| ) | |
| return entity | |
| async def delete( | |
| self, | |
| item_id: UUID, | |
| tenant_id: UUID, | |
| user_id: UUID | |
| ) -> bool: | |
| """ | |
| Soft delete {entity_class} | |
| Performance: <50ms p95 | |
| """ | |
| entity = await self.get_by_id(item_id, tenant_id) | |
| if not entity: | |
| return False | |
| # Soft delete | |
| from datetime import datetime | |
| entity.deleted_at = datetime.utcnow() | |
| entity.deleted_by = user_id | |
| await self.session.commit() | |
| logger.info( | |
| "{name}_deleted", | |
| entity_id=str(entity.id), | |
| tenant_id=str(tenant_id), | |
| user_id=str(user_id) | |
| ) | |
| return True | |
| ''' | |
| # ============================================================================ | |
| # GENERATOR LOGIC | |
| # ============================================================================ | |
| def create_tool_structure( | |
| name: str, | |
| display_name: str, | |
| category: str, | |
| standards: List[str], | |
| description: str, | |
| phi_protected: bool = True | |
| ): | |
| """Create complete tool structure from templates.""" | |
| # Paths | |
| base_path = Path(__file__).parent.parent.parent / "src" / "apps" / name | |
| services_path = base_path / "services" | |
| adapters_path = base_path / "adapters" | |
| events_path = base_path / "events" | |
| tests_path = Path(__file__).parent.parent.parent / "tests" / "apps" / name | |
| # Create directories | |
| base_path.mkdir(parents=True, exist_ok=True) | |
| services_path.mkdir(parents=True, exist_ok=True) | |
| adapters_path.mkdir(parents=True, exist_ok=True) | |
| events_path.mkdir(parents=True, exist_ok=True) | |
| tests_path.mkdir(parents=True, exist_ok=True) | |
| # Entity class name (PascalCase) | |
| entity_class = "".join(word.capitalize() for word in name.split("_")) | |
| table_name = f"{name}_records" | |
| plural = f"{name}s" | |
| # Format standards | |
| standards_str = ", ".join(standards) | |
| standards_list = "\n ".join([f"- {s}: Compliance requirement" for s in standards]) | |
| # Template context | |
| context = { | |
| "name": name, | |
| "display_name": display_name, | |
| "category": category, | |
| "standards": standards_str, | |
| "standards_list": standards_list, | |
| "description": description, | |
| "entity_class": entity_class, | |
| "table_name": table_name, | |
| "plural": plural, | |
| "phi_protected": "YES" if phi_protected else "NO", | |
| "timestamp": datetime.now().isoformat() | |
| } | |
| # Generate files | |
| files = { | |
| base_path / "__init__.py": INIT_TEMPLATE.format(**context), | |
| base_path / "models.py": MODELS_TEMPLATE.format(**context), | |
| base_path / "schemas.py": SCHEMAS_TEMPLATE.format(**context), | |
| base_path / "routes.py": ROUTES_TEMPLATE.format(**context), | |
| services_path / f"{name}_service.py": SERVICE_TEMPLATE.format(**context), | |
| services_path / "__init__.py": f"from .{name}_service import {entity_class}Service\n", | |
| adapters_path / "__init__.py": "# Event adapters\n", | |
| events_path / "__init__.py": "# Domain events\n", | |
| tests_path / "__init__.py": "# Tests\n", | |
| } | |
| for file_path, content in files.items(): | |
| file_path.write_text(content) | |
| print(f"✅ Created: {file_path}") | |
| print(f"\n🎉 Tool '{name}' created successfully!") | |
| print(f"\n📋 Next steps:") | |
| print(f"1. Review generated files in: src/apps/{name}/") | |
| print(f"2. Customize domain models in: src/apps/{name}/models.py") | |
| print(f"3. Implement business logic in: src/apps/{name}/services/{name}_service.py") | |
| print(f"4. Create tests in: tests/apps/{name}/") | |
| print(f"5. Register tool: python scripts/governance/register_tool.py --slug {name}") | |
| print(f"6. Create migration: alembic revision --autogenerate -m 'Add {name} tool'") | |
| def main(): | |
| parser = argparse.ArgumentParser(description="Generate standardized tool structure") | |
| parser.add_argument("--name", required=True, help="Tool name (lowercase, underscores)") | |
| parser.add_argument("--display-name", required=True, help="Display name (e.g., 'MedNote (Clinical Documentation)')") | |
| parser.add_argument("--category", required=True, choices=["clinical", "financial", "logistics", "support", "platform"], help="Tool category") | |
| parser.add_argument("--standards", required=True, help="Comma-separated standards (e.g., 'HL7 FHIR,21 CFR Part 11')") | |
| parser.add_argument("--description", required=True, help="Tool description") | |
| parser.add_argument("--no-phi", action="store_true", help="Tool does not handle PHI") | |
| args = parser.parse_args() | |
| # Parse standards | |
| standards = [s.strip() for s in args.standards.split(",")] | |
| create_tool_structure( | |
| name=args.name, | |
| display_name=args.display_name, | |
| category=args.category, | |
| standards=standards, | |
| description=args.description, | |
| phi_protected=not args.no_phi | |
| ) | |
| if __name__ == "__main__": | |
| main() | |