Normalize OpenAI base URLs

This commit is contained in:
2026-04-04 23:17:17 +08:00
parent 7e8523fdaa
commit 0b7cad7da3
2 changed files with 21 additions and 2 deletions

View File

@@ -22,6 +22,14 @@ def _auth_headers(api_key_env: str | None) -> dict[str, str]:
return headers
def _openai_url(base_url: str, path: str) -> str:
root = base_url.rstrip("/")
normalized_path = "/" + path.lstrip("/")
if root.endswith("/v1") and normalized_path.startswith("/v1/"):
normalized_path = normalized_path[len("/v1") :]
return root + normalized_path
def wait_for_server(base_url: str, path: str, timeout_s: float) -> None:
deadline = time.monotonic() + timeout_s
url = f"{base_url.rstrip('/')}{path}"
@@ -52,7 +60,7 @@ def chat_completion(
payload["messages"] = [{"role": "system", "content": system_prompt}, *messages]
data = json.dumps(payload).encode("utf-8")
request = urllib.request.Request(
url=f"{base_url.rstrip('/')}/v1/chat/completions",
url=_openai_url(base_url, "/v1/chat/completions"),
headers=_auth_headers(api_key_env),
data=data,
method="POST",
@@ -80,7 +88,7 @@ def stream_chat_completion(
) -> StreamMetrics:
data = json.dumps(body).encode("utf-8")
request = urllib.request.Request(
url=f"{base_url.rstrip('/')}/v1/chat/completions",
url=_openai_url(base_url, "/v1/chat/completions"),
headers=_auth_headers(None),
data=data,
method="POST",