File size: 1,089 Bytes
34b531b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
from __future__ import annotations

from contextvars import ContextVar
import os


_gemini_api_key: ContextVar[str] = ContextVar("gemini_api_key", default="")
_hf_api_key: ContextVar[str] = ContextVar("hf_api_key", default="")


def set_runtime_api_keys(*, gemini_api_key: str = "", hf_api_key: str = "") -> None:
    _gemini_api_key.set(gemini_api_key.strip())
    _hf_api_key.set(hf_api_key.strip())


def get_gemini_api_key() -> str:
    runtime_key = _gemini_api_key.get()
    if runtime_key or _requires_user_keys():
        return runtime_key
    return os.getenv("GEMINI_API_KEY", "").strip()


def get_hf_api_key() -> str:
    runtime_key = _hf_api_key.get()
    if runtime_key or _requires_user_keys():
        return runtime_key
    return (
        os.getenv("HF_API_KEY")
        or os.getenv("HG_API_KEY")
        or os.getenv("HUGGINGFACEHUB_API_TOKEN")
        or ""
    ).strip()


def has_hf_api_key() -> bool:
    return bool(get_hf_api_key())


def _requires_user_keys() -> bool:
    return os.getenv("REQUIRE_USER_API_KEYS", "").strip().lower() in {"1", "true", "yes"}