Using dotenv instead of parsing keys ourselves (#1295)

### Motivation and Context

This changes our parsing of the .env file to use
[`python-dotenv`](https://pypi.org/project/python-dotenv/) which will be
more flexible.
Tested that the notebooks would still run correctly.
This commit is contained in:
Mark Karle
2023-06-07 15:53:32 -07:00
committed by GitHub
parent 05d9e72322
commit 4c4670acb2
3 changed files with 11 additions and 34 deletions
+2 -2
View File
@@ -2629,7 +2629,7 @@ six = ">=1.5"
name = "python-dotenv"
version = "1.0.0"
description = "Read key-value pairs from a .env file and set them as environment variables"
category = "dev"
category = "main"
optional = false
python-versions = ">=3.8"
files = [
@@ -4036,4 +4036,4 @@ cffi = ["cffi (>=1.11)"]
[metadata]
lock-version = "2.0"
python-versions = "^3.8"
content-hash = "da5651575ed9ca821808283ee9a4ab370ffce1c7f63ee6533080857d913bad67"
content-hash = "4596fb06a8467cdd8eed62bd1d425c0f7cdd704405b0fc15ed79af4d98a6ee5f"
+1
View File
@@ -11,6 +11,7 @@ python = "^3.8"
numpy = "^1.24.2"
openai = "^0.27.0"
aiofiles = "^23.1.0"
python-dotenv = "1.0.0"
[tool.poetry.group.dev.dependencies]
pre-commit = "2.21.0"
+8 -32
View File
@@ -1,6 +1,7 @@
# Copyright (c) Microsoft. All rights reserved.
from typing import Optional, Tuple
from dotenv import dotenv_values
def openai_settings_from_dot_env() -> Tuple[str, Optional[str]]:
@@ -11,20 +12,9 @@ def openai_settings_from_dot_env() -> Tuple[str, Optional[str]]:
Tuple[str, str]: The OpenAI API key, the OpenAI organization ID
"""
api_key, org_id = None, None
with open(".env", "r") as f:
lines = f.readlines()
for line in lines:
if line.startswith("OPENAI_API_KEY"):
parts = line.split("=")[1:]
api_key = "=".join(parts).strip().strip('"')
continue
if line.startswith("OPENAI_ORG_ID"):
parts = line.split("=")[1:]
org_id = "=".join(parts).strip().strip('"')
continue
config = dotenv_values(".env")
api_key = config.get("OPENAI_API_KEY", None)
org_id = config.get("OPENAI_ORG_ID", None)
assert api_key is not None, "OpenAI API key not found in .env file"
@@ -42,24 +32,10 @@ def azure_openai_settings_from_dot_env(include_deployment=True) -> Tuple[str, st
"""
deployment, api_key, endpoint = None, None, None
with open(".env", "r") as f:
lines = f.readlines()
for line in lines:
if include_deployment and line.startswith("AZURE_OPENAI_DEPLOYMENT_NAME"):
parts = line.split("=")[1:]
deployment = "=".join(parts).strip().strip('"')
continue
if line.startswith("AZURE_OPENAI_API_KEY"):
parts = line.split("=")[1:]
api_key = "=".join(parts).strip().strip('"')
continue
if line.startswith("AZURE_OPENAI_ENDPOINT"):
parts = line.split("=")[1:]
endpoint = "=".join(parts).strip().strip('"')
continue
config = dotenv_values(".env")
deployment = config.get("AZURE_OPENAI_DEPLOYMENT_NAME", None)
api_key = config.get("AZURE_OPENAI_API_KEY", None)
endpoint = config.get("AZURE_OPENAI_ENDPOINT", None)
# Azure requires the deployment name, the API key and the endpoint URL.
if include_deployment: