-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathtest_unit.py
More file actions
1529 lines (1273 loc) · 51.5 KB
/
Copy pathtest_unit.py
File metadata and controls
1529 lines (1273 loc) · 51.5 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
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""Tests for the normalized client module.
This module tests:
1. UiPathNormalizedClient initialization and client creation
2. Completions.create (sync, non-streaming)
3. Completions.stream (sync, streaming)
4. Completions.acreate (async, non-streaming)
5. Tool calling (tool definition building, tool_choice resolution)
6. Structured output (Pydantic, TypedDict, dict schemas)
7. Embeddings.create and Embeddings.acreate
8. Response type parsing (ChatCompletion, ChatCompletionChunk, EmbeddingResponse)
"""
import json
from collections.abc import Generator
from typing import TypedDict
from unittest.mock import AsyncMock, MagicMock, patch
import pytest
from pydantic import BaseModel
from uipath.llm_client.clients.normalized import (
ChatCompletion,
ChatCompletionChunk,
Choice,
Delta,
EmbeddingData,
EmbeddingResponse,
Message,
ToolCall,
ToolCallChunk,
UiPathNormalizedClient,
Usage,
)
from uipath.llm_client.clients.normalized.completions import (
Completions,
_aiter_sse,
_build_request,
_build_response_format,
_build_tool_definition,
_iter_sse,
_parse_response,
_parse_stream_chunk,
_parse_structured_output,
_parse_tool_call,
_parse_tool_call_chunk,
_resolve_tool_choice,
)
from uipath.llm_client.clients.normalized.embeddings import _parse_embedding_response
from uipath.llm_client.settings.utils import SingletonMeta
# ============================================================================
# Fixtures
# ============================================================================
_CLIENT_MODULE = "uipath.llm_client.clients.normalized.client"
@pytest.fixture(autouse=True)
def clear_singleton_instances():
"""Clear singleton instances before each test to ensure isolation."""
SingletonMeta._instances.clear()
yield
SingletonMeta._instances.clear()
@pytest.fixture
def mock_settings():
settings = MagicMock()
settings.build_base_url.return_value = "https://gateway.uipath.com/llm/v1"
settings.build_auth_headers.return_value = {"Authorization": "Bearer test-token"}
settings.build_auth_pipeline.return_value = None
return settings
@pytest.fixture
def mock_sync_client():
client = MagicMock()
return client
@pytest.fixture
def mock_async_client():
client = AsyncMock()
return client
# ============================================================================
# Response parsing helpers
# ============================================================================
SAMPLE_COMPLETION_RESPONSE = {
"id": "chatcmpl-123",
"created": 1234567890,
"model": "gpt-4o",
"choices": [
{
"index": 0,
"message": {
"role": "assistant",
"content": "Hello! How can I help you?",
},
"finish_reason": "stop",
}
],
"usage": {
"prompt_tokens": 10,
"completion_tokens": 8,
"total_tokens": 18,
},
}
SAMPLE_TOOL_CALL_RESPONSE = {
"id": "chatcmpl-456",
"created": 1234567890,
"model": "gpt-4o",
"choices": [
{
"index": 0,
"message": {
"role": "assistant",
"content": "",
"tool_calls": [
{
"id": "call_abc123",
"name": "get_weather",
"arguments": {"city": "London"},
}
],
},
"finish_reason": "tool_calls",
}
],
"usage": {
"prompt_tokens": 15,
"completion_tokens": 20,
"total_tokens": 35,
},
}
SAMPLE_STREAM_CHUNKS = [
{
"id": "chatcmpl-789",
"created": 1234567890,
"model": "gpt-4o",
"choices": [
{
"index": 0,
"delta": {"role": "assistant", "content": "Hello"},
"finish_reason": None,
}
],
},
{
"id": "chatcmpl-789",
"created": 1234567890,
"model": "gpt-4o",
"choices": [
{
"index": 0,
"delta": {"content": " world!"},
"finish_reason": None,
}
],
},
{
"id": "chatcmpl-789",
"created": 1234567890,
"model": "gpt-4o",
"choices": [
{
"index": 0,
"delta": {},
"finish_reason": "stop",
}
],
"usage": {
"prompt_tokens": 5,
"completion_tokens": 3,
"total_tokens": 8,
},
},
]
SAMPLE_EMBEDDING_RESPONSE = {
"data": [
{"embedding": [0.1, 0.2, 0.3], "index": 0},
{"embedding": [0.4, 0.5, 0.6], "index": 1},
],
"model": "text-embedding-ada-002",
"usage": {"prompt_tokens": 5, "total_tokens": 5},
}
# ============================================================================
# Test: Response type parsing
# ============================================================================
class TestParseResponse:
def test_basic_completion(self):
result = _parse_response(SAMPLE_COMPLETION_RESPONSE)
assert isinstance(result, ChatCompletion)
assert result.id == "chatcmpl-123"
assert result.model == "gpt-4o"
assert len(result.choices) == 1
assert result.choices[0].message.content == "Hello! How can I help you?"
assert result.choices[0].finish_reason == "stop"
assert result.usage.prompt_tokens == 10
assert result.usage.completion_tokens == 8
assert result.usage.total_tokens == 18
def test_tool_call_response(self):
result = _parse_response(SAMPLE_TOOL_CALL_RESPONSE)
assert len(result.choices[0].message.tool_calls) == 1
tc = result.choices[0].message.tool_calls[0]
assert tc.id == "call_abc123"
assert tc.name == "get_weather"
assert tc.arguments == {"city": "London"}
def test_empty_response(self):
result = _parse_response({"choices": [], "usage": {}})
assert len(result.choices) == 0
assert result.usage.prompt_tokens == 0
def test_tool_call_with_string_arguments(self):
data = {
"choices": [
{
"message": {
"tool_calls": [
{
"id": "call_1",
"name": "func",
"arguments": '{"key": "value"}',
}
]
}
}
],
"usage": {},
}
result = _parse_response(data)
tc = result.choices[0].message.tool_calls[0]
assert tc.arguments == {"key": "value"}
def test_tool_call_with_invalid_json_arguments(self):
data = {
"choices": [
{
"message": {
"tool_calls": [
{
"id": "call_1",
"name": "func",
"arguments": "not json",
}
]
}
}
],
"usage": {},
}
result = _parse_response(data)
tc = result.choices[0].message.tool_calls[0]
assert tc.arguments == {}
class TestParseStreamChunk:
def test_content_chunk(self):
result = _parse_stream_chunk(SAMPLE_STREAM_CHUNKS[0])
assert isinstance(result, ChatCompletionChunk)
assert result.id == "chatcmpl-789"
assert len(result.choices) == 1
assert result.choices[0].delta.content == "Hello"
assert result.choices[0].delta.role == "assistant"
def test_chunk_with_usage(self):
result = _parse_stream_chunk(SAMPLE_STREAM_CHUNKS[2])
assert result.usage is not None
assert result.usage.prompt_tokens == 5
assert result.choices[0].finish_reason == "stop"
def test_chunk_without_usage(self):
result = _parse_stream_chunk(SAMPLE_STREAM_CHUNKS[0])
assert result.usage is None
def test_stream_tool_call_chunk(self):
data = {
"id": "chatcmpl-tc",
"choices": [
{
"delta": {
"tool_calls": [
{
"id": "call_1",
"name": "get_weather",
"arguments": '{"city":',
"index": 0,
}
]
}
}
],
}
result = _parse_stream_chunk(data)
assert len(result.choices[0].delta.tool_calls) == 1
tc = result.choices[0].delta.tool_calls[0]
assert tc.name == "get_weather"
assert tc.arguments == '{"city":'
def test_stream_tool_call_with_function_format(self):
data = {
"id": "chatcmpl-tc",
"choices": [
{
"delta": {
"tool_calls": [
{
"id": "call_1",
"function": {
"name": "get_weather",
"arguments": '{"city": "Paris"}',
},
"index": 0,
}
]
}
}
],
}
result = _parse_stream_chunk(data)
tc = result.choices[0].delta.tool_calls[0]
assert tc.name == "get_weather"
assert tc.arguments == '{"city": "Paris"}'
class TestParseEmbeddingResponse:
def test_basic_embedding(self):
result = _parse_embedding_response(SAMPLE_EMBEDDING_RESPONSE)
assert isinstance(result, EmbeddingResponse)
assert len(result.data) == 2
assert result.data[0].embedding == [0.1, 0.2, 0.3]
assert result.data[1].embedding == [0.4, 0.5, 0.6]
assert result.model == "text-embedding-ada-002"
assert result.usage.prompt_tokens == 5
def test_empty_embedding(self):
result = _parse_embedding_response({"data": [], "usage": {}})
assert len(result.data) == 0
# ============================================================================
# Test: Structured output
# ============================================================================
class TestBuildResponseFormat:
def test_pydantic_model(self):
class MyModel(BaseModel):
name: str
age: int
result = _build_response_format(MyModel)
assert result["type"] == "json_schema"
assert result["json_schema"]["name"] == "MyModel"
assert result["json_schema"]["strict"] is True
assert "properties" in result["json_schema"]["schema"]
def test_typed_dict(self):
class MyDict(TypedDict):
name: str
score: float
result = _build_response_format(MyDict)
assert result["type"] == "json_schema"
assert result["json_schema"]["name"] == "MyDict"
assert result["json_schema"]["strict"] is True
schema = result["json_schema"]["schema"]
assert schema["type"] == "object"
assert "name" in schema["properties"]
assert "score" in schema["properties"]
assert schema["properties"]["name"]["type"] == "string"
assert schema["properties"]["score"]["type"] == "number"
def test_dict_schema(self):
schema = {
"name": "my_schema",
"schema": {"type": "object", "properties": {"x": {"type": "integer"}}},
}
result = _build_response_format(schema)
assert result["type"] == "json_schema"
assert result["json_schema"] == schema
def test_unsupported_type(self):
with pytest.raises(TypeError, match="Unsupported response_format"):
_build_response_format("not a type") # type: ignore[arg-type]
class TestParseStructuredOutput:
def test_parse_pydantic(self):
class Answer(BaseModel):
text: str
score: float
content = '{"text": "hello", "score": 0.9}'
result = _parse_structured_output(content, Answer)
assert isinstance(result, Answer)
assert result.text == "hello"
assert result.score == 0.9
def test_parse_dict(self):
content = '{"key": "value"}'
result = _parse_structured_output(content, {"type": "object"})
assert result == {"key": "value"}
def test_parse_invalid_json(self):
result = _parse_structured_output("not json", str)
assert result is None
def test_response_with_structured_output(self):
class Answer(BaseModel):
text: str
data = {
"choices": [
{
"message": {
"content": '{"text": "hello"}',
}
}
],
"usage": {},
}
result = _parse_response(data, response_format=Answer)
assert result.choices[0].message.parsed is not None
assert isinstance(result.choices[0].message.parsed, Answer)
assert result.choices[0].message.parsed.text == "hello"
def test_response_without_structured_output(self):
data = {
"choices": [
{
"message": {
"content": "plain text",
}
}
],
"usage": {},
}
result = _parse_response(data)
assert result.choices[0].message.parsed is None
# ============================================================================
# Test: Tool definition building
# ============================================================================
class TestBuildToolDefinition:
def test_dict_passthrough(self):
tool = {"name": "my_tool", "description": "does stuff", "parameters": {}}
result = _build_tool_definition(tool)
assert result is tool
def test_pydantic_model(self):
class WeatherInput(BaseModel):
"""Get weather for a city."""
city: str
units: str = "celsius"
result = _build_tool_definition(WeatherInput)
assert result["name"] == "WeatherInput"
assert result["description"] == "Get weather for a city."
assert "properties" in result["parameters"]
assert "city" in result["parameters"]["properties"]
def test_callable(self):
def get_weather(city: str, units: str = "celsius") -> str:
"""Get weather for a city."""
return f"Weather in {city}"
result = _build_tool_definition(get_weather)
assert result["name"] == "get_weather"
assert result["description"] == "Get weather for a city."
assert "city" in result["parameters"]["properties"]
assert "city" in result["parameters"]["required"]
assert "units" not in result["parameters"]["required"]
def test_unsupported_type(self):
with pytest.raises(TypeError, match="Unsupported tool type"):
_build_tool_definition(42) # type: ignore[arg-type]
class TestToolChoiceResolution:
def test_auto(self):
result = _resolve_tool_choice("auto", [])
assert result == "auto"
def test_required(self):
result = _resolve_tool_choice("required", [])
assert result == "required"
def test_none(self):
result = _resolve_tool_choice("none", [])
assert result == "none"
def test_specific_tool(self):
tools = [{"name": "get_weather"}, {"name": "search"}]
result = _resolve_tool_choice("get_weather", tools)
assert result == {"type": "tool", "name": "get_weather"}
def test_unknown_becomes_auto(self):
result = _resolve_tool_choice("unknown_tool", [{"name": "other"}])
assert result == "auto"
def test_dict_passthrough(self):
choice = {"type": "required"}
result = _resolve_tool_choice(choice, [])
assert result is choice
# ============================================================================
# Test: Tool call parsing
# ============================================================================
class TestParseToolCall:
def test_basic(self):
tc = _parse_tool_call({"id": "call_1", "name": "func", "arguments": {"x": 1}})
assert tc.id == "call_1"
assert tc.name == "func"
assert tc.arguments == {"x": 1}
def test_string_arguments(self):
tc = _parse_tool_call({"id": "call_1", "name": "func", "arguments": '{"x": 1}'})
assert tc.arguments == {"x": 1}
def test_invalid_string_arguments(self):
tc = _parse_tool_call({"id": "call_1", "name": "func", "arguments": "not json"})
assert tc.arguments == {}
class TestParseToolCallChunk:
def test_flat_format(self):
tc = _parse_tool_call_chunk(
{"id": "call_1", "name": "func", "arguments": '{"x":', "index": 0}
)
assert tc.name == "func"
assert tc.arguments == '{"x":'
def test_function_format(self):
tc = _parse_tool_call_chunk(
{
"id": "call_1",
"function": {"name": "func", "arguments": '{"x": 1}'},
"index": 0,
}
)
assert tc.name == "func"
assert tc.arguments == '{"x": 1}'
def test_dict_arguments_converted(self):
tc = _parse_tool_call_chunk(
{"id": "call_1", "name": "func", "arguments": {"x": 1}, "index": 0}
)
assert tc.arguments == '{"x": 1}'
# ============================================================================
# Test: Client initialization
# ============================================================================
class TestUiPathNormalizedClientInit:
@patch(f"{_CLIENT_MODULE}.build_httpx_client")
@patch(f"{_CLIENT_MODULE}.get_default_client_settings")
def test_default_settings(self, mock_get_settings, mock_build):
mock_settings = MagicMock()
mock_settings.build_auth_pipeline.return_value = None
mock_get_settings.return_value = mock_settings
client = UiPathNormalizedClient(model_name="gpt-4o")
assert client._model_name == "gpt-4o"
mock_get_settings.assert_called_once()
@patch(f"{_CLIENT_MODULE}.build_httpx_client")
def test_custom_settings(self, mock_build):
settings = MagicMock()
settings.build_auth_pipeline.return_value = None
client = UiPathNormalizedClient(model_name="gpt-4o", client_settings=settings)
assert client._client_settings is settings
@patch(f"{_CLIENT_MODULE}.build_httpx_client")
@patch(f"{_CLIENT_MODULE}.get_default_client_settings")
def test_has_completions_namespace(self, mock_get_settings, mock_build):
mock_settings = MagicMock()
mock_settings.build_auth_pipeline.return_value = None
mock_get_settings.return_value = mock_settings
mock_build.return_value = MagicMock()
client = UiPathNormalizedClient(model_name="gpt-4o")
assert hasattr(client, "completions")
assert isinstance(client.completions, Completions)
@patch(f"{_CLIENT_MODULE}.build_httpx_client")
@patch(f"{_CLIENT_MODULE}.get_default_client_settings")
def test_has_embeddings_namespace(self, mock_get_settings, mock_build):
mock_settings = MagicMock()
mock_settings.build_auth_pipeline.return_value = None
mock_get_settings.return_value = mock_settings
mock_build.return_value = MagicMock()
client = UiPathNormalizedClient(model_name="gpt-4o")
from uipath.llm_client.clients.normalized.embeddings import Embeddings
assert hasattr(client, "embeddings")
assert isinstance(client.embeddings, Embeddings)
@patch(f"{_CLIENT_MODULE}.build_httpx_client")
@patch(f"{_CLIENT_MODULE}.get_default_client_settings")
def test_completions_api_config(self, mock_get_settings, mock_build):
mock_settings = MagicMock()
mock_settings.build_auth_pipeline.return_value = None
mock_get_settings.return_value = mock_settings
client = UiPathNormalizedClient(model_name="gpt-4o")
assert client._completions_api_config.api_type == "completions"
assert client._completions_api_config.routing_mode == "normalized"
assert client._completions_api_config.freeze_base_url is True
@patch(f"{_CLIENT_MODULE}.build_httpx_client")
@patch(f"{_CLIENT_MODULE}.get_default_client_settings")
def test_embeddings_api_config(self, mock_get_settings, mock_build):
mock_settings = MagicMock()
mock_settings.build_auth_pipeline.return_value = None
mock_get_settings.return_value = mock_settings
client = UiPathNormalizedClient(model_name="gpt-4o")
assert client._embeddings_api_config.api_type == "embeddings"
assert client._embeddings_api_config.routing_mode == "normalized"
assert client._embeddings_api_config.freeze_base_url is True
# ============================================================================
# Test: Completions.create (sync, non-streaming)
# ============================================================================
class TestCompletionsCreate:
def test_basic_create(self, mock_sync_client):
mock_response = MagicMock()
mock_response.json.return_value = SAMPLE_COMPLETION_RESPONSE
mock_sync_client.request.return_value = mock_response
client_obj = MagicMock()
client_obj._sync_client = mock_sync_client
completions = Completions(client_obj)
result = completions.create(
messages=[{"role": "user", "content": "Hello"}],
)
assert isinstance(result, ChatCompletion)
assert result.choices[0].message.content == "Hello! How can I help you?"
mock_sync_client.request.assert_called_once()
call_kwargs = mock_sync_client.request.call_args
body = call_kwargs.kwargs["json"]
assert body["messages"] == [{"role": "user", "content": "Hello"}]
def test_create_with_params(self, mock_sync_client):
mock_response = MagicMock()
mock_response.json.return_value = SAMPLE_COMPLETION_RESPONSE
mock_sync_client.request.return_value = mock_response
client_obj = MagicMock()
client_obj._sync_client = mock_sync_client
completions = Completions(client_obj)
completions.create(
messages=[{"role": "user", "content": "Hello"}],
max_tokens=100,
temperature=0.5,
top_p=0.9,
stop=["END"],
n=2,
presence_penalty=0.1,
frequency_penalty=0.2,
)
body = mock_sync_client.request.call_args.kwargs["json"]
assert body["max_tokens"] == 100
assert body["temperature"] == 0.5
assert body["top_p"] == 0.9
assert body["stop"] == ["END"]
assert body["n"] == 2
assert body["presence_penalty"] == 0.1
assert body["frequency_penalty"] == 0.2
def test_create_omits_none_params(self, mock_sync_client):
mock_response = MagicMock()
mock_response.json.return_value = SAMPLE_COMPLETION_RESPONSE
mock_sync_client.request.return_value = mock_response
client_obj = MagicMock()
client_obj._sync_client = mock_sync_client
completions = Completions(client_obj)
completions.create(
messages=[{"role": "user", "content": "Hello"}],
)
body = mock_sync_client.request.call_args.kwargs["json"]
assert "max_tokens" not in body
assert "temperature" not in body
assert "stop" not in body
def test_create_with_tools(self, mock_sync_client):
mock_response = MagicMock()
mock_response.json.return_value = SAMPLE_TOOL_CALL_RESPONSE
mock_sync_client.request.return_value = mock_response
client_obj = MagicMock()
client_obj._sync_client = mock_sync_client
completions = Completions(client_obj)
result = completions.create(
messages=[{"role": "user", "content": "What's the weather?"}],
tools=[
{
"name": "get_weather",
"description": "Get weather",
"parameters": {
"type": "object",
"properties": {"city": {"type": "string"}},
},
}
],
tool_choice="auto",
)
body = mock_sync_client.request.call_args.kwargs["json"]
assert "tools" in body
assert body["tool_choice"] == "auto"
assert len(result.choices[0].message.tool_calls) == 1
def test_create_with_response_format(self, mock_sync_client):
class MyOutput(BaseModel):
answer: str
mock_response = MagicMock()
mock_response.json.return_value = {
"choices": [{"message": {"content": '{"answer": "42"}'}}],
"usage": {},
}
mock_sync_client.request.return_value = mock_response
client_obj = MagicMock()
client_obj._sync_client = mock_sync_client
completions = Completions(client_obj)
result = completions.create(
messages=[{"role": "user", "content": "What is 6*7?"}],
response_format=MyOutput,
)
body = mock_sync_client.request.call_args.kwargs["json"]
assert "response_format" in body
assert body["response_format"]["type"] == "json_schema"
assert result.choices[0].message.parsed is not None
assert result.choices[0].message.parsed.answer == "42"
def test_create_with_kwargs(self, mock_sync_client):
mock_response = MagicMock()
mock_response.json.return_value = SAMPLE_COMPLETION_RESPONSE
mock_sync_client.request.return_value = mock_response
client_obj = MagicMock()
client_obj._sync_client = mock_sync_client
completions = Completions(client_obj)
completions.create(
messages=[{"role": "user", "content": "Hello"}],
reasoning={"effort": "high"},
)
body = mock_sync_client.request.call_args.kwargs["json"]
assert body["reasoning"] == {"effort": "high"}
# ============================================================================
# Test: Completions.stream (sync, streaming)
# ============================================================================
class TestCompletionsStream:
def test_stream_yields_chunks(self, mock_sync_client):
sse_lines = [f"data: {json.dumps(chunk)}" for chunk in SAMPLE_STREAM_CHUNKS]
mock_response = MagicMock()
mock_response.iter_lines.return_value = iter(sse_lines)
mock_sync_client.stream.return_value.__enter__ = MagicMock(return_value=mock_response)
mock_sync_client.stream.return_value.__exit__ = MagicMock(return_value=False)
client_obj = MagicMock()
client_obj._sync_client = mock_sync_client
completions = Completions(client_obj)
chunks = list(
completions.stream(
messages=[{"role": "user", "content": "Hello"}],
)
)
assert len(chunks) == 3
assert chunks[0].choices[0].delta.content == "Hello"
assert chunks[1].choices[0].delta.content == " world!"
assert chunks[2].choices[0].finish_reason == "stop"
def test_stream_skips_invalid_json(self, mock_sync_client):
lines = [
"data: {invalid json",
f"data: {json.dumps(SAMPLE_STREAM_CHUNKS[0])}",
"", # empty line
]
mock_response = MagicMock()
mock_response.iter_lines.return_value = iter(lines)
mock_sync_client.stream.return_value.__enter__ = MagicMock(return_value=mock_response)
mock_sync_client.stream.return_value.__exit__ = MagicMock(return_value=False)
client_obj = MagicMock()
client_obj._sync_client = mock_sync_client
completions = Completions(client_obj)
chunks = list(
completions.stream(
messages=[{"role": "user", "content": "Hello"}],
)
)
assert len(chunks) == 1
def test_stream_skips_empty_id(self, mock_sync_client):
lines = [
f"data: {json.dumps({'id': '', 'choices': []})}",
f"data: {json.dumps(SAMPLE_STREAM_CHUNKS[0])}",
]
mock_response = MagicMock()
mock_response.iter_lines.return_value = iter(lines)
mock_sync_client.stream.return_value.__enter__ = MagicMock(return_value=mock_response)
mock_sync_client.stream.return_value.__exit__ = MagicMock(return_value=False)
client_obj = MagicMock()
client_obj._sync_client = mock_sync_client
completions = Completions(client_obj)
chunks = list(
completions.stream(
messages=[{"role": "user", "content": "Hello"}],
)
)
assert len(chunks) == 1
def test_stream_sets_stream_flag(self, mock_sync_client):
mock_response = MagicMock()
mock_response.iter_lines.return_value = iter([])
mock_sync_client.stream.return_value.__enter__ = MagicMock(return_value=mock_response)
mock_sync_client.stream.return_value.__exit__ = MagicMock(return_value=False)
client_obj = MagicMock()
client_obj._sync_client = mock_sync_client
completions = Completions(client_obj)
list(
completions.stream(
messages=[{"role": "user", "content": "Hello"}],
)
)
call_kwargs = mock_sync_client.stream.call_args
body = call_kwargs.kwargs["json"]
assert body["stream"] is True
# ============================================================================
# Test: Completions.acreate (async, non-streaming)
# ============================================================================
class TestAsyncCompletionsCreate:
@pytest.mark.asyncio
async def test_basic_acreate(self, mock_async_client):
mock_response = MagicMock()
mock_response.json.return_value = SAMPLE_COMPLETION_RESPONSE
mock_async_client.request.return_value = mock_response
client_obj = MagicMock()
client_obj._async_client = mock_async_client
completions = Completions(client_obj)
result = await completions.acreate(
messages=[{"role": "user", "content": "Hello"}],
)
assert isinstance(result, ChatCompletion)
assert result.choices[0].message.content == "Hello! How can I help you?"
# ============================================================================
# Test: Embeddings
# ============================================================================
class TestEmbeddingsCreate:
def test_basic_create(self):
mock_response = MagicMock()
mock_response.json.return_value = SAMPLE_EMBEDDING_RESPONSE
mock_client = MagicMock()
mock_client.request.return_value = mock_response
client_obj = MagicMock()
client_obj._embedding_sync_client = mock_client
from uipath.llm_client.clients.normalized.embeddings import Embeddings
embeddings = Embeddings(client_obj)
result = embeddings.create(input=["Hello world", "Goodbye"])
assert isinstance(result, EmbeddingResponse)
assert len(result.data) == 2
assert result.data[0].embedding == [0.1, 0.2, 0.3]
body = mock_client.request.call_args.kwargs["json"]
assert body["input"] == ["Hello world", "Goodbye"]
def test_string_input_wrapped(self):
mock_response = MagicMock()
mock_response.json.return_value = SAMPLE_EMBEDDING_RESPONSE
mock_client = MagicMock()
mock_client.request.return_value = mock_response
client_obj = MagicMock()
client_obj._embedding_sync_client = mock_client
from uipath.llm_client.clients.normalized.embeddings import Embeddings
embeddings = Embeddings(client_obj)
embeddings.create(input="Hello world")
body = mock_client.request.call_args.kwargs["json"]
assert body["input"] == ["Hello world"]
class TestAsyncEmbeddingsCreate:
@pytest.mark.asyncio
async def test_basic_acreate(self):
mock_response = MagicMock()
mock_response.json.return_value = SAMPLE_EMBEDDING_RESPONSE
mock_client = AsyncMock()
mock_client.request.return_value = mock_response
client_obj = MagicMock()
client_obj._embedding_async_client = mock_client
from uipath.llm_client.clients.normalized.embeddings import Embeddings
embeddings = Embeddings(client_obj)
result = await embeddings.acreate(input=["Hello world"])
assert isinstance(result, EmbeddingResponse)
assert len(result.data) == 2
# ============================================================================
# Test: Type models
# ============================================================================
class TestTypeModels:
def test_usage_defaults(self):
usage = Usage()
assert usage.prompt_tokens == 0
assert usage.completion_tokens == 0
assert usage.total_tokens == 0
assert usage.cache_read_input_tokens == 0
def test_tool_call(self):
tc = ToolCall(id="call_1", name="func", arguments={"x": 1})
assert tc.id == "call_1"
assert tc.name == "func"
assert tc.arguments == {"x": 1}