-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathtest_sdk.py
More file actions
1797 lines (1568 loc) · 86.4 KB
/
Copy pathtest_sdk.py
File metadata and controls
1797 lines (1568 loc) · 86.4 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
#!/usr/bin/env python3
"""AssistantHub Python SDK Test Suite."""
from __future__ import annotations
import os
import sys
import time
import traceback
import uuid
import asyncio
from dataclasses import dataclass, field
from typing import Any, Callable, Optional
# Add the SDK to the path
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
from assistanthub_sdk import AssistantHubClient, AsyncAssistantHubClient
from assistanthub_sdk.models import (
Assistant,
AssistantDocument,
AssistantDocumentSelectionItem,
AssistantSettings,
AssistantToolPolicy,
AssistantToolPolicyValidationRequest,
AssistantToolPolicyValidationResult,
AssistantToolPolicyTestResult,
CifsCrawlRepositorySettings,
CrawlPlan,
CrawlScheduleSettings,
ChatLocalAttachment,
ChatCompletionMessage,
ChatCompletionRequest,
ChatCompletionRetrieval,
ChatCompletionResponse,
ChatCompletionUsage,
ChatHistory,
Credential,
EvalFact,
ExternalSearchConfigurationStatus,
AssistantTokenUsageTelemetry,
NfsCrawlRepositorySettings,
PartioEndpointConfig,
PartioEndpointRequest,
TenantMetadata,
UserMaster,
WebCrawlRepositorySettings,
)
from assistanthub_sdk.enums import (
NfsVersion,
RepositoryType,
ScheduleInterval,
WebAuthType,
)
@dataclass
class TestResult:
"""Result of a single test execution."""
__test__ = False
test_name: str
passed: bool
runtime_ms: float
error_message: Optional[str] = None
class TestRunner:
"""Runs tests and collects results, matching the C# TestRunner output format."""
__test__ = False
def __init__(self) -> None:
self._results: list[TestResult] = []
@property
def results(self) -> list[TestResult]:
return self._results
def run_test(self, test_name: str, test_func: Callable[[], None]) -> TestResult:
start = time.perf_counter()
try:
test_func()
elapsed_ms = (time.perf_counter() - start) * 1000.0
result = TestResult(test_name=test_name, passed=True, runtime_ms=elapsed_ms)
sys.stdout.write(" PASS ")
except Exception as ex:
elapsed_ms = (time.perf_counter() - start) * 1000.0
error_msg = str(ex)
result = TestResult(
test_name=test_name, passed=False, runtime_ms=elapsed_ms, error_message=error_msg
)
sys.stdout.write(" FAIL ")
sys.stdout.write(" {} ({:.1f}ms)\n".format(result.test_name, result.runtime_ms))
if not result.passed:
sys.stdout.write(" {}\n".format(result.error_message))
self._results.append(result)
return result
def print_summary(self, total_runtime_ms: float) -> None:
passed = sum(1 for r in self._results if r.passed)
failed = sum(1 for r in self._results if not r.passed)
failures = [r for r in self._results if not r.passed]
print()
print("=" * 80)
print("TEST SUMMARY")
print("=" * 80)
print(" Total: {}".format(len(self._results)))
print(" Passed: {}".format(passed))
print(" Failed: {}".format(failed))
print(" Runtime: {:.1f}ms".format(total_runtime_ms))
print()
if failures:
print("FAILED TESTS:")
for f in failures:
sys.stdout.write(" FAIL ")
sys.stdout.write(" {}\n".format(f.test_name))
sys.stdout.write(" {}\n".format(f.error_message))
print()
if failed > 0:
print("OVERALL: FAIL")
else:
print("OVERALL: PASS")
# ---------------------------------------------------------------------------
# Assertion helpers
# ---------------------------------------------------------------------------
def assert_true(condition: bool, message: str) -> None:
if not condition:
raise AssertionError("{}: expected true".format(message))
def assert_false(condition: bool, message: str) -> None:
if condition:
raise AssertionError("{}: expected false".format(message))
def assert_not_none(value: Any, label: str) -> None:
if value is None:
raise AssertionError("{} should not be None".format(label))
def assert_equal(expected: Any, actual: Any, label: str) -> None:
if expected != actual:
raise AssertionError("{}: expected '{}' but got '{}'".format(label, expected, actual))
def assert_starts_with(value: str, prefix: str, label: str) -> None:
if not value.startswith(prefix):
raise AssertionError("{}: expected to start with '{}' but got '{}'".format(label, prefix, value))
def assert_gte(value: int, minimum: int, label: str) -> None:
if value < minimum:
raise AssertionError("{}: expected >= {} but got {}".format(label, minimum, value))
# ---------------------------------------------------------------------------
# Unique suffix generator
# ---------------------------------------------------------------------------
def unique_suffix() -> str:
return uuid.uuid4().hex[:8]
# ---------------------------------------------------------------------------
# Local SDK contract tests
# ---------------------------------------------------------------------------
def _truthy(value: Optional[str]) -> bool:
if value is None:
return False
return value.strip().lower() in ("1", "true", "yes", "y")
def local_only_requested() -> bool:
if _truthy(os.environ.get("ASSISTANTHUB_SDK_LOCAL_ONLY")):
return True
for arg in sys.argv[1:]:
normalized = arg.strip().lower()
if normalized in ("--local-only", "local-only", "localonly=true", "local=true"):
return True
return False
def run_sdk_contract_tests(runner: TestRunner) -> None:
def test_request_attached_document_ids() -> None:
request = ChatCompletionRequest(
messages=[ChatCompletionMessage(role="user", content="Summarize this document.")],
attached_document_ids=["adoc_one", "adoc_two"],
top_p=0.8,
max_tokens=512,
)
payload = request.model_dump(by_alias=True, exclude_none=True)
assert_true("attached_document_ids" in payload, "request should use attached_document_ids")
assert_false("AttachedDocumentIds" in payload, "request should not use PascalCase attachment key")
assert_equal(["adoc_one", "adoc_two"], payload["attached_document_ids"], "attached document IDs")
assert_equal(0.8, payload["top_p"], "top_p alias")
assert_equal(512, payload["max_tokens"], "max_tokens alias")
round_trip = ChatCompletionRequest.model_validate(payload)
assert_equal(
["adoc_one", "adoc_two"],
round_trip.attached_document_ids,
"round-trip attached document IDs",
)
def test_request_local_attachments() -> None:
request = ChatCompletionRequest(
messages=[ChatCompletionMessage(role="user", content="Summarize this local file.")],
local_attachments=[
ChatLocalAttachment(
name="notes.txt",
content_type="text/plain",
base64_content="SGVsbG8=",
)
],
)
payload = request.model_dump(by_alias=True, exclude_none=True)
assert_true("local_attachments" in payload, "request should use local_attachments")
assert_false("LocalAttachments" in payload, "request should not use PascalCase local attachment key")
assert_equal(1, len(payload["local_attachments"]), "local attachment count")
assert_equal("notes.txt", payload["local_attachments"][0]["name"], "local attachment name")
assert_equal("SGVsbG8=", payload["local_attachments"][0]["base64_content"], "local attachment base64")
round_trip = ChatCompletionRequest.model_validate(payload)
assert_equal(1, len(round_trip.local_attachments or []), "round-trip local attachment count")
assert_equal("notes.txt", round_trip.local_attachments[0].name, "round-trip local attachment name")
def test_response_retrieval_attached_document_metadata() -> None:
response = ChatCompletionResponse.model_validate(
{
"id": "chatcmpl_local",
"object": "chat.completion",
"created": 0,
"model": "test-model",
"choices": [
{
"index": 0,
"message": {"role": "assistant", "content": "done", "thinking": "hidden reasoning"},
"finish_reason": "stop",
}
],
"usage": {
"prompt_tokens": 12,
"completion_tokens": 4,
"total_tokens": 16,
"tool_definition_tokens": 5,
"prompt_tokens_details": {
"cached_tokens": 3,
"tool_tokens": 5,
},
"completion_tokens_details": {
"reasoning_tokens": 7,
},
},
"tool_calls": [
{
"tool_call_id": "call_search",
"tool_name": "collection_search",
"display_label": "Searching collection",
"iteration": 1,
"sequence_number": 1,
"success": True,
"denied": False,
"truncated": False,
"output_characters": 128,
"result_count": 3,
"credits_used": 2,
"provider_latency_ms": 45.5,
"duration_ms": 12.5,
"summary": "Searching collection completed.",
}
],
"retrieval": {
"collection_id": "col_abc123",
"duration_ms": 42.7,
"chunks_returned": 3,
"rerank_duration_ms": 5.5,
"rerank_input_count": 4,
"rerank_output_count": 2,
"attached_document_ids": ["adoc_one"],
"attached_documents": [
{
"Id": "adoc_one",
"Name": "Policy Handbook",
"OriginalFilename": "policy.pdf",
"ContentType": "application/pdf",
"SizeBytes": 12345,
"CreatedUtc": "2026-01-01T00:00:00Z",
"LastUpdateUtc": "2026-01-02T00:00:00Z",
}
],
"document_filter_applied": True,
"chunks": [
{
"document_id": "adoc_one",
"score": 0.91,
"rerank_score": 8.5,
"fusion_score": 0.42,
"text_score": 0.66,
"content": "Local fixture content.",
"position": 7,
}
],
},
"citations": {
"sources": [
{
"index": 1,
"document_id": "adoc_one",
"document_name": "Policy Handbook",
"content_type": "application/pdf",
"score": 0.91,
"rerank_score": 8.5,
"excerpt": "Local fixture content.",
"download_url": "/v1.0/assistants/asst_local/documents/adoc_one/download",
}
],
"referenced_indices": [1],
"auto_populated": False,
},
}
)
assert_not_none(response.retrieval, "ChatCompletionResponse retrieval")
assert_equal("hidden reasoning", response.choices[0].message.thinking, "response message thinking")
retrieval = response.retrieval
assert_equal("col_abc123", retrieval.collection_id, "retrieval collection ID")
assert_equal(42.7, retrieval.duration_ms, "retrieval duration")
assert_equal(3, retrieval.chunks_returned, "retrieval chunks returned")
assert_equal(["adoc_one"], retrieval.attached_document_ids, "retrieval attached document IDs")
assert_true(retrieval.document_filter_applied, "document filter applied")
assert_not_none(retrieval.attached_documents, "attached document metadata")
assert_equal("adoc_one", retrieval.attached_documents[0].id, "attached document metadata ID")
assert_equal("policy.pdf", retrieval.attached_documents[0].original_filename, "attached document filename")
assert_not_none(retrieval.chunks, "retrieval chunks")
assert_equal("adoc_one", retrieval.chunks[0].document_id, "retrieval chunk document ID")
assert_equal(8.5, retrieval.chunks[0].rerank_score, "retrieval chunk rerank score")
payload = retrieval.model_dump(by_alias=True, exclude_none=True)
assert_true("collection_id" in payload, "retrieval payload collection_id")
assert_true("duration_ms" in payload, "retrieval payload duration_ms")
assert_true("chunks_returned" in payload, "retrieval payload chunks_returned")
assert_true("attached_document_ids" in payload, "retrieval payload attached_document_ids")
assert_true("attached_documents" in payload, "retrieval payload attached_documents")
assert_true("document_filter_applied" in payload, "retrieval payload document_filter_applied")
assert_true("document_id" in payload["chunks"][0], "retrieval chunk payload document_id")
assert_true("rerank_score" in payload["chunks"][0], "retrieval chunk payload rerank_score")
doc_payload = payload["attached_documents"][0]
assert_false("S3Key" in doc_payload, "selection metadata should not expose S3Key")
assert_false("BucketName" in doc_payload, "selection metadata should not expose BucketName")
assert_false("s3_key" in doc_payload, "selection metadata should not expose s3_key")
assert_false("bucket_name" in doc_payload, "selection metadata should not expose bucket_name")
assert_not_none(response.citations, "ChatCompletionResponse citations")
assert_equal("adoc_one", response.citations.sources[0].document_id, "citation document ID")
citation_payload = response.citations.model_dump(by_alias=True, exclude_none=True)
assert_true("referenced_indices" in citation_payload, "citation payload referenced_indices")
assert_true("document_id" in citation_payload["sources"][0], "citation payload document_id")
assert_not_none(response.tool_calls, "ChatCompletionResponse tool_calls")
assert_equal(1, len(response.tool_calls), "tool_calls count")
assert_equal("collection_search", response.tool_calls[0].tool_name, "tool trace name")
assert_equal("Searching collection", response.tool_calls[0].display_label, "tool trace label")
assert_equal(3, response.tool_calls[0].result_count, "tool trace result count")
assert_equal(2, response.tool_calls[0].credits_used, "tool trace credits used")
assert_equal(45.5, response.tool_calls[0].provider_latency_ms, "tool trace provider latency")
tool_payload = response.model_dump(by_alias=True, exclude_none=True)["tool_calls"][0]
assert_true("tool_name" in tool_payload, "tool trace payload tool_name")
assert_true("result_count" in tool_payload, "tool trace payload result_count")
assert_true("credits_used" in tool_payload, "tool trace payload credits_used")
assert_true("provider_latency_ms" in tool_payload, "tool trace payload provider_latency_ms")
assert_false("ArgumentsJson" in tool_payload, "tool trace should not expose arguments")
assert_false("OutputJson" in tool_payload, "tool trace should not expose raw output")
assert_not_none(response.usage, "ChatCompletionResponse usage")
assert_equal(16, response.usage.total_tokens, "usage total tokens")
assert_equal(5, response.usage.tool_definition_tokens, "usage tool-definition tokens")
assert_not_none(response.usage.prompt_tokens_details, "usage prompt token details")
assert_equal(3, response.usage.prompt_tokens_details.cached_tokens, "usage cached tokens")
assert_not_none(response.usage.completion_tokens_details, "usage completion token details")
assert_equal(7, response.usage.completion_tokens_details.reasoning_tokens, "usage reasoning tokens")
usage_payload = response.usage.model_dump(by_alias=True, exclude_none=True)
assert_true("tool_definition_tokens" in usage_payload, "usage payload tool_definition_tokens")
assert_true("completion_tokens_details" in usage_payload, "usage payload completion_tokens_details")
tokens = AssistantTokenUsageTelemetry.model_validate(
{"Input": 12, "Output": 4, "Total": 16, "Reasoning": 7, "ToolDefinitions": 5}
)
assert_equal(7, tokens.reasoning, "telemetry reasoning tokens")
assert_equal(5, tokens.tool_definitions, "telemetry tool-definition tokens")
def test_tool_policy_settings_round_trip() -> None:
settings = AssistantSettings.model_validate(
{
"InferenceEndpointId": "cep_response",
"ToolRoutingInferenceEndpointId": "cep_router",
"RetrievalGateInferenceEndpointId": "cep_gate",
"QueryRewriteInferenceEndpointId": "cep_rewrite",
"RerankInferenceEndpointId": "cep_rerank",
"EmbeddingEndpointId": "eep_embed",
"ExposeThinking": True,
"ToolPolicyJson": "{}",
"ToolPolicy": {
"EnableToolCalls": True,
"EnableCollectionSearchTool": True,
"EnableDocumentAtomExtractionTool": True,
"EnableWebSearchTool": True,
"ToolChoiceMode": "Required",
"MaxToolIterations": 4,
"MaxToolResultItems": 9,
"AllowedToolNames": ["collection_search"],
"MaxSearchTopK": 7,
"MaxDocumentsConsideredPerSearch": 25,
"MaxResultsConsideredPerSearch": 50,
"MaxAtomExtractionBytes": 2097152,
"MaxAtomExtractionCharacters": 24000,
"AllowedSearchModes": ["FullText"],
"ReturnFullSearchContent": True,
"MaxWebResults": 3,
"TavilyEndpoint": "https://assistant.tavily.test/search",
"TavilyApiKey": "assistant-key",
"AllowUngovernedWebAccess": True,
"AllowedWebDomains": ["example.com"],
"BlockedWebDomains": ["blocked.example"],
},
}
)
assert_equal("cep_response", settings.inference_endpoint_id, "settings InferenceEndpointId")
assert_equal("cep_router", settings.tool_routing_inference_endpoint_id, "settings ToolRoutingInferenceEndpointId")
assert_equal("cep_gate", settings.retrieval_gate_inference_endpoint_id, "settings RetrievalGateInferenceEndpointId")
assert_equal("cep_rewrite", settings.query_rewrite_inference_endpoint_id, "settings QueryRewriteInferenceEndpointId")
assert_equal("cep_rerank", settings.rerank_inference_endpoint_id, "settings RerankInferenceEndpointId")
assert_equal(True, settings.expose_thinking, "settings ExposeThinking")
assert_equal("eep_embed", settings.embedding_endpoint_id, "settings EmbeddingEndpointId")
assert_equal("{}", settings.tool_policy_json, "settings ToolPolicyJson")
assert_not_none(settings.tool_policy, "settings ToolPolicy")
assert_true(settings.tool_policy.enable_tool_calls, "settings EnableToolCalls")
assert_true(settings.tool_policy.enable_collection_search_tool, "settings EnableCollectionSearchTool")
assert_true(settings.tool_policy.enable_document_atom_extraction_tool, "settings EnableDocumentAtomExtractionTool")
assert_true(settings.tool_policy.enable_web_search_tool, "settings EnableWebSearchTool")
assert_equal("Required", settings.tool_policy.tool_choice_mode, "settings ToolChoiceMode")
assert_equal(4, settings.tool_policy.max_tool_iterations, "settings MaxToolIterations")
assert_equal(9, settings.tool_policy.max_tool_result_items, "settings MaxToolResultItems")
assert_equal(["collection_search"], settings.tool_policy.allowed_tool_names, "settings AllowedToolNames")
assert_equal(7, settings.tool_policy.max_search_top_k, "settings MaxSearchTopK")
assert_equal(25, settings.tool_policy.max_documents_considered_per_search, "settings MaxDocumentsConsideredPerSearch")
assert_equal(50, settings.tool_policy.max_results_considered_per_search, "settings MaxResultsConsideredPerSearch")
assert_equal(2097152, settings.tool_policy.max_atom_extraction_bytes, "settings MaxAtomExtractionBytes")
assert_equal(24000, settings.tool_policy.max_atom_extraction_characters, "settings MaxAtomExtractionCharacters")
assert_equal(["FullText"], settings.tool_policy.allowed_search_modes, "settings AllowedSearchModes")
assert_true(settings.tool_policy.return_full_search_content, "settings ReturnFullSearchContent")
assert_equal(3, settings.tool_policy.max_web_results, "settings MaxWebResults")
assert_equal("https://assistant.tavily.test/search", settings.tool_policy.tavily_endpoint, "settings TavilyEndpoint")
assert_equal("assistant-key", settings.tool_policy.tavily_api_key, "settings TavilyApiKey")
assert_true(settings.tool_policy.allow_ungoverned_web_access, "settings AllowUngovernedWebAccess")
assert_equal(["example.com"], settings.tool_policy.allowed_web_domains, "settings AllowedWebDomains")
payload = settings.model_dump(by_alias=True, exclude_none=True)
assert_equal("cep_router", payload["toolRoutingInferenceEndpointId"], "settings payload toolRoutingInferenceEndpointId")
assert_true("ToolPolicyJson" in payload, "settings payload ToolPolicyJson")
assert_true("ToolPolicy" in payload, "settings payload ToolPolicy")
assert_true("EnableToolCalls" in payload["ToolPolicy"], "settings payload EnableToolCalls")
assert_true("ToolChoiceMode" in payload["ToolPolicy"], "settings payload ToolChoiceMode")
assert_true("AllowedToolNames" in payload["ToolPolicy"], "settings payload AllowedToolNames")
assert_true("AllowedSearchModes" in payload["ToolPolicy"], "settings payload AllowedSearchModes")
assert_true("MaxDocumentsConsideredPerSearch" in payload["ToolPolicy"], "settings payload MaxDocumentsConsideredPerSearch")
assert_true("MaxResultsConsideredPerSearch" in payload["ToolPolicy"], "settings payload MaxResultsConsideredPerSearch")
assert_true("ReturnFullSearchContent" in payload["ToolPolicy"], "settings payload ReturnFullSearchContent")
assert_true("TavilyEndpoint" in payload["ToolPolicy"], "settings payload TavilyEndpoint")
assert_true("AllowUngovernedWebAccess" in payload["ToolPolicy"], "settings payload AllowUngovernedWebAccess")
assert_true("AllowedWebDomains" in payload["ToolPolicy"], "settings payload AllowedWebDomains")
assert_false("toolPolicy" in payload, "settings payload should not use lower-camel ToolPolicy")
assert_false("enableToolCalls" in payload["ToolPolicy"], "policy payload should not use lower-camel EnableToolCalls")
legacy_policy = AssistantToolPolicy.model_validate(
{
"enableToolCalls": True,
"enableCollectionSearchTool": True,
"returnFullSearchContent": True,
"maxDocumentsConsideredPerSearch": 11,
"maxResultsConsideredPerSearch": 22,
"allowedWebDomains": ["legacy.example"],
}
)
assert_true(legacy_policy.enable_tool_calls, "legacy EnableToolCalls alias")
assert_true(legacy_policy.enable_collection_search_tool, "legacy collection search alias")
assert_true(legacy_policy.return_full_search_content, "legacy ReturnFullSearchContent alias")
assert_equal(11, legacy_policy.max_documents_considered_per_search, "legacy MaxDocumentsConsideredPerSearch alias")
assert_equal(22, legacy_policy.max_results_considered_per_search, "legacy MaxResultsConsideredPerSearch alias")
assert_equal(["legacy.example"], legacy_policy.allowed_web_domains, "legacy allowed web domains")
validation_request = AssistantToolPolicyValidationRequest(tool_policy=legacy_policy)
validation_payload = validation_request.model_dump(by_alias=True, exclude_none=True)
assert_true("ToolPolicy" in validation_payload, "validation request ToolPolicy")
assert_true("EnableToolCalls" in validation_payload["ToolPolicy"], "validation request EnableToolCalls")
validation_result = AssistantToolPolicyValidationResult.model_validate(
{
"Success": False,
"Message": "Policy invalid.",
"ToolPolicyJson": "{}",
"ToolPolicy": {
"EnableToolCalls": True,
"EnableCollectionSearchTool": True,
"TavilyEndpoint": "https://assistant.tavily.test/search",
"AllowedWebDomains": ["example.com"],
},
"Tools": [],
"Errors": ["EnableToolCalls is true but no enabled tool is currently executable."],
"ErrorCodes": ["no_available_tools"],
}
)
assert_true(not validation_result.success, "validation result success")
assert_not_none(validation_result.tool_policy, "validation result ToolPolicy")
assert_true(validation_result.tool_policy.enable_collection_search_tool, "validation result collection search")
assert_equal("https://assistant.tavily.test/search", validation_result.tool_policy.tavily_endpoint, "validation result TavilyEndpoint")
assert_equal(["example.com"], validation_result.tool_policy.allowed_web_domains, "validation result AllowedWebDomains")
assert_equal(["no_available_tools"], validation_result.error_codes, "validation result ErrorCodes")
diagnostics_result = AssistantToolPolicyTestResult.model_validate(
{
"Success": False,
"Message": "Tool diagnostics found blocking issues.",
"AssistantId": "asst_local",
"InferenceEndpointId": "cep_local",
"ToolRoutingInferenceEndpointId": "cep_router",
"EffectiveToolRoutingInferenceEndpointId": "cep_router",
"EndpointResolved": True,
"EndpointModel": "qwen3-tool",
"EndpointApiFormat": "OpenAI",
"EndpointActive": True,
"EndpointSupportsToolCalling": False,
"EndpointToolCallingApiFormat": None,
"EndpointSupportsParallelToolCalls": False,
"EndpointSupportsStreamingToolCalls": False,
"Validation": {"Success": True, "Errors": [], "ErrorCodes": []},
"Tools": [],
"Warnings": [],
"Errors": ["The effective tool-routing completion endpoint does not explicitly support tool calling."],
"ErrorCodes": ["tool_routing_endpoint_not_tool_capable"],
}
)
assert_true(not diagnostics_result.success, "diagnostics result success")
assert_equal("cep_router", diagnostics_result.tool_routing_inference_endpoint_id, "diagnostics configured tool routing endpoint")
assert_equal("cep_router", diagnostics_result.effective_tool_routing_inference_endpoint_id, "diagnostics effective tool routing endpoint")
assert_true(diagnostics_result.endpoint_resolved, "diagnostics endpoint resolved")
assert_equal("qwen3-tool", diagnostics_result.endpoint_model, "diagnostics endpoint model")
assert_equal(["tool_routing_endpoint_not_tool_capable"], diagnostics_result.error_codes, "diagnostics ErrorCodes")
endpoint = PartioEndpointConfig.model_validate(
{
"Id": "ep_tool",
"Model": "qwen3",
"Endpoint": "http://localhost:11434",
"ApiFormat": "OpenAI",
"SupportsToolCalling": True,
"ToolCallingApiFormat": "OpenAIChatCompletions",
"SupportsParallelToolCalls": True,
"SupportsStreamingToolCalls": True,
}
)
assert_true(endpoint.supports_tool_calling, "endpoint SupportsToolCalling")
assert_equal("OpenAIChatCompletions", endpoint.tool_calling_api_format, "endpoint ToolCallingApiFormat")
endpoint_payload = PartioEndpointRequest(
model="qwen3",
endpoint="http://localhost:11434",
api_format="OpenAI",
supports_tool_calling=True,
tool_calling_api_format="OpenAIChatCompletions",
supports_parallel_tool_calls=True,
supports_streaming_tool_calls=True,
).model_dump(by_alias=True, exclude_none=True)
assert_true(endpoint_payload["supportsToolCalling"], "endpoint payload supportsToolCalling")
assert_equal("OpenAIChatCompletions", endpoint_payload["toolCallingApiFormat"], "endpoint payload toolCallingApiFormat")
def test_external_search_status_model_and_route() -> None:
status = ExternalSearchConfigurationStatus.model_validate(
{
"enabled": True,
"enabledProviders": 1,
"configuredProviders": 1,
"misconfiguredProviders": 0,
}
)
assert_true(status.enabled, "external-search status enabled")
assert_equal(1, status.configured_providers, "external-search configured providers")
payload = status.model_dump(by_alias=True)
assert_true("ConfiguredProviders" in payload, "external-search status uses server aliases")
assert_false("ApiKey" in payload, "external-search status must not expose secrets")
class Response:
def json(self) -> dict[str, Any]:
return {
"Enabled": True,
"EnabledProviders": 1,
"ConfiguredProviders": 1,
"MisconfiguredProviders": 0,
}
class ProbeClient(AssistantHubClient):
def __init__(self) -> None:
super().__init__("http://localhost:6600", api_key="test-key")
self.captured_method: Optional[str] = None
self.captured_path: Optional[str] = None
def _request(self, method: str, path: str, **kwargs: Any) -> Response:
self.captured_method = method
self.captured_path = path
return Response()
client = ProbeClient()
try:
result = client.get_external_search_status()
assert_equal("GET", client.captured_method, "external-search status method")
assert_equal("/v1.0/configuration/external-search/status", client.captured_path, "external-search status path")
assert_true(result.enabled, "external-search status client enabled")
finally:
client.close()
def test_assistant_tool_call_trace_routes() -> None:
class Response:
def __init__(self, payload: dict[str, Any]) -> None:
self._payload = payload
def json(self) -> dict[str, Any]:
return self._payload
class ProbeClient(AssistantHubClient):
def __init__(self) -> None:
super().__init__("http://localhost:6600", api_key="test-key")
self.requests: list[dict[str, Any]] = []
def _request(self, method: str, path: str, **kwargs: Any) -> Response:
self.requests.append({"method": method, "path": path, "kwargs": kwargs})
if method == "GET" and path == "/v1.0/assistants/asst_local/tool-calls":
return Response(
{
"Success": True,
"MaxResults": 5,
"TotalRecords": 1,
"RecordsRemaining": 0,
"EndOfResults": True,
"Objects": [
{
"Id": "atc_local",
"AssistantId": "asst_local",
"TraceId": "trace_local",
"ToolName": "collection_search",
"ArgumentsJson": "[redacted]",
"Success": True,
}
],
}
)
if method == "GET" and path == "/v1.0/assistants/asst_local/tool-calls/atc_local":
return Response(
{
"Id": "atc_local",
"AssistantId": "asst_local",
"ToolName": "collection_search",
"Success": True,
}
)
if method == "DELETE" and path == "/v1.0/assistants/asst_local/tool-calls":
return Response({"DeletedCount": 1})
if method == "DELETE" and path == "/v1.0/assistants/asst_local/tool-calls/atc_local":
return Response({})
return Response({})
client = ProbeClient()
try:
listed = client.list_assistant_tool_calls(
"asst_local",
max_results=5,
trace_id="trace_local",
tool_name="collection_search",
success=True,
)
assert_equal(1, len(listed.objects), "tool-call list count")
assert_equal("atc_local", listed.objects[0].id, "tool-call list id")
assert_equal("collection_search", listed.objects[0].tool_name, "tool-call list tool")
assert_false("secret" in (listed.objects[0].arguments_json or "").lower(), "tool-call list arguments redacted")
record = client.get_assistant_tool_call("asst_local", "atc_local")
assert_equal("atc_local", record.id, "tool-call get id")
deleted = client.delete_assistant_tool_calls("asst_local", tool_name="collection_search")
assert_equal(1, deleted.deleted_count, "tool-call bulk delete count")
client.delete_assistant_tool_call("asst_local", "atc_local")
assert_equal("GET", client.requests[0]["method"], "tool-call list method")
assert_equal("/v1.0/assistants/asst_local/tool-calls", client.requests[0]["path"], "tool-call list path")
assert_equal("trace_local", client.requests[0]["kwargs"]["params"]["traceId"], "tool-call list trace query")
assert_equal("collection_search", client.requests[0]["kwargs"]["params"]["toolName"], "tool-call list tool query")
assert_equal(True, client.requests[0]["kwargs"]["params"]["success"], "tool-call list success query")
assert_equal("GET", client.requests[1]["method"], "tool-call get method")
assert_equal("/v1.0/assistants/asst_local/tool-calls/atc_local", client.requests[1]["path"], "tool-call get path")
assert_equal("DELETE", client.requests[2]["method"], "tool-call bulk delete method")
assert_equal("collection_search", client.requests[2]["kwargs"]["params"]["toolName"], "tool-call bulk delete query")
assert_equal("DELETE", client.requests[3]["method"], "tool-call delete method")
assert_equal("/v1.0/assistants/asst_local/tool-calls/atc_local", client.requests[3]["path"], "tool-call delete path")
finally:
client.close()
def test_async_assistant_tool_call_trace_routes() -> None:
class Response:
def __init__(self, payload: dict[str, Any]) -> None:
self._payload = payload
def json(self) -> dict[str, Any]:
return self._payload
class ProbeClient(AsyncAssistantHubClient):
def __init__(self) -> None:
super().__init__("http://localhost:6600", api_key="test-key")
self.requests: list[dict[str, Any]] = []
async def _request(self, method: str, path: str, **kwargs: Any) -> Response:
self.requests.append({"method": method, "path": path, "kwargs": kwargs})
if method == "GET" and path == "/v1.0/assistants/asst_local/tool-calls":
return Response(
{
"Success": True,
"MaxResults": 5,
"TotalRecords": 1,
"RecordsRemaining": 0,
"EndOfResults": True,
"Objects": [
{
"Id": "atc_local",
"AssistantId": "asst_local",
"TraceId": "trace_local",
"ToolName": "collection_search",
"ArgumentsJson": "[redacted]",
"Success": True,
}
],
}
)
if method == "GET" and path == "/v1.0/assistants/asst_local/tool-calls/atc_local":
return Response(
{
"Id": "atc_local",
"AssistantId": "asst_local",
"ToolName": "collection_search",
"Success": True,
}
)
if method == "DELETE" and path == "/v1.0/assistants/asst_local/tool-calls":
return Response({"DeletedCount": 1})
if method == "DELETE" and path == "/v1.0/assistants/asst_local/tool-calls/atc_local":
return Response({})
return Response({})
async def run_probe() -> None:
client = ProbeClient()
try:
listed = await client.list_assistant_tool_calls(
"asst_local",
max_results=5,
trace_id="trace_local",
tool_name="collection_search",
success=True,
)
assert_equal(1, len(listed.objects), "async tool-call list count")
assert_equal("atc_local", listed.objects[0].id, "async tool-call list id")
record = await client.get_assistant_tool_call("asst_local", "atc_local")
assert_equal("atc_local", record.id, "async tool-call get id")
deleted = await client.delete_assistant_tool_calls("asst_local", tool_name="collection_search")
assert_equal(1, deleted.deleted_count, "async tool-call bulk delete count")
await client.delete_assistant_tool_call("asst_local", "atc_local")
assert_equal("GET", client.requests[0]["method"], "async tool-call list method")
assert_equal("/v1.0/assistants/asst_local/tool-calls", client.requests[0]["path"], "async tool-call list path")
assert_equal("trace_local", client.requests[0]["kwargs"]["params"]["traceId"], "async tool-call list trace query")
assert_equal("collection_search", client.requests[0]["kwargs"]["params"]["toolName"], "async tool-call list tool query")
assert_equal(True, client.requests[0]["kwargs"]["params"]["success"], "async tool-call list success query")
assert_equal("GET", client.requests[1]["method"], "async tool-call get method")
assert_equal("/v1.0/assistants/asst_local/tool-calls/atc_local", client.requests[1]["path"], "async tool-call get path")
assert_equal("DELETE", client.requests[2]["method"], "async tool-call bulk delete method")
assert_equal("collection_search", client.requests[2]["kwargs"]["params"]["toolName"], "async tool-call bulk delete query")
assert_equal("DELETE", client.requests[3]["method"], "async tool-call delete method")
assert_equal("/v1.0/assistants/asst_local/tool-calls/atc_local", client.requests[3]["path"], "async tool-call delete path")
finally:
await client.close()
asyncio.run(run_probe())
def test_chat_history_attached_document_metadata() -> None:
history = ChatHistory.model_validate(
{
"Id": "chist_local",
"TenantId": "default",
"ThreadId": "thr_local",
"AssistantId": "asst_local",
"AttachedDocumentIdsJson": "[\"adoc_one\"]",
"AttachedDocumentsJson": "[{\"Id\":\"adoc_one\",\"Name\":\"Policy Handbook\"}]",
"CreatedUtc": "2026-01-01T00:00:00Z",
"LastUpdateUtc": "2026-01-01T00:00:00Z",
}
)
assert_equal("chist_local", history.id, "history ID")
assert_true("adoc_one" in history.attached_document_ids_json, "history attached document IDs JSON")
assert_true("Policy Handbook" in history.attached_documents_json, "history attached documents JSON")
runner.run_test("SDK contract: ChatCompletionRequest serializes attached_document_ids", test_request_attached_document_ids)
runner.run_test("SDK contract: ChatCompletionRequest serializes local_attachments", test_request_local_attachments)
runner.run_test(
"SDK contract: ChatCompletionResponse parses attached document retrieval metadata",
test_response_retrieval_attached_document_metadata,
)
runner.run_test("SDK contract: AssistantToolPolicy settings round-trip", test_tool_policy_settings_round_trip)
runner.run_test("SDK contract: ExternalSearch status model and route", test_external_search_status_model_and_route)
runner.run_test("SDK contract: assistant tool-call trace routes", test_assistant_tool_call_trace_routes)
runner.run_test("SDK contract: async assistant tool-call trace routes", test_async_assistant_tool_call_trace_routes)
runner.run_test(
"SDK contract: ChatHistory parses attached document metadata",
test_chat_history_attached_document_metadata,
)
def test_local_sdk_contracts_pass_under_pytest() -> None:
runner = TestRunner()
run_sdk_contract_tests(runner)
failures = [r for r in runner.results if not r.passed]
assert len(runner.results) > 0
assert not failures, "; ".join(
"{}: {}".format(r.test_name, r.error_message) for r in failures
)
def test_runner_records_assertion_failures_under_pytest() -> None:
def fail() -> None:
raise AssertionError("expected failure")
runner = TestRunner()
result = runner.run_test("Runner: records assertion failures", fail)
assert result.passed is False
assert result.error_message == "expected failure"
# ---------------------------------------------------------------------------
# Test groups
# ---------------------------------------------------------------------------
def run_health_tests(runner: TestRunner, client: AssistantHubClient) -> None:
def test_health_check() -> None:
result = client.health_check()
assert_not_none(result, "HealthCheck result")
def test_whoami() -> None:
identity = client.whoami()
assert_not_none(identity, "WhoAmI result")
assert_true(isinstance(identity, dict), "WhoAmI should return a valid JSON object")
runner.run_test("Health: HealthCheck returns true", test_health_check)
runner.run_test("Health: WhoAmI returns authenticated identity", test_whoami)
def run_tenant_tests(runner: TestRunner, client: AssistantHubClient) -> None:
created_tenant_id: list[Optional[str]] = [None]
created_user_id: list[Optional[str]] = [None]
created_credential_id: list[Optional[str]] = [None]
suffix = unique_suffix()
def test_list_tenants() -> None:
result = client.list_tenants()
assert_not_none(result, "ListTenants result")
assert_not_none(result.objects, "ListTenants result.objects")
assert_gte(len(result.objects), 1, "ListTenants count")
def test_create_tenant() -> None:
tenant = TenantMetadata(name="test-tenant-" + suffix, active=True)
response = client.create_tenant(tenant)
assert_true(isinstance(response, dict), "CreateTenant should return a JSON object")
tenant_data = response.get("Tenant", {})
created_tenant_id[0] = tenant_data.get("Id")
assert_not_none(created_tenant_id[0], "Created tenant ID")
assert_starts_with(created_tenant_id[0], "ten_", "Created tenant ID prefix")
def test_get_tenant() -> None:
assert_not_none(created_tenant_id[0], "createdTenantId from previous test")
tenant = client.get_tenant(created_tenant_id[0])
assert_not_none(tenant, "GetTenant result")
assert_equal(created_tenant_id[0], tenant.id, "Tenant ID")
assert_equal("test-tenant-" + suffix, tenant.name, "Tenant Name")
def test_update_tenant() -> None:
assert_not_none(created_tenant_id[0], "createdTenantId from previous test")
tenant = TenantMetadata(name="test-tenant-updated-" + suffix, active=True)
updated = client.update_tenant(created_tenant_id[0], tenant)
assert_not_none(updated, "UpdateTenant result")
assert_equal("test-tenant-updated-" + suffix, updated.name, "Updated tenant name")
def test_list_users() -> None:
assert_not_none(created_tenant_id[0], "createdTenantId from previous test")
result = client.list_users(created_tenant_id[0])
assert_not_none(result, "ListUsers result")
assert_not_none(result.objects, "ListUsers result.objects")
def test_create_user() -> None:
assert_not_none(created_tenant_id[0], "createdTenantId from previous test")
user = UserMaster(
first_name="Test",
last_name="User",
email="testuser-" + suffix + "@example.com",
active=True,
)
created = client.create_user(created_tenant_id[0], user)
assert_not_none(created, "CreateUser result")
assert_not_none(created.id, "Created user ID")
assert_starts_with(created.id, "usr_", "Created user ID prefix")
created_user_id[0] = created.id
def test_create_credential() -> None:
assert_not_none(created_tenant_id[0], "createdTenantId from previous test")
credential = Credential(name="test-cred-" + suffix, active=True)
created = client.create_credential(created_tenant_id[0], credential)
assert_not_none(created, "CreateCredential result")
assert_not_none(created.id, "Created credential ID")
assert_starts_with(created.id, "cred_", "Created credential ID prefix")
created_credential_id[0] = created.id
def test_delete_credential() -> None:
assert_not_none(created_tenant_id[0], "createdTenantId from previous test")
assert_not_none(created_credential_id[0], "createdCredentialId from previous test")
client.delete_credential(created_tenant_id[0], created_credential_id[0])
def test_delete_user() -> None:
assert_not_none(created_tenant_id[0], "createdTenantId from previous test")
assert_not_none(created_user_id[0], "createdUserId from previous test")
client.delete_user(created_tenant_id[0], created_user_id[0])
def test_delete_tenant() -> None:
assert_not_none(created_tenant_id[0], "createdTenantId from previous test")
client.delete_tenant(created_tenant_id[0])
runner.run_test("Tenant: List tenants returns results", test_list_tenants)
runner.run_test("Tenant: Create tenant with unique name", test_create_tenant)
runner.run_test("Tenant: Get tenant by ID", test_get_tenant)
runner.run_test("Tenant: Update tenant name", test_update_tenant)
runner.run_test("Tenant: List users in tenant", test_list_users)
runner.run_test("Tenant: Create user in tenant", test_create_user)
runner.run_test("Tenant: Create credential in tenant", test_create_credential)
runner.run_test("Tenant: Delete credential", test_delete_credential)
runner.run_test("Tenant: Delete user", test_delete_user)
runner.run_test("Tenant: Delete tenant", test_delete_tenant)
def run_assistant_tests(runner: TestRunner, client: AssistantHubClient) -> None:
created_assistant_id: list[Optional[str]] = [None]
suffix = unique_suffix()
def test_create() -> None:
assistant = Assistant(
name="test-assistant-" + suffix,
description="Test assistant created by SDK tests",
)
created = client.create_assistant(assistant)
assert_not_none(created, "CreateAssistant result")
assert_not_none(created.id, "Created assistant ID")
assert_starts_with(created.id, "asst_", "Created assistant ID prefix")
assert_equal("test-assistant-" + suffix, created.name, "Created assistant name")
created_assistant_id[0] = created.id
def test_list() -> None:
assert_not_none(created_assistant_id[0], "createdAssistantId from previous test")
result = client.list_assistants()
assert_not_none(result, "ListAssistants result")
assert_not_none(result.objects, "ListAssistants result.objects")
found = any(a.id == created_assistant_id[0] for a in result.objects)
assert_true(found, "Created assistant should appear in list")
def test_get() -> None:
assert_not_none(created_assistant_id[0], "createdAssistantId from previous test")
assistant = client.get_assistant(created_assistant_id[0])