Skip to content

Commit 261c56a

Browse files
authored
Enhance robustness (#11)
1 parent add7e7c commit 261c56a

File tree

1 file changed

+32
-8
lines changed
  • src/turtle_agent/scripts

1 file changed

+32
-8
lines changed

src/turtle_agent/scripts/llm.py

Lines changed: 32 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -23,17 +23,17 @@ def get_llm():
2323
"""A helper function to get the LLM instance."""
2424
dotenv.load_dotenv(dotenv.find_dotenv())
2525

26-
APIM_SUBSCRIPTION_KEY = os.getenv("APIM_SUBSCRIPTION_KEY")
26+
APIM_SUBSCRIPTION_KEY = get_env_variable("APIM_SUBSCRIPTION_KEY")
2727
default_headers = {}
28-
if APIM_SUBSCRIPTION_KEY != None:
28+
if APIM_SUBSCRIPTION_KEY is not None:
2929
# only set this if the APIM API requires a subscription...
3030
default_headers["Ocp-Apim-Subscription-Key"] = APIM_SUBSCRIPTION_KEY
3131

3232
# Set up authority and credentials for Azure authentication
3333
credential = ClientSecretCredential(
34-
tenant_id=os.getenv("AZURE_TENANT_ID"),
35-
client_id=os.getenv("AZURE_CLIENT_ID"),
36-
client_secret=os.getenv("AZURE_CLIENT_SECRET"),
34+
tenant_id=get_env_variable("AZURE_TENANT_ID"),
35+
client_id=get_env_variable("AZURE_CLIENT_ID"),
36+
client_secret=get_env_variable("AZURE_CLIENT_SECRET"),
3737
authority="https://login.microsoftonline.com",
3838
)
3939

@@ -42,12 +42,36 @@ def get_llm():
4242
)
4343

4444
llm = AzureChatOpenAI(
45-
azure_deployment=os.getenv("DEPLOYMENT_ID"),
45+
azure_deployment=get_env_variable("DEPLOYMENT_ID"),
4646
azure_ad_token_provider=token_provider,
4747
openai_api_type="azure_ad",
48-
api_version=os.getenv("API_VERSION"),
49-
azure_endpoint=os.getenv("API_ENDPOINT"),
48+
api_version=get_env_variable("API_VERSION"),
49+
azure_endpoint=get_env_variable("API_ENDPOINT"),
5050
default_headers=default_headers,
5151
)
5252

5353
return llm
54+
55+
56+
def get_env_variable(var_name):
57+
"""
58+
Retrieves the value of the specified environment variable.
59+
60+
Args:
61+
var_name (str): The name of the environment variable to retrieve.
62+
63+
Returns:
64+
str: The value of the environment variable.
65+
66+
Raises:
67+
ValueError: If the environment variable is not set.
68+
69+
This function provides a consistent and safe way to retrieve environment variables.
70+
By using this function, we ensure that all required environment variables are present
71+
before proceeding with any operations. If a variable is not set, the function will
72+
raise a ValueError, making it easier to debug configuration issues.
73+
"""
74+
value = os.getenv(var_name)
75+
if value is None:
76+
raise ValueError(f"Environment variable {var_name} is not set.")
77+
return value

0 commit comments

Comments
 (0)