-
Notifications
You must be signed in to change notification settings - Fork 21.5k
Expand file tree
/
Copy pathtest_base.py
More file actions
3812 lines (3293 loc) · 133 KB
/
test_base.py
File metadata and controls
3812 lines (3293 loc) · 133 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
"""Test OpenAI Chat API wrapper."""
from __future__ import annotations
import json
import warnings
from functools import partial
from types import TracebackType
from typing import Any, Literal, cast
from unittest.mock import AsyncMock, MagicMock, patch
import httpx
import openai
import pytest
from langchain_core.exceptions import ContextOverflowError
from langchain_core.load import dumps, loads
from langchain_core.messages import (
AIMessage,
AIMessageChunk,
BaseMessage,
FunctionMessage,
HumanMessage,
InvalidToolCall,
SystemMessage,
ToolCall,
ToolMessage,
)
from langchain_core.messages import content as types
from langchain_core.messages.ai import UsageMetadata
from langchain_core.messages.block_translators.openai import (
_convert_from_v03_ai_message,
)
from langchain_core.outputs import ChatGeneration, ChatResult
from langchain_core.runnables import RunnableLambda
from langchain_core.runnables.base import RunnableBinding, RunnableSequence
from langchain_core.tracers.base import BaseTracer
from langchain_core.tracers.schemas import Run
from openai.types.responses import ResponseOutputMessage, ResponseReasoningItem
from openai.types.responses.response import IncompleteDetails, Response
from openai.types.responses.response_error import ResponseError
from openai.types.responses.response_file_search_tool_call import (
ResponseFileSearchToolCall,
Result,
)
from openai.types.responses.response_function_tool_call import ResponseFunctionToolCall
from openai.types.responses.response_function_web_search import (
ActionSearch,
ResponseFunctionWebSearch,
)
from openai.types.responses.response_output_refusal import ResponseOutputRefusal
from openai.types.responses.response_output_text import ResponseOutputText
from openai.types.responses.response_reasoning_item import Summary
from openai.types.responses.response_usage import (
InputTokensDetails,
OutputTokensDetails,
ResponseUsage,
)
from pydantic import BaseModel, Field, SecretStr
from typing_extensions import Self, TypedDict
from langchain_openai import ChatOpenAI
from langchain_openai.chat_models._compat import (
_FUNCTION_CALL_IDS_MAP_KEY,
_convert_from_v1_to_chat_completions,
_convert_from_v1_to_responses,
_convert_to_v03_ai_message,
)
from langchain_openai.chat_models.base import (
OpenAIRefusalError,
_construct_lc_result_from_responses_api,
_construct_responses_api_input,
_convert_dict_to_message,
_convert_message_to_dict,
_convert_to_openai_response_format,
_create_usage_metadata,
_create_usage_metadata_responses,
_format_message_content,
_get_last_messages,
_make_computer_call_output_from_message,
_model_prefers_responses_api,
_oai_structured_outputs_parser,
_resize,
)
def test_openai_model_param() -> None:
llm = ChatOpenAI(model="foo")
assert llm.model_name == "foo"
assert llm.model == "foo"
llm = ChatOpenAI(model_name="foo") # type: ignore[call-arg]
assert llm.model_name == "foo"
assert llm.model == "foo"
llm = ChatOpenAI(max_tokens=10) # type: ignore[call-arg]
assert llm.max_tokens == 10
llm = ChatOpenAI(max_completion_tokens=10)
assert llm.max_tokens == 10
@pytest.mark.parametrize("async_api", [True, False])
def test_streaming_attribute_should_stream(async_api: bool) -> None:
llm = ChatOpenAI(model="foo", streaming=True)
assert llm._should_stream(async_api=async_api)
def test_openai_client_caching() -> None:
"""Test that the OpenAI client is cached."""
llm1 = ChatOpenAI(model="gpt-4.1-mini")
llm2 = ChatOpenAI(model="gpt-4.1-mini")
assert llm1.root_client._client is llm2.root_client._client
llm3 = ChatOpenAI(model="gpt-4.1-mini", base_url="foo")
assert llm1.root_client._client is not llm3.root_client._client
llm4 = ChatOpenAI(model="gpt-4.1-mini", timeout=None)
assert llm1.root_client._client is llm4.root_client._client
llm5 = ChatOpenAI(model="gpt-4.1-mini", timeout=3)
assert llm1.root_client._client is not llm5.root_client._client
llm6 = ChatOpenAI(
model="gpt-4.1-mini", timeout=httpx.Timeout(timeout=60.0, connect=5.0)
)
assert llm1.root_client._client is not llm6.root_client._client
llm7 = ChatOpenAI(model="gpt-4.1-mini", timeout=(5, 1))
assert llm1.root_client._client is not llm7.root_client._client
def test_profile() -> None:
model = ChatOpenAI(model="gpt-4")
assert model.profile
assert not model.profile["structured_output"]
model = ChatOpenAI(model="gpt-5")
assert model.profile
assert model.profile["structured_output"]
assert model.profile["tool_calling"]
# Test overwriting a field
model.profile["tool_calling"] = False
assert not model.profile["tool_calling"]
# Test we didn't mutate
model = ChatOpenAI(model="gpt-5")
assert model.profile
assert model.profile["tool_calling"]
# Test passing in profile
model = ChatOpenAI(model="gpt-5", profile={"tool_calling": False})
assert model.profile == {"tool_calling": False}
# Test overrides for gpt-5 input tokens
model = ChatOpenAI(model="gpt-5")
assert model.profile["max_input_tokens"] == 272_000
def test_openai_o1_temperature() -> None:
llm = ChatOpenAI(model="o1-preview")
assert llm.temperature == 1
llm = ChatOpenAI(model_name="o1-mini") # type: ignore[call-arg]
assert llm.temperature == 1
def test_function_message_dict_to_function_message() -> None:
content = json.dumps({"result": "Example #1"})
name = "test_function"
result = _convert_dict_to_message(
{"role": "function", "name": name, "content": content}
)
assert isinstance(result, FunctionMessage)
assert result.name == name
assert result.content == content
def test__convert_dict_to_message_human() -> None:
message = {"role": "user", "content": "foo"}
result = _convert_dict_to_message(message)
expected_output = HumanMessage(content="foo")
assert result == expected_output
assert _convert_message_to_dict(expected_output) == message
def test__convert_dict_to_message_human_with_name() -> None:
message = {"role": "user", "content": "foo", "name": "test"}
result = _convert_dict_to_message(message)
expected_output = HumanMessage(content="foo", name="test")
assert result == expected_output
assert _convert_message_to_dict(expected_output) == message
def test__convert_dict_to_message_ai() -> None:
message = {"role": "assistant", "content": "foo"}
result = _convert_dict_to_message(message)
expected_output = AIMessage(content="foo")
assert result == expected_output
assert _convert_message_to_dict(expected_output) == message
def test__convert_dict_to_message_ai_with_name() -> None:
message = {"role": "assistant", "content": "foo", "name": "test"}
result = _convert_dict_to_message(message)
expected_output = AIMessage(content="foo", name="test")
assert result == expected_output
assert _convert_message_to_dict(expected_output) == message
def test__convert_dict_to_message_system() -> None:
message = {"role": "system", "content": "foo"}
result = _convert_dict_to_message(message)
expected_output = SystemMessage(content="foo")
assert result == expected_output
assert _convert_message_to_dict(expected_output) == message
def test__convert_dict_to_message_developer() -> None:
message = {"role": "developer", "content": "foo"}
result = _convert_dict_to_message(message)
expected_output = SystemMessage(
content="foo", additional_kwargs={"__openai_role__": "developer"}
)
assert result == expected_output
assert _convert_message_to_dict(expected_output) == message
def test__convert_dict_to_message_system_with_name() -> None:
message = {"role": "system", "content": "foo", "name": "test"}
result = _convert_dict_to_message(message)
expected_output = SystemMessage(content="foo", name="test")
assert result == expected_output
assert _convert_message_to_dict(expected_output) == message
def test__convert_dict_to_message_tool() -> None:
message = {"role": "tool", "content": "foo", "tool_call_id": "bar"}
result = _convert_dict_to_message(message)
expected_output = ToolMessage(content="foo", tool_call_id="bar")
assert result == expected_output
assert _convert_message_to_dict(expected_output) == message
def test__convert_dict_to_message_tool_call() -> None:
raw_tool_call = {
"id": "call_wm0JY6CdwOMZ4eTxHWUThDNz",
"function": {
"arguments": '{"name": "Sally", "hair_color": "green"}',
"name": "GenerateUsername",
},
"type": "function",
}
message = {"role": "assistant", "content": None, "tool_calls": [raw_tool_call]}
result = _convert_dict_to_message(message)
expected_output = AIMessage(
content="",
tool_calls=[
ToolCall(
name="GenerateUsername",
args={"name": "Sally", "hair_color": "green"},
id="call_wm0JY6CdwOMZ4eTxHWUThDNz",
type="tool_call",
)
],
)
assert result == expected_output
assert _convert_message_to_dict(expected_output) == message
# Test malformed tool call
raw_tool_calls: list = [
{
"id": "call_wm0JY6CdwOMZ4eTxHWUThDNz",
"function": {"arguments": "oops", "name": "GenerateUsername"},
"type": "function",
},
{
"id": "call_abc123",
"function": {
"arguments": '{"name": "Sally", "hair_color": "green"}',
"name": "GenerateUsername",
},
"type": "function",
},
]
raw_tool_calls = sorted(raw_tool_calls, key=lambda x: x["id"])
message = {"role": "assistant", "content": None, "tool_calls": raw_tool_calls}
result = _convert_dict_to_message(message)
expected_output = AIMessage(
content="",
invalid_tool_calls=[
InvalidToolCall(
name="GenerateUsername",
args="oops",
id="call_wm0JY6CdwOMZ4eTxHWUThDNz",
error=(
"Function GenerateUsername arguments:\n\noops\n\nare not "
"valid JSON. Received JSONDecodeError Expecting value: line 1 "
"column 1 (char 0)\nFor troubleshooting, visit: https://docs"
".langchain.com/oss/python/langchain/errors/OUTPUT_PARSING_FAILURE "
),
type="invalid_tool_call",
)
],
tool_calls=[
ToolCall(
name="GenerateUsername",
args={"name": "Sally", "hair_color": "green"},
id="call_abc123",
type="tool_call",
)
],
)
assert result == expected_output
reverted_message_dict = _convert_message_to_dict(expected_output)
reverted_message_dict["tool_calls"] = sorted(
reverted_message_dict["tool_calls"], key=lambda x: x["id"]
)
assert reverted_message_dict == message
class MockAsyncContextManager:
def __init__(self, chunk_list: list) -> None:
self.current_chunk = 0
self.chunk_list = chunk_list
self.chunk_num = len(chunk_list)
async def __aenter__(self) -> Self:
return self
async def __aexit__(
self,
exc_type: type[BaseException] | None,
exc: BaseException | None,
tb: TracebackType | None,
) -> None:
pass
def __aiter__(self) -> MockAsyncContextManager:
return self
async def __anext__(self) -> dict:
if self.current_chunk < self.chunk_num:
chunk = self.chunk_list[self.current_chunk]
self.current_chunk += 1
return chunk
raise StopAsyncIteration
class MockSyncContextManager:
def __init__(self, chunk_list: list) -> None:
self.current_chunk = 0
self.chunk_list = chunk_list
self.chunk_num = len(chunk_list)
def __enter__(self) -> Self:
return self
def __exit__(
self,
exc_type: type[BaseException] | None,
exc: BaseException | None,
tb: TracebackType | None,
) -> None:
pass
def __iter__(self) -> MockSyncContextManager:
return self
def __next__(self) -> dict:
if self.current_chunk < self.chunk_num:
chunk = self.chunk_list[self.current_chunk]
self.current_chunk += 1
return chunk
raise StopIteration
GLM4_STREAM_META = """{"id":"20240722102053e7277a4f94e848248ff9588ed37fb6e6","created":1721614853,"model":"glm-4","choices":[{"index":0,"delta":{"role":"assistant","content":"\u4eba\u5de5\u667a\u80fd"}}]}
{"id":"20240722102053e7277a4f94e848248ff9588ed37fb6e6","created":1721614853,"model":"glm-4","choices":[{"index":0,"delta":{"role":"assistant","content":"\u52a9\u624b"}}]}
{"id":"20240722102053e7277a4f94e848248ff9588ed37fb6e6","created":1721614853,"model":"glm-4","choices":[{"index":0,"delta":{"role":"assistant","content":","}}]}
{"id":"20240722102053e7277a4f94e848248ff9588ed37fb6e6","created":1721614853,"model":"glm-4","choices":[{"index":0,"delta":{"role":"assistant","content":"\u4f60\u53ef\u4ee5"}}]}
{"id":"20240722102053e7277a4f94e848248ff9588ed37fb6e6","created":1721614853,"model":"glm-4","choices":[{"index":0,"delta":{"role":"assistant","content":"\u53eb\u6211"}}]}
{"id":"20240722102053e7277a4f94e848248ff9588ed37fb6e6","created":1721614853,"model":"glm-4","choices":[{"index":0,"delta":{"role":"assistant","content":"AI"}}]}
{"id":"20240722102053e7277a4f94e848248ff9588ed37fb6e6","created":1721614853,"model":"glm-4","choices":[{"index":0,"delta":{"role":"assistant","content":"\u52a9\u624b"}}]}
{"id":"20240722102053e7277a4f94e848248ff9588ed37fb6e6","created":1721614853,"model":"glm-4","choices":[{"index":0,"delta":{"role":"assistant","content":"。"}}]}
{"id":"20240722102053e7277a4f94e848248ff9588ed37fb6e6","created":1721614853,"model":"glm-4","choices":[{"index":0,"finish_reason":"stop","delta":{"role":"assistant","content":""}}],"usage":{"prompt_tokens":13,"completion_tokens":10,"total_tokens":23}}
[DONE]""" # noqa: E501
@pytest.fixture
def mock_glm4_completion() -> list:
list_chunk_data = GLM4_STREAM_META.split("\n")
result_list = []
for msg in list_chunk_data:
if msg != "[DONE]":
result_list.append(json.loads(msg))
return result_list
async def test_glm4_astream(mock_glm4_completion: list) -> None:
llm_name = "glm-4"
llm = ChatOpenAI(model=llm_name, stream_usage=True)
mock_client = AsyncMock()
async def mock_create(*args: Any, **kwargs: Any) -> MockAsyncContextManager:
return MockAsyncContextManager(mock_glm4_completion)
mock_client.create = mock_create
usage_chunk = mock_glm4_completion[-1]
usage_metadata: UsageMetadata | None = None
with patch.object(llm, "async_client", mock_client):
async for chunk in llm.astream("你的名字叫什么?只回答名字"):
assert isinstance(chunk, AIMessageChunk)
if chunk.usage_metadata is not None:
usage_metadata = chunk.usage_metadata
assert usage_metadata is not None
assert usage_metadata["input_tokens"] == usage_chunk["usage"]["prompt_tokens"]
assert usage_metadata["output_tokens"] == usage_chunk["usage"]["completion_tokens"]
assert usage_metadata["total_tokens"] == usage_chunk["usage"]["total_tokens"]
def test_glm4_stream(mock_glm4_completion: list) -> None:
llm_name = "glm-4"
llm = ChatOpenAI(model=llm_name, stream_usage=True)
mock_client = MagicMock()
def mock_create(*args: Any, **kwargs: Any) -> MockSyncContextManager:
return MockSyncContextManager(mock_glm4_completion)
mock_client.create = mock_create
usage_chunk = mock_glm4_completion[-1]
usage_metadata: UsageMetadata | None = None
with patch.object(llm, "client", mock_client):
for chunk in llm.stream("你的名字叫什么?只回答名字"):
assert isinstance(chunk, AIMessageChunk)
if chunk.usage_metadata is not None:
usage_metadata = chunk.usage_metadata
assert usage_metadata is not None
assert usage_metadata["input_tokens"] == usage_chunk["usage"]["prompt_tokens"]
assert usage_metadata["output_tokens"] == usage_chunk["usage"]["completion_tokens"]
assert usage_metadata["total_tokens"] == usage_chunk["usage"]["total_tokens"]
DEEPSEEK_STREAM_DATA = """{"id":"d3610c24e6b42518a7883ea57c3ea2c3","choices":[{"index":0,"delta":{"content":"","role":"assistant"},"finish_reason":null,"logprobs":null}],"created":1721630271,"model":"deepseek-chat","system_fingerprint":"fp_7e0991cad4","object":"chat.completion.chunk","usage":null}
{"choices":[{"delta":{"content":"我是","role":"assistant"},"finish_reason":null,"index":0,"logprobs":null}],"created":1721630271,"id":"d3610c24e6b42518a7883ea57c3ea2c3","model":"deepseek-chat","object":"chat.completion.chunk","system_fingerprint":"fp_7e0991cad4","usage":null}
{"choices":[{"delta":{"content":"Deep","role":"assistant"},"finish_reason":null,"index":0,"logprobs":null}],"created":1721630271,"id":"d3610c24e6b42518a7883ea57c3ea2c3","model":"deepseek-chat","object":"chat.completion.chunk","system_fingerprint":"fp_7e0991cad4","usage":null}
{"choices":[{"delta":{"content":"Seek","role":"assistant"},"finish_reason":null,"index":0,"logprobs":null}],"created":1721630271,"id":"d3610c24e6b42518a7883ea57c3ea2c3","model":"deepseek-chat","object":"chat.completion.chunk","system_fingerprint":"fp_7e0991cad4","usage":null}
{"choices":[{"delta":{"content":" Chat","role":"assistant"},"finish_reason":null,"index":0,"logprobs":null}],"created":1721630271,"id":"d3610c24e6b42518a7883ea57c3ea2c3","model":"deepseek-chat","object":"chat.completion.chunk","system_fingerprint":"fp_7e0991cad4","usage":null}
{"choices":[{"delta":{"content":",","role":"assistant"},"finish_reason":null,"index":0,"logprobs":null}],"created":1721630271,"id":"d3610c24e6b42518a7883ea57c3ea2c3","model":"deepseek-chat","object":"chat.completion.chunk","system_fingerprint":"fp_7e0991cad4","usage":null}
{"choices":[{"delta":{"content":"一个","role":"assistant"},"finish_reason":null,"index":0,"logprobs":null}],"created":1721630271,"id":"d3610c24e6b42518a7883ea57c3ea2c3","model":"deepseek-chat","object":"chat.completion.chunk","system_fingerprint":"fp_7e0991cad4","usage":null}
{"choices":[{"delta":{"content":"由","role":"assistant"},"finish_reason":null,"index":0,"logprobs":null}],"created":1721630271,"id":"d3610c24e6b42518a7883ea57c3ea2c3","model":"deepseek-chat","object":"chat.completion.chunk","system_fingerprint":"fp_7e0991cad4","usage":null}
{"choices":[{"delta":{"content":"深度","role":"assistant"},"finish_reason":null,"index":0,"logprobs":null}],"created":1721630271,"id":"d3610c24e6b42518a7883ea57c3ea2c3","model":"deepseek-chat","object":"chat.completion.chunk","system_fingerprint":"fp_7e0991cad4","usage":null}
{"choices":[{"delta":{"content":"求","role":"assistant"},"finish_reason":null,"index":0,"logprobs":null}],"created":1721630271,"id":"d3610c24e6b42518a7883ea57c3ea2c3","model":"deepseek-chat","object":"chat.completion.chunk","system_fingerprint":"fp_7e0991cad4","usage":null}
{"choices":[{"delta":{"content":"索","role":"assistant"},"finish_reason":null,"index":0,"logprobs":null}],"created":1721630271,"id":"d3610c24e6b42518a7883ea57c3ea2c3","model":"deepseek-chat","object":"chat.completion.chunk","system_fingerprint":"fp_7e0991cad4","usage":null}
{"choices":[{"delta":{"content":"公司","role":"assistant"},"finish_reason":null,"index":0,"logprobs":null}],"created":1721630271,"id":"d3610c24e6b42518a7883ea57c3ea2c3","model":"deepseek-chat","object":"chat.completion.chunk","system_fingerprint":"fp_7e0991cad4","usage":null}
{"choices":[{"delta":{"content":"开发的","role":"assistant"},"finish_reason":null,"index":0,"logprobs":null}],"created":1721630271,"id":"d3610c24e6b42518a7883ea57c3ea2c3","model":"deepseek-chat","object":"chat.completion.chunk","system_fingerprint":"fp_7e0991cad4","usage":null}
{"choices":[{"delta":{"content":"智能","role":"assistant"},"finish_reason":null,"index":0,"logprobs":null}],"created":1721630271,"id":"d3610c24e6b42518a7883ea57c3ea2c3","model":"deepseek-chat","object":"chat.completion.chunk","system_fingerprint":"fp_7e0991cad4","usage":null}
{"choices":[{"delta":{"content":"助手","role":"assistant"},"finish_reason":null,"index":0,"logprobs":null}],"created":1721630271,"id":"d3610c24e6b42518a7883ea57c3ea2c3","model":"deepseek-chat","object":"chat.completion.chunk","system_fingerprint":"fp_7e0991cad4","usage":null}
{"choices":[{"delta":{"content":"。","role":"assistant"},"finish_reason":null,"index":0,"logprobs":null}],"created":1721630271,"id":"d3610c24e6b42518a7883ea57c3ea2c3","model":"deepseek-chat","object":"chat.completion.chunk","system_fingerprint":"fp_7e0991cad4","usage":null}
{"choices":[{"delta":{"content":"","role":null},"finish_reason":"stop","index":0,"logprobs":null}],"created":1721630271,"id":"d3610c24e6b42518a7883ea57c3ea2c3","model":"deepseek-chat","object":"chat.completion.chunk","system_fingerprint":"fp_7e0991cad4","usage":{"completion_tokens":15,"prompt_tokens":11,"total_tokens":26}}
[DONE]""" # noqa: E501
@pytest.fixture
def mock_deepseek_completion() -> list[dict]:
list_chunk_data = DEEPSEEK_STREAM_DATA.split("\n")
result_list = []
for msg in list_chunk_data:
if msg != "[DONE]":
result_list.append(json.loads(msg))
return result_list
async def test_deepseek_astream(mock_deepseek_completion: list) -> None:
llm_name = "deepseek-chat"
llm = ChatOpenAI(model=llm_name, stream_usage=True)
mock_client = AsyncMock()
async def mock_create(*args: Any, **kwargs: Any) -> MockAsyncContextManager:
return MockAsyncContextManager(mock_deepseek_completion)
mock_client.create = mock_create
usage_chunk = mock_deepseek_completion[-1]
usage_metadata: UsageMetadata | None = None
with patch.object(llm, "async_client", mock_client):
async for chunk in llm.astream("你的名字叫什么?只回答名字"):
assert isinstance(chunk, AIMessageChunk)
if chunk.usage_metadata is not None:
usage_metadata = chunk.usage_metadata
assert usage_metadata is not None
assert usage_metadata["input_tokens"] == usage_chunk["usage"]["prompt_tokens"]
assert usage_metadata["output_tokens"] == usage_chunk["usage"]["completion_tokens"]
assert usage_metadata["total_tokens"] == usage_chunk["usage"]["total_tokens"]
def test_deepseek_stream(mock_deepseek_completion: list) -> None:
llm_name = "deepseek-chat"
llm = ChatOpenAI(model=llm_name, stream_usage=True)
mock_client = MagicMock()
def mock_create(*args: Any, **kwargs: Any) -> MockSyncContextManager:
return MockSyncContextManager(mock_deepseek_completion)
mock_client.create = mock_create
usage_chunk = mock_deepseek_completion[-1]
usage_metadata: UsageMetadata | None = None
with patch.object(llm, "client", mock_client):
for chunk in llm.stream("你的名字叫什么?只回答名字"):
assert isinstance(chunk, AIMessageChunk)
if chunk.usage_metadata is not None:
usage_metadata = chunk.usage_metadata
assert usage_metadata is not None
assert usage_metadata["input_tokens"] == usage_chunk["usage"]["prompt_tokens"]
assert usage_metadata["output_tokens"] == usage_chunk["usage"]["completion_tokens"]
assert usage_metadata["total_tokens"] == usage_chunk["usage"]["total_tokens"]
OPENAI_STREAM_DATA = """{"id":"chatcmpl-9nhARrdUiJWEMd5plwV1Gc9NCjb9M","object":"chat.completion.chunk","created":1721631035,"model":"gpt-4o-2024-05-13","system_fingerprint":"fp_18cc0f1fa0","choices":[{"index":0,"delta":{"role":"assistant","content":""},"logprobs":null,"finish_reason":null}],"usage":null}
{"id":"chatcmpl-9nhARrdUiJWEMd5plwV1Gc9NCjb9M","object":"chat.completion.chunk","created":1721631035,"model":"gpt-4o-2024-05-13","system_fingerprint":"fp_18cc0f1fa0","choices":[{"index":0,"delta":{"content":"我是"},"logprobs":null,"finish_reason":null}],"usage":null}
{"id":"chatcmpl-9nhARrdUiJWEMd5plwV1Gc9NCjb9M","object":"chat.completion.chunk","created":1721631035,"model":"gpt-4o-2024-05-13","system_fingerprint":"fp_18cc0f1fa0","choices":[{"index":0,"delta":{"content":"助手"},"logprobs":null,"finish_reason":null}],"usage":null}
{"id":"chatcmpl-9nhARrdUiJWEMd5plwV1Gc9NCjb9M","object":"chat.completion.chunk","created":1721631035,"model":"gpt-4o-2024-05-13","system_fingerprint":"fp_18cc0f1fa0","choices":[{"index":0,"delta":{"content":"。"},"logprobs":null,"finish_reason":null}],"usage":null}
{"id":"chatcmpl-9nhARrdUiJWEMd5plwV1Gc9NCjb9M","object":"chat.completion.chunk","created":1721631035,"model":"gpt-4o-2024-05-13","system_fingerprint":"fp_18cc0f1fa0","choices":[{"index":0,"delta":{},"logprobs":null,"finish_reason":"stop"}],"usage":null}
{"id":"chatcmpl-9nhARrdUiJWEMd5plwV1Gc9NCjb9M","object":"chat.completion.chunk","created":1721631035,"model":"gpt-4o-2024-05-13","system_fingerprint":"fp_18cc0f1fa0","choices":[],"usage":{"prompt_tokens":14,"completion_tokens":3,"total_tokens":17}}
[DONE]""" # noqa: E501
@pytest.fixture
def mock_openai_completion() -> list[dict]:
list_chunk_data = OPENAI_STREAM_DATA.split("\n")
result_list = []
for msg in list_chunk_data:
if msg != "[DONE]":
result_list.append(json.loads(msg))
return result_list
async def test_openai_astream(mock_openai_completion: list) -> None:
llm_name = "gpt-4o"
llm = ChatOpenAI(model=llm_name)
assert llm.stream_usage
mock_client = AsyncMock()
async def mock_create(*args: Any, **kwargs: Any) -> MockAsyncContextManager:
return MockAsyncContextManager(mock_openai_completion)
mock_client.create = mock_create
usage_chunk = mock_openai_completion[-1]
usage_metadata: UsageMetadata | None = None
with patch.object(llm, "async_client", mock_client):
async for chunk in llm.astream("你的名字叫什么?只回答名字"):
assert isinstance(chunk, AIMessageChunk)
if chunk.usage_metadata is not None:
usage_metadata = chunk.usage_metadata
assert usage_metadata is not None
assert usage_metadata["input_tokens"] == usage_chunk["usage"]["prompt_tokens"]
assert usage_metadata["output_tokens"] == usage_chunk["usage"]["completion_tokens"]
assert usage_metadata["total_tokens"] == usage_chunk["usage"]["total_tokens"]
def test_openai_stream(mock_openai_completion: list) -> None:
llm_name = "gpt-4o"
llm = ChatOpenAI(model=llm_name)
assert llm.stream_usage
mock_client = MagicMock()
call_kwargs = []
def mock_create(*args: Any, **kwargs: Any) -> MockSyncContextManager:
call_kwargs.append(kwargs)
return MockSyncContextManager(mock_openai_completion)
mock_client.create = mock_create
usage_chunk = mock_openai_completion[-1]
usage_metadata: UsageMetadata | None = None
with patch.object(llm, "client", mock_client):
for chunk in llm.stream("你的名字叫什么?只回答名字"):
assert isinstance(chunk, AIMessageChunk)
if chunk.usage_metadata is not None:
usage_metadata = chunk.usage_metadata
assert call_kwargs[-1]["stream_options"] == {"include_usage": True}
assert usage_metadata is not None
assert usage_metadata["input_tokens"] == usage_chunk["usage"]["prompt_tokens"]
assert usage_metadata["output_tokens"] == usage_chunk["usage"]["completion_tokens"]
assert usage_metadata["total_tokens"] == usage_chunk["usage"]["total_tokens"]
# Verify no streaming outside of default base URL or clients
for param, value in {
"stream_usage": False,
"openai_proxy": "http://localhost:7890",
"openai_api_base": "https://example.com/v1",
"base_url": "https://example.com/v1",
"client": mock_client,
"root_client": mock_client,
"async_client": mock_client,
"root_async_client": mock_client,
"http_client": httpx.Client(),
"http_async_client": httpx.AsyncClient(),
}.items():
llm = ChatOpenAI(model=llm_name, **{param: value}) # type: ignore[arg-type]
assert not llm.stream_usage
with patch.object(llm, "client", mock_client):
_ = list(llm.stream("..."))
assert "stream_options" not in call_kwargs[-1]
@pytest.fixture
def mock_completion() -> dict:
return {
"id": "chatcmpl-7fcZavknQda3SQ",
"object": "chat.completion",
"created": 1689989000,
"model": "gpt-3.5-turbo-0613",
"choices": [
{
"index": 0,
"message": {"role": "assistant", "content": "Bar Baz", "name": "Erick"},
"finish_reason": "stop",
}
],
}
@pytest.fixture
def mock_client(mock_completion: dict) -> MagicMock:
rtn = MagicMock()
mock_create = MagicMock()
mock_resp = MagicMock()
mock_resp.headers = {"content-type": "application/json"}
mock_resp.parse.return_value = mock_completion
mock_create.return_value = mock_resp
rtn.with_raw_response.create = mock_create
rtn.create.return_value = mock_completion
return rtn
@pytest.fixture
def mock_async_client(mock_completion: dict) -> AsyncMock:
rtn = AsyncMock()
mock_create = AsyncMock()
mock_resp = MagicMock()
mock_resp.parse.return_value = mock_completion
mock_create.return_value = mock_resp
rtn.with_raw_response.create = mock_create
rtn.create.return_value = mock_completion
return rtn
def test_openai_invoke(mock_client: MagicMock) -> None:
llm = ChatOpenAI()
with patch.object(llm, "client", mock_client):
res = llm.invoke("bar")
assert res.content == "Bar Baz"
# headers are not in response_metadata if include_response_headers not set
assert "headers" not in res.response_metadata
assert mock_client.with_raw_response.create.called
async def test_openai_ainvoke(mock_async_client: AsyncMock) -> None:
llm = ChatOpenAI()
with patch.object(llm, "async_client", mock_async_client):
res = await llm.ainvoke("bar")
assert res.content == "Bar Baz"
# headers are not in response_metadata if include_response_headers not set
assert "headers" not in res.response_metadata
assert mock_async_client.with_raw_response.create.called
@pytest.mark.parametrize(
"model",
[
"gpt-3.5-turbo",
"gpt-4",
"gpt-3.5-0125",
"gpt-4-0125-preview",
"gpt-4-turbo-preview",
"gpt-4-vision-preview",
],
)
def test__get_encoding_model(model: str) -> None:
ChatOpenAI(model=model)._get_encoding_model()
def test_openai_invoke_name(mock_client: MagicMock) -> None:
llm = ChatOpenAI()
with patch.object(llm, "client", mock_client):
messages = [HumanMessage(content="Foo", name="Katie")]
res = llm.invoke(messages)
call_args, call_kwargs = mock_client.with_raw_response.create.call_args
assert len(call_args) == 0 # no positional args
call_messages = call_kwargs["messages"]
assert len(call_messages) == 1
assert call_messages[0]["role"] == "user"
assert call_messages[0]["content"] == "Foo"
assert call_messages[0]["name"] == "Katie"
# check return type has name
assert res.content == "Bar Baz"
assert res.name == "Erick"
def test_function_calls_with_tool_calls(mock_client: MagicMock) -> None:
# Test that we ignore function calls if tool_calls are present
llm = ChatOpenAI(model="gpt-4.1-mini")
tool_call_message = AIMessage(
content="",
additional_kwargs={
"function_call": {
"name": "get_weather",
"arguments": '{"location": "Boston"}',
}
},
tool_calls=[
{
"name": "get_weather",
"args": {"location": "Boston"},
"id": "abc123",
"type": "tool_call",
}
],
)
messages = [
HumanMessage("What's the weather in Boston?"),
tool_call_message,
ToolMessage(content="It's sunny.", name="get_weather", tool_call_id="abc123"),
]
with patch.object(llm, "client", mock_client):
_ = llm.invoke(messages)
_, call_kwargs = mock_client.with_raw_response.create.call_args
call_messages = call_kwargs["messages"]
tool_call_message_payload = call_messages[1]
assert "tool_calls" in tool_call_message_payload
assert "function_call" not in tool_call_message_payload
# Test we don't ignore function calls if tool_calls are not present
cast(AIMessage, messages[1]).tool_calls = []
with patch.object(llm, "client", mock_client):
_ = llm.invoke(messages)
_, call_kwargs = mock_client.with_raw_response.create.call_args
call_messages = call_kwargs["messages"]
tool_call_message_payload = call_messages[1]
assert "function_call" in tool_call_message_payload
assert "tool_calls" not in tool_call_message_payload
def test_custom_token_counting() -> None:
def token_encoder(text: str) -> list[int]:
return [1, 2, 3]
llm = ChatOpenAI(custom_get_token_ids=token_encoder)
assert llm.get_token_ids("foo") == [1, 2, 3]
def test_format_message_content() -> None:
content: Any = "hello"
assert content == _format_message_content(content)
content = None
assert content == _format_message_content(content)
content = []
assert content == _format_message_content(content)
content = [
{"type": "text", "text": "What is in this image?"},
{"type": "image_url", "image_url": {"url": "url.com"}},
]
assert content == _format_message_content(content)
content = [
{"type": "text", "text": "hello"},
{
"type": "tool_use",
"id": "toolu_01A09q90qw90lq917835lq9",
"name": "get_weather",
"input": {"location": "San Francisco, CA", "unit": "celsius"},
},
]
assert _format_message_content(content) == [{"type": "text", "text": "hello"}]
# Standard multi-modal inputs
contents = [
{"type": "image", "source_type": "url", "url": "https://..."}, # v0
{"type": "image", "url": "https://..."}, # v1
]
expected = [{"type": "image_url", "image_url": {"url": "https://..."}}]
for content in contents:
assert expected == _format_message_content([content])
contents = [
{
"type": "image",
"source_type": "base64",
"data": "<base64 data>",
"mime_type": "image/png",
},
{"type": "image", "base64": "<base64 data>", "mime_type": "image/png"},
]
expected = [
{
"type": "image_url",
"image_url": {"url": "data:image/png;base64,<base64 data>"},
}
]
for content in contents:
assert expected == _format_message_content([content])
contents = [
{
"type": "file",
"source_type": "base64",
"data": "<base64 data>",
"mime_type": "application/pdf",
"filename": "my_file",
},
{
"type": "file",
"base64": "<base64 data>",
"mime_type": "application/pdf",
"filename": "my_file",
},
]
expected = [
{
"type": "file",
"file": {
"filename": "my_file",
"file_data": "data:application/pdf;base64,<base64 data>",
},
}
]
for content in contents:
assert expected == _format_message_content([content])
# Test warn if PDF is missing a filename
pdf_block = {
"type": "file",
"base64": "<base64 data>",
"mime_type": "application/pdf",
}
expected = [
# N.B. this format is invalid for OpenAI
{
"type": "file",
"file": {"file_data": "data:application/pdf;base64,<base64 data>"},
}
]
with pytest.warns(match="filename"):
assert expected == _format_message_content([pdf_block])
contents = [
{"type": "file", "source_type": "id", "id": "file-abc123"},
{"type": "file", "file_id": "file-abc123"},
]
expected = [{"type": "file", "file": {"file_id": "file-abc123"}}]
for content in contents:
assert expected == _format_message_content([content])
class GenerateUsername(BaseModel):
"Get a username based on someone's name and hair color."
name: str
hair_color: str
class MakeASandwich(BaseModel):
"Make a sandwich given a list of ingredients."
bread_type: str
cheese_type: str
condiments: list[str]
vegetables: list[str]
@pytest.mark.parametrize(
"tool_choice",
[
"any",
"none",
"auto",
"required",
"GenerateUsername",
{"type": "function", "function": {"name": "MakeASandwich"}},
False,
None,
],
)
@pytest.mark.parametrize("strict", [True, False, None])
def test_bind_tools_tool_choice(tool_choice: Any, strict: bool | None) -> None:
"""Test passing in manually construct tool call message."""
llm = ChatOpenAI(model="gpt-3.5-turbo-0125", temperature=0)
llm.bind_tools(
tools=[GenerateUsername, MakeASandwich], tool_choice=tool_choice, strict=strict
)
@pytest.mark.parametrize(
"schema", [GenerateUsername, GenerateUsername.model_json_schema()]
)
@pytest.mark.parametrize("method", ["json_schema", "function_calling", "json_mode"])
@pytest.mark.parametrize("include_raw", [True, False])
@pytest.mark.parametrize("strict", [True, False, None])
def test_with_structured_output(
schema: type | dict[str, Any] | None,
method: Literal["function_calling", "json_mode", "json_schema"],
include_raw: bool,
strict: bool | None,
) -> None:
"""Test passing in manually construct tool call message."""
if method == "json_mode":
strict = None
llm = ChatOpenAI(model="gpt-3.5-turbo-0125", temperature=0)
llm.with_structured_output(
schema, method=method, strict=strict, include_raw=include_raw
)
def test_get_num_tokens_from_messages() -> None:
llm = ChatOpenAI(model="gpt-4o")
messages = [
SystemMessage("you're a good assistant"),
HumanMessage("how are you"),
HumanMessage(
[
{"type": "text", "text": "what's in this image"},
{"type": "image_url", "image_url": {"url": "https://foobar.com"}},
{
"type": "image_url",
"image_url": {"url": "https://foobar.com", "detail": "low"},
},
]
),
AIMessage("a nice bird"),
AIMessage(
"",
tool_calls=[
ToolCall(id="foo", name="bar", args={"arg1": "arg1"}, type="tool_call")
],
),
AIMessage(
"",
additional_kwargs={
"function_call": {
"arguments": json.dumps({"arg1": "arg1"}),
"name": "fun",
}
},
),
AIMessage(
"text",
tool_calls=[
ToolCall(id="foo", name="bar", args={"arg1": "arg1"}, type="tool_call")
],
),
ToolMessage("foobar", tool_call_id="foo"),
]
expected = 431 # Updated to match token count with mocked 100x100 image
# Mock _url_to_size to avoid PIL dependency in unit tests
with patch("langchain_openai.chat_models.base._url_to_size") as mock_url_to_size:
mock_url_to_size.return_value = (100, 100) # 100x100 pixel image
actual = llm.get_num_tokens_from_messages(messages)
assert expected == actual
# Test file inputs
messages = [
HumanMessage(
[
"Summarize this document.",
{
"type": "file",
"file": {
"filename": "my file",
"file_data": "data:application/pdf;base64,<data>",
},
},