-
Notifications
You must be signed in to change notification settings - Fork 1
/
env_helper.py
305 lines (270 loc) · 12.2 KB
/
env_helper.py
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
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
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
import os
import logging
import threading
from dotenv import load_dotenv
from azure.identity import DefaultAzureCredential, get_bearer_token_provider
from azure.keyvault.secrets import SecretClient
from .config.conversation_flow import ConversationFlow
logger = logging.getLogger(__name__)
class EnvHelper:
_instance = None
_lock = threading.Lock()
def __new__(cls):
with cls._lock:
if cls._instance is None:
instance = super(EnvHelper, cls).__new__(cls)
instance.__load_config()
cls._instance = instance
return cls._instance
def __load_config(self, **kwargs) -> None:
load_dotenv()
logger.info("Initializing EnvHelper")
# Wrapper for Azure Key Vault
self.secretHelper = SecretHelper()
self.LOGLEVEL = os.environ.get("LOGLEVEL", "INFO").upper()
# Azure
self.AZURE_SUBSCRIPTION_ID = os.getenv("AZURE_SUBSCRIPTION_ID", "")
self.AZURE_RESOURCE_GROUP = os.getenv("AZURE_RESOURCE_GROUP", "")
# Azure Search
self.AZURE_SEARCH_SERVICE = os.getenv("AZURE_SEARCH_SERVICE", "")
self.AZURE_SEARCH_INDEX = os.getenv("AZURE_SEARCH_INDEX", "")
self.AZURE_SEARCH_USE_SEMANTIC_SEARCH = self.get_env_var_bool(
"AZURE_SEARCH_USE_SEMANTIC_SEARCH", "False"
)
self.AZURE_SEARCH_SEMANTIC_SEARCH_CONFIG = os.getenv(
"AZURE_SEARCH_SEMANTIC_SEARCH_CONFIG", "default"
)
self.AZURE_SEARCH_INDEX_IS_PRECHUNKED = os.getenv(
"AZURE_SEARCH_INDEX_IS_PRECHUNKED", ""
)
self.AZURE_SEARCH_FILTER = os.getenv("AZURE_SEARCH_FILTER", "")
self.AZURE_SEARCH_TOP_K = int(os.getenv("AZURE_SEARCH_TOP_K", "5"))
self.AZURE_SEARCH_ENABLE_IN_DOMAIN = (
os.getenv("AZURE_SEARCH_ENABLE_IN_DOMAIN", "true").lower() == "true"
)
self.AZURE_SEARCH_FIELDS_ID = os.getenv("AZURE_SEARCH_FIELDS_ID", "id")
self.AZURE_SEARCH_CONTENT_COLUMNS = os.getenv(
"AZURE_SEARCH_CONTENT_COLUMNS", "content"
)
self.AZURE_SEARCH_CONTENT_VECTOR_COLUMNS = os.getenv(
"AZURE_SEARCH_CONTENT_VECTOR_COLUMNS", "content_vector"
)
self.AZURE_SEARCH_DIMENSIONS = os.getenv("AZURE_SEARCH_DIMENSIONS", "1536")
self.AZURE_SEARCH_FILENAME_COLUMN = os.getenv(
"AZURE_SEARCH_FILENAME_COLUMN", "filepath"
)
self.AZURE_SEARCH_TITLE_COLUMN = os.getenv("AZURE_SEARCH_TITLE_COLUMN", "title")
self.AZURE_SEARCH_URL_COLUMN = os.getenv("AZURE_SEARCH_URL_COLUMN", "url")
self.AZURE_SEARCH_FIELDS_TAG = os.getenv("AZURE_SEARCH_FIELDS_TAG", "tag")
self.AZURE_SEARCH_FIELDS_METADATA = os.getenv(
"AZURE_SEARCH_FIELDS_METADATA", "metadata"
)
self.AZURE_SEARCH_CONVERSATIONS_LOG_INDEX = os.getenv(
"AZURE_SEARCH_CONVERSATIONS_LOG_INDEX", "conversations"
)
# Integrated Vectorization
self.AZURE_SEARCH_DATASOURCE_NAME = os.getenv(
"AZURE_SEARCH_DATASOURCE_NAME", ""
)
self.AZURE_SEARCH_INDEXER_NAME = os.getenv("AZURE_SEARCH_INDEXER_NAME", "")
self.AZURE_SEARCH_USE_INTEGRATED_VECTORIZATION = self.get_env_var_bool(
"AZURE_SEARCH_USE_INTEGRATED_VECTORIZATION", "False"
)
self.AZURE_AUTH_TYPE = os.getenv("AZURE_AUTH_TYPE", "keys")
# Azure OpenAI
self.AZURE_OPENAI_RESOURCE = os.getenv("AZURE_OPENAI_RESOURCE", "")
self.AZURE_OPENAI_MODEL = os.getenv("AZURE_OPENAI_MODEL", "")
self.AZURE_OPENAI_MODEL_NAME = os.getenv(
"AZURE_OPENAI_MODEL_NAME", "gpt-35-turbo"
)
self.AZURE_OPENAI_VISION_MODEL = os.getenv("AZURE_OPENAI_VISION_MODEL", "gpt-4")
self.AZURE_OPENAI_TEMPERATURE = os.getenv("AZURE_OPENAI_TEMPERATURE", "0")
self.AZURE_OPENAI_TOP_P = os.getenv("AZURE_OPENAI_TOP_P", "1.0")
self.AZURE_OPENAI_MAX_TOKENS = os.getenv("AZURE_OPENAI_MAX_TOKENS", "1000")
self.AZURE_OPENAI_STOP_SEQUENCE = os.getenv("AZURE_OPENAI_STOP_SEQUENCE", "")
self.AZURE_OPENAI_SYSTEM_MESSAGE = os.getenv(
"AZURE_OPENAI_SYSTEM_MESSAGE",
"You are an AI assistant that helps people find information.",
)
self.AZURE_OPENAI_API_VERSION = os.getenv(
"AZURE_OPENAI_API_VERSION", "2024-02-01"
)
self.AZURE_OPENAI_STREAM = os.getenv("AZURE_OPENAI_STREAM", "true")
self.AZURE_OPENAI_EMBEDDING_MODEL = os.getenv(
"AZURE_OPENAI_EMBEDDING_MODEL", ""
)
self.SHOULD_STREAM = (
True if self.AZURE_OPENAI_STREAM.lower() == "true" else False
)
self.AZURE_TOKEN_PROVIDER = get_bearer_token_provider(
DefaultAzureCredential(), "https://cognitiveservices.azure.com/.default"
)
self.USE_ADVANCED_IMAGE_PROCESSING = self.get_env_var_bool(
"USE_ADVANCED_IMAGE_PROCESSING", "False"
)
self.AZURE_COMPUTER_VISION_ENDPOINT = os.getenv(
"AZURE_COMPUTER_VISION_ENDPOINT"
)
self.AZURE_COMPUTER_VISION_TIMEOUT = self.get_env_var_float(
"AZURE_COMPUTER_VISION_TIMEOUT", 30
)
self.AZURE_COMPUTER_VISION_VECTORIZE_IMAGE_API_VERSION = os.getenv(
"AZURE_COMPUTER_VISION_VECTORIZE_IMAGE_API_VERSION", "2024-02-01"
)
self.AZURE_COMPUTER_VISION_VECTORIZE_IMAGE_MODEL_VERSION = os.getenv(
"AZURE_COMPUTER_VISION_VECTORIZE_IMAGE_MODEL_VERSION", "2023-04-15"
)
# Initialize Azure keys based on authentication type and environment settings.
# When AZURE_AUTH_TYPE is "rbac", azure keys are None or an empty string.
if self.AZURE_AUTH_TYPE == "rbac":
self.AZURE_SEARCH_KEY = None
self.AZURE_OPENAI_API_KEY = ""
self.AZURE_SPEECH_KEY = None
self.AZURE_COMPUTER_VISION_KEY = None
else:
self.AZURE_SEARCH_KEY = self.secretHelper.get_secret("AZURE_SEARCH_KEY")
self.AZURE_OPENAI_API_KEY = self.secretHelper.get_secret(
"AZURE_OPENAI_API_KEY"
)
self.AZURE_SPEECH_KEY = self.secretHelper.get_secret(
"AZURE_SPEECH_SERVICE_KEY"
)
self.AZURE_COMPUTER_VISION_KEY = self.secretHelper.get_secret(
"AZURE_COMPUTER_VISION_KEY"
)
# Set env for Azure OpenAI
self.AZURE_OPENAI_ENDPOINT = os.environ.get(
"AZURE_OPENAI_ENDPOINT",
f"https://{self.AZURE_OPENAI_RESOURCE}.openai.azure.com/",
)
# Set env for OpenAI SDK
self.OPENAI_API_TYPE = "azure" if self.AZURE_AUTH_TYPE == "keys" else "azure_ad"
self.OPENAI_API_KEY = self.AZURE_OPENAI_API_KEY
self.OPENAI_API_VERSION = self.AZURE_OPENAI_API_VERSION
os.environ["OPENAI_API_TYPE"] = self.OPENAI_API_TYPE
os.environ["OPENAI_API_KEY"] = self.OPENAI_API_KEY
os.environ["OPENAI_API_VERSION"] = self.OPENAI_API_VERSION
# Azure Functions - Batch processing
self.BACKEND_URL = os.getenv("BACKEND_URL", "http://localhost:7071")
self.FUNCTION_KEY = os.getenv("FUNCTION_KEY")
self.AzureWebJobsStorage = os.getenv("AzureWebJobsStorage", "")
self.DOCUMENT_PROCESSING_QUEUE_NAME = os.getenv(
"DOCUMENT_PROCESSING_QUEUE_NAME", "doc-processing"
)
# Azure Blob Storage
self.AZURE_BLOB_ACCOUNT_NAME = os.getenv("AZURE_BLOB_ACCOUNT_NAME", "")
self.AZURE_BLOB_ACCOUNT_KEY = self.secretHelper.get_secret(
"AZURE_BLOB_ACCOUNT_KEY"
)
self.AZURE_BLOB_CONTAINER_NAME = os.getenv("AZURE_BLOB_CONTAINER_NAME", "")
self.AZURE_STORAGE_ACCOUNT_ENDPOINT = os.getenv(
"AZURE_STORAGE_ACCOUNT_ENDPOINT",
f"https://{self.AZURE_BLOB_ACCOUNT_NAME}.blob.core.windows.net/",
)
# Azure Form Recognizer
self.AZURE_FORM_RECOGNIZER_ENDPOINT = os.getenv(
"AZURE_FORM_RECOGNIZER_ENDPOINT", ""
)
self.AZURE_FORM_RECOGNIZER_KEY = self.secretHelper.get_secret(
"AZURE_FORM_RECOGNIZER_KEY"
)
# Azure App Insights
# APPLICATIONINSIGHTS_ENABLED will be True when the application runs in App Service
self.APPLICATIONINSIGHTS_ENABLED = self.get_env_var_bool(
"APPLICATIONINSIGHTS_ENABLED", "False"
)
# Azure AI Content Safety
self.AZURE_CONTENT_SAFETY_ENDPOINT = os.getenv(
"AZURE_CONTENT_SAFETY_ENDPOINT", ""
)
if (
"https" not in self.AZURE_CONTENT_SAFETY_ENDPOINT
and "api.cognitive.microsoft.com" not in self.AZURE_CONTENT_SAFETY_ENDPOINT
):
self.AZURE_CONTENT_SAFETY_ENDPOINT = self.AZURE_FORM_RECOGNIZER_ENDPOINT
self.AZURE_CONTENT_SAFETY_KEY = self.secretHelper.get_secret(
"AZURE_CONTENT_SAFETY_KEY"
)
# Orchestration Settings
self.ORCHESTRATION_STRATEGY = os.getenv(
"ORCHESTRATION_STRATEGY", "openai_function"
)
# Conversation Type - which chooses between custom or byod
self.CONVERSATION_FLOW = os.getenv(
"CONVERSATION_FLOW", ConversationFlow.CUSTOM.value
)
# Speech Service
self.AZURE_SPEECH_SERVICE_NAME = os.getenv("AZURE_SPEECH_SERVICE_NAME", "")
self.AZURE_SPEECH_SERVICE_REGION = os.getenv("AZURE_SPEECH_SERVICE_REGION")
self.AZURE_SPEECH_RECOGNIZER_LANGUAGES = self.get_env_var_array(
"AZURE_SPEECH_RECOGNIZER_LANGUAGES", "en-US"
)
self.AZURE_SPEECH_REGION_ENDPOINT = os.environ.get(
"AZURE_SPEECH_REGION_ENDPOINT",
f"https://{self.AZURE_SPEECH_SERVICE_REGION}.api.cognitive.microsoft.com/",
)
self.LOAD_CONFIG_FROM_BLOB_STORAGE = self.get_env_var_bool(
"LOAD_CONFIG_FROM_BLOB_STORAGE"
)
def should_use_data(self) -> bool:
if (
self.AZURE_SEARCH_SERVICE
and self.AZURE_SEARCH_INDEX
and (self.AZURE_SEARCH_KEY or self.AZURE_AUTH_TYPE == "rbac")
):
return True
return False
def is_chat_model(self):
if "gpt-4" in self.AZURE_OPENAI_MODEL_NAME.lower():
return True
return False
def get_env_var_bool(self, var_name: str, default: str = "True") -> bool:
return os.getenv(var_name, default).lower() == "true"
def get_env_var_array(self, var_name: str, default: str = ""):
return os.getenv(var_name, default).split(",")
def get_env_var_float(self, var_name: str, default: int):
return float(os.getenv(var_name, default))
def is_auth_type_keys(self):
return self.AZURE_AUTH_TYPE == "keys"
@staticmethod
def check_env():
for attr, value in EnvHelper().__dict__.items():
if value == "":
logger.warning(f"{attr} is not set in the environment variables.")
@classmethod
def clear_instance(cls):
if cls._instance is not None:
cls._instance = None
class SecretHelper:
def __init__(self) -> None:
"""
Initializes an instance of the SecretHelper class.
The constructor sets the USE_KEY_VAULT attribute based on the value of the USE_KEY_VAULT environment variable.
If USE_KEY_VAULT is set to "true" (case-insensitive), it initializes a SecretClient object using the
AZURE_KEY_VAULT_ENDPOINT environment variable and the DefaultAzureCredential.
Args:
None
Returns:
None
"""
self.USE_KEY_VAULT = os.getenv("USE_KEY_VAULT", "").lower() == "true"
self.secret_client = None
if self.USE_KEY_VAULT:
self.secret_client = SecretClient(
os.environ.get("AZURE_KEY_VAULT_ENDPOINT"), DefaultAzureCredential()
)
def get_secret(self, secret_name: str) -> str:
"""
Retrieves the value of a secret from the environment variables or Azure Key Vault.
Args:
secret_name (str): The name of the secret or "".
Returns:
str: The value of the secret.
Raises:
None
"""
return (
self.secret_client.get_secret(os.getenv(secret_name, "")).value
if self.USE_KEY_VAULT
else os.getenv(secret_name, "")
)