Skip to content

honeyhive.config.models.base

Base configuration models for HoneyHive SDK.

This module provides the base Pydantic models that contain common fields shared across different domain-specific configurations. This approach eliminates duplication while maintaining type safety and validation.

The models follow graceful degradation principles - invalid values are logged as warnings and replaced with safe defaults to prevent crashing the host application.

logger module-attribute

logger = getLogger(__name__)

ServerURLMixin

Mixin for server URL configuration with HH_API_URL environment variable support.

This mixin provides the server_url field with proper environment variable loading for classes that need to support custom HoneyHive server URLs. It can be used by both APIClientConfig and TracerConfig to avoid field duplication.

Environment Variables

HH_API_URL: Custom HoneyHive server URL

Examples:

>>> class MyConfig(BaseHoneyHiveConfig, ServerURLMixin):
...     pass
>>> config = MyConfig()  # Loads from HH_API_URL if set
Source code in src/honeyhive/config/models/base.py
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
class ServerURLMixin:  # pylint: disable=too-few-public-methods
    """Mixin for server URL configuration with HH_API_URL environment variable support.

    This mixin provides the server_url field with proper environment variable loading
    for classes that need to support custom HoneyHive server URLs. It can be used
    by both APIClientConfig and TracerConfig to avoid field duplication.

    Environment Variables:
        HH_API_URL: Custom HoneyHive server URL

    Examples:
        >>> class MyConfig(BaseHoneyHiveConfig, ServerURLMixin):
        ...     pass
        >>> config = MyConfig()  # Loads from HH_API_URL if set
    """

    server_url: str = Field(
        default="https://api.dp1.us.honeyhive.ai",
        description="Custom HoneyHive server URL",
        validation_alias=AliasChoices("HH_API_URL", "server_url"),
        examples=[
            "https://api.dp1.us.honeyhive.ai",
            "https://custom.honeyhive.com",
        ],
    )

    @field_validator("server_url", mode="before")
    @classmethod
    def validate_server_url(cls, v: Any) -> str:
        """Validate server URL format with graceful degradation.

        Args:
            v: The server URL to validate

        Returns:
            The validated and normalized server URL, or default if invalid
        """
        if v is None:
            return "https://api.dp1.us.honeyhive.ai"

        validated = _safe_validate_url(
            v,
            "server_url",
            allow_none=False,
            default="https://api.dp1.us.honeyhive.ai",
        )
        # Remove trailing slash for consistency
        return validated.rstrip("/") if validated else "https://api.dp1.us.honeyhive.ai"

server_url class-attribute instance-attribute

server_url: str = Field(
    default="https://api.dp1.us.honeyhive.ai",
    description="Custom HoneyHive server URL",
    validation_alias=AliasChoices(
        "HH_API_URL", "server_url"
    ),
    examples=[
        "https://api.dp1.us.honeyhive.ai",
        "https://custom.honeyhive.com",
    ],
)

validate_server_url classmethod

validate_server_url(v: Any) -> str

Validate server URL format with graceful degradation.

Parameters:

Name Type Description Default
v Any

The server URL to validate

required

Returns:

Type Description
str

The validated and normalized server URL, or default if invalid

Source code in src/honeyhive/config/models/base.py
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
@field_validator("server_url", mode="before")
@classmethod
def validate_server_url(cls, v: Any) -> str:
    """Validate server URL format with graceful degradation.

    Args:
        v: The server URL to validate

    Returns:
        The validated and normalized server URL, or default if invalid
    """
    if v is None:
        return "https://api.dp1.us.honeyhive.ai"

    validated = _safe_validate_url(
        v,
        "server_url",
        allow_none=False,
        default="https://api.dp1.us.honeyhive.ai",
    )
    # Remove trailing slash for consistency
    return validated.rstrip("/") if validated else "https://api.dp1.us.honeyhive.ai"

BaseHoneyHiveConfig

Bases: BaseSettings

Base configuration model with common HoneyHive fields.

This base class contains fields that are commonly used across different parts of the SDK (tracer, API client, evaluation, etc.) to avoid duplication and ensure consistent validation.

Common Fields
  • api_key: HoneyHive API key for authentication
  • project: Deprecated project name (optional; backend infers scope from API key)
  • test_mode: Enable test mode (no data sent to backend)
  • verbose: Enable verbose logging
Example

This class is not used directly but inherited by domain-specific configs:

class TracerConfig(BaseHoneyHiveConfig): ... session_name: Optional[str] = None ... source: str = "dev"

config = TracerConfig(api_key="hh_...", project="my-project") print(config.api_key) # Inherited from base hh_...

