diff --git a/CHANGELOG.md b/CHANGELOG.md index 9031ad2..f25279f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -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. diff --git a/docs/openapi.json b/docs/openapi.json index 56f45c3..993efe1 100644 --- a/docs/openapi.json +++ b/docs/openapi.json @@ -307,6 +307,32 @@ } ], "title": "Name" + }, + "tool_calls": { + "anyOf": [ + { + "items": { + "additionalProperties": true, + "type": "object" + }, + "type": "array" + }, + { + "type": "null" + } + ], + "title": "Tool Calls" + }, + "tool_call_id": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Tool Call Id" } }, "type": "object", diff --git a/docs/openapi.yaml b/docs/openapi.yaml index 9f1ccb2..1cc586b 100644 --- a/docs/openapi.yaml +++ b/docs/openapi.yaml @@ -210,6 +210,19 @@ components: - type: string - type: 'null' title: Name + tool_calls: + anyOf: + - items: + additionalProperties: true + type: object + type: array + - type: 'null' + title: Tool Calls + tool_call_id: + anyOf: + - type: string + - type: 'null' + title: Tool Call Id type: object required: - role diff --git a/src/queryrouter/api/openai_compat.py b/src/queryrouter/api/openai_compat.py index 202470f..0dcc411 100644 --- a/src/queryrouter/api/openai_compat.py +++ b/src/queryrouter/api/openai_compat.py @@ -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): @@ -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, @@ -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 @@ -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() diff --git a/tests/test_openai_compat.py b/tests/test_openai_compat.py index f8830a4..f000612 100644 --- a/tests/test_openai_compat.py +++ b/tests/test_openai_compat.py @@ -5,6 +5,9 @@ from __future__ import annotations +from typing import Any + +import httpx import pytest from fastapi.testclient import TestClient @@ -14,6 +17,7 @@ PROVIDER_CONFIG, ChatCompletionRequest, ChatMessage, + _build_upstream_body, _extract_query, _get_provider_key, _get_provider_url, @@ -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."""