theskumar/python-dotenv

How to get openai api_key from the local environment [if api_key is already set in the environment ]

lakshmiprabharamesh opened this issue · 1 comments

Requesting to add the below code snippet in the Python-dotenv documentation under Other Use cases section.

It will be very helpful for developers looking to develop applications with LLM's like ChatGPT.

`from dotenv import load_dotenv, find_dotenv

dotenv_path = find_dotenv()

_ = load_dotenv(find_dotenv()) # read local .env file

openai.api_key = os.getenv(OPENAI_API_KEY)`

Already on documentation with **os.environ not sure how is this different.

import os
from dotenv import dotenv_values

config = {
    **dotenv_values(".env.shared"),  # load shared development variables
    **dotenv_values(".env.secret"),  # load sensitive variables
    **os.environ,  # override loaded values with environment variables
}

Here's the example

❯ cat .env.shared
key="foo"
❯ export key="bar"
import os
from dotenv import dotenv_values

config = {
    **dotenv_values(".env.shared"),  # load shared development variables
    **dotenv_values(".env.secret"),  # load sensitive variables
    **os.environ,  # override loaded values with environment variables
}

class openai:
    api_key: str

openai.api_key = config['key']
print(f"KEY: {openai.api_key}") 
❯ python test.py
OPEN AI API KEY: bar