Source code in src/honeyhive/config/models/base.py
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
class BaseHoneyHiveConfig(BaseSettings):
    """Base configuration model with common HoneyHive fields.

    This base class contains fields that are commonly used across different
    parts of the SDK (tracer, API client, evaluation, etc.) to avoid
    duplication and ensure consistent validation.

    Common Fields:
        - api_key: HoneyHive API key for authentication
        - project: Deprecated project name (optional; backend infers scope from API key)
        - test_mode: Enable test mode (no data sent to backend)
        - verbose: Enable verbose logging

    Example:
        This class is not used directly but inherited by domain-specific configs:

        >>> class TracerConfig(BaseHoneyHiveConfig):
        ...     session_name: Optional[str] = None
        ...     source: str = "dev"
        >>>
        >>> config = TracerConfig(api_key="hh_...", project="my-project")
        >>> print(config.api_key)  # Inherited from base
        hh_...
    """

    api_key: Optional[str] = Field(  # type: ignore[call-overload,pydantic-alias]
        default=None,
        description="HoneyHive API key for authentication",
        validation_alias=AliasChoices("HH_API_KEY", "api_key"),
        examples=["hh_1234567890abcdef"],
    )

    project: Optional[str] = Field(  # type: ignore[call-overload,pydantic-alias]
        default=None,
        description=(
            "Deprecated. Legacy project name accepted for backwards compatibility "
            "but no longer used — the backend infers project context from the API "
            "key. Will be removed in v2.0."
        ),
        validation_alias=AliasChoices("HH_PROJECT", "project"),
        examples=["my-llm-project", "chatbot-v2"],
    )

    test_mode: bool = Field(  # type: ignore[call-overload,pydantic-alias]
        default=False,
        description="Enable test mode (no data sent to backend)",
        validation_alias=AliasChoices("HH_TEST_MODE", "test_mode"),
    )

    verbose: bool = Field(  # type: ignore[call-overload,pydantic-alias]
        default=False,
        description="Enable verbose logging output and debug mode",
        validation_alias=AliasChoices("HH_VERBOSE", "verbose"),
    )

    model_config = SettingsConfigDict(
        validate_assignment=True,
        extra="forbid",  # Prevent accidental typos in field names
        case_sensitive=False,
    )

    def __init__(self, **data: Any) -> None:
        """Initialize base config with unified verbose/debug mode handling."""
        # Handle verbose mode from HH_VERBOSE environment variable
        if "verbose" not in data:
            # Check HH_VERBOSE environment variable
            verbose_env = os.getenv("HH_VERBOSE", "").lower()

            # Set verbose=True if HH_VERBOSE is true
            if verbose_env in ("true", "1", "yes", "on"):
                data["verbose"] = True

        super().__init__(**data)

    @field_validator("api_key", mode="before")
    @classmethod
    def validate_api_key(cls, v: Any) -> Optional[str]:
        """Validate API key format with graceful degradation.

        Args:
            v: The API key value to validate

        Returns:
            The validated and normalized API key, or None if invalid
        """
        validated = _safe_validate_string(v, "api_key", allow_none=True, default=None)
        if validated is not None:
            # Basic format validation - should start with 'hh_' for HoneyHive keys
            if not validated.startswith(("hh_", "sk-")):
                # Warning: not an error to maintain backwards compatibility
                logger.debug(
                    "API key does not follow standard format (hh_* or sk_*): %s...",
                    validated[:8],
                    extra={
                        "honeyhive_data": {
                            "api_key_prefix": validated[:3] if validated else None
                        }
                    },
                )
        return validated

    @field_validator("project", mode="before")
    @classmethod
    def validate_project(cls, v: Any) -> Optional[str]:
        """Validate project name format with graceful degradation.

        Args:
            v: The project name to validate

        Returns:
            The validated and normalized project name, or None if invalid
        """
        validated = _safe_validate_string(v, "project", allow_none=True, default=None)
        if validated is not None:
            # Basic validation - no special characters that could cause issues
            invalid_chars = ["/", "\\", "?", "#", "&"]
            if any(char in validated for char in invalid_chars):
                logger.warning(
                    "Project name contains invalid characters. Using None.",
                    extra={
                        "honeyhive_data": {
                            "project": validated,
                            "invalid_chars": invalid_chars,
                        }
                    },
                )
                return None
        return validated

    @field_validator("test_mode", "verbose", mode="before")
    @classmethod
    def validate_boolean_fields(cls, v: Any) -> bool:
        """Validate boolean fields with graceful degradation.

        Args:
            v: The value to validate as boolean

        Returns:
            The validated boolean value, or False if invalid
        """
        if v is None:
            return False

        if isinstance(v, bool):
            return v

        if isinstance(v, str):
            # Handle common boolean string representations
            lower_v = v.lower().strip()
            if lower_v in ("true", "1", "yes", "on", "enabled"):
                return True
            if lower_v in ("false", "0", "no", "off", "disabled", ""):
                return False
            # Invalid boolean string - log warning and return default
            logger.warning(
                "Invalid boolean value: %s. Using False as default.",
                v,
                extra={"honeyhive_data": {"invalid_boolean": v}},
            )
            return False

        # For non-string, non-bool types, log warning and return default
        logger.warning(
            "Invalid boolean type: %s. Using False as default.",
            type(v).__name__,
            extra={
                "honeyhive_data": {"invalid_type": type(v).__name__, "value": str(v)}
            },
        )
        return False

