fix: bracket MemoryBank() with temp env to honor BYOK
Browse files
server.py
CHANGED
|
@@ -108,8 +108,23 @@ def _has_memory_bank(cfg: dict) -> bool:
|
|
| 108 |
|
| 109 |
|
| 110 |
def _build_memory_bank(path: str, *, openai_api_key: str) -> MemoryBank:
|
| 111 |
-
"""Load the prebuilt bank; force embeddings to use the caller's key.
|
| 112 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 113 |
bank._client = OpenAI(api_key=openai_api_key) # noqa: SLF001
|
| 114 |
return bank
|
| 115 |
|
|
|
|
| 108 |
|
| 109 |
|
| 110 |
def _build_memory_bank(path: str, *, openai_api_key: str) -> MemoryBank:
|
| 111 |
+
"""Load the prebuilt bank; force embeddings to use the caller's key.
|
| 112 |
+
|
| 113 |
+
MemoryBank.__init__ instantiates ``OpenAI()`` with no args, which raises
|
| 114 |
+
on the Space because OPENAI_API_KEY is not in the env. We bracket the
|
| 115 |
+
constructor with a temporary env mutation, then replace the client.
|
| 116 |
+
The mutation is safe because no coroutine yields between the set and
|
| 117 |
+
the constructor (single-threaded asyncio).
|
| 118 |
+
"""
|
| 119 |
+
prev = os.environ.get("OPENAI_API_KEY")
|
| 120 |
+
os.environ["OPENAI_API_KEY"] = openai_api_key
|
| 121 |
+
try:
|
| 122 |
+
bank = MemoryBank(store_dir=path)
|
| 123 |
+
finally:
|
| 124 |
+
if prev is None:
|
| 125 |
+
os.environ.pop("OPENAI_API_KEY", None)
|
| 126 |
+
else:
|
| 127 |
+
os.environ["OPENAI_API_KEY"] = prev
|
| 128 |
bank._client = OpenAI(api_key=openai_api_key) # noqa: SLF001
|
| 129 |
return bank
|
| 130 |
|