|
3 | 3 | import ast |
4 | 4 | import asyncio |
5 | 5 | import json |
| 6 | +from abc import ABC, abstractmethod |
| 7 | +from functools import lru_cache |
6 | 8 | from pathlib import Path |
7 | 9 | from types import SimpleNamespace |
8 | 10 | from typing import Any, Optional |
@@ -60,20 +62,43 @@ async def stream(_question): |
60 | 62 | namespace["LLMFactory"] = factory |
61 | 63 | handler = load_symbol("apps/system/api/aimodel.py", "check_llm", namespace) |
62 | 64 |
|
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 | + |
64 | 89 | info = namespace["AiModelCreator"]( |
65 | 90 | name="test", |
66 | 91 | model_type=0, |
67 | 92 | base_model="test", |
68 | 93 | supplier=15, |
69 | | - protocol=1, |
| 94 | + protocol=protocol, |
70 | 95 | api_domain="https://example.test/v1", |
71 | 96 | api_key="test-key", |
72 | 97 | config_list=rows, |
73 | 98 | ) |
74 | 99 |
|
75 | 100 | async def consume(): |
76 | | - response = await handler(info, lambda key, **_kwargs: key) |
| 101 | + response = await handler(info, lambda key, **kwargs: kwargs.get("msg", key)) |
77 | 102 | assert isinstance(response, StreamingResponse) |
78 | 103 | return [json.loads(chunk) async for chunk in response.body_iterator] |
79 | 104 |
|
@@ -141,3 +166,141 @@ def test_validation_mixed_configuration(validation): |
141 | 166 | "max_tokens": 1024, |
142 | 167 | "extra_body": {"enable_thinking": False}, |
143 | 168 | } |
| 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 []) |
0 commit comments