File size: 4,013 Bytes
d4052d1
 
 
 
 
 
 
 
 
 
 
 
adecb62
d4052d1
 
 
 
 
 
a807c4d
d4052d1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e9bcee8
 
d4052d1
 
 
e9bcee8
d4052d1
e9bcee8
d4052d1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e9bcee8
d4052d1
e9bcee8
d4052d1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fcb34bb
 
d4052d1
 
fcb34bb
 
 
 
 
 
d4052d1
ec0cbf8
fcb34bb
d4052d1
 
fcb34bb
 
d4052d1
ec0cbf8
fcb34bb
d4052d1
 
e9bcee8
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
"""
utils.py

This file contains utility functions that are shared across the project.
These functions provide reusable logic to simplify code in other modules.

Key Features:
- Validates that required environment variables are set, raising meaningful errors otherwise.
- Provides helper functions for text validation and truncation.

Functions:
- truncate_text: Truncates a string to a specified length with ellipses.
- validate_env_var: Ensures the presence of a specific environment variable and retrieves its value.
- validate_prompt_length: Ensures that a prompt does not exceed the specified maximum length.
"""

# Standard Library Imports
import os
# Local Application Imports
from src.config import logger


def truncate_text(text: str, max_length: int = 50) -> str:
    """
    Truncate a string to the specified length, appending ellipses if necessary.

    Args:
        text (str): The text to truncate.
        max_length (int): The maximum length of the truncated string.

    Returns:
        str: The truncated text.

    Examples:
        >>> truncate_text("Hello, World!", 5)
        'Hello...'
        >>> truncate_text("Short string", 20)
        'Short string'
        >>> truncate_text("Edge case with zero length", 0)
        ''
    """
    if max_length <= 0:
        logger.warning(f'Invalid max_length={max_length}. Returning empty string.')
        return ''

    is_truncated = len(text) > max_length
    if is_truncated:
        logger.debug(f'Truncated text to {max_length} characters.')
    
    return text[:max_length] + ('...' if is_truncated else '')


def validate_env_var(var_name: str) -> str:
    """
    Validates that an environment variable is set and returns its value.

    Args:
        var_name (str): The name of the environment variable to validate.

    Returns:
        str: The value of the environment variable.

    Raises:
        ValueError: If the environment variable is not set.
    
    Examples:
        >>> import os
        >>> os.environ["EXAMPLE_VAR"] = "example_value"
        >>> validate_env_var("EXAMPLE_VAR")
        'example_value'

        >>> validate_env_var("MISSING_VAR")
        Traceback (most recent call last):
          ...
        ValueError: MISSING_VAR is not set. Please ensure it is defined in your environment variables.
    """
    value = os.environ.get(var_name, '')
    if not value:
        raise ValueError(f'{var_name} is not set. Please ensure it is defined in your environment variables.')
    return value


def validate_prompt_length(prompt: str, max_length: int, min_length: int) -> None:
    """
    Validates that a prompt is within specified minimum and maximum length limits.

    Args:
        prompt (str): The input prompt to validate.
        max_length (int): The maximum allowed length for the prompt.
        min_length (int): The minimum required length for the prompt.

    Raises:
        ValueError: If the prompt is empty, too short, or exceeds max_length.

    Example:
        >>> validate_prompt_length("Hello world", max_length=500, min_length=5)
        # Passes validation

        >>> validate_prompt_length("", max_length=300, min_length=10)
        # Raises ValueError: "Prompt must be at least 10 characters long."
    """
    stripped_prompt = prompt.strip()
    prompt_length = len(stripped_prompt)
    
    logger.debug(f'Prompt length being validated: {prompt_length} characters')

    # Check if prompt is too short
    if prompt_length < min_length:
        raise ValueError(
            f'Error: prompt must be at least {min_length} character(s) long. '
            f'Received only {prompt_length}.'
        )

    # Check if prompt exceeds max length
    if prompt_length > max_length:
        raise ValueError(
            f'Error: the prompt exceeds the maximum allowed length of {max_length} characters. '
            f'Your prompt contains {prompt_length} characters.'
        )

    logger.debug(f'Prompt length validation passed for prompt: {truncate_text(stripped_prompt)}')