Skip to content

Commit 287935a

Browse files
fix(models): resolve constructor conflicts and honor stream usage
Resolve duplicate OpenAI and vLLM constructor options while preserving configured model, credentials and endpoint precedence. Default OpenAI stream usage to true and honor explicit false in synchronous and asynchronous calls. Validation: 83 focused tests passed locally; changed test files pass Ruff; git diff --check passes. GitHub Typos Check passed. No live provider or deployment validation was performed.
1 parent 5278859 commit 287935a

4 files changed

Lines changed: 181 additions & 17 deletions

File tree

‎backend/apps/ai_model/model_factory.py‎

Lines changed: 14 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -69,13 +69,14 @@ def llm(self) -> BaseChatModel:
6969

7070
class OpenAIvLLM(BaseLLM):
7171
def _init_llm(self) -> VLLMOpenAI:
72-
return VLLMOpenAI(
73-
openai_api_key=self.config.api_key or 'Empty',
74-
openai_api_base=self.config.api_base_url,
75-
model_name=self.config.model_name,
76-
streaming=True,
72+
options = {
7773
**self.config.additional_params,
78-
)
74+
"openai_api_key": self.config.api_key or 'Empty',
75+
"openai_api_base": self.config.api_base_url,
76+
"model_name": self.config.model_name,
77+
"streaming": True,
78+
}
79+
return VLLMOpenAI(**options)
7980

8081

8182
class OpenAIAzureLLM(BaseLLM):
@@ -99,13 +100,14 @@ def _init_llm(self) -> AzureChatOpenAI:
99100

100101
class OpenAILLM(BaseLLM):
101102
def _init_llm(self) -> BaseChatModel:
102-
return BaseChatOpenAI(
103-
model=self.config.model_name,
104-
api_key=self.config.api_key or 'Empty',
105-
base_url=self.config.api_base_url,
106-
stream_usage=True,
103+
options = {
104+
"stream_usage": True,
107105
**self.config.additional_params,
108-
)
106+
"model": self.config.model_name,
107+
"api_key": self.config.api_key or 'Empty',
108+
"base_url": self.config.api_base_url,
109+
}
110+
return BaseChatOpenAI(**options)
109111

110112
def generate(self, prompt: str) -> str:
111113
return self.llm.invoke(prompt)

‎backend/apps/ai_model/openai/llm.py‎

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -113,7 +113,6 @@ def get_last_generation_info(self) -> dict[str, Any] | None:
113113
return self.usage_metadata
114114

115115
def _stream(self, *args: Any, **kwargs: Any) -> Iterator[ChatGenerationChunk]:
116-
kwargs['stream_usage'] = True
117116
for chunk in super()._stream(*args, **kwargs):
118117
if chunk.message.usage_metadata is not None:
119118
self.usage_metadata = chunk.message.usage_metadata

‎backend/tests/test_model_validation_parameters.py‎

Lines changed: 166 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,8 @@
33
import ast
44
import asyncio
55
import json
6+
from abc import ABC, abstractmethod
7+
from functools import lru_cache
68
from pathlib import Path
79
from types import SimpleNamespace
810
from typing import Any, Optional
@@ -60,20 +62,43 @@ async def stream(_question):
6062
namespace["LLMFactory"] = factory
6163
handler = load_symbol("apps/system/api/aimodel.py", "check_llm", namespace)
6264

63-
def run(rows):
65+
def run(rows, *, protocol=1, provider=None):
66+
if provider is not None:
67+
namespace.update(
68+
ABC=ABC,
69+
abstractmethod=abstractmethod,
70+
BaseChatModel=object,
71+
BaseChatOpenAI=provider,
72+
VLLMOpenAI=provider,
73+
AzureChatOpenAI=object,
74+
Type=type,
75+
lru_cache=lru_cache,
76+
)
77+
for name in (
78+
"BaseLLM",
79+
"OpenAILLM",
80+
"OpenAIvLLM",
81+
"OpenAIAzureLLM",
82+
"LLMFactory",
83+
):
84+
load_symbol("apps/ai_model/model_factory.py", name, namespace)
85+
factory.create_llm.side_effect = namespace["LLMFactory"].create_llm
86+
namespace["LLMFactory"] = factory
87+
provider.return_value = SimpleNamespace(astream=stream)
88+
6489
info = namespace["AiModelCreator"](
6590
name="test",
6691
model_type=0,
6792
base_model="test",
6893
supplier=15,
69-
protocol=1,
94+
protocol=protocol,
7095
api_domain="https://example.test/v1",
7196
api_key="test-key",
7297
config_list=rows,
7398
)
7499

75100
async def consume():
76-
response = await handler(info, lambda key, **_kwargs: key)
101+
response = await handler(info, lambda key, **kwargs: kwargs.get("msg", key))
77102
assert isinstance(response, StreamingResponse)
78103
return [json.loads(chunk) async for chunk in response.body_iterator]
79104

