-
Notifications
You must be signed in to change notification settings - Fork 164
Expand file tree
/
Copy pathtest_inference_sync.py
More file actions
509 lines (450 loc) · 19.1 KB
/
Copy pathtest_inference_sync.py
File metadata and controls
509 lines (450 loc) · 19.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
#####################################################################
# This files has been automatically generated from:
# ../async/test_inference_async.py
#
# DO NOT EDIT THIS FILE! Edit the async test case listed above,
# and regenerate the synchronous test cases with async2sync.py
#####################################################################
"""Test making simple predictions with the API."""
import json
import logging
from contextlib import nullcontext
import pytest
from pytest import LogCaptureFixture as LogCap
from lmstudio import (
AssistantResponse,
Client,
PredictionStream,
Chat,
LlmInfo,
LlmLoadModelConfig,
LlmPredictionConfig,
LlmPredictionConfigDict,
LlmPredictionFragment,
LlmPredictionStats,
LMStudioModelNotFoundError,
LMStudioPredictionError,
LMStudioPresetNotFoundError,
PredictionResult,
PredictionRoundResult,
ResponseSchema,
TextData,
ToolCallRequest,
)
from tests.support import (
ADDITION_TOOL_SPEC,
EXPECTED_LLM_ID,
GBNF_GRAMMAR,
PROMPT,
RESPONSE_FORMATS,
RESPONSE_SCHEMA,
SCHEMA_FIELDS,
SHORT_PREDICTION_CONFIG,
TOOL_LLM_ID,
check_sdk_error,
)
# respond and complete are the same under the hood so we only test respond once
@pytest.mark.lmstudio
def test_respond_past_history_sync(caplog: LogCap) -> None:
history = Chat("You are an obedient assistant.")
history.add_user_message("Say something.")
history.add_assistant_response("Hello, world!")
history.add_user_message("Respond with exactly what you just said.")
caplog.set_level(logging.DEBUG)
model_id = EXPECTED_LLM_ID
with Client() as client:
llm = client.llm.model(model_id)
response = llm.respond(history, config=SHORT_PREDICTION_CONFIG)
logging.info(f"LLM response: {response!r}")
assert response.content == "Hello, world!"
@pytest.mark.lmstudio
def test_complete_nostream_sync(caplog: LogCap) -> None:
prompt = PROMPT
caplog.set_level(logging.DEBUG)
model_id = EXPECTED_LLM_ID
with Client() as client:
llm = client.llm.model(model_id)
response = llm.complete(prompt, config=SHORT_PREDICTION_CONFIG)
# The continuation from the LLM will change, but it won't be an empty string
logging.info(f"LLM response: {response!r}")
assert isinstance(response, PredictionResult)
assert response.content
@pytest.mark.lmstudio
def test_complete_stream_sync(caplog: LogCap) -> None:
prompt = PROMPT
caplog.set_level(logging.DEBUG)
model_id = EXPECTED_LLM_ID
with Client() as client:
session = client.llm
prediction_stream = session._complete_stream(
model_id, prompt, config=SHORT_PREDICTION_CONFIG
)
assert isinstance(prediction_stream, PredictionStream)
# Also exercise the explicit context management interface
with prediction_stream:
for fragment in prediction_stream:
logging.info(f"Fragment: {fragment}")
assert fragment.content
assert isinstance(fragment.content, str)
response = prediction_stream.result()
# The continuation from the LLM will change, but it won't be an empty string
logging.info(f"LLM response: {response!r}")
assert isinstance(response, PredictionResult)
assert response.content
assert response.parsed is response.content
@pytest.mark.lmstudio
@pytest.mark.parametrize("format_type", RESPONSE_FORMATS)
def test_complete_structured_response_format_sync(
format_type: ResponseSchema, caplog: LogCap
) -> None:
prompt = PROMPT
caplog.set_level(logging.DEBUG)
model_id = EXPECTED_LLM_ID
with Client() as client:
llm = client.llm.model(model_id)
response = llm.complete(prompt, response_format=format_type)
assert isinstance(response, PredictionResult)
logging.info(f"LLM response: {response!r}")
assert isinstance(response.content, str)
assert isinstance(response.parsed, dict)
assert response.parsed == json.loads(response.content)
assert SCHEMA_FIELDS.keys() == response.parsed.keys()
@pytest.mark.lmstudio
def test_complete_structured_config_json_sync(caplog: LogCap) -> None:
prompt = PROMPT
caplog.set_level(logging.DEBUG)
model_id = EXPECTED_LLM_ID
with Client() as client:
llm = client.llm.model(model_id)
config: LlmPredictionConfigDict = {
# snake_case keys are accepted at runtime,
# but the type hinted spelling is the camelCase names
# This test case checks the schema field name is converted,
# but *not* the snake_case and camelCase field names in the
# schema itself
"structured": {
"type": "json",
"json_schema": RESPONSE_SCHEMA,
} # type: ignore[typeddict-item]
}
response = llm.complete(prompt, config=config)
assert isinstance(response, PredictionResult)
logging.info(f"LLM response: {response!r}")
assert isinstance(response.content, str)
assert isinstance(response.parsed, dict)
assert response.parsed == json.loads(response.content)
assert SCHEMA_FIELDS.keys() == response.parsed.keys()
@pytest.mark.lmstudio
def test_complete_structured_config_gbnf_sync(caplog: LogCap) -> None:
prompt = PROMPT
caplog.set_level(logging.DEBUG)
model_id = EXPECTED_LLM_ID
with Client() as client:
llm = client.llm.model(model_id)
config: LlmPredictionConfigDict = {
# snake_case keys are accepted at runtime,
# but the type hinted spelling is the camelCase names
# This test case checks the schema field name is converted,
# but *not* the snake_case and camelCase field names in the
# schema itself
"structured": {
"type": "gbnf",
"gbnf_grammar": GBNF_GRAMMAR,
} # type: ignore[typeddict-item]
}
response = llm.complete(prompt, config=config)
assert isinstance(response, PredictionResult)
logging.info(f"LLM response: {response!r}")
assert isinstance(response.content, str)
assert isinstance(response.parsed, dict)
assert response.parsed == json.loads(response.content)
assert SCHEMA_FIELDS.keys() == response.parsed.keys()
@pytest.mark.lmstudio
def test_callbacks_text_completion_sync(caplog: LogCap) -> None:
messages: list[AssistantResponse] = []
progress_reports: list[float] = []
def progress_update(progress: float) -> None:
assert progress >= 0.0
assert progress <= 1.0
if progress_reports:
assert progress > progress_reports[-1]
progress_reports.append(progress)
num_first_token_notifications = 0
def count_first_token_notification() -> None:
nonlocal num_first_token_notifications
num_first_token_notifications += 1
callback_content: list[str] = []
def record_fragment(fragment: LlmPredictionFragment) -> None:
callback_content.append(fragment.content)
caplog.set_level(logging.DEBUG)
model_id = EXPECTED_LLM_ID
with Client() as client:
# SDK ensures 0.0 and 1.0 prompt processing callbacks are emitted,
# even if the server doesn't send any prompt processing events
llm = client.llm.model(model_id)
prediction_stream = llm.complete_stream(
PROMPT,
config=SHORT_PREDICTION_CONFIG,
on_message=messages.append,
on_first_token=count_first_token_notification,
on_prediction_fragment=record_fragment,
on_prompt_processing_progress=progress_update,
)
# This test case also covers the explicit context management interface
iteration_content: list[str] = []
with prediction_stream:
iteration_content = [fragment.content for fragment in prediction_stream]
assert len(messages) == 1
message = messages[0]
assert message.role == "assistant"
assert len(message.content) == 1
message_data = message.content[0]
assert isinstance(message_data, TextData)
assert message_data.text == "".join(iteration_content)
assert num_first_token_notifications == 1
assert callback_content == iteration_content
assert progress_reports[0] == 0.0
assert progress_reports[-1] == 1.0
@pytest.mark.lmstudio
def test_callbacks_chat_response_sync(caplog: LogCap) -> None:
messages: list[AssistantResponse] = []
progress_reports: list[float] = []
def progress_update(progress: float) -> None:
assert progress >= 0.0
assert progress <= 1.0
if progress_reports:
assert progress > progress_reports[-1]
progress_reports.append(progress)
num_first_token_notifications = 0
def count_first_token_notification() -> None:
nonlocal num_first_token_notifications
num_first_token_notifications += 1
callback_content: list[str] = []
def record_fragment(fragment: LlmPredictionFragment) -> None:
callback_content.append(fragment.content)
caplog.set_level(logging.DEBUG)
model_id = EXPECTED_LLM_ID
with Client() as client:
# SDK ensures 0.0 and 1.0 prompt processing callbacks are emitted,
# even if the server doesn't send any prompt processing events
llm = client.llm.model(model_id)
prediction_stream = llm.respond_stream(
PROMPT,
config=SHORT_PREDICTION_CONFIG,
on_message=messages.append,
on_first_token=count_first_token_notification,
on_prediction_fragment=record_fragment,
on_prompt_processing_progress=progress_update,
)
# This test case also covers the explicit context management interface
iteration_content: list[str] = []
with prediction_stream:
iteration_content = [fragment.content for fragment in prediction_stream]
assert len(messages) == 1
message = messages[0]
assert message.role == "assistant"
assert len(message.content) == 1
message_data = message.content[0]
assert isinstance(message_data, TextData)
assert message_data.text == "".join(iteration_content)
assert num_first_token_notifications == 1
assert callback_content == iteration_content
assert progress_reports[0] == 0.0
assert progress_reports[-1] == 1.0
@pytest.mark.lmstudio
def test_complete_prediction_metadata_sync(caplog: LogCap) -> None:
prompt = PROMPT
caplog.set_level(logging.DEBUG)
model_id = EXPECTED_LLM_ID
with Client() as client:
llm = client.llm.model(model_id)
response = llm.complete(prompt, config=SHORT_PREDICTION_CONFIG)
assert isinstance(response, PredictionResult)
# The initial query from the LLM will change, but we expect it to be a question
logging.info(f"LLM response: {response.content!r}")
assert response.stats
assert response.model_info
assert response.load_config
assert response.prediction_config
assert isinstance(response.stats, LlmPredictionStats)
assert isinstance(response.model_info, LlmInfo)
assert isinstance(response.load_config, LlmLoadModelConfig)
assert isinstance(response.prediction_config, LlmPredictionConfig)
@pytest.mark.lmstudio
def test_invalid_model_request_nostream_sync(caplog: LogCap) -> None:
caplog.set_level(logging.DEBUG)
with Client() as client:
# Deliberately create an invalid model handle
model = client.llm._create_handle("No such model")
# This should error rather than timing out,
# but avoid any risk of the client hanging...
with nullcontext():
with pytest.raises(LMStudioModelNotFoundError) as exc_info:
model.complete("Some text")
check_sdk_error(exc_info, __file__)
@pytest.mark.lmstudio
def test_invalid_model_request_stream_sync(caplog: LogCap) -> None:
caplog.set_level(logging.DEBUG)
with Client() as client:
# Deliberately create an invalid model handle
model = client.llm._create_handle("No such model")
# This should error rather than timing out,
# but avoid any risk of the client hanging...
with nullcontext():
prediction_stream = model.complete_stream("Some text")
with prediction_stream:
with pytest.raises(LMStudioModelNotFoundError) as exc_info:
prediction_stream.wait_for_result()
check_sdk_error(exc_info, __file__)
@pytest.mark.lmstudio
def test_invalid_preset_request_nostream_sync(caplog: LogCap) -> None:
caplog.set_level(logging.DEBUG)
with Client() as client:
model = client.llm.model()
# This should error rather than timing out,
# but avoid any risk of the client hanging...
with nullcontext():
with pytest.raises(LMStudioPresetNotFoundError) as exc_info:
model.complete("Some text", preset="No such preset")
check_sdk_error(exc_info, __file__)
@pytest.mark.lmstudio
def test_invalid_preset_request_stream_sync(caplog: LogCap) -> None:
caplog.set_level(logging.DEBUG)
with Client() as client:
model = client.llm.model()
# This should error rather than timing out,
# but avoid any risk of the client hanging...
with nullcontext():
prediction_stream = model.complete_stream(
"Some text", preset="No such preset"
)
with prediction_stream:
with pytest.raises(LMStudioPresetNotFoundError) as exc_info:
prediction_stream.wait_for_result()
check_sdk_error(exc_info, __file__)
@pytest.mark.lmstudio
def test_cancel_prediction_sync(caplog: LogCap) -> None:
prompt = "This is a test prompt."
model_id = EXPECTED_LLM_ID
num_times = 0
caplog.set_level(logging.DEBUG)
with Client() as client:
session = client.llm
stream = session._complete_stream(model_id, prompt=prompt)
for _ in stream:
stream.cancel()
num_times += 1
assert stream.stats
assert stream.stats.stop_reason == "userStopped"
# ensure __aiter__ closes correctly
assert num_times == 1
@pytest.mark.lmstudio
def test_tool_using_agent_sync(caplog: LogCap) -> None:
caplog.set_level(logging.DEBUG)
model_id = TOOL_LLM_ID
with Client() as client:
llm = client.llm.model(model_id)
chat = Chat()
chat.add_user_message("What is the sum of 123 and 3210?")
tools = [ADDITION_TOOL_SPEC]
# Ensure ignoring the round index passes static type checks
predictions: list[PredictionResult] = []
act_result = llm.act(chat, tools, on_prediction_completed=predictions.append)
assert len(predictions) > 1
assert act_result.rounds == len(predictions)
assert "3333" in predictions[-1].content
for _logger_name, log_level, message in caplog.record_tuples:
if log_level != logging.INFO:
continue
if message.startswith("Tool call:"):
break
else:
assert False, "Failed to find tool call logging entry"
assert "123" in message
assert "3210" in message
@pytest.mark.lmstudio
def test_tool_using_agent_callbacks_sync(caplog: LogCap) -> None:
caplog.set_level(logging.DEBUG)
model_id = TOOL_LLM_ID
with Client() as client:
llm = client.llm.model(model_id)
chat = Chat()
# Ensure the first response is a combination of text and tool use requests
chat.add_user_message("First say 'Hi'. Then calculate 1 + 3 with the tool.")
tools = [ADDITION_TOOL_SPEC]
round_starts: list[int] = []
round_ends: list[int] = []
first_tokens: list[int] = []
predictions: list[PredictionRoundResult] = []
fragments: list[LlmPredictionFragment] = []
fragment_round_indices: set[int] = set()
def _append_fragment(f: LlmPredictionFragment, round_index: int) -> None:
last_fragment_round_index = max(fragment_round_indices, default=-1)
assert round_index >= last_fragment_round_index
fragments.append(f)
fragment_round_indices.add(round_index)
# TODO: Also check on_prompt_processing_progress and handling invalid messages
# (although it isn't clear how to provoke calls to the latter without mocking)
act_result = llm.act(
chat,
tools,
on_first_token=first_tokens.append,
on_prediction_fragment=_append_fragment,
on_message=chat.append,
on_round_start=round_starts.append,
on_round_end=round_ends.append,
on_prediction_completed=predictions.append,
)
num_rounds = act_result.rounds
sequential_round_indices = list(range(num_rounds))
assert num_rounds > 1
assert [p.round_index for p in predictions] == sequential_round_indices
assert round_starts == sequential_round_indices
assert round_ends == sequential_round_indices
expected_token_indices = [p.round_index for p in predictions if p.content]
assert expected_token_indices == sequential_round_indices
assert first_tokens == expected_token_indices
assert fragment_round_indices == set(expected_token_indices)
assert len(chat._messages) == 2 * num_rounds # No tool results in last round
cloned_chat = chat.copy()
assert cloned_chat._messages == chat._messages
# Also check coroutine support in the asynchronous API
# (this becomes a regular sync tool in the sync API tests)
def divide(numerator: float, denominator: float) -> float:
"""Divide the given numerator by the given denominator. Return the result."""
return numerator / denominator
@pytest.mark.lmstudio
def test_tool_using_agent_error_handling_sync(caplog: LogCap) -> None:
caplog.set_level(logging.DEBUG)
model_id = TOOL_LLM_ID
with Client() as client:
llm = client.llm.model(model_id)
chat = Chat()
chat.add_user_message(
"Attempt to divide 1 by 0 using the tool. Explain the result."
)
tools = [divide]
predictions: list[PredictionRoundResult] = []
request_failures: list[LMStudioPredictionError] = []
def _handle_invalid_request(
exc: LMStudioPredictionError, request: ToolCallRequest | None
) -> None:
if request is not None:
request_failures.append(exc)
act_result = llm.act(
chat,
tools,
handle_invalid_tool_request=_handle_invalid_request,
on_prediction_completed=predictions.append,
)
assert len(predictions) > 1
assert act_result.rounds == len(predictions)
# Ensure the tool call failure was reported to the user callback
assert len(request_failures) == 1
tool_failure_exc = request_failures[0]
assert isinstance(tool_failure_exc, LMStudioPredictionError)
assert isinstance(tool_failure_exc.__cause__, ZeroDivisionError)
# If the content checks prove too flaky in practice, they can be dropped
completed_response = predictions[-1].content.lower()
assert "divid" in completed_response # Accepts both "divide" and "dividing"
assert "zero" in completed_response