api_key class-attribute instance-attribute

api_key: Optional[str] = Field(
    default=None,
    description="HoneyHive API key for authentication",
    validation_alias=AliasChoices("HH_API_KEY", "api_key"),
    examples=["hh_1234567890abcdef"],
)

project class-attribute instance-attribute

project: Optional[str] = Field(
    default=None,
    description="Deprecated. Legacy project name accepted for backwards compatibility but no longer used — the backend infers project context from the API key. Will be removed in v2.0.",
    validation_alias=AliasChoices("HH_PROJECT", "project"),
    examples=["my-llm-project", "chatbot-v2"],
)

test_mode class-attribute instance-attribute

test_mode: bool = Field(
    default=False,
    description="Enable test mode (no data sent to backend)",
    validation_alias=AliasChoices(
        "HH_TEST_MODE", "test_mode"
    ),
)

verbose class-attribute instance-attribute

verbose: bool = Field(
    default=False,
    description="Enable verbose logging output and debug mode",
    validation_alias=AliasChoices("HH_VERBOSE", "verbose"),
)

validate_api_key classmethod

validate_api_key(v: Any) -> Optional[str]

Validate API key format with graceful degradation.

Parameters:

Name Type Description Default
v Any

The API key value to validate

required

Returns:

Type Description
Optional[str]

The validated and normalized API key, or None if invalid

Source code in src/honeyhive/config/models/base.py
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
@field_validator("api_key", mode="before")
@classmethod
def validate_api_key(cls, v: Any) -> Optional[str]:
    """Validate API key format with graceful degradation.

    Args:
        v: The API key value to validate

    Returns:
        The validated and normalized API key, or None if invalid
    """
    validated = _safe_validate_string(v, "api_key", allow_none=True, default=None)
    if validated is not None:
        # Basic format validation - should start with 'hh_' for HoneyHive keys
        if not validated.startswith(("hh_", "sk-")):
            # Warning: not an error to maintain backwards compatibility
            logger.debug(
                "API key does not follow standard format (hh_* or sk_*): %s...",
                validated[:8],
                extra={
                    "honeyhive_data": {
                        "api_key_prefix": validated[:3] if validated else None
                    }
                },
            )
    return validated

validate_project classmethod

validate_project(v: Any) -> Optional[str]

Validate project name format with graceful degradation.

Parameters:

Name Type Description Default
v Any

The project name to validate

required

Returns:

Type Description
Optional[str]

The validated and normalized project name, or None if invalid

Source code in src/honeyhive/config/models/base.py
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
@field_validator("project", mode="before")
@classmethod
def validate_project(cls, v: Any) -> Optional[str]:
    """Validate project name format with graceful degradation.

    Args:
        v: The project name to validate

    Returns:
        The validated and normalized project name, or None if invalid
    """
    validated = _safe_validate_string(v, "project", allow_none=True, default=None)
    if validated is not None:
        # Basic validation - no special characters that could cause issues
        invalid_chars = ["/", "\\", "?", "#", "&"]
        if any(char in validated for char in invalid_chars):
            logger.warning(
                "Project name contains invalid characters. Using None.",
                extra={
                    "honeyhive_data": {
                        "project": validated,
                        "invalid_chars": invalid_chars,
                    }
                },
            )
            return None
    return validated

validate_boolean_fields classmethod

validate_boolean_fields(v: Any) -> bool

Validate boolean fields with graceful degradation.

Parameters:

Name Type Description Default
v Any

The value to validate as boolean

required

Returns:

Type Description
bool

The validated boolean value, or False if invalid

Source code in src/honeyhive/config/models/base.py
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
@field_validator("test_mode", "verbose", mode="before")
@classmethod
def validate_boolean_fields(cls, v: Any) -> bool:
    """Validate boolean fields with graceful degradation.

    Args:
        v: The value to validate as boolean

    Returns:
        The validated boolean value, or False if invalid
    """
    if v is None:
        return False

    if isinstance(v, bool):
        return v

    if isinstance(v, str):
        # Handle common boolean string representations
        lower_v = v.lower().strip()
        if lower_v in ("true", "1", "yes", "on", "enabled"):
            return True
        if lower_v in ("false", "0", "no", "off", "disabled", ""):
            return False
        # Invalid boolean string - log warning and return default
        logger.warning(
            "Invalid boolean value: %s. Using False as default.",
            v,
            extra={"honeyhive_data": {"invalid_boolean": v}},
        )
        return False

    # For non-string, non-bool types, log warning and return default
    logger.warning(
        "Invalid boolean type: %s. Using False as default.",
        type(v).__name__,
        extra={
            "honeyhive_data": {"invalid_type": type(v).__name__, "value": str(v)}
        },
    )
    return False