@@ -141,3 +166,141 @@ def test_validation_mixed_configuration(validation):
141166
"max_tokens": 1024,
142167
"extra_body": {"enable_thinking": False},
143168
}
169+
170+
171+
@pytest.mark.parametrize(
172+
"protocol, streaming_key, constructor_options",
173+
[
174+
(
175+
1,
176+
"stream_usage",
177+
{
178+
"model": "test",
179+
"api_key": "test-key",
180+
"base_url": "https://example.test/v1",
181+
},
182+
),
183+
(
184+
2,
185+
"streaming",
186+
{
187+
"model_name": "test",
188+
"openai_api_key": "test-key",
189+
"openai_api_base": "https://example.test/v1",
190+
},
191+
),
192+
],
193+
)
194+
def test_validation_resolves_constructor_option_conflicts(
195+
validation, protocol, streaming_key, constructor_options
196+
):
197+
provider = Mock()
198+
params = {streaming_key: False, "temperature": 0}
199+
params.update(dict.fromkeys(constructor_options, "configured-override"))
200+
201+
assert (
202+
validation(
203+
[{"key": key, "val": value, "name": key} for key, value in params.items()],
204+
protocol=protocol,
205+
provider=provider,
206+
)
207+
== params
208+
)
209+
provider.assert_called_once_with(
210+
**constructor_options, **{streaming_key: protocol == 2, "temperature": 0}
211+
)
212+
213+
214+
@pytest.mark.parametrize("stream_usage", [None, True, False])
215+
def test_validation_defaults_stream_usage_without_overriding_configuration(
216+
validation, stream_usage
217+
):
218+
provider = Mock()
219+
params = {} if stream_usage is None else {"stream_usage": stream_usage}
220+
assert (
221+
validation(
222+
[{"key": key, "val": value, "name": key} for key, value in params.items()],
223+
provider=provider,
224+
)
225+
== params
226+
)
227+
assert provider.call_args.kwargs["stream_usage"] is (
228+
True if stream_usage is None else stream_usage
229+
)
230+
231+
232+
@pytest.mark.parametrize("asynchronous", [False, True])
233+
@pytest.mark.parametrize("stream_usage", [False, True])
234+
def test_openai_stream_usage_reaches_provider_request(asynchronous, stream_usage):
235+
import httpx
236+
237+
from apps.ai_model.openai.llm import BaseChatOpenAI
238+
239+
requests = []
240+
241+
def respond(request):
242+
payload = json.loads(request.content)
243+
requests.append(payload)
244+
chunks = [
245+
{
246+
"choices": [
247+
{
248+
"index": 0,
249+
"delta": {"role": "assistant", "content": "ok"},
250+
"finish_reason": "stop",
251+
}
252+
]
253+
}
254+
]
255+
if payload.get("stream_options", {}).get("include_usage"):
256+
chunks.append(
257+
{
258+
"choices": [],
259+
"usage": {
260+
"prompt_tokens": 2,
261+
"completion_tokens": 1,
262+
"total_tokens": 3,
263+
},
264+
}
265+
)
266+
body = (
267+
"".join(f"data: {json.dumps(chunk)}\n\n" for chunk in chunks)
268+
+ "data: [DONE]\n\n"
269+
)
270+
return httpx.Response(
271+
200, headers={"content-type": "text/event-stream"}, content=body
272+
)
273+
274+
async def consume_async():
275+
async with httpx.AsyncClient(transport=httpx.MockTransport(respond)) as client:
276+
llm = BaseChatOpenAI(
277+
model="test",
278+
api_key="test-key",
279+
base_url="https://example.test/v1",
280+
stream_usage=stream_usage,
281+
http_async_client=client,
282+
)
283+
return [chunk async for chunk in llm.astream("test")]
284+
285+
if asynchronous:
286+
chunks = asyncio.run(consume_async())
287+
else:
288+
with httpx.Client(transport=httpx.MockTransport(respond)) as client:
289+
llm = BaseChatOpenAI(
290+
model="test",
291+
api_key="test-key",
292+
base_url="https://example.test/v1",
293+
stream_usage=stream_usage,
294+
http_client=client,
295+
)
296+
chunks = list(llm.stream("test"))
297+
298+
assert len(requests) == 1
299+
assert requests[0]["stream"] is True
300+
assert (
301+
requests[0].get("stream_options", {}).get("include_usage", False)
302+
is stream_usage
303+
)
304+
assert "".join(chunk.content for chunk in chunks) == "ok"
305+
usage = [chunk.usage_metadata for chunk in chunks if chunk.usage_metadata]
306+
assert [item["total_tokens"] for item in usage] == ([3] if stream_usage else [])

‎backend/tests/test_supplier_config.py‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -225,7 +225,7 @@ def test_llm_config_has_api_base_url(self):
225225

226226
def test_openai_llm_passes_base_url(self):
227227
"""OpenAILLM should pass base_url to BaseChatOpenAI."""
228-
self.assertIn("base_url=self.config.api_base_url", self.factory_content)
228+
self.assertIn('"base_url": self.config.api_base_url', self.factory_content)
229229

230230

231231
if __name__ == "__main__":

0 commit comments

Comments
 (0)