-
Notifications
You must be signed in to change notification settings - Fork 23.4k
Expand file tree
/
Copy pathtest_chat_models.py
More file actions
3194 lines (2836 loc) · 126 KB
/
Copy pathtest_chat_models.py
File metadata and controls
3194 lines (2836 loc) · 126 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
"""Unit tests for `ChatOpenRouter` chat model."""
from __future__ import annotations
import warnings
from typing import Any, Literal
from unittest.mock import AsyncMock, MagicMock, patch
import pytest
from langchain_core.load import dumpd, dumps, load
from langchain_core.messages import (
AIMessage,
AIMessageChunk,
ChatMessage,
ChatMessageChunk,
HumanMessage,
HumanMessageChunk,
SystemMessage,
SystemMessageChunk,
ToolMessage,
)
from langchain_core.runnables import RunnableBinding
from pydantic import BaseModel, Field, SecretStr
from langchain_openrouter.chat_models import (
ChatOpenRouter,
_convert_chunk_to_message_chunk,
_convert_dict_to_message,
_convert_file_block_to_openrouter,
_convert_message_to_dict,
_convert_video_block_to_openrouter,
_create_usage_metadata,
_format_message_content,
_has_file_content_blocks,
_wrap_messages_for_sdk,
)
MODEL_NAME = "openai/gpt-4o-mini"
def _make_model(**kwargs: Any) -> ChatOpenRouter:
"""Create a `ChatOpenRouter` with sane defaults for unit tests."""
defaults: dict[str, Any] = {"model": MODEL_NAME, "api_key": SecretStr("test-key")}
defaults.update(kwargs)
return ChatOpenRouter(**defaults)
# ---------------------------------------------------------------------------
# Pydantic schemas used across multiple test classes
# ---------------------------------------------------------------------------
class GetWeather(BaseModel):
"""Get the current weather in a given location."""
location: str = Field(description="The city and state")
class GenerateUsername(BaseModel):
"""Generate a username from a full name."""
name: str = Field(description="The full name")
hair_color: str = Field(description="The hair color")
# ---------------------------------------------------------------------------
# Mock helpers for SDK responses
# ---------------------------------------------------------------------------
_SIMPLE_RESPONSE_DICT: dict[str, Any] = {
"id": "gen-abc123",
"choices": [
{
"message": {"role": "assistant", "content": "Hello!"},
"finish_reason": "stop",
"index": 0,
}
],
"usage": {
"prompt_tokens": 10,
"completion_tokens": 5,
"total_tokens": 15,
},
"model": MODEL_NAME,
"object": "chat.completion",
"created": 1700000000.0,
}
_TOOL_RESPONSE_DICT: dict[str, Any] = {
"id": "gen-tool123",
"choices": [
{
"message": {
"role": "assistant",
"content": None,
"tool_calls": [
{
"id": "call_1",
"type": "function",
"function": {
"name": "GetWeather",
"arguments": '{"location": "San Francisco"}',
},
}
],
},
"finish_reason": "tool_calls",
"index": 0,
}
],
"usage": {"prompt_tokens": 20, "completion_tokens": 10, "total_tokens": 30},
"model": MODEL_NAME,
"object": "chat.completion",
"created": 1700000000.0,
}
_STREAM_CHUNKS: list[dict[str, Any]] = [
{
"choices": [{"delta": {"role": "assistant", "content": ""}, "index": 0}],
"model": MODEL_NAME,
"object": "chat.completion.chunk",
"created": 1700000000.0,
"id": "gen-stream1",
},
{
"choices": [{"delta": {"content": "Hello"}, "index": 0}],
"model": MODEL_NAME,
"object": "chat.completion.chunk",
"created": 1700000000.0,
"id": "gen-stream1",
},
{
"choices": [{"delta": {"content": " world"}, "index": 0}],
"model": MODEL_NAME,
"object": "chat.completion.chunk",
"created": 1700000000.0,
"id": "gen-stream1",
},
{
"choices": [{"delta": {}, "finish_reason": "stop", "index": 0}],
"usage": {"prompt_tokens": 5, "completion_tokens": 2, "total_tokens": 7},
"model": MODEL_NAME,
"object": "chat.completion.chunk",
"created": 1700000000.0,
"id": "gen-stream1",
},
]
def _make_sdk_response(response_dict: dict[str, Any]) -> MagicMock:
"""Build a MagicMock that behaves like an SDK ChatResponse."""
mock = MagicMock()
mock.model_dump.return_value = response_dict
return mock
class _MockSyncStream:
"""Synchronous iterator that mimics the SDK EventStream."""
def __init__(self, chunks: list[dict[str, Any]]) -> None:
self._chunks = chunks
def __iter__(self) -> _MockSyncStream:
return self
def __next__(self) -> MagicMock:
if not self._chunks:
raise StopIteration
chunk = self._chunks.pop(0)
mock = MagicMock()
mock.model_dump.return_value = chunk
return mock
class _MockAsyncStream:
"""Async iterator that mimics the SDK EventStreamAsync."""
def __init__(self, chunks: list[dict[str, Any]]) -> None:
self._chunks = list(chunks)
def __aiter__(self) -> _MockAsyncStream:
return self
async def __anext__(self) -> MagicMock:
if not self._chunks:
raise StopAsyncIteration
chunk = self._chunks.pop(0)
mock = MagicMock()
mock.model_dump.return_value = chunk
return mock
# ===========================================================================
# Instantiation tests
# ===========================================================================
class TestChatOpenRouterInstantiation:
"""Tests for `ChatOpenRouter` instantiation."""
def test_basic_instantiation(self) -> None:
"""Test basic model instantiation with required params."""
model = _make_model()
assert model.model_name == MODEL_NAME
assert model.model == MODEL_NAME
assert model.openrouter_api_base is None
def test_api_key_from_field(self) -> None:
"""Test that API key is properly set."""
model = _make_model()
assert model.openrouter_api_key is not None
assert model.openrouter_api_key.get_secret_value() == "test-key"
def test_api_key_from_env(self, monkeypatch: pytest.MonkeyPatch) -> None:
"""Test that API key is read from OPENROUTER_API_KEY env var."""
monkeypatch.setenv("OPENROUTER_API_KEY", "env-key-123")
model = ChatOpenRouter(model=MODEL_NAME)
assert model.openrouter_api_key is not None
assert model.openrouter_api_key.get_secret_value() == "env-key-123"
def test_missing_api_key_raises(self, monkeypatch: pytest.MonkeyPatch) -> None:
"""Test that missing API key raises ValueError."""
monkeypatch.delenv("OPENROUTER_API_KEY", raising=False)
with pytest.raises(ValueError, match="OPENROUTER_API_KEY must be set"):
ChatOpenRouter(model=MODEL_NAME)
def test_model_required(self) -> None:
"""Test that model name is required."""
with pytest.raises((ValueError, TypeError)):
ChatOpenRouter(api_key=SecretStr("test-key")) # type: ignore[call-arg]
def test_secret_masking(self) -> None:
"""Test that API key is not exposed in string representation."""
model = _make_model(api_key=SecretStr("super-secret"))
model_str = str(model)
assert "super-secret" not in model_str
def test_secret_masking_repr(self) -> None:
"""Test that API key is masked in repr too."""
model = _make_model(api_key=SecretStr("super-secret"))
assert "super-secret" not in repr(model)
def test_api_key_is_secret_str(self) -> None:
"""Test that openrouter_api_key is a SecretStr instance."""
model = _make_model()
assert isinstance(model.openrouter_api_key, SecretStr)
def test_llm_type(self) -> None:
"""Test _llm_type property."""
model = _make_model()
assert model._llm_type == "openrouter-chat"
def test_ls_params(self) -> None:
"""Test LangSmith params include openrouter provider."""
model = _make_model()
ls_params = model._get_ls_params()
assert ls_params["ls_provider"] == "openrouter"
def test_ls_params_includes_max_tokens(self) -> None:
"""Test that ls_max_tokens is set when max_tokens is configured."""
model = _make_model(max_tokens=512)
ls_params = model._get_ls_params()
assert ls_params["ls_max_tokens"] == 512
def test_ls_params_stop_string_wrapped_in_list(self) -> None:
"""Test that a string stop value is wrapped in a list for ls_stop."""
model = _make_model(stop_sequences="END")
ls_params = model._get_ls_params()
assert ls_params["ls_stop"] == ["END"]
def test_ls_params_stop_list_passthrough(self) -> None:
"""Test that a list stop value is passed through directly."""
model = _make_model(stop_sequences=["END", "STOP"])
ls_params = model._get_ls_params()
assert ls_params["ls_stop"] == ["END", "STOP"]
def test_client_created(self) -> None:
"""Test that OpenRouter SDK client is created."""
model = _make_model()
assert model.client is not None
def test_client_reused_for_same_params(self) -> None:
"""Test that the SDK client is reused when model is re-validated."""
model = _make_model()
client_1 = model.client
# Re-validate does not replace the existing client
model.validate_environment() # type: ignore[operator]
assert model.client is client_1
def test_app_url_passed_to_client(self) -> None:
"""Test that app_url is passed as HTTP-Referer header via httpx clients."""
with patch("openrouter.OpenRouter") as mock_cls:
mock_cls.return_value = MagicMock()
ChatOpenRouter(
model=MODEL_NAME,
api_key=SecretStr("test-key"),
app_url="https://myapp.com",
)
call_kwargs = mock_cls.call_args[1]
assert call_kwargs["client"].headers["HTTP-Referer"] == "https://myapp.com"
def test_app_title_passed_to_client(self) -> None:
"""Test that app_title is passed as X-Title header via httpx clients."""
with patch("openrouter.OpenRouter") as mock_cls:
mock_cls.return_value = MagicMock()
ChatOpenRouter(
model=MODEL_NAME,
api_key=SecretStr("test-key"),
app_title="My App",
)
call_kwargs = mock_cls.call_args[1]
assert call_kwargs["client"].headers["X-Title"] == "My App"
def test_default_attribution_headers(self) -> None:
"""Test that default attribution headers are sent when not overridden."""
with patch("openrouter.OpenRouter") as mock_cls:
mock_cls.return_value = MagicMock()
ChatOpenRouter(
model=MODEL_NAME,
api_key=SecretStr("test-key"),
)
call_kwargs = mock_cls.call_args[1]
sync_headers = call_kwargs["client"].headers
assert sync_headers["HTTP-Referer"] == "https://docs.langchain.com"
assert sync_headers["X-Title"] == "LangChain"
def test_user_attribution_overrides_defaults(self) -> None:
"""Test that user-supplied attribution overrides the defaults."""
with patch("openrouter.OpenRouter") as mock_cls:
mock_cls.return_value = MagicMock()
ChatOpenRouter(
model=MODEL_NAME,
api_key=SecretStr("test-key"),
app_url="https://my-custom-app.com",
app_title="My Custom App",
)
call_kwargs = mock_cls.call_args[1]
sync_headers = call_kwargs["client"].headers
assert sync_headers["HTTP-Referer"] == "https://my-custom-app.com"
assert sync_headers["X-Title"] == "My Custom App"
def test_app_categories_passed_to_client(self) -> None:
"""Test that app_categories injects custom httpx clients with header."""
with patch("openrouter.OpenRouter") as mock_cls:
mock_cls.return_value = MagicMock()
ChatOpenRouter(
model=MODEL_NAME,
api_key=SecretStr("test-key"),
app_categories=["cli-agent", "programming-app"],
)
call_kwargs = mock_cls.call_args[1]
# Custom httpx clients should be created
assert "client" in call_kwargs
assert "async_client" in call_kwargs
# Verify the header value is comma-joined
sync_headers = call_kwargs["client"].headers
assert sync_headers["X-OpenRouter-Categories"] == (
"cli-agent,programming-app"
)
async_headers = call_kwargs["async_client"].headers
assert async_headers["X-OpenRouter-Categories"] == (
"cli-agent,programming-app"
)
def test_app_categories_none_no_categories_header(self) -> None:
"""Test that no X-OpenRouter-Categories header when categories unset."""
with patch("openrouter.OpenRouter") as mock_cls:
mock_cls.return_value = MagicMock()
ChatOpenRouter(
model=MODEL_NAME,
api_key=SecretStr("test-key"),
)
call_kwargs = mock_cls.call_args[1]
# httpx clients still created for X-Title default
sync_headers = call_kwargs["client"].headers
assert "X-OpenRouter-Categories" not in sync_headers
def test_app_categories_empty_list_no_categories_header(self) -> None:
"""Test that an empty list does not inject categories header."""
with patch("openrouter.OpenRouter") as mock_cls:
mock_cls.return_value = MagicMock()
ChatOpenRouter(
model=MODEL_NAME,
api_key=SecretStr("test-key"),
app_categories=[],
)
call_kwargs = mock_cls.call_args[1]
sync_headers = call_kwargs["client"].headers
assert "X-OpenRouter-Categories" not in sync_headers
def test_app_categories_with_other_attribution(self) -> None:
"""Test that app_categories coexists with app_url and app_title."""
with patch("openrouter.OpenRouter") as mock_cls:
mock_cls.return_value = MagicMock()
ChatOpenRouter(
model=MODEL_NAME,
api_key=SecretStr("test-key"),
app_url="https://myapp.com",
app_title="My App",
app_categories=["cli-agent"],
)
call_kwargs = mock_cls.call_args[1]
sync_headers = call_kwargs["client"].headers
assert sync_headers["HTTP-Referer"] == "https://myapp.com"
assert sync_headers["X-Title"] == "My App"
assert sync_headers["X-OpenRouter-Categories"] == "cli-agent"
def test_app_title_none_no_x_title_header(self) -> None:
"""Test that X-Title header is omitted when app_title is explicitly None."""
with patch("openrouter.OpenRouter") as mock_cls:
mock_cls.return_value = MagicMock()
ChatOpenRouter(
model=MODEL_NAME,
api_key=SecretStr("test-key"),
app_title=None,
)
call_kwargs = mock_cls.call_args[1]
sync_headers = call_kwargs["client"].headers
assert "X-Title" not in sync_headers
def test_app_url_none_no_referer_header(self) -> None:
"""Test that HTTP-Referer header is omitted when app_url is explicitly None."""
with patch("openrouter.OpenRouter") as mock_cls:
mock_cls.return_value = MagicMock()
ChatOpenRouter(
model=MODEL_NAME,
api_key=SecretStr("test-key"),
app_url=None,
)
call_kwargs = mock_cls.call_args[1]
sync_headers = call_kwargs["client"].headers
assert "HTTP-Referer" not in sync_headers
def test_no_attribution_no_custom_clients(self) -> None:
"""Test that no httpx clients are created when all attribution is None."""
with patch("openrouter.OpenRouter") as mock_cls:
mock_cls.return_value = MagicMock()
ChatOpenRouter(
model=MODEL_NAME,
api_key=SecretStr("test-key"),
app_url=None,
app_title=None,
app_categories=None,
)
call_kwargs = mock_cls.call_args[1]
assert "client" not in call_kwargs
assert "async_client" not in call_kwargs
def test_default_headers_passed_to_client(self) -> None:
"""Test that default_headers are forwarded to the underlying httpx clients.
Without this support, user-supplied headers like xAI's
``x-grok-conv-id`` (used for sticky-routing prompt cache hits) had no
way to reach the upstream provider — they were silently absorbed into
``model_kwargs`` by the ``build_extra`` validator.
"""
with patch("openrouter.OpenRouter") as mock_cls:
mock_cls.return_value = MagicMock()
ChatOpenRouter(
model=MODEL_NAME,
api_key=SecretStr("test-key"),
default_headers={"x-grok-conv-id": "session-abc-123"},
)
call_kwargs = mock_cls.call_args[1]
# Custom httpx clients are created and the header is set on both.
assert "client" in call_kwargs
assert "async_client" in call_kwargs
sync_headers = call_kwargs["client"].headers
assert sync_headers["x-grok-conv-id"] == "session-abc-123"
async_headers = call_kwargs["async_client"].headers
assert async_headers["x-grok-conv-id"] == "session-abc-123"
def test_default_headers_coexist_with_app_attribution(self) -> None:
"""Test that default_headers merges with built-in attribution headers."""
with patch("openrouter.OpenRouter") as mock_cls:
mock_cls.return_value = MagicMock()
ChatOpenRouter(
model=MODEL_NAME,
api_key=SecretStr("test-key"),
app_url="https://myapp.com",
app_title="My App",
default_headers={
"x-grok-conv-id": "session-xyz",
"x-custom-trace-id": "trace-001",
},
)
call_kwargs = mock_cls.call_args[1]
sync_headers = call_kwargs["client"].headers
# Built-in attribution preserved
assert sync_headers["HTTP-Referer"] == "https://myapp.com"
assert sync_headers["X-Title"] == "My App"
# User-supplied headers also present
assert sync_headers["x-grok-conv-id"] == "session-xyz"
assert sync_headers["x-custom-trace-id"] == "trace-001"
def test_default_headers_override_app_attribution(self) -> None:
"""Test that default_headers takes precedence over collidng built-in keys."""
with patch("openrouter.OpenRouter") as mock_cls:
mock_cls.return_value = MagicMock()
ChatOpenRouter(
model=MODEL_NAME,
api_key=SecretStr("test-key"),
app_title="Default Title",
default_headers={"X-Title": "Override Title"},
)
call_kwargs = mock_cls.call_args[1]
sync_headers = call_kwargs["client"].headers
# default_headers wins over the built-in app_title-derived value
assert sync_headers["X-Title"] == "Override Title"
def test_default_headers_none_no_custom_headers(self) -> None:
"""Test that default_headers=None doesn't interfere with default behavior."""
with patch("openrouter.OpenRouter") as mock_cls:
mock_cls.return_value = MagicMock()
ChatOpenRouter(
model=MODEL_NAME,
api_key=SecretStr("test-key"),
default_headers=None,
)
call_kwargs = mock_cls.call_args[1]
# Default app-attribution headers still present
sync_headers = call_kwargs["client"].headers
assert sync_headers["HTTP-Referer"] == "https://docs.langchain.com"
assert sync_headers["X-Title"] == "LangChain"
# No spurious extra headers
assert "x-grok-conv-id" not in sync_headers
def test_reasoning_in_params(self) -> None:
"""Test that `reasoning` is included in default params."""
model = _make_model(reasoning={"effort": "high"})
params = model._default_params
assert params["reasoning"] == {"effort": "high"}
def test_openrouter_provider_in_params(self) -> None:
"""Test that `openrouter_provider` is included in default params."""
model = _make_model(openrouter_provider={"order": ["Anthropic"]})
params = model._default_params
assert params["provider"] == {"order": ["Anthropic"]}
def test_route_in_params(self) -> None:
"""Test that `route` is included in default params."""
model = _make_model(route="fallback")
params = model._default_params
assert params["route"] == "fallback"
def test_optional_params_excluded_when_none(self) -> None:
"""Test that None optional params are not in default params."""
model = _make_model()
params = model._default_params
assert "temperature" not in params
assert "max_tokens" not in params
assert "top_p" not in params
assert "reasoning" not in params
def test_temperature_included_when_set(self) -> None:
"""Test that temperature is included when explicitly set."""
model = _make_model(temperature=0.5)
params = model._default_params
assert params["temperature"] == 0.5
# ===========================================================================
# Serialization tests
# ===========================================================================
class TestSerialization:
"""Tests for serialization round-trips."""
def test_is_lc_serializable(self) -> None:
"""Test that ChatOpenRouter declares itself as serializable."""
assert ChatOpenRouter.is_lc_serializable() is True
def test_dumpd_load_roundtrip(self) -> None:
"""Test that dumpd/load round-trip preserves model config."""
model = _make_model(temperature=0.7, max_tokens=100)
serialized = dumpd(model)
deserialized = load(
serialized,
valid_namespaces=["langchain_openrouter"],
allowed_objects="all",
secrets_from_env=False,
secrets_map={"OPENROUTER_API_KEY": "test-key"},
)
assert isinstance(deserialized, ChatOpenRouter)
assert deserialized.model_name == MODEL_NAME
assert deserialized.temperature == 0.7
assert deserialized.max_tokens == 100
def test_dumps_does_not_leak_secrets(self) -> None:
"""Test that dumps output does not contain the raw API key."""
model = _make_model(api_key=SecretStr("super-secret-key"))
serialized = dumps(model)
assert "super-secret-key" not in serialized
# ===========================================================================
# Mocked generate / stream tests
# ===========================================================================
class TestMockedGenerate:
"""Tests for _generate / _agenerate with a mocked SDK client."""
def test_invoke_basic(self) -> None:
"""Test basic invoke returns an AIMessage via mocked SDK."""
model = _make_model()
model.client = MagicMock()
model.client.chat.send.return_value = _make_sdk_response(_SIMPLE_RESPONSE_DICT)
result = model.invoke("Hello")
assert isinstance(result, AIMessage)
assert result.content == "Hello!"
model.client.chat.send.assert_called_once()
def test_invoke_with_tool_response(self) -> None:
"""Test invoke that returns tool calls."""
model = _make_model()
model.client = MagicMock()
model.client.chat.send.return_value = _make_sdk_response(_TOOL_RESPONSE_DICT)
result = model.invoke("What's the weather?")
assert isinstance(result, AIMessage)
assert len(result.tool_calls) == 1
assert result.tool_calls[0]["name"] == "GetWeather"
def test_invoke_passes_correct_messages(self) -> None:
"""Test that invoke converts messages and passes them to the SDK."""
model = _make_model()
model.client = MagicMock()
model.client.chat.send.return_value = _make_sdk_response(_SIMPLE_RESPONSE_DICT)
model.invoke([HumanMessage(content="Hi")])
call_kwargs = model.client.chat.send.call_args[1]
assert call_kwargs["messages"] == [{"role": "user", "content": "Hi"}]
def test_invoke_strips_internal_kwargs(self) -> None:
"""Test that LangChain-internal kwargs are stripped before SDK call."""
model = _make_model()
model.client = MagicMock()
model.client.chat.send.return_value = _make_sdk_response(_SIMPLE_RESPONSE_DICT)
model._generate(
[HumanMessage(content="Hi")],
ls_structured_output_format={"kwargs": {"method": "function_calling"}},
)
call_kwargs = model.client.chat.send.call_args[1]
assert "ls_structured_output_format" not in call_kwargs
def test_invoke_usage_metadata(self) -> None:
"""Test that usage metadata is populated on the response."""
model = _make_model()
model.client = MagicMock()
model.client.chat.send.return_value = _make_sdk_response(_SIMPLE_RESPONSE_DICT)
result = model.invoke("Hello")
assert isinstance(result, AIMessage)
assert result.usage_metadata is not None
assert result.usage_metadata["input_tokens"] == 10
assert result.usage_metadata["output_tokens"] == 5
assert result.usage_metadata["total_tokens"] == 15
def test_stream_basic(self) -> None:
"""Test streaming returns AIMessageChunks via mocked SDK."""
model = _make_model()
model.client = MagicMock()
model.client.chat.send.return_value = _MockSyncStream(
[dict(c) for c in _STREAM_CHUNKS]
)
chunks = list(model.stream("Hello"))
assert len(chunks) > 0
assert all(isinstance(c, AIMessageChunk) for c in chunks)
# Concatenated content should be "Hello world"
full_content = "".join(c.content for c in chunks if isinstance(c.content, str))
assert "Hello" in full_content
assert "world" in full_content
def test_stream_passes_stream_true(self) -> None:
"""Test that stream sends stream=True to the SDK."""
model = _make_model()
model.client = MagicMock()
model.client.chat.send.return_value = _MockSyncStream(
[dict(c) for c in _STREAM_CHUNKS]
)
list(model.stream("Hello"))
call_kwargs = model.client.chat.send.call_args[1]
assert call_kwargs["stream"] is True
def test_invoke_with_streaming_flag(self) -> None:
"""Test that invoke delegates to stream when streaming=True."""
model = _make_model(streaming=True)
model.client = MagicMock()
model.client.chat.send.return_value = _MockSyncStream(
[dict(c) for c in _STREAM_CHUNKS]
)
result = model.invoke("Hello")
assert isinstance(result, AIMessage)
call_kwargs = model.client.chat.send.call_args[1]
assert call_kwargs["stream"] is True
async def test_ainvoke_basic(self) -> None:
"""Test async invoke returns an AIMessage via mocked SDK."""
model = _make_model()
model.client = MagicMock()
model.client.chat.send_async = AsyncMock(
return_value=_make_sdk_response(_SIMPLE_RESPONSE_DICT)
)
result = await model.ainvoke("Hello")
assert isinstance(result, AIMessage)
assert result.content == "Hello!"
model.client.chat.send_async.assert_awaited_once()
async def test_astream_basic(self) -> None:
"""Test async streaming returns AIMessageChunks via mocked SDK."""
model = _make_model()
model.client = MagicMock()
model.client.chat.send_async = AsyncMock(
return_value=_MockAsyncStream(_STREAM_CHUNKS)
)
chunks = [c async for c in model.astream("Hello")]
assert len(chunks) > 0
assert all(isinstance(c, AIMessageChunk) for c in chunks)
def test_stream_response_metadata_fields(self) -> None:
"""Test response-level metadata in streaming response_metadata."""
model = _make_model()
model.client = MagicMock()
stream_chunks: list[dict[str, Any]] = [
{
"choices": [
{"delta": {"role": "assistant", "content": "Hi"}, "index": 0}
],
"model": "anthropic/claude-sonnet-4-5",
"system_fingerprint": "fp_stream123",
"object": "chat.completion.chunk",
"created": 1700000000.0,
"id": "gen-stream-meta",
},
{
"choices": [
{
"delta": {},
"finish_reason": "stop",
"native_finish_reason": "end_turn",
"index": 0,
}
],
"model": "anthropic/claude-sonnet-4-5",
"system_fingerprint": "fp_stream123",
"object": "chat.completion.chunk",
"created": 1700000000.0,
"id": "gen-stream-meta",
},
]
model.client.chat.send.return_value = _MockSyncStream(stream_chunks)
chunks = list(model.stream("Hello"))
assert len(chunks) >= 2
# Find the chunk with finish_reason (final metadata chunk)
final = [
c for c in chunks if c.response_metadata.get("finish_reason") == "stop"
]
assert len(final) == 1
meta = final[0].response_metadata
assert meta["model_name"] == "anthropic/claude-sonnet-4-5"
assert meta["system_fingerprint"] == "fp_stream123"
assert meta["native_finish_reason"] == "end_turn"
assert meta["finish_reason"] == "stop"
assert meta["id"] == "gen-stream-meta"
assert meta["created"] == 1700000000
assert meta["object"] == "chat.completion.chunk"
async def test_astream_response_metadata_fields(self) -> None:
"""Test response-level metadata in async streaming response_metadata."""
model = _make_model()
model.client = MagicMock()
stream_chunks: list[dict[str, Any]] = [
{
"choices": [
{"delta": {"role": "assistant", "content": "Hi"}, "index": 0}
],
"model": "anthropic/claude-sonnet-4-5",
"system_fingerprint": "fp_async123",
"object": "chat.completion.chunk",
"created": 1700000000.0,
"id": "gen-astream-meta",
},
{
"choices": [
{
"delta": {},
"finish_reason": "stop",
"native_finish_reason": "end_turn",
"index": 0,
}
],
"model": "anthropic/claude-sonnet-4-5",
"system_fingerprint": "fp_async123",
"object": "chat.completion.chunk",
"created": 1700000000.0,
"id": "gen-astream-meta",
},
]
model.client.chat.send_async = AsyncMock(
return_value=_MockAsyncStream(stream_chunks)
)
chunks = [c async for c in model.astream("Hello")]
assert len(chunks) >= 2
# Find the chunk with finish_reason (final metadata chunk)
final = [
c for c in chunks if c.response_metadata.get("finish_reason") == "stop"
]
assert len(final) == 1
meta = final[0].response_metadata
assert meta["model_name"] == "anthropic/claude-sonnet-4-5"
assert meta["system_fingerprint"] == "fp_async123"
assert meta["native_finish_reason"] == "end_turn"
assert meta["id"] == "gen-astream-meta"
assert meta["created"] == 1700000000
assert meta["object"] == "chat.completion.chunk"
# ===========================================================================
# Request payload verification
# ===========================================================================
class TestRequestPayload:
"""Tests verifying the exact dict sent to the SDK."""
def test_message_format_in_payload(self) -> None:
"""Test that messages are formatted correctly in the SDK call."""
model = _make_model(temperature=0)
model.client = MagicMock()
model.client.chat.send.return_value = _make_sdk_response(_SIMPLE_RESPONSE_DICT)
model.invoke(
[
SystemMessage(content="You are helpful."),
HumanMessage(content="Hi"),
]
)
call_kwargs = model.client.chat.send.call_args[1]
assert call_kwargs["messages"] == [
{"role": "system", "content": "You are helpful."},
{"role": "user", "content": "Hi"},
]
def test_model_kwargs_forwarded(self) -> None:
"""Test that extra model_kwargs are included in the SDK call."""
model = _make_model(model_kwargs={"top_k": 50})
model.client = MagicMock()
model.client.chat.send.return_value = _make_sdk_response(_SIMPLE_RESPONSE_DICT)
model.invoke("Hi")
call_kwargs = model.client.chat.send.call_args[1]
assert call_kwargs["top_k"] == 50
def test_stop_sequences_in_payload(self) -> None:
"""Test that stop sequences are passed to the SDK."""
model = _make_model()
model.client = MagicMock()
model.client.chat.send.return_value = _make_sdk_response(_SIMPLE_RESPONSE_DICT)
model.invoke("Hi", stop=["END"])
call_kwargs = model.client.chat.send.call_args[1]
assert call_kwargs["stop"] == ["END"]
def test_tool_format_in_payload(self) -> None:
"""Test that tools are formatted in OpenAI-compatible structure."""
model = _make_model()
model.client = MagicMock()
model.client.chat.send.return_value = _make_sdk_response(_TOOL_RESPONSE_DICT)
bound = model.bind_tools([GetWeather])
bound.invoke("What's the weather?")
call_kwargs = model.client.chat.send.call_args[1]
tools = call_kwargs["tools"]
assert len(tools) == 1
assert tools[0]["type"] == "function"
assert tools[0]["function"]["name"] == "GetWeather"
assert "parameters" in tools[0]["function"]
def test_openrouter_params_in_payload(self) -> None:
"""Test that OpenRouter-specific params appear in the SDK call."""
model = _make_model(
reasoning={"effort": "high"},
openrouter_provider={"order": ["Anthropic"]},
route="fallback",
)
model.client = MagicMock()
model.client.chat.send.return_value = _make_sdk_response(_SIMPLE_RESPONSE_DICT)
model.invoke("Hi")
call_kwargs = model.client.chat.send.call_args[1]
assert call_kwargs["reasoning"] == {"effort": "high"}
assert call_kwargs["provider"] == {"order": ["Anthropic"]}
assert call_kwargs["route"] == "fallback"
# ===========================================================================
# bind_tools tests
# ===========================================================================
class TestBindTools:
"""Tests for the bind_tools public method."""
@pytest.mark.parametrize(
"tool_choice",
[
"auto",
"none",
"required",
"GetWeather",
{"type": "function", "function": {"name": "GetWeather"}},
None,
],
)
def test_bind_tools_tool_choice(self, tool_choice: Any) -> None:
"""Test bind_tools accepts various tool_choice values."""
model = _make_model()
bound = model.bind_tools(
[GetWeather, GenerateUsername], tool_choice=tool_choice
)
assert isinstance(bound, RunnableBinding)
def test_bind_tools_bool_true_single_tool(self) -> None:
"""Test bind_tools with tool_choice=True and a single tool."""
model = _make_model()
bound = model.bind_tools([GetWeather], tool_choice=True)
assert isinstance(bound, RunnableBinding)
kwargs = bound.kwargs
assert kwargs["tool_choice"] == {
"type": "function",
"function": {"name": "GetWeather"},
}
def test_bind_tools_bool_true_multiple_tools_raises(self) -> None:
"""Test bind_tools with tool_choice=True and multiple tools raises."""
model = _make_model()
with pytest.raises(ValueError, match="tool_choice can only be True"):
model.bind_tools([GetWeather, GenerateUsername], tool_choice=True)
def test_bind_tools_any_maps_to_required(self) -> None:
"""Test that tool_choice='any' is mapped to 'required'."""
model = _make_model()
bound = model.bind_tools([GetWeather], tool_choice="any")
assert isinstance(bound, RunnableBinding)
assert bound.kwargs["tool_choice"] == "required"
def test_bind_tools_string_name_becomes_dict(self) -> None:
"""Test that a specific tool name string is converted to a dict."""
model = _make_model()
bound = model.bind_tools([GetWeather], tool_choice="GetWeather")
assert isinstance(bound, RunnableBinding)
assert bound.kwargs["tool_choice"] == {
"type": "function",
"function": {"name": "GetWeather"},
}
def test_bind_tools_formats_tools_correctly(self) -> None:
"""Test that tools are converted to OpenAI format."""
model = _make_model()
bound = model.bind_tools([GetWeather])
assert isinstance(bound, RunnableBinding)
tools = bound.kwargs["tools"]
assert len(tools) == 1
assert tools[0]["type"] == "function"
assert tools[0]["function"]["name"] == "GetWeather"
def test_bind_tools_no_choice_omits_key(self) -> None:
"""Test that tool_choice=None does not set tool_choice in kwargs."""
model = _make_model()
bound = model.bind_tools([GetWeather], tool_choice=None)
assert isinstance(bound, RunnableBinding)
assert "tool_choice" not in bound.kwargs
def test_bind_tools_strict_forwarded(self) -> None:
"""Test that strict param is forwarded to tool definitions."""
model = _make_model()
bound = model.bind_tools([GetWeather], strict=True)
assert isinstance(bound, RunnableBinding)
tools = bound.kwargs["tools"]
assert tools[0]["function"]["strict"] is True
def test_bind_tools_strict_none_by_default(self) -> None:
"""Test that strict is not set when not provided."""
model = _make_model()
bound = model.bind_tools([GetWeather])
assert isinstance(bound, RunnableBinding)
tools = bound.kwargs["tools"]