|
2 | 2 |
|
3 | 3 | import json |
4 | 4 | import os |
| 5 | +import sys |
5 | 6 | import platform |
6 | 7 | from typing import TYPE_CHECKING, Any, Dict |
7 | 8 |
|
|
12 | 13 | import together |
13 | 14 | from together import error |
14 | 15 | from together.utils._log import _console_log_level |
| 16 | +from together.utils import log_info |
15 | 17 |
|
16 | 18 |
|
17 | 19 | def get_headers( |
@@ -82,3 +84,41 @@ def default_api_key(api_key: str | None = None) -> str | None: |
82 | 84 | return os.environ.get("TOGETHER_API_KEY") |
83 | 85 |
|
84 | 86 | raise error.AuthenticationError(together.constants.MISSING_API_KEY_MESSAGE) |
| 87 | + |
| 88 | + |
| 89 | +def get_google_colab_secret(secret_name: str = "TOGETHER_API_KEY") -> str | None: |
| 90 | + """ |
| 91 | + Checks to see if the user is running in Google Colab, and looks for the Together API Key secret. |
| 92 | +
|
| 93 | + Args: |
| 94 | + secret_name (str, optional). Defaults to TOGETHER_API_KEY |
| 95 | +
|
| 96 | + Returns: |
| 97 | + str: if the API key is found; None if an error occurred or the secret was not found. |
| 98 | + """ |
| 99 | + # If running in Google Colab, check for Together in notebook secrets |
| 100 | + if "google.colab" in sys.modules: |
| 101 | + if TYPE_CHECKING: |
| 102 | + from google.colab import userdata # type: ignore |
| 103 | + else: |
| 104 | + from google.colab import userdata |
| 105 | + |
| 106 | + try: |
| 107 | + api_key = userdata.get(secret_name) |
| 108 | + if not isinstance(api_key, str): |
| 109 | + return None |
| 110 | + else: |
| 111 | + return str(api_key) |
| 112 | + except userdata.NotebookAccessError: |
| 113 | + log_info( |
| 114 | + "The TOGETHER_API_KEY Colab secret was found, but notebook access is disabled. Please enable notebook " |
| 115 | + "access for the secret." |
| 116 | + ) |
| 117 | + except userdata.SecretNotFoundError: |
| 118 | + # warn and carry on |
| 119 | + log_info("Colab: No Google Colab secret named TOGETHER_API_KEY was found.") |
| 120 | + |
| 121 | + return None |
| 122 | + |
| 123 | + else: |
| 124 | + return None |
0 commit comments