|
| 1 | +# --------------------------------------------------------- |
| 2 | +# Copyright (c) Microsoft Corporation. All rights reserved. |
| 3 | +# --------------------------------------------------------- |
| 4 | + |
| 5 | +import os |
| 6 | +import re |
| 7 | +from abc import ABC, abstractmethod |
| 8 | +from dataclasses import dataclass |
| 9 | +from typing import Any, ClassVar, Mapping, Optional, Set, Union |
| 10 | + |
| 11 | +from azure.ai.evaluation.legacy.prompty._exceptions import MissingRequiredInputError |
| 12 | +from azure.ai.evaluation.legacy.prompty._utils import dataclass_from_dict |
| 13 | + |
| 14 | + |
| 15 | +ENV_VAR_PATTERN = re.compile(r"^\$\{env:(.*)\}$") |
| 16 | + |
| 17 | + |
| 18 | +def _parse_environment_variable(value: Union[str, Any]) -> Union[str, Any]: |
| 19 | + """Get environment variable from ${env:ENV_NAME}. If not found, return original value. |
| 20 | +
|
| 21 | + :param value: The value to parse. |
| 22 | + :type value: str | Any |
| 23 | + :return: The parsed value |
| 24 | + :rtype: str | Any""" |
| 25 | + if not isinstance(value, str): |
| 26 | + return value |
| 27 | + |
| 28 | + result = re.match(ENV_VAR_PATTERN, value) |
| 29 | + if result: |
| 30 | + env_name = result.groups()[0] |
| 31 | + return os.environ.get(env_name, value) |
| 32 | + |
| 33 | + return value |
| 34 | + |
| 35 | + |
| 36 | +def _is_empty_connection_config(connection_dict: Mapping[str, Any]) -> bool: |
| 37 | + ignored_fields = set(["azure_deployment", "model"]) |
| 38 | + keys = {k for k, v in connection_dict.items() if v} |
| 39 | + return len(keys - ignored_fields) == 0 |
| 40 | + |
| 41 | + |
| 42 | +@dataclass |
| 43 | +class Connection(ABC): |
| 44 | + """Base class for all connection classes.""" |
| 45 | + |
| 46 | + @property |
| 47 | + @abstractmethod |
| 48 | + def type(self) -> str: |
| 49 | + """Gets the type of the connection. |
| 50 | +
|
| 51 | + :return: The type of the connection. |
| 52 | + :rtype: str""" |
| 53 | + ... |
| 54 | + |
| 55 | + @abstractmethod |
| 56 | + def is_valid(self, missing_fields: Optional[Set[str]] = None) -> bool: |
| 57 | + """Check if the connection is valid. |
| 58 | +
|
| 59 | + :param missing_fields: If set, this will be populated with the missing required fields. |
| 60 | + :type missing_fields: Set[str] | None |
| 61 | + :return: True if the connection is valid, False otherwise. |
| 62 | + :rtype: bool""" |
| 63 | + ... |
| 64 | + |
| 65 | + @staticmethod |
| 66 | + def parse_from_config(model_configuration: Mapping[str, Any]) -> "Connection": |
| 67 | + """Parse a connection from a model configuration. |
| 68 | +
|
| 69 | + :param model_configuration: The model configuration. |
| 70 | + :type model_configuration: Mapping[str, Any] |
| 71 | + :return: The connection. |
| 72 | + :rtype: Connection |
| 73 | + """ |
| 74 | + connection: Connection |
| 75 | + connection_dict = {k: _parse_environment_variable(v) for k, v in model_configuration.items()} |
| 76 | + connection_type = connection_dict.pop("type", "") |
| 77 | + |
| 78 | + if connection_type in [AzureOpenAIConnection.TYPE, "azure_openai"]: |
| 79 | + if _is_empty_connection_config(connection_dict): |
| 80 | + connection = AzureOpenAIConnection.from_env() |
| 81 | + else: |
| 82 | + connection = dataclass_from_dict(AzureOpenAIConnection, connection_dict) |
| 83 | + |
| 84 | + elif connection_type in [OpenAIConnection.TYPE, "openai"]: |
| 85 | + if _is_empty_connection_config(connection_dict): |
| 86 | + connection = OpenAIConnection.from_env() |
| 87 | + else: |
| 88 | + connection = dataclass_from_dict(OpenAIConnection, connection_dict) |
| 89 | + |
| 90 | + else: |
| 91 | + error_message = ( |
| 92 | + f"'{connection_type}' is not a supported connection type. Valid values are " |
| 93 | + f"[{AzureOpenAIConnection.TYPE}, {OpenAIConnection.TYPE}]" |
| 94 | + ) |
| 95 | + raise MissingRequiredInputError(error_message) |
| 96 | + |
| 97 | + missing_fields: Set[str] = set() |
| 98 | + if not connection.is_valid(missing_fields): |
| 99 | + raise MissingRequiredInputError( |
| 100 | + f"The following required fields are missing for connection {connection.type}: " |
| 101 | + f"{', '.join(missing_fields)}" |
| 102 | + ) |
| 103 | + |
| 104 | + return connection |
| 105 | + |
| 106 | + |
| 107 | +@dataclass |
| 108 | +class OpenAIConnection(Connection): |
| 109 | + """Connection class for OpenAI endpoints.""" |
| 110 | + |
| 111 | + base_url: str |
| 112 | + api_key: Optional[str] = None |
| 113 | + organization: Optional[str] = None |
| 114 | + |
| 115 | + TYPE: ClassVar[str] = "openai" |
| 116 | + |
| 117 | + @property |
| 118 | + def type(self) -> str: |
| 119 | + return OpenAIConnection.TYPE |
| 120 | + |
| 121 | + @classmethod |
| 122 | + def from_env(cls) -> "OpenAIConnection": |
| 123 | + return cls( |
| 124 | + base_url=os.environ.get("OPENAI_BASE_URL", ""), |
| 125 | + api_key=os.environ.get("OPENAI_API_KEY"), |
| 126 | + organization=os.environ.get("OPENAI_ORG_ID"), |
| 127 | + ) |
| 128 | + |
| 129 | + def is_valid(self, missing_fields: Optional[Set[str]] = None) -> bool: |
| 130 | + if missing_fields is None: |
| 131 | + missing_fields = set() |
| 132 | + if not self.base_url: |
| 133 | + missing_fields.add("base_url") |
| 134 | + if not self.api_key: |
| 135 | + missing_fields.add("api_key") |
| 136 | + if not self.organization: |
| 137 | + missing_fields.add("organization") |
| 138 | + return not bool(missing_fields) |
| 139 | + |
| 140 | + |
| 141 | +@dataclass |
| 142 | +class AzureOpenAIConnection(Connection): |
| 143 | + """Connection class for Azure OpenAI endpoints.""" |
| 144 | + |
| 145 | + azure_endpoint: str |
| 146 | + api_key: Optional[str] = None # TODO ralphe: Replace this TokenCredential to allow for more flexible authentication |
| 147 | + azure_deployment: Optional[str] = None |
| 148 | + api_version: Optional[str] = None |
| 149 | + resource_id: Optional[str] = None |
| 150 | + |
| 151 | + TYPE: ClassVar[str] = "azure_openai" |
| 152 | + |
| 153 | + @property |
| 154 | + def type(self) -> str: |
| 155 | + return AzureOpenAIConnection.TYPE |
| 156 | + |
| 157 | + @classmethod |
| 158 | + def from_env(cls) -> "AzureOpenAIConnection": |
| 159 | + return cls( |
| 160 | + azure_endpoint=os.environ.get("AZURE_OPENAI_ENDPOINT", ""), |
| 161 | + api_key=os.environ.get("AZURE_OPENAI_API_KEY"), |
| 162 | + azure_deployment=os.environ.get("AZURE_OPENAI_DEPLOYMENT"), |
| 163 | + api_version=os.environ.get("AZURE_OPENAI_API_VERSION", "2024-02-01"), |
| 164 | + ) |
| 165 | + |
| 166 | + def __post_init__(self): |
| 167 | + # set default API version |
| 168 | + if not self.api_version: |
| 169 | + self.api_version = "2024-02-01" |
| 170 | + |
| 171 | + def is_valid(self, missing_fields: Optional[Set[str]] = None) -> bool: |
| 172 | + if missing_fields is None: |
| 173 | + missing_fields = set() |
| 174 | + if not self.azure_endpoint: |
| 175 | + missing_fields.add("azure_endpoint") |
| 176 | + if not self.api_key: |
| 177 | + missing_fields.add("api_key") |
| 178 | + if not self.azure_deployment: |
| 179 | + missing_fields.add("azure_deployment") |
| 180 | + if not self.api_version: |
| 181 | + missing_fields.add("api_version") |
| 182 | + return not bool(missing_fields) |
0 commit comments