# coding: utf-8

"""
    Mixpeek API

    This is the Mixpeek API, providing access to various endpoints for data processing and retrieval.

    The version of the OpenAPI document: 1.3.0
    Contact: info@mixpeek.com
    Generated by OpenAPI Generator (https://openapi-generator.tech)

    Do not edit the class manually.
"""  # noqa: E501


from __future__ import annotations
import pprint
import re  # noqa: F401
import json

from pydantic import BaseModel, ConfigDict, Field, StrictBool, StrictStr
from typing import Any, ClassVar, Dict, List, Optional, Union
from typing_extensions import Annotated
from mixpeek.models.llm_labeling_input_output import LLMLabelingInputOutput
from mixpeek.models.llm_provider import LLMProvider
from mixpeek.models.model_name import ModelName
from mixpeek.models.response_shape import ResponseShape
from typing import Optional, Set
from typing_extensions import Self

class LLMLabelingOutput(BaseModel):
    """
    Configuration for LLM-based cluster labeling.  Supports multiple LLM providers with comprehensive model selection: - OpenAI: GPT-4o, GPT-4o-mini, GPT-4.1, O3-mini (best for quality) - Google: Gemini 2.5 Flash, Gemini 1.5 Flash (best for speed and cost) - Anthropic: Claude 3.5 Sonnet, Claude 3.5 Haiku (best for reasoning)  All models are defined as enums and validated at API level.
    """ # noqa: E501
    enabled: Optional[StrictBool] = Field(default=False, description="Whether to generate labels for clusters using LLM. When enabled, clusters will have semantic labels like 'High-Performance Laptops' instead of generic labels like 'Cluster 0'.")
    labeling_inputs: Optional[LLMLabelingInputOutput] = Field(default=None, description="Input configuration for LLM labeling. Supports flexible input mappings for multimodal inputs (text, images, videos, audio). Use input_mappings for advanced multimodal labeling with providers like Gemini. If not provided (null/undefined), the full document payload will be serialized as JSON and sent to the LLM, providing complete context for semantic labeling.")
    provider: Optional[LLMProvider] = Field(default=None, description="LLM provider to use for labeling. Supported providers: - openai: GPT models (GPT-4o, GPT-4o-mini, GPT-4.1, O3-mini) - google: Gemini models (Gemini 2.5 Flash, Gemini 1.5 Flash) - anthropic: Claude models (Claude 3.5 Sonnet, Claude 3.5 Haiku)  If not specified, automatically inferred from model_name.")
    model_name: Optional[ModelName] = None
    include_summary: Optional[StrictBool] = Field(default=True, description="Whether to generate cluster summaries")
    include_keywords: Optional[StrictBool] = Field(default=True, description="Whether to extract keywords for clusters")
    max_samples_per_cluster: Optional[Annotated[int, Field(le=20, strict=True, ge=1)]] = Field(default=10, description="Maximum representative documents to send to LLM per cluster for semantic analysis")
    sample_text_max_length: Optional[Annotated[int, Field(le=500, strict=True, ge=50)]] = Field(default=200, description="Maximum characters per document sample text")
    use_embedding_dedup: Optional[StrictBool] = Field(default=False, description="Enable embedding-based label deduplication to prevent near-duplicate labels (requires sentence-transformers)")
    embedding_similarity_threshold: Optional[Union[Annotated[float, Field(le=1.0, strict=True, ge=0.5)], Annotated[int, Field(le=1, strict=True, ge=1)]]] = Field(default=0.8, description="Cosine similarity threshold for duplicate label detection (labels above this are considered duplicates)")
    cache_ttl_seconds: Optional[Annotated[int, Field(le=2592000, strict=True, ge=0)]] = Field(default=604800, description="Time-to-live for cached labels in seconds. Labels for clusters with identical representative documents will be reused within this TTL window, reducing LLM API costs. Default: 604800 (7 days). Set to 0 to disable caching.")
    custom_prompt: Optional[StrictStr] = Field(default=None, description="OPTIONAL. Custom prompt template for LLM labeling. NOT REQUIRED - uses default discriminative prompt if not provided. When provided, completely replaces the default prompt. Your custom prompt receives cluster information but you must format it yourself. Use when:   - Need domain-specific labeling (e.g., medical, legal, technical)   - Want different label format (e.g., emoji labels, code names)   - Require specific output structure   - Have custom business logic for categorization Default prompt includes: cluster document samples, forbidden labels for uniqueness, and JSON response format. See engine/clusters/labeling/prompts.py for reference. Example: 'Analyze these product clusters and generate SHORT category names (2-3 words max) focusing on product type and price range. Return JSON: [{\"cluster_id\": \"cl_0\", \"label\": \"...\"}]'")
    response_shape: Optional[ResponseShape] = None
    parameters: Optional[Dict[str, Any]] = Field(default=None, description="Provider-specific parameters forwarded to the LLM service. For OpenAI: temperature, max_tokens, top_p, json_output, etc. For Google: temperature, top_k, max_output_tokens, json_output, etc.")
    __properties: ClassVar[List[str]] = ["enabled", "labeling_inputs", "provider", "model_name", "include_summary", "include_keywords", "max_samples_per_cluster", "sample_text_max_length", "use_embedding_dedup", "embedding_similarity_threshold", "cache_ttl_seconds", "custom_prompt", "response_shape", "parameters"]

    model_config = ConfigDict(
        populate_by_name=True,
        validate_assignment=True,
        protected_namespaces=(),
    )


    def to_str(self) -> str:
        """Returns the string representation of the model using alias"""
        return pprint.pformat(self.model_dump(by_alias=True))

    def to_json(self) -> str:
        """Returns the JSON representation of the model using alias"""
        # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead
        return json.dumps(self.to_dict())

    @classmethod
    def from_json(cls, json_str: str) -> Optional[Self]:
        """Create an instance of LLMLabelingOutput from a JSON string"""
        return cls.from_dict(json.loads(json_str))

    def to_dict(self) -> Dict[str, Any]:
        """Return the dictionary representation of the model using alias.

        This has the following differences from calling pydantic's
        `self.model_dump(by_alias=True)`:

        * `None` is only added to the output dict for nullable fields that
          were set at model initialization. Other fields with value `None`
          are ignored.
        """
        excluded_fields: Set[str] = set([
        ])

        _dict = self.model_dump(
            by_alias=True,
            exclude=excluded_fields,
            exclude_none=True,
        )
        # override the default output from pydantic by calling `to_dict()` of labeling_inputs
        if self.labeling_inputs:
            _dict['labeling_inputs'] = self.labeling_inputs.to_dict()
        # override the default output from pydantic by calling `to_dict()` of model_name
        if self.model_name:
            _dict['model_name'] = self.model_name.to_dict()
        # override the default output from pydantic by calling `to_dict()` of response_shape
        if self.response_shape:
            _dict['response_shape'] = self.response_shape.to_dict()
        return _dict

    @classmethod
    def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]:
        """Create an instance of LLMLabelingOutput from a dict"""
        if obj is None:
            return None

        if not isinstance(obj, dict):
            return cls.model_validate(obj)

        _obj = cls.model_validate({
            "enabled": obj.get("enabled") if obj.get("enabled") is not None else False,
            "labeling_inputs": LLMLabelingInputOutput.from_dict(obj["labeling_inputs"]) if obj.get("labeling_inputs") is not None else None,
            "provider": obj.get("provider"),
            "model_name": ModelName.from_dict(obj["model_name"]) if obj.get("model_name") is not None else None,
            "include_summary": obj.get("include_summary") if obj.get("include_summary") is not None else True,
            "include_keywords": obj.get("include_keywords") if obj.get("include_keywords") is not None else True,
            "max_samples_per_cluster": obj.get("max_samples_per_cluster") if obj.get("max_samples_per_cluster") is not None else 10,
            "sample_text_max_length": obj.get("sample_text_max_length") if obj.get("sample_text_max_length") is not None else 200,
            "use_embedding_dedup": obj.get("use_embedding_dedup") if obj.get("use_embedding_dedup") is not None else False,
            "embedding_similarity_threshold": obj.get("embedding_similarity_threshold") if obj.get("embedding_similarity_threshold") is not None else 0.8,
            "cache_ttl_seconds": obj.get("cache_ttl_seconds") if obj.get("cache_ttl_seconds") is not None else 604800,
            "custom_prompt": obj.get("custom_prompt"),
            "response_shape": ResponseShape.from_dict(obj["response_shape"]) if obj.get("response_shape") is not None else None,
            "parameters": obj.get("parameters")
        })
        return _obj


