Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ All notable changes to QueryRouter++ are documented here.
- Unused `RouterTrainer` and query-taxonomy loader classes.

### Fixed
- **OpenAI proxy**: tool-calling turns keep `tool_calls` / `tool_call_id`, standard OpenAI params (`stop`, `seed`, `tools`, `tool_choice`, `response_format`, penalties, `max_completion_tokens`...) are forwarded upstream, and an unreachable provider returns 502 instead of 500.
- `QueryRouter()` without `data_dir` now finds `data_models/`.
- docker-compose health check (curl is not in the slim image); MongoDB password is required and bound to localhost.
- Exploration notebook paths and benchmark columns.
Expand Down
26 changes: 26 additions & 0 deletions docs/openapi.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

13 changes: 13 additions & 0 deletions docs/openapi.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

37 changes: 36 additions & 1 deletion src/queryrouter/api/openai_compat.py
Original file line number Diff line number Diff line change
Expand Up @@ -80,6 +80,10 @@ class ChatMessage(BaseModel):
role: str
content: str | list[Any] | None = None
name: str | None = None
# Tool-calling turns: dropping these makes the upstream reject the
# conversation ("tool" messages must answer a prior tool_call id).
tool_calls: list[dict[str, Any]] | None = None
tool_call_id: str | None = None


class ChatCompletionRequest(BaseModel):
Expand Down Expand Up @@ -183,6 +187,27 @@ def _resolve_preference(request: ChatCompletionRequest) -> str:
return preference


# Standard OpenAI chat parameters forwarded verbatim when the client sends them.
# QueryRouter-only fields (routing_preference, modelKwargs) are never forwarded.
_PASSTHROUGH_PARAMS: tuple[str, ...] = (
"stop",
"presence_penalty",
"frequency_penalty",
"seed",
"n",
"logit_bias",
"logprobs",
"top_logprobs",
"user",
"tools",
"tool_choice",
"parallel_tool_calls",
"response_format",
"max_completion_tokens",
"stream_options",
)


def _build_upstream_body(
request: ChatCompletionRequest,
model_id: str,
Expand All @@ -199,6 +224,10 @@ def _build_upstream_body(
body["top_p"] = request.top_p
if request.max_tokens is not None:
body["max_tokens"] = request.max_tokens
extra = request.model_extra or {}
for key in _PASSTHROUGH_PARAMS:
if extra.get(key) is not None:
body[key] = extra[key]
return body


Expand Down Expand Up @@ -331,7 +360,13 @@ async def chat_completions(request: ChatCompletionRequest) -> Any:

# Non-streaming
async with httpx.AsyncClient(timeout=120.0) as client:
resp = await client.post(url, json=upstream_body, headers=headers)
try:
resp = await client.post(url, json=upstream_body, headers=headers)
except httpx.HTTPError as exc:
raise HTTPException(
status_code=502,
detail=f"Provider '{provider}' unreachable: {type(exc).__name__}",
) from exc
if resp.status_code != 200:
raise HTTPException(status_code=resp.status_code, detail=resp.text)
data = resp.json()
Expand Down
76 changes: 76 additions & 0 deletions tests/test_openai_compat.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,9 @@

from __future__ import annotations

from typing import Any

import httpx
import pytest
from fastapi.testclient import TestClient

Expand All @@ -14,6 +17,7 @@
PROVIDER_CONFIG,
ChatCompletionRequest,
ChatMessage,
_build_upstream_body,
_extract_query,
_get_provider_key,
_get_provider_url,
Expand Down Expand Up @@ -130,6 +134,78 @@ def test_empty_messages_returns_400(self) -> None:
)
assert response.status_code == 400

def test_unreachable_upstream_returns_502(self, monkeypatch: pytest.MonkeyPatch) -> None:
for provider, (_, key_env) in PROVIDER_CONFIG.items():
monkeypatch.setenv(key_env, "test-key")
monkeypatch.setenv(
f"QUERYROUTER_{_provider_env_name(provider)}_BASE_URL",
"http://upstream.invalid/v1",
)

async def _unreachable(self: httpx.AsyncClient, *args: Any, **kwargs: Any) -> None:
raise httpx.ConnectError("unreachable")

monkeypatch.setattr(httpx.AsyncClient, "post", _unreachable)
response = client.post(
"/v1/chat/completions",
json={
"model": "queryrouter-auto",
"messages": [{"role": "user", "content": "Hello"}],
},
)
assert response.status_code == 502
assert "unreachable" in response.json()["detail"]


class TestBuildUpstreamBody:
def test_forwards_standard_openai_params(self) -> None:
req = ChatCompletionRequest.model_validate(
{
"messages": [{"role": "user", "content": "hi"}],
"stop": ["END"],
"seed": 7,
"tool_choice": "auto",
"tools": [{"type": "function", "function": {"name": "weather"}}],
"response_format": {"type": "json_object"},
"routing_preference": "cost",
"modelKwargs": {"routing_preference": "cost"},
}
)
body = _build_upstream_body(req, "gpt-test")
assert body["model"] == "gpt-test"
assert body["stop"] == ["END"]
assert body["seed"] == 7
assert body["tool_choice"] == "auto"
assert body["tools"][0]["function"]["name"] == "weather"
assert body["response_format"] == {"type": "json_object"}
assert "routing_preference" not in body
assert "modelKwargs" not in body

def test_keeps_tool_call_fields_on_messages(self) -> None:
req = ChatCompletionRequest.model_validate(
{
"messages": [
{"role": "user", "content": "Weather in Lille?"},
{
"role": "assistant",
"content": None,
"tool_calls": [
{
"id": "call_1",
"type": "function",
"function": {"name": "weather", "arguments": "{}"},
}
],
},
{"role": "tool", "tool_call_id": "call_1", "content": "Sunny"},
]
}
)
messages = _build_upstream_body(req, "gpt-test")["messages"]
assert messages[1]["tool_calls"][0]["id"] == "call_1"
assert "content" not in messages[1]
assert messages[2]["tool_call_id"] == "call_1"


class TestProviderConfig:
"""Every provider in the model data must be reachable through the proxy."""
Expand Down