|
1 | 1 | import logging |
2 | 2 | import os |
3 | | -from typing import Optional |
| 3 | +from typing import Dict, Optional |
4 | 4 |
|
5 | 5 | import requests |
| 6 | +from dotenv import dotenv_values, find_dotenv, load_dotenv |
6 | 7 |
|
7 | 8 | logger = logging.getLogger(__name__) |
8 | 9 |
|
9 | 10 |
|
| 11 | +def find_dotenv_path(search_path: Optional[str] = None) -> Optional[str]: |
| 12 | + """ |
| 13 | + Find the .env file path, searching .env.dev first, then .env. |
| 14 | +
|
| 15 | + Args: |
| 16 | + search_path: Directory to search from. If None, uses current working directory. |
| 17 | +
|
| 18 | + Returns: |
| 19 | + Path to the .env file if found, otherwise None. |
| 20 | + """ |
| 21 | + # If a specific search path is provided, look there first |
| 22 | + if search_path: |
| 23 | + env_dev_path = os.path.join(search_path, ".env.dev") |
| 24 | + if os.path.isfile(env_dev_path): |
| 25 | + return env_dev_path |
| 26 | + env_path = os.path.join(search_path, ".env") |
| 27 | + if os.path.isfile(env_path): |
| 28 | + return env_path |
| 29 | + return None |
| 30 | + |
| 31 | + # Otherwise use find_dotenv to search up the directory tree |
| 32 | + env_dev_path = find_dotenv(filename=".env.dev", raise_error_if_not_found=False, usecwd=True) |
| 33 | + if env_dev_path: |
| 34 | + return env_dev_path |
| 35 | + env_path = find_dotenv(filename=".env", raise_error_if_not_found=False, usecwd=True) |
| 36 | + if env_path: |
| 37 | + return env_path |
| 38 | + return None |
| 39 | + |
| 40 | + |
| 41 | +def get_dotenv_values(search_path: Optional[str] = None) -> Dict[str, Optional[str]]: |
| 42 | + """ |
| 43 | + Get all key-value pairs from the .env file. |
| 44 | +
|
| 45 | + Args: |
| 46 | + search_path: Directory to search from. If None, uses current working directory. |
| 47 | +
|
| 48 | + Returns: |
| 49 | + Dictionary of environment variable names to values. |
| 50 | + """ |
| 51 | + dotenv_path = find_dotenv_path(search_path) |
| 52 | + if dotenv_path: |
| 53 | + return dotenv_values(dotenv_path) |
| 54 | + return {} |
| 55 | + |
| 56 | + |
| 57 | +# --- Load .env files --- |
| 58 | +# Attempt to load .env.dev first, then .env as a fallback. |
| 59 | +# This happens when the module is imported. |
| 60 | +# We use override=False (default) so that existing environment variables |
| 61 | +# (e.g., set in the shell) are NOT overridden by .env files. |
| 62 | +_DOTENV_PATH = find_dotenv_path() |
| 63 | +if _DOTENV_PATH: |
| 64 | + load_dotenv(dotenv_path=_DOTENV_PATH, override=False) |
| 65 | + logger.debug(f"eval_protocol.auth: Loaded environment variables from: {_DOTENV_PATH}") |
| 66 | +else: |
| 67 | + logger.debug( |
| 68 | + "eval_protocol.auth: No .env.dev or .env file found. Relying on shell/existing environment variables." |
| 69 | + ) |
| 70 | +# --- End .env loading --- |
| 71 | + |
| 72 | + |
10 | 73 | def get_fireworks_api_key() -> Optional[str]: |
11 | 74 | """ |
12 | 75 | Retrieves the Fireworks API key. |
|
0 commit comments