tarzanagh commited on
Commit
08ff82f
·
verified ·
1 Parent(s): 4a4e780

Fix stale event loop + .env loading

Browse files
src/passage_entity/benchmark_runner.py CHANGED
@@ -79,17 +79,24 @@ from src.passage_entity.utils import QuerySolution
79
  # ---------------------------------------------------------------------------
80
  from openai import AsyncOpenAI
81
 
82
- # Shared client avoids "Event loop is closed" errors from abandoned clients
83
- _openai_clients: dict = {}
84
-
 
 
 
 
 
 
 
 
 
 
85
  def _get_client(base_url="https://api.openai.com/v1", api_key=""):
86
- key = (base_url, api_key)
87
- if key not in _openai_clients:
88
- _openai_clients[key] = AsyncOpenAI(
89
- base_url=base_url,
90
- api_key=api_key or os.environ.get("OPENAI_API_KEY", ""),
91
- )
92
- return _openai_clients[key]
93
 
94
  async def _openai_complete(model, prompt, system_prompt=None, history_messages=[],
95
  base_url="https://api.openai.com/v1", api_key="", **kwargs):
 
79
  # ---------------------------------------------------------------------------
80
  from openai import AsyncOpenAI
81
 
82
+ # Load .env file if present (for API keys)
83
+ _dotenv_path = os.path.join(os.path.dirname(__file__), "..", "..", ".env")
84
+ if os.path.isfile(_dotenv_path):
85
+ with open(_dotenv_path) as _f:
86
+ for _line in _f:
87
+ _line = _line.strip()
88
+ if _line and not _line.startswith("#") and "=" in _line:
89
+ _k, _v = _line.split("=", 1)
90
+ _v = _v.strip().strip('"').strip("'")
91
+ if _k.strip() not in os.environ:
92
+ os.environ[_k.strip()] = _v
93
+
94
+ # Create a fresh client per call — avoids stale event loop issues
95
  def _get_client(base_url="https://api.openai.com/v1", api_key=""):
96
+ return AsyncOpenAI(
97
+ base_url=base_url,
98
+ api_key=api_key or os.environ.get("OPENAI_API_KEY", ""),
99
+ )
 
 
 
100
 
101
  async def _openai_complete(model, prompt, system_prompt=None, history_messages=[],
102
  base_url="https://api.openai.com/v1", api_key="", **kwargs):