-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest_llm_provider.py
More file actions
2461 lines (2093 loc) · 90.6 KB
/
Copy pathtest_llm_provider.py
File metadata and controls
2461 lines (2093 loc) · 90.6 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
"""Focused tests for the llm-provider module.
The conformance suite (``tests/conformance/test_llm_provider.py``)
covers the spec's behavioral surface end-to-end against the
fixtures. These unit tests fill gaps the conformance suite doesn't
exercise directly: per-role construction errors that fixtures only
hit through the boundary, the tool-call-id verbatim guarantee,
the canonical category-string contract, and the
``classify_http_error`` mapping table.
"""
from __future__ import annotations
import json
from collections.abc import Callable
from contextvars import Token
from typing import Any, cast
import httpx
import pytest
from pydantic import ValidationError
from openarmature.graph.events import LlmCompletionEvent, LlmFailedEvent, NodeEvent
from openarmature.graph.middleware import RetryConfig, deterministic_backoff
from openarmature.graph.observer import ObserverEvent
from openarmature.llm import (
PROVIDER_AUTHENTICATION,
PROVIDER_INVALID_MODEL,
PROVIDER_INVALID_REQUEST,
PROVIDER_INVALID_RESPONSE,
PROVIDER_MODEL_NOT_LOADED,
PROVIDER_RATE_LIMIT,
PROVIDER_UNAVAILABLE,
TRANSIENT_CATEGORIES,
AssistantMessage,
LlmProviderError,
OpenAIProvider,
ProviderAuthentication,
ProviderInvalidModel,
ProviderInvalidRequest,
ProviderInvalidResponse,
ProviderModelNotLoaded,
ProviderRateLimit,
ProviderUnavailable,
ProviderUnsupportedContentBlock,
StructuredOutputInvalid,
SystemMessage,
Tool,
ToolCall,
ToolMessage,
Usage,
UserMessage,
classify_http_error,
validate_message_list,
validate_tools,
)
from openarmature.observability.correlation import (
_set_active_dispatch,
_set_attempt_index,
_set_branch_name,
_set_correlation_id,
_set_fan_out_index,
_set_invocation_id,
_set_namespace_prefix,
)
from openarmature.observability.metadata import set_invocation_metadata
_DispatchToken = Token[Callable[[ObserverEvent], None] | None]
# ---------------------------------------------------------------------------
# Per-role message construction (Pydantic-on-Message layer)
# ---------------------------------------------------------------------------
def test_system_message_empty_content_rejected() -> None:
with pytest.raises(ValidationError):
SystemMessage(content="")
def test_user_message_empty_content_rejected() -> None:
with pytest.raises(ValidationError):
UserMessage(content="")
def test_assistant_empty_content_without_tool_calls_rejected() -> None:
with pytest.raises(ValidationError):
AssistantMessage(content="")
def test_assistant_empty_content_with_tool_calls_ok() -> None:
# Content MAY be empty when tool_calls is non-empty per spec §3.
msg = AssistantMessage(
content="",
tool_calls=[ToolCall(id="call_1", name="echo", arguments={"text": "hi"})],
)
assert msg.content == ""
assert msg.tool_calls is not None
assert msg.tool_calls[0].id == "call_1"
def test_tool_message_construction_does_not_check_id_match() -> None:
# Per spec §3 "Validation timing": the per-message layer does NOT
# check whether tool_call_id corresponds to an earlier assistant
# ToolCall.id — that's the boundary check's job. So a ToolMessage
# with a fabricated id is constructible on its own.
msg = ToolMessage(content="result", tool_call_id="never-issued")
assert msg.tool_call_id == "never-issued"
# ---------------------------------------------------------------------------
# Tool-call id verbatim preservation (spec §3 MUST NOT rewrite)
# ---------------------------------------------------------------------------
@pytest.mark.parametrize(
"raw_id",
[
"call_abc123",
"call_3f9c2c12-3a44-4f6a-9d2e-fbb12c0e2d77", # uuid w/ hyphens
"bifrost_abc-def", # vendor-prefixed
"TOOL/CALL/01", # path-shaped
"id with spaces", # whitespace tolerated
"", # empty string — opaque correlator, no normalization
],
)
def test_tool_call_id_preserved_verbatim(raw_id: str) -> None:
tc = ToolCall(id=raw_id, name="f", arguments={})
assert tc.id == raw_id
# And through Pydantic dump/load round trip — no normalizer should
# change the id.
dumped = tc.model_dump()
assert dumped["id"] == raw_id
rebuilt = ToolCall.model_validate(dumped)
assert rebuilt.id == raw_id
# ---------------------------------------------------------------------------
# List-level boundary validation (validate_message_list)
# ---------------------------------------------------------------------------
def test_validate_empty_list_rejected() -> None:
with pytest.raises(ProviderInvalidRequest, match="non-empty"):
validate_message_list([])
def test_validate_first_message_must_be_system_or_user() -> None:
with pytest.raises(ProviderInvalidRequest, match="first message MUST"):
validate_message_list([AssistantMessage(content="hi")])
def test_validate_system_message_only_at_first_position() -> None:
msgs = [
UserMessage(content="hi"),
SystemMessage(content="surprise"),
]
with pytest.raises(ProviderInvalidRequest, match="system message MUST be the first"):
validate_message_list(msgs)
def test_validate_last_message_must_be_user_or_tool() -> None:
msgs = [
UserMessage(content="hi"),
AssistantMessage(content="hello"),
]
with pytest.raises(ProviderInvalidRequest, match="last message"):
validate_message_list(msgs)
def test_validate_tool_message_id_must_match_earlier_assistant() -> None:
msgs = [
UserMessage(content="run echo"),
AssistantMessage(
content="",
tool_calls=[ToolCall(id="call_real", name="echo", arguments={})],
),
ToolMessage(content="ok", tool_call_id="call_FAKE"),
]
with pytest.raises(ProviderInvalidRequest, match="does not match any earlier"):
validate_message_list(msgs)
def test_validate_tool_message_id_matches_real_call_passes() -> None:
msgs = [
UserMessage(content="run echo"),
AssistantMessage(
content="",
tool_calls=[ToolCall(id="call_real", name="echo", arguments={})],
),
ToolMessage(content="ok", tool_call_id="call_real"),
]
validate_message_list(msgs) # no raise
def test_validate_minimal_user_only_passes() -> None:
validate_message_list([UserMessage(content="hi")])
def test_validate_system_then_user_passes() -> None:
validate_message_list([SystemMessage(content="be helpful"), UserMessage(content="hi")])
# ---------------------------------------------------------------------------
# validate_tools — duplicate name rejection
# ---------------------------------------------------------------------------
def test_validate_tools_none_or_empty() -> None:
validate_tools(None)
validate_tools([])
def test_validate_tools_unique_names_pass() -> None:
validate_tools(
[
Tool(name="a", description="", parameters={}),
Tool(name="b", description="", parameters={}),
]
)
def test_validate_tools_duplicate_names_rejected() -> None:
with pytest.raises(ProviderInvalidRequest, match="duplicate tool name"):
validate_tools(
[
Tool(name="echo", description="", parameters={}),
Tool(name="echo", description="", parameters={}),
]
)
# ---------------------------------------------------------------------------
# OpenAIProvider base_url validation
# ---------------------------------------------------------------------------
def test_openai_provider_rejects_v1_suffix() -> None:
with pytest.raises(ValueError, match=r"base_url must not end with '/v1'"):
OpenAIProvider(base_url="http://localhost:8090/v1", model="m", api_key="k")
def test_openai_provider_rejects_v1_suffix_with_trailing_slash() -> None:
with pytest.raises(ValueError, match=r"base_url must not end with '/v1'"):
OpenAIProvider(base_url="http://localhost:8090/v1/", model="m", api_key="k")
def test_openai_provider_rejects_openai_cloud_with_v1() -> None:
# The motivating real-world case: api.openai.com/v1 is in the
# OpenAI docs as the API endpoint, but for OpenAIProvider's
# base_url the /v1 must be omitted.
with pytest.raises(ValueError, match=r"base_url must not end with '/v1'"):
OpenAIProvider(base_url="https://api.openai.com/v1", model="gpt-4", api_key="k")
def test_openai_provider_accepts_host_root() -> None:
provider = OpenAIProvider(base_url="https://api.openai.com", model="gpt-4", api_key="k")
assert provider.base_url == "https://api.openai.com"
def test_openai_provider_accepts_host_root_with_trailing_slash() -> None:
provider = OpenAIProvider(base_url="http://localhost:8090/", model="m", api_key="k")
assert provider.base_url == "http://localhost:8090"
def test_openai_provider_accepts_non_v1_path() -> None:
# Proxy prefixes (Cloudflare AI Gateway, internal reverse proxies)
# are intentional and left alone.
provider = OpenAIProvider(
base_url="https://gateway.example.com/openai-proxy",
model="m",
api_key="k",
)
assert provider.base_url == "https://gateway.example.com/openai-proxy"
def test_openai_provider_accepts_v1_in_middle_of_path() -> None:
# Only a trailing /v1 is rejected — proxies that include /v1
# somewhere mid-path are intentional.
provider = OpenAIProvider(
base_url="https://gateway.example.com/v1/openai-proxy",
model="m",
api_key="k",
)
assert provider.base_url == "https://gateway.example.com/v1/openai-proxy"
def test_openai_provider_rejects_v1_with_query_string() -> None:
# The trailing slash on the path is followed by a query string,
# so a URL-level rstrip("/") doesn't normalize it. The parsed
# path's own trailing slash MUST be stripped before the suffix
# check or this case slips through.
with pytest.raises(ValueError, match=r"base_url must not end with '/v1'"):
OpenAIProvider(base_url="https://host/v1/?token=abc", model="m", api_key="k")
def test_openai_provider_rejects_v1_with_fragment() -> None:
# Same shape as the query-string case but with a URL fragment.
with pytest.raises(ValueError, match=r"base_url must not end with '/v1'"):
OpenAIProvider(base_url="https://host/v1/#frag", model="m", api_key="k")
# ---------------------------------------------------------------------------
# Error categories — canonical string contract + __cause__ preservation
# ---------------------------------------------------------------------------
@pytest.mark.parametrize(
("cls", "expected_category"),
[
(ProviderAuthentication, PROVIDER_AUTHENTICATION),
(ProviderUnavailable, PROVIDER_UNAVAILABLE),
(ProviderInvalidModel, PROVIDER_INVALID_MODEL),
(ProviderModelNotLoaded, PROVIDER_MODEL_NOT_LOADED),
(ProviderRateLimit, PROVIDER_RATE_LIMIT),
(ProviderInvalidResponse, PROVIDER_INVALID_RESPONSE),
(ProviderInvalidRequest, PROVIDER_INVALID_REQUEST),
],
)
def test_error_category_matches_canonical_string(cls: type[LlmProviderError], expected_category: str) -> None:
err = cls("boom")
assert err.category == expected_category
def test_provider_rate_limit_retry_after_accessor() -> None:
err = ProviderRateLimit("429", retry_after=30.0)
assert err.retry_after == 30.0
bare = ProviderRateLimit("429")
assert bare.retry_after is None
def test_error_cause_preserved() -> None:
underlying = RuntimeError("wire failure")
try:
try:
raise underlying
except RuntimeError as exc:
raise ProviderUnavailable("unreachable") from exc
except ProviderUnavailable as out:
assert out.__cause__ is underlying
# ---------------------------------------------------------------------------
# TRANSIENT_CATEGORIES — must match exactly the spec's transient set
# ---------------------------------------------------------------------------
def test_transient_categories_exact_set() -> None:
assert TRANSIENT_CATEGORIES == frozenset(
{
PROVIDER_RATE_LIMIT,
PROVIDER_UNAVAILABLE,
PROVIDER_MODEL_NOT_LOADED,
}
)
def test_transient_categories_excludes_terminal_categories() -> None:
for terminal in (
PROVIDER_AUTHENTICATION,
PROVIDER_INVALID_MODEL,
PROVIDER_INVALID_REQUEST,
PROVIDER_INVALID_RESPONSE,
):
assert terminal not in TRANSIENT_CATEGORIES
# ---------------------------------------------------------------------------
# classify_http_error — wire-mapping table (spec §8.1.3)
# ---------------------------------------------------------------------------
def _wire_response(
status: int, body: dict[str, object] | None = None, headers: dict[str, str] | None = None
) -> httpx.Response:
"""Build an httpx.Response with the given status/body/headers."""
return httpx.Response(
status,
json=body if body is not None else {},
headers=headers or {},
)
def test_classify_401_to_authentication() -> None:
err = classify_http_error(_wire_response(401))
assert isinstance(err, ProviderAuthentication)
def test_classify_403_to_authentication() -> None:
err = classify_http_error(_wire_response(403))
assert isinstance(err, ProviderAuthentication)
def test_classify_400_to_invalid_request() -> None:
err = classify_http_error(_wire_response(400))
assert isinstance(err, ProviderInvalidRequest)
def test_classify_404_with_model_not_found_to_invalid_model() -> None:
err = classify_http_error(
_wire_response(
404,
{"error": {"code": "model_not_found", "message": "no such model"}},
)
)
assert isinstance(err, ProviderInvalidModel)
def test_classify_404_without_model_marker_to_unavailable() -> None:
err = classify_http_error(_wire_response(404))
assert isinstance(err, ProviderUnavailable)
def test_classify_429_with_retry_after_to_rate_limit() -> None:
err = classify_http_error(_wire_response(429, {"error": {"message": "slow down"}}, {"Retry-After": "30"}))
assert isinstance(err, ProviderRateLimit)
assert err.retry_after == 30.0
def test_classify_429_without_retry_after_to_rate_limit_no_value() -> None:
err = classify_http_error(_wire_response(429))
assert isinstance(err, ProviderRateLimit)
assert err.retry_after is None
def test_classify_503_with_model_not_loaded_to_model_not_loaded() -> None:
err = classify_http_error(
_wire_response(
503,
{"error": {"type": "model_not_loaded", "message": "loading"}},
)
)
assert isinstance(err, ProviderModelNotLoaded)
def test_classify_503_without_marker_to_unavailable() -> None:
err = classify_http_error(_wire_response(503))
assert isinstance(err, ProviderUnavailable)
def test_classify_500_to_unavailable() -> None:
err = classify_http_error(_wire_response(500))
assert isinstance(err, ProviderUnavailable)
def test_classify_502_to_unavailable() -> None:
err = classify_http_error(_wire_response(502))
assert isinstance(err, ProviderUnavailable)
def test_classify_504_to_unavailable() -> None:
err = classify_http_error(_wire_response(504))
assert isinstance(err, ProviderUnavailable)
# ---------------------------------------------------------------------------
# complete() input non-mutation (spec §5: "messages MUST NOT be mutated")
# ---------------------------------------------------------------------------
async def test_complete_does_not_mutate_messages_or_tools() -> None:
"""The input messages/tools list MUST NOT be mutated by complete().
Snapshot the inputs (deep-copy via Pydantic round-trip), run a
happy-path call, and assert the input objects remain equal to
their pre-call snapshots after the call returns.
"""
def _ok(_req: httpx.Request) -> httpx.Response:
return httpx.Response(
200,
json={
"id": "x",
"object": "chat.completion",
"created": 0,
"model": "m",
"choices": [
{
"index": 0,
"message": {"role": "assistant", "content": "ok"},
"finish_reason": "stop",
}
],
"usage": {"prompt_tokens": 1, "completion_tokens": 1, "total_tokens": 2},
},
)
provider = OpenAIProvider(
base_url="http://test",
model="m",
api_key="k",
transport=httpx.MockTransport(_ok),
)
try:
messages = [
SystemMessage(content="be helpful"),
UserMessage(content="hello"),
]
tools = [Tool(name="echo", description="", parameters={})]
before_messages = [m.model_copy(deep=True) for m in messages]
before_tools = [t.model_copy(deep=True) for t in tools]
await provider.complete(messages, tools)
# Same instances; same field values; lists not reordered or resized.
assert len(messages) == len(before_messages)
assert len(tools) == len(before_tools)
for actual, expected in zip(messages, before_messages, strict=True):
assert actual == expected
for actual_t, expected_t in zip(tools, before_tools, strict=True):
assert actual_t == expected_t
finally:
await provider.aclose()
# ---------------------------------------------------------------------------
# Usage non-negative constraint (spec §6: "non-negative integer or None")
# ---------------------------------------------------------------------------
def test_usage_negative_token_count_rejected_at_construction() -> None:
with pytest.raises(ValidationError):
Usage(prompt_tokens=-1, completion_tokens=0, total_tokens=0)
async def test_complete_negative_usage_surfaces_as_invalid_response() -> None:
"""A wire response carrying a negative token count MUST surface as
``provider_invalid_response`` rather than silently passing through —
spec §6 token counts are non-negative integers."""
def _bad(_req: httpx.Request) -> httpx.Response:
return httpx.Response(
200,
json={
"id": "x",
"object": "chat.completion",
"created": 0,
"model": "m",
"choices": [
{
"index": 0,
"message": {"role": "assistant", "content": "ok"},
"finish_reason": "stop",
}
],
"usage": {"prompt_tokens": -5, "completion_tokens": 1, "total_tokens": 1},
},
)
provider = OpenAIProvider(
base_url="http://test",
model="m",
api_key="k",
transport=httpx.MockTransport(_bad),
)
try:
with pytest.raises(ProviderInvalidResponse, match="invalid usage record"):
await provider.complete([UserMessage(content="hi")])
finally:
await provider.aclose()
# ---------------------------------------------------------------------------
# Usage cache-stat fields (proposal 0047 — llm-provider §6 extension)
# ---------------------------------------------------------------------------
def test_usage_cache_fields_default_to_none() -> None:
# Backwards-compat: existing Usage constructions that don't pass
# cache fields produce instances with cached_tokens = None and
# cache_creation_tokens = None (the "not reported" state, distinct
# from a "reported zero" value of 0).
usage = Usage(prompt_tokens=1, completion_tokens=2, total_tokens=3)
assert usage.cached_tokens is None
assert usage.cache_creation_tokens is None
def test_usage_negative_cached_tokens_rejected_at_construction() -> None:
with pytest.raises(ValidationError):
Usage(prompt_tokens=0, completion_tokens=0, total_tokens=0, cached_tokens=-1)
def test_usage_negative_cache_creation_tokens_rejected_at_construction() -> None:
with pytest.raises(ValidationError):
Usage(prompt_tokens=0, completion_tokens=0, total_tokens=0, cache_creation_tokens=-1)
def _make_openai_response_with_usage(usage_body: dict[str, object]) -> httpx.MockTransport:
"""Build a MockTransport returning a minimal Chat Completions
response with the given ``usage`` body. Helper for the cache-stat
end-to-end tests below.
"""
def _handler(_req: httpx.Request) -> httpx.Response:
return httpx.Response(
200,
json={
"id": "x",
"object": "chat.completion",
"created": 0,
"model": "m",
"choices": [
{
"index": 0,
"message": {"role": "assistant", "content": "ok"},
"finish_reason": "stop",
}
],
"usage": usage_body,
},
)
return httpx.MockTransport(_handler)
async def test_complete_sources_cached_tokens_from_nested_prompt_tokens_details() -> None:
# Cache-hit reported with a positive value. Spec §8.1.2: the
# OpenAI-compat mapping sources cached_tokens from
# usage.prompt_tokens_details.cached_tokens.
transport = _make_openai_response_with_usage(
{
"prompt_tokens": 100,
"completion_tokens": 20,
"total_tokens": 120,
"prompt_tokens_details": {"cached_tokens": 75},
}
)
provider = OpenAIProvider(base_url="http://test", model="m", api_key="k", transport=transport)
try:
response = await provider.complete([UserMessage(content="hi")])
assert response.usage.cached_tokens == 75
# cache_creation_tokens is not sourced by the OpenAI-compat
# mapping per spec §8.1.2.
assert response.usage.cache_creation_tokens is None
finally:
await provider.aclose()
async def test_complete_reports_zero_cached_tokens_distinct_from_absent() -> None:
# The spec mandates the absent-vs-reported-zero distinction:
# absent (None) means the provider didn't report; 0 means the
# provider reported zero hits. Locks down the distinction.
transport = _make_openai_response_with_usage(
{
"prompt_tokens": 100,
"completion_tokens": 20,
"total_tokens": 120,
"prompt_tokens_details": {"cached_tokens": 0},
}
)
provider = OpenAIProvider(base_url="http://test", model="m", api_key="k", transport=transport)
try:
response = await provider.complete([UserMessage(content="hi")])
assert response.usage.cached_tokens == 0
finally:
await provider.aclose()
async def test_complete_cached_tokens_absent_when_prompt_tokens_details_missing() -> None:
# Common pre-cache path: vLLM without --enable-prompt-tokens-details,
# OpenAI responses pre-cache-support, etc. No prompt_tokens_details
# nesting at all → cached_tokens stays None.
transport = _make_openai_response_with_usage(
{"prompt_tokens": 100, "completion_tokens": 20, "total_tokens": 120}
)
provider = OpenAIProvider(base_url="http://test", model="m", api_key="k", transport=transport)
try:
response = await provider.complete([UserMessage(content="hi")])
assert response.usage.cached_tokens is None
finally:
await provider.aclose()
async def test_complete_cached_tokens_absent_when_nested_key_missing() -> None:
# Defensive: prompt_tokens_details dict exists (provider may report
# other details there, e.g., audio_tokens) but cached_tokens is
# absent within it. Sourcing path stays defensive — no KeyError,
# cached_tokens stays None.
transport = _make_openai_response_with_usage(
{
"prompt_tokens": 100,
"completion_tokens": 20,
"total_tokens": 120,
"prompt_tokens_details": {"audio_tokens": 0},
}
)
provider = OpenAIProvider(base_url="http://test", model="m", api_key="k", transport=transport)
try:
response = await provider.complete([UserMessage(content="hi")])
assert response.usage.cached_tokens is None
finally:
await provider.aclose()
async def test_complete_excludes_unset_cached_tokens_when_wire_did_not_report() -> None:
# When the wire response doesn't carry prompt_tokens_details (or
# carries it without a cached_tokens key), the parser leaves the
# Pydantic field unset. model_dump(exclude_unset=True) then omits
# cached_tokens entirely, giving downstream consumers a clean
# wire-shape projection. Attribute access still returns None per
# the spec's absent-vs-reported distinction.
transport = _make_openai_response_with_usage(
{"prompt_tokens": 100, "completion_tokens": 20, "total_tokens": 120}
)
provider = OpenAIProvider(base_url="http://test", model="m", api_key="k", transport=transport)
try:
response = await provider.complete([UserMessage(content="hi")])
assert response.usage.cached_tokens is None
dumped = response.usage.model_dump(exclude_unset=True)
assert "cached_tokens" not in dumped
# Conversely, when the wire DID report (covered separately
# above), the field IS set and appears in the projection.
finally:
await provider.aclose()
async def test_complete_includes_cached_tokens_in_exclude_unset_dump_when_wire_reported() -> None:
# Companion to the no-wire-report case above: when the wire reports
# prompt_tokens_details.cached_tokens, the field IS marked set and
# appears in model_dump(exclude_unset=True). Locks down the
# bidirectional projection for downstream consumers.
transport = _make_openai_response_with_usage(
{
"prompt_tokens": 100,
"completion_tokens": 20,
"total_tokens": 120,
"prompt_tokens_details": {"cached_tokens": 75},
}
)
provider = OpenAIProvider(base_url="http://test", model="m", api_key="k", transport=transport)
try:
response = await provider.complete([UserMessage(content="hi")])
dumped = response.usage.model_dump(exclude_unset=True)
assert dumped.get("cached_tokens") == 75
finally:
await provider.aclose()
async def test_complete_cached_tokens_absent_when_prompt_tokens_details_not_a_dict() -> None:
# Defensive against malformed wire responses: if prompt_tokens_details
# is a non-dict scalar / string / list, the isinstance guard in the
# parser treats it as absent rather than crashing. cached_tokens
# stays None.
transport = _make_openai_response_with_usage(
{
"prompt_tokens": 100,
"completion_tokens": 20,
"total_tokens": 120,
"prompt_tokens_details": "unexpected_shape",
}
)
provider = OpenAIProvider(base_url="http://test", model="m", api_key="k", transport=transport)
try:
response = await provider.complete([UserMessage(content="hi")])
assert response.usage.cached_tokens is None
finally:
await provider.aclose()
async def test_complete_negative_cached_tokens_surfaces_as_invalid_response() -> None:
# Same invariant the existing test pins for prompt_tokens — a
# wire response carrying a negative cache count MUST surface as
# ``provider_invalid_response`` rather than silently passing through.
transport = _make_openai_response_with_usage(
{
"prompt_tokens": 100,
"completion_tokens": 20,
"total_tokens": 120,
"prompt_tokens_details": {"cached_tokens": -1},
}
)
provider = OpenAIProvider(base_url="http://test", model="m", api_key="k", transport=transport)
try:
with pytest.raises(ProviderInvalidResponse, match="invalid usage record"):
await provider.complete([UserMessage(content="hi")])
finally:
await provider.aclose()
async def test_complete_populates_cached_tokens_on_typed_event() -> None:
# Proposal 0047: Response.usage.cached_tokens MUST flow onto the
# typed LlmCompletionEvent's usage record so observers driving
# §5.5.3.1 cache attribute emission have the cache stat available.
# This locks the field at the provider-event boundary; the
# conformance fixture 040 covers the end-to-end OTel span
# attribute path.
events, token = _collecting_dispatch()
transport = _make_openai_response_with_usage(
{
"prompt_tokens": 100,
"completion_tokens": 5,
"total_tokens": 105,
"prompt_tokens_details": {"cached_tokens": 42},
}
)
provider = OpenAIProvider(base_url="http://test", model="m", api_key="k", transport=transport)
try:
await provider.complete([UserMessage(content="hi")])
finally:
await provider.aclose()
_release_dispatch(token)
typed = next(e for e in events if isinstance(e, LlmCompletionEvent))
assert typed.usage is not None
assert typed.usage.cached_tokens == 42
# The OpenAI-compat mapping leaves cache_creation_tokens absent
# per spec §8.1.2; verify the field stays None on the typed event.
assert typed.usage.cache_creation_tokens is None
async def test_complete_leaves_cached_tokens_none_when_provider_silent() -> None:
# Companion to the populated case: when the wire response omits
# prompt_tokens_details, Response.usage.cached_tokens stays None
# and the typed event's Usage record reflects that.
events, token = _collecting_dispatch()
transport = _make_openai_response_with_usage(
{"prompt_tokens": 100, "completion_tokens": 5, "total_tokens": 105}
)
provider = OpenAIProvider(base_url="http://test", model="m", api_key="k", transport=transport)
try:
await provider.complete([UserMessage(content="hi")])
finally:
await provider.aclose()
_release_dispatch(token)
typed = next(e for e in events if isinstance(e, LlmCompletionEvent))
assert typed.usage is not None
assert typed.usage.cached_tokens is None
assert typed.usage.cache_creation_tokens is None
# RuntimeConfig.from_partial — Python ergonomic introduced alongside
# proposal 0032. Wire-layer null-skip already drops Nones; this just
# lets callers splat a partial dict without filtering at the call site.
def test_runtime_config_from_partial_drops_nones() -> None:
from openarmature.llm import RuntimeConfig
config = RuntimeConfig.from_partial(temperature=0.7, max_tokens=None, top_p=0.9, seed=None)
assert config.temperature == 0.7
assert config.top_p == 0.9
# max_tokens and seed default to None on a base RuntimeConfig, so
# `is None` alone doesn't prove the drop. model_fields_set carries
# only explicitly-set fields, so its absence proves from_partial
# filtered the None kwargs before __init__ ran.
assert "max_tokens" not in config.model_fields_set
assert "seed" not in config.model_fields_set
assert config.max_tokens is None
assert config.seed is None
def test_runtime_config_from_partial_forwards_extras() -> None:
from openarmature.llm import RuntimeConfig
config = RuntimeConfig.from_partial(temperature=0.5, repetition_penalty=1.05, top_k=None)
assert config.temperature == 0.5
assert (config.model_extra or {}) == {"repetition_penalty": 1.05}
def test_runtime_config_from_partial_empty() -> None:
from openarmature.llm import RuntimeConfig
config = RuntimeConfig.from_partial()
assert config.temperature is None
assert config.frequency_penalty is None
assert config.stop_sequences is None
def test_readiness_probe_unknown_mode_rejected_at_construction() -> None:
# Literal type is a static hint, not a runtime guard. Unknown modes
# would otherwise silently no-op both dispatch branches in ready()
# and report ready, so reject at construction.
with pytest.raises(ValueError, match="readiness_probe must be one of"):
OpenAIProvider(
base_url="http://test",
model="m",
api_key="k",
readiness_probe="bogus", # pyright: ignore[reportArgumentType]
)
# ---------------------------------------------------------------------------
# ready() readiness_probe modes
# ---------------------------------------------------------------------------
# Verifies the v0.12.0 default-flip: chat_completions is the strict probe
# (actually exercises inference), models is the opt-in catalog-only probe,
# both runs catalog then chat. Conformance fixture 007 owns the catalog-only
# semantics — these tests cover the new wire paths and the dispatch.
async def test_ready_chat_completions_200_passes() -> None:
def _ok(req: httpx.Request) -> httpx.Response:
assert req.url.path == "/v1/chat/completions"
return httpx.Response(
200,
json={
"id": "x",
"object": "chat.completion",
"created": 0,
"model": "m",
"choices": [
{
"index": 0,
"message": {"role": "assistant", "content": "."},
"finish_reason": "length",
}
],
"usage": {"prompt_tokens": 1, "completion_tokens": 1, "total_tokens": 2},
},
)
provider = OpenAIProvider(
base_url="http://test",
model="m",
api_key="k",
transport=httpx.MockTransport(_ok),
)
try:
await provider.ready()
finally:
await provider.aclose()
async def test_ready_chat_completions_405_surfaces_unavailable() -> None:
# The Bifrost-style proxy case: the catalog endpoint may answer 200
# (which the older default probe accepted), but POST /v1/chat/completions
# returns 405 because the proxy doesn't actually serve completions.
# classify_http_error routes 405 through ProviderUnavailable.
def _405(req: httpx.Request) -> httpx.Response:
assert req.url.path == "/v1/chat/completions"
return httpx.Response(405, json={"error": {"message": "method not allowed"}})
provider = OpenAIProvider(
base_url="http://test",
model="m",
api_key="k",
transport=httpx.MockTransport(_405),
)
try:
with pytest.raises(ProviderUnavailable):
await provider.ready()
finally:
await provider.aclose()
async def test_ready_chat_completions_401_surfaces_authentication() -> None:
def _401(_req: httpx.Request) -> httpx.Response:
return httpx.Response(401, json={"error": {"message": "Invalid API key"}})
provider = OpenAIProvider(
base_url="http://test",
model="m",
api_key="k",
transport=httpx.MockTransport(_401),
)
try:
with pytest.raises(ProviderAuthentication):
await provider.ready()
finally:
await provider.aclose()
async def test_ready_chat_completions_404_model_not_found_surfaces_invalid_model() -> None:
def _404(_req: httpx.Request) -> httpx.Response:
return httpx.Response(
404,
json={"error": {"code": "model_not_found", "message": "no such model 'm'"}},
)
provider = OpenAIProvider(
base_url="http://test",
model="m",
api_key="k",
transport=httpx.MockTransport(_404),
)
try:
with pytest.raises(ProviderInvalidModel):
await provider.ready()
finally:
await provider.aclose()
async def test_ready_both_runs_catalog_then_chat() -> None:
# The both-mode contract: catalog probe first (so catalog-only failures
# short-circuit before the billable chat call), then chat probe. This
# test verifies both endpoints get hit in order on the happy path.
seen: list[str] = []
def _handler(req: httpx.Request) -> httpx.Response:
seen.append(req.url.path)
if req.url.path == "/v1/models":
return httpx.Response(
200,
json={"object": "list", "data": [{"id": "m", "object": "model"}]},
)
return httpx.Response(
200,
json={
"id": "x",
"object": "chat.completion",