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
26 changes: 14 additions & 12 deletions backend/apps/ai_model/model_factory.py
Original file line number Diff line number Diff line change
Expand Up @@ -69,13 +69,14 @@ def llm(self) -> BaseChatModel:

class OpenAIvLLM(BaseLLM):
def _init_llm(self) -> VLLMOpenAI:
return VLLMOpenAI(
openai_api_key=self.config.api_key or 'Empty',
openai_api_base=self.config.api_base_url,
model_name=self.config.model_name,
streaming=True,
options = {
**self.config.additional_params,
)
"openai_api_key": self.config.api_key or 'Empty',
"openai_api_base": self.config.api_base_url,
"model_name": self.config.model_name,
"streaming": True,
}
return VLLMOpenAI(**options)


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

class OpenAILLM(BaseLLM):
def _init_llm(self) -> BaseChatModel:
return BaseChatOpenAI(
model=self.config.model_name,
api_key=self.config.api_key or 'Empty',
base_url=self.config.api_base_url,
stream_usage=True,
options = {
"stream_usage": True,
**self.config.additional_params,
)
"model": self.config.model_name,
"api_key": self.config.api_key or 'Empty',
"base_url": self.config.api_base_url,
}
return BaseChatOpenAI(**options)

def generate(self, prompt: str) -> str:
return self.llm.invoke(prompt)
Expand Down
1 change: 0 additions & 1 deletion backend/apps/ai_model/openai/llm.py
Original file line number Diff line number Diff line change
Expand Up @@ -113,7 +113,6 @@ def get_last_generation_info(self) -> dict[str, Any] | None:
return self.usage_metadata

def _stream(self, *args: Any, **kwargs: Any) -> Iterator[ChatGenerationChunk]:
kwargs['stream_usage'] = True
for chunk in super()._stream(*args, **kwargs):
if chunk.message.usage_metadata is not None:
self.usage_metadata = chunk.message.usage_metadata
Expand Down
169 changes: 166 additions & 3 deletions backend/tests/test_model_validation_parameters.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@
import ast
import asyncio
import json
from abc import ABC, abstractmethod
from functools import lru_cache
from pathlib import Path
from types import SimpleNamespace
from typing import Any, Optional
Expand Down Expand Up @@ -60,20 +62,43 @@ async def stream(_question):
namespace["LLMFactory"] = factory
handler = load_symbol("apps/system/api/aimodel.py", "check_llm", namespace)

def run(rows):
def run(rows, *, protocol=1, provider=None):
if provider is not None:
namespace.update(
ABC=ABC,
abstractmethod=abstractmethod,
BaseChatModel=object,
BaseChatOpenAI=provider,
VLLMOpenAI=provider,
AzureChatOpenAI=object,
Type=type,
lru_cache=lru_cache,
)
for name in (
"BaseLLM",
"OpenAILLM",
"OpenAIvLLM",
"OpenAIAzureLLM",
"LLMFactory",
):
load_symbol("apps/ai_model/model_factory.py", name, namespace)
factory.create_llm.side_effect = namespace["LLMFactory"].create_llm
namespace["LLMFactory"] = factory
provider.return_value = SimpleNamespace(astream=stream)

info = namespace["AiModelCreator"](
name="test",
model_type=0,
base_model="test",
supplier=15,
protocol=1,
protocol=protocol,
api_domain="https://example.test/v1",
api_key="test-key",
config_list=rows,
)

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

Expand Down Expand Up @@ -141,3 +166,141 @@ def test_validation_mixed_configuration(validation):
"max_tokens": 1024,
"extra_body": {"enable_thinking": False},
}


@pytest.mark.parametrize(
"protocol, streaming_key, constructor_options",
[
(
1,
"stream_usage",
{
"model": "test",
"api_key": "test-key",
"base_url": "https://example.test/v1",
},
),
(
2,
"streaming",
{
"model_name": "test",
"openai_api_key": "test-key",
"openai_api_base": "https://example.test/v1",
},
),
],
)
def test_validation_resolves_constructor_option_conflicts(
validation, protocol, streaming_key, constructor_options
):
provider = Mock()
params = {streaming_key: False, "temperature": 0}
params.update(dict.fromkeys(constructor_options, "configured-override"))

assert (
validation(
[{"key": key, "val": value, "name": key} for key, value in params.items()],
protocol=protocol,
provider=provider,
)
== params
)
provider.assert_called_once_with(
**constructor_options, **{streaming_key: protocol == 2, "temperature": 0}
)


@pytest.mark.parametrize("stream_usage", [None, True, False])
def test_validation_defaults_stream_usage_without_overriding_configuration(
validation, stream_usage
):
provider = Mock()
params = {} if stream_usage is None else {"stream_usage": stream_usage}
assert (
validation(
[{"key": key, "val": value, "name": key} for key, value in params.items()],
provider=provider,
)
== params
)
assert provider.call_args.kwargs["stream_usage"] is (
True if stream_usage is None else stream_usage
)


@pytest.mark.parametrize("asynchronous", [False, True])
@pytest.mark.parametrize("stream_usage", [False, True])
def test_openai_stream_usage_reaches_provider_request(asynchronous, stream_usage):
import httpx

from apps.ai_model.openai.llm import BaseChatOpenAI

requests = []

def respond(request):
payload = json.loads(request.content)
requests.append(payload)
chunks = [
{
"choices": [
{
"index": 0,
"delta": {"role": "assistant", "content": "ok"},
"finish_reason": "stop",
}
]
}
]
if payload.get("stream_options", {}).get("include_usage"):
chunks.append(
{
"choices": [],
"usage": {
"prompt_tokens": 2,
"completion_tokens": 1,
"total_tokens": 3,
},
}
)
body = (
"".join(f"data: {json.dumps(chunk)}\n\n" for chunk in chunks)
+ "data: [DONE]\n\n"
)
return httpx.Response(
200, headers={"content-type": "text/event-stream"}, content=body
)

async def consume_async():
async with httpx.AsyncClient(transport=httpx.MockTransport(respond)) as client:
llm = BaseChatOpenAI(
model="test",
api_key="test-key",
base_url="https://example.test/v1",
stream_usage=stream_usage,
http_async_client=client,
)
return [chunk async for chunk in llm.astream("test")]

if asynchronous:
chunks = asyncio.run(consume_async())
else:
with httpx.Client(transport=httpx.MockTransport(respond)) as client:
llm = BaseChatOpenAI(
model="test",
api_key="test-key",
base_url="https://example.test/v1",
stream_usage=stream_usage,
http_client=client,
)
chunks = list(llm.stream("test"))

assert len(requests) == 1
assert requests[0]["stream"] is True
assert (
requests[0].get("stream_options", {}).get("include_usage", False)
is stream_usage
)
assert "".join(chunk.content for chunk in chunks) == "ok"
usage = [chunk.usage_metadata for chunk in chunks if chunk.usage_metadata]
assert [item["total_tokens"] for item in usage] == ([3] if stream_usage else [])
2 changes: 1 addition & 1 deletion backend/tests/test_supplier_config.py
Original file line number Diff line number Diff line change
Expand Up @@ -225,7 +225,7 @@ def test_llm_config_has_api_base_url(self):

def test_openai_llm_passes_base_url(self):
"""OpenAILLM should pass base_url to BaseChatOpenAI."""
self.assertIn("base_url=self.config.api_base_url", self.factory_content)
self.assertIn('"base_url": self.config.api_base_url', self.factory_content)


if __name__ == "__main__":
Expand Down
Loading