-
Notifications
You must be signed in to change notification settings - Fork 53
Expand file tree
/
Copy pathchat_models.py
More file actions
1799 lines (1567 loc) · 75.5 KB
/
chat_models.py
File metadata and controls
1799 lines (1567 loc) · 75.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""Databricks chat models."""
import json
import logging
import warnings
from functools import cached_property
from operator import itemgetter
from typing import (
Any,
AsyncIterator,
Callable,
Dict,
Iterator,
List,
Literal,
Mapping,
Optional,
Sequence,
Type,
Union,
cast,
)
from databricks import sdk
from langchain_core.callbacks import AsyncCallbackManagerForLLMRun, CallbackManagerForLLMRun
from langchain_core.language_models import BaseChatModel
from langchain_core.language_models.base import LanguageModelInput
from langchain_core.messages import (
AIMessage,
AIMessageChunk,
BaseMessage,
BaseMessageChunk,
ChatMessage,
ChatMessageChunk,
FunctionMessage,
HumanMessage,
HumanMessageChunk,
InputTokenDetails,
OutputTokenDetails,
SystemMessage,
SystemMessageChunk,
ToolMessage,
ToolMessageChunk,
UsageMetadata,
)
from langchain_core.messages.ai import UsageMetadata
from langchain_core.messages.tool import tool_call_chunk
from langchain_core.output_parsers import JsonOutputParser, PydanticOutputParser
from langchain_core.output_parsers.base import OutputParserLike
from langchain_core.output_parsers.openai_tools import (
JsonOutputKeyToolsParser,
PydanticToolsParser,
make_invalid_tool_call,
parse_tool_call,
)
from langchain_core.outputs import ChatGeneration, ChatGenerationChunk, ChatResult
from langchain_core.runnables import Runnable, RunnableMap, RunnablePassthrough
from langchain_core.tools import BaseTool
from langchain_core.utils.function_calling import convert_to_openai_tool
from langchain_core.utils.pydantic import is_basemodel_subclass
from openai import AsyncOpenAI, AsyncStream, OpenAI, Stream
from openai.types.chat import ChatCompletion, ChatCompletionChunk
from openai.types.completion_usage import CompletionUsage
from openai.types.responses import Response, ResponseStreamEvent, ResponseUsage
from pydantic import BaseModel, ConfigDict, Field
from typing_extensions import override
from databricks_langchain.utils import get_async_openai_client, get_openai_client
logger = logging.getLogger(__name__)
class ChatDatabricks(BaseChatModel):
"""Databricks chat model integration.
**Instantiate**:
.. code-block:: python
from databricks_langchain import ChatDatabricks
# Using default authentication (e.g., from environment variables)
llm = ChatDatabricks(
model="databricks-claude-3-7-sonnet",
temperature=0,
max_tokens=500,
timeout=30.0, # Timeout in seconds
max_retries=3, # Maximum number of retries
)
# Using a sdk.WorkspaceClient instance for custom authentication
from databricks.sdk import sdk.WorkspaceClient
workspace_client = sdk.WorkspaceClient(host="...", token="...")
llm = ChatDatabricks(
model="databricks-claude-3-7-sonnet",
workspace_client=workspace_client,
)
For Responses API endpoints like a ResponsesAgent, set ``use_responses_api=True``:
.. code-block:: python
llm = ChatDatabricks(
model="my-responses-agent-endpoint",
use_responses_api=True,
)
**Invoke**:
.. code-block:: python
messages = [
("system", "You are a helpful translator. Translate the user sentence to French."),
("human", "I love programming."),
]
llm.invoke(messages)
.. code-block:: python
AIMessage(
content="J'adore la programmation.",
response_metadata={"prompt_tokens": 32, "completion_tokens": 9, "total_tokens": 41},
id="run-64eebbdd-88a8-4a25-b508-21e9a5f146c5-0",
)
**Stream**:
.. code-block:: python
for chunk in llm.stream(messages):
print(chunk)
.. code-block:: python
content='J' id='run-609b8f47-e580-4691-9ee4-e2109f53155e'
content="'" id='run-609b8f47-e580-4691-9ee4-e2109f53155e'
content='ad' id='run-609b8f47-e580-4691-9ee4-e2109f53155e'
content='ore' id='run-609b8f47-e580-4691-9ee4-e2109f53155e'
content=' la' id='run-609b8f47-e580-4691-9ee4-e2109f53155e'
content=' programm' id='run-609b8f47-e580-4691-9ee4-e2109f53155e'
content='ation' id='run-609b8f47-e580-4691-9ee4-e2109f53155e'
content='.' id='run-609b8f47-e580-4691-9ee4-e2109f53155e'
content='' response_metadata={'finish_reason': 'stop'} id='run-609b8f47-e580-4691-9ee4-e2109f53155e'
.. code-block:: python
stream = llm.stream(messages)
full = next(stream)
for chunk in stream:
full += chunk
full
.. code-block:: python
AIMessageChunk(
content="J'adore la programmation.",
response_metadata={"finish_reason": "stop"},
id="run-4cef851f-6223-424f-ad26-4a54e5852aa5",
)
To get token usage returned when streaming, pass the ``stream_usage`` kwarg:
.. code-block:: python
stream = llm.stream(messages, stream_usage=True)
next(stream).usage_metadata
.. code-block:: python
{"input_tokens": 28, "output_tokens": 5, "total_tokens": 33}
Alternatively, setting ``stream_usage`` when instantiating the model can be
useful when incorporating ``ChatDatabricks`` into LCEL chains-- or when using
methods like ``.with_structured_output``, which generate chains under the
hood.
.. code-block:: python
llm = ChatDatabricks(model="databricks-claude-3-7-sonnet", stream_usage=True)
structured_llm = llm.with_structured_output(...)
**Async**:
.. code-block:: python
await llm.ainvoke(messages)
# stream:
# async for chunk in llm.astream(messages)
# batch:
# await llm.abatch([messages])
.. code-block:: python
AIMessage(
content="J'adore la programmation.",
response_metadata={"prompt_tokens": 32, "completion_tokens": 9, "total_tokens": 41},
id="run-e4bb043e-772b-4e1d-9f98-77ccc00c0271-0",
)
**Tool calling**:
.. code-block:: python
from pydantic import BaseModel, Field
class GetWeather(BaseModel):
'''Get the current weather in a given location'''
location: str = Field(..., description="The city and state, e.g. San Francisco, CA")
class GetPopulation(BaseModel):
'''Get the current population in a given location'''
location: str = Field(..., description="The city and state, e.g. San Francisco, CA")
llm_with_tools = llm.bind_tools([GetWeather, GetPopulation])
ai_msg = llm_with_tools.invoke(
"Which city is hotter today and which is bigger: LA or NY?"
)
ai_msg.tool_calls
.. code-block:: python
[
{
"name": "GetWeather",
"args": {"location": "Los Angeles, CA"},
"id": "call_ea0a6004-8e64-4ae8-a192-a40e295bfa24",
"type": "tool_call",
}
]
To use tool calls, your model endpoint must support ``tools`` parameter. See [Function calling on Databricks](https://python.langchain.com/docs/integrations/chat/databricks/#function-calling-on-databricks) for more information.
**Custom inputs and outputs**:
Pass additional context or configuration to the model using the ``custom_inputs`` keyword argument.
Access model-specific metadata from the ``custom_outputs`` attribute of the response.
.. code-block:: python
# Pass custom inputs to the model
messages = [("human", "Hello, how are you?")]
custom_inputs = {"user_id": "12345", "session_id": "abc123"}
response = llm.invoke(messages, custom_inputs=custom_inputs)
print(response.content)
# Access custom outputs from the response (if provided by the model)
if hasattr(response, "custom_outputs"):
print(f"Custom outputs: {response.custom_outputs}")
.. code-block:: python
# Custom inputs also work with streaming
for chunk in llm.stream(messages, custom_inputs=custom_inputs):
print(chunk.content, end="")
# Check for custom outputs in chunks
if hasattr(chunk, "custom_outputs"):
print(f"Custom outputs: {chunk.custom_outputs}")
""" # noqa: E501
model_config = ConfigDict(populate_by_name=True)
model: str = Field(alias="endpoint")
"""Name of Databricks Model Serving endpoint to query."""
target_uri: Optional[str] = None
"""The target MLflow deployment URI to use. Deprecated: use workspace_client instead."""
workspace_client: Optional[sdk.WorkspaceClient] = Field(default=None, exclude=True)
"""Optional WorkspaceClient instance to use for authentication. If not provided, uses default authentication."""
temperature: Optional[float] = None
"""Sampling temperature. Higher values make the model more creative."""
n: int = 1
"""The number of completion choices to generate."""
stop: Optional[List[str]] = None
"""List of strings to stop generation at."""
max_tokens: Optional[int] = None
"""The maximum number of tokens to generate."""
extra_params: Optional[Dict[str, Any]] = None
"""Whether to include usage metadata in streaming output. If True, additional
message chunks will be generated during the stream including usage metadata.
"""
stream_usage: bool = True
"""Any extra parameters to pass to the endpoint."""
use_responses_api: bool = False
"""Whether to use the Responses API to format inputs and outputs."""
timeout: Optional[float] = None
"""Timeout in seconds for the HTTP request. If None, uses the default timeout."""
max_retries: Optional[int] = None
"""Maximum number of retries for failed requests. If None, uses the default retry count."""
@property
def endpoint(self) -> str:
warnings.warn(
"The `endpoint` attribute is deprecated and will be removed in a future version. "
"Use `model` instead.",
DeprecationWarning,
stacklevel=2,
)
return self.model
@endpoint.setter
def endpoint(self, value: str) -> None:
warnings.warn(
"The `endpoint` attribute is deprecated and will be removed in a future version. "
"Use `model` instead.",
DeprecationWarning,
stacklevel=2,
)
self.model = value
def _get_client_kwargs(self) -> Dict[str, Any]:
"""Prepare kwargs for OpenAI client initialization."""
openai_kwargs = {}
if self.timeout is not None:
openai_kwargs["timeout"] = self.timeout
if self.max_retries is not None:
openai_kwargs["max_retries"] = self.max_retries
return openai_kwargs
@cached_property
def client(self) -> OpenAI:
# Always use OpenAI client (supports both chat completions and responses API)
return get_openai_client(
workspace_client=self.workspace_client, **self._get_client_kwargs()
)
@cached_property
def async_client(self) -> AsyncOpenAI:
# Async OpenAI client using AsyncDatabricksOpenAI from databricks-openai
return get_async_openai_client(
workspace_client=self.workspace_client, **self._get_client_kwargs()
)
def __init__(self, **kwargs: Any):
super().__init__(**kwargs)
# Handle deprecated target_uri parameter
if self.target_uri:
warnings.warn(
"The 'target_uri' parameter is deprecated and will be removed in a future version. "
"Use 'workspace_client' parameter instead.",
DeprecationWarning,
stacklevel=2,
)
if self.workspace_client:
raise ValueError(
"Cannot specify both 'workspace_client' and 'target_uri'. "
"Please use 'workspace_client' only."
)
self.use_responses_api = kwargs.get("use_responses_api", False)
self.extra_params = self.extra_params or {}
@property
def _default_params(self) -> Dict[str, Any]:
exclude_if_none = {
"temperature": self.temperature,
"n": self.n,
"stop": self.stop,
"max_tokens": self.max_tokens,
"extra_params": self.extra_params,
}
params = {
"model": self.model,
**{k: v for k, v in exclude_if_none.items() if v is not None},
}
return params
def _generate(
self,
messages: List[BaseMessage],
stop: Optional[List[str]] = None,
run_manager: Optional[CallbackManagerForLLMRun] = None,
*,
custom_inputs: Optional[Dict[str, Any]] = None,
**kwargs: Any,
) -> ChatResult:
data = self._prepare_inputs(messages, stop, custom_inputs=custom_inputs, **kwargs)
if self.use_responses_api:
# Use OpenAI client with responses API
resp = self.client.responses.create(**data)
return self._convert_responses_api_response_to_chat_result(resp)
else:
# Use OpenAI client with chat completions API
resp = self.client.chat.completions.create(**data)
return self._convert_response_to_chat_result(resp)
async def _agenerate(
self,
messages: List[BaseMessage],
stop: Optional[List[str]] = None,
run_manager: Optional[AsyncCallbackManagerForLLMRun] = None,
*,
custom_inputs: Optional[Dict[str, Any]] = None,
**kwargs: Any,
) -> ChatResult:
data = self._prepare_inputs(messages, stop, custom_inputs=custom_inputs, **kwargs)
if self.use_responses_api:
# Use async OpenAI client with responses API
resp = await self.async_client.responses.create(**data)
return self._convert_responses_api_response_to_chat_result(resp)
else:
# Use async OpenAI client with chat completions API
resp = await self.async_client.chat.completions.create(**data)
return self._convert_response_to_chat_result(resp)
def _prepare_inputs(
self,
messages: List[BaseMessage],
stop: Optional[List[str]] = None,
stream: bool = False,
*,
custom_inputs: Optional[Dict[str, Any]] = None,
**kwargs: Any,
) -> Dict[str, Any]:
data: Dict[str, Any] = {
"model": self.model,
"stream": stream,
**(self.extra_params or {}),
**kwargs,
}
if custom_inputs is not None:
data["extra_body"] = {
"custom_inputs": custom_inputs,
}
# Format data based on whether we're using responses API or chat completions
if self.use_responses_api:
# Responses API expects "input" parameter and has different supported parameters
data["input"] = _convert_lc_messages_to_responses_api(messages)
# Responses API only supports temperature, not max_tokens, stop, or n
if self.temperature is not None:
data["temperature"] = self.temperature
# Convert tools from Chat Completions format to Responses API format
if "tools" in data:
data["tools"] = [
{
"type": "function",
"name": t["function"]["name"],
"description": t["function"].get("description", ""),
"parameters": t["function"].get("parameters", {}),
}
if "function" in t
else t
for t in data["tools"]
]
else:
# Chat completions API expects "messages" parameter
data["messages"] = [_convert_message_to_dict(msg) for msg in messages]
if self.temperature is not None:
data["temperature"] = self.temperature
if stop := self.stop or stop:
data["stop"] = stop
if self.max_tokens is not None:
data["max_tokens"] = self.max_tokens
if self.n != 1:
data["n"] = self.n
return data
def _convert_responses_api_response_to_chat_result(self, response: Response) -> ChatResult:
"""
A Responses API response has an array of messages, but a ChatResult can only have a single message.
To accomodate this, we combine the messages into a single message, following LangChain convention.
"""
# Handle error response
if response.error:
raise ValueError(response.error)
# Combine all content and tool calls from output items
content_blocks = []
tool_calls = []
invalid_tool_calls = []
for item in response.output:
if item.type == "message":
if item.content is not None: # ty:ignore[unresolved-attribute]: astral-sh/ty#1479 should fix this
for content in item.content: # ty:ignore[unresolved-attribute]: astral-sh/ty#1479 should fix this
if content.type == "output_text":
annotations = []
if content.annotations: # ty:ignore[unresolved-attribute]: astral-sh/ty#1479 should fix this
# Convert annotation objects to dictionaries
annotations = [
ann.model_dump() if hasattr(ann, "model_dump") else ann
for ann in content.annotations # ty:ignore[unresolved-attribute]: astral-sh/ty#1479 should fix this
]
content_blocks.append(
{
"type": "text",
"text": content.text, # ty:ignore[unresolved-attribute]: astral-sh/ty#1479 should fix this
"annotations": annotations,
"id": getattr(content, "id", None),
}
)
elif content.type == "refusal":
content_blocks.append(
{
"type": "refusal",
"refusal": content.refusal, # ty:ignore[unresolved-attribute]: astral-sh/ty#1479 should fix this
"id": getattr(content, "id", None),
}
)
elif item.type == "function_call":
# Convert to dict for content_blocks to maintain backward compatibility
item_dict = {
"type": "function_call",
"name": item.name, # ty:ignore[unresolved-attribute]: astral-sh/ty#1479 should fix this
"arguments": item.arguments, # ty:ignore[unresolved-attribute]: astral-sh/ty#1479 should fix this
"call_id": item.call_id, # ty:ignore[unresolved-attribute]: astral-sh/ty#1479 should fix this
}
content_blocks.append(item_dict)
try:
args = json.loads(item.arguments, strict=False) # ty:ignore[unresolved-attribute, invalid-argument-type]: astral-sh/ty#1479 should fix this
error = None
except json.JSONDecodeError as e:
error = str(e)
args = item.arguments # ty:ignore[unresolved-attribute]: astral-sh/ty#1479 should fix this
if error is None:
tool_calls.append(
{
"type": "tool_call",
"name": item.name, # ty:ignore[unresolved-attribute]: astral-sh/ty#1479 should fix this
"args": args,
"id": item.call_id, # ty:ignore[unresolved-attribute]: astral-sh/ty#1479 should fix this
}
)
else:
invalid_tool_calls.append(
{
"type": "invalid_tool_call",
"name": item.name, # ty:ignore[unresolved-attribute]: astral-sh/ty#1479 should fix this
"args": args,
"id": item.call_id, # ty:ignore[unresolved-attribute]: astral-sh/ty#1479 should fix this
"error": error,
}
)
elif item.type == "function_call_output":
content_blocks.append(
{
"role": "tool",
"content": item.output,
"tool_call_id": item.call_id,
}
)
elif item.type in (
"reasoning",
"web_search_call",
"file_search_call",
"computer_call",
"code_interpreter_call",
"mcp_call",
"mcp_list_tools",
"mcp_approval_request",
"image_generation_call",
):
# For these special types, convert to dict if possible.
# Use exclude_none to drop default None fields (e.g. status, namespace)
# that FMAPI rejects as unknown parameters.
if hasattr(item, "model_dump"):
content_blocks.append(item.model_dump(exclude_none=True))
else:
content_blocks.append(item)
usage_metadata = None
if response.usage is not None:
usage_metadata = ChatDatabricks._convert_responses_usage_to_usage_metadata(
response.usage
)
# Create AI message with combined content and tool calls
message = AIMessage(
content=content_blocks,
tool_calls=tool_calls,
invalid_tool_calls=invalid_tool_calls,
id=response.id,
usage_metadata=usage_metadata,
)
if hasattr(response, "custom_outputs"):
message.custom_outputs = response.custom_outputs # ty:ignore[unresolved-attribute]
return ChatResult(generations=[ChatGeneration(message=message)])
def _convert_chatagent_response_to_chat_result(self, response: Any) -> ChatResult:
"""
A ChatAgent response has an array of messages, but a ChatResult can only have a single message.
To accomodate this, we combine the messages into a single message, following LangChain convention.
ex: https://github.com/langchain-ai/langchain/blob/2d3020f6cd9d3bf94738f2b6732b68acc55d9cce/libs/partners/openai/langchain_openai/chat_models/base.py#L3739
"""
# Since we only enter this when response.messages exists, we can directly access it
messages = response.messages
message = AIMessage(content=messages, id=getattr(response, "id", None))
if hasattr(response, "custom_outputs"):
message.custom_outputs = response.custom_outputs # ty:ignore[unresolved-attribute]
return ChatResult(generations=[ChatGeneration(message=message)])
@staticmethod
def _convert_completion_usage_to_usage_metadata(usage: CompletionUsage) -> UsageMetadata:
if usage.prompt_tokens_details is not None:
# Most likely an OpenAI Model
input_token_details = None
if usage.prompt_tokens_details:
input_token_details = InputTokenDetails(
audio=usage.prompt_tokens_details.audio_tokens or 0,
cache_read=usage.prompt_tokens_details.cached_tokens or 0,
)
output_token_details = None
if usage.completion_tokens_details is not None:
output_token_details = OutputTokenDetails(
reasoning=usage.completion_tokens_details.reasoning_tokens or 0,
audio=usage.completion_tokens_details.audio_tokens or 0,
)
result: UsageMetadata = {
"input_tokens": usage.prompt_tokens or 0,
"output_tokens": usage.completion_tokens or 0,
"total_tokens": usage.total_tokens or 0,
}
if input_token_details is not None:
result["input_token_details"] = input_token_details
if output_token_details is not None:
result["output_token_details"] = output_token_details
return result
elif getattr(usage, "cache_read_input_tokens", None) is not None:
# Most likely Claude Model
cache_read_input_tokens = getattr(usage, "cache_read_input_tokens", None) or 0
cache_creation_input_tokens = getattr(usage, "cache_creation_input_tokens", None) or 0
usage_metadata = UsageMetadata(
input_tokens=(usage.prompt_tokens or 0)
+ cache_read_input_tokens
+ cache_creation_input_tokens,
output_tokens=usage.completion_tokens or 0,
total_tokens=usage.total_tokens or 0,
input_token_details=InputTokenDetails(
cache_read=cache_read_input_tokens, cache_creation=cache_creation_input_tokens
),
)
return usage_metadata
else:
return UsageMetadata(
input_tokens=usage.prompt_tokens or 0,
output_tokens=usage.completion_tokens or 0,
total_tokens=usage.total_tokens or 0,
)
@staticmethod
def _convert_responses_usage_to_usage_metadata(usage: ResponseUsage) -> UsageMetadata:
input_token_details = None
if usage.input_tokens_details is not None:
input_token_details = InputTokenDetails(
cache_read=usage.input_tokens_details.cached_tokens or 0,
)
output_token_details = None
if usage.output_tokens_details is not None:
output_token_details = OutputTokenDetails(
reasoning=usage.output_tokens_details.reasoning_tokens or 0,
)
return UsageMetadata(
input_tokens=usage.input_tokens,
output_tokens=usage.output_tokens,
total_tokens=usage.total_tokens,
input_token_details=input_token_details,
output_token_details=output_token_details,
)
def _convert_response_to_chat_result(self, response: ChatCompletion) -> ChatResult:
# Check if this is a ChatAgent response (has messages but no choices)
if (
hasattr(response, "choices")
and response.choices is None
and hasattr(response, "messages")
):
return self._convert_chatagent_response_to_chat_result(response)
generations = []
for choice in response.choices:
message_dict = choice.message.model_dump(exclude_unset=True)
# Ensure content is not None
if message_dict.get("content") is None:
message_dict["content"] = ""
generation_info = {}
if choice.finish_reason:
generation_info["finish_reason"] = choice.finish_reason
generations.append(
ChatGeneration(
message=_convert_dict_to_message(message_dict, response.usage),
generation_info=generation_info,
)
)
llm_output = {}
if response.usage:
llm_output["usage"] = {
"prompt_tokens": response.usage.prompt_tokens,
"completion_tokens": response.usage.completion_tokens,
"total_tokens": response.usage.total_tokens,
}
# Add individual token counts for backwards compatibility with tests
llm_output["prompt_tokens"] = response.usage.prompt_tokens
llm_output["completion_tokens"] = response.usage.completion_tokens
llm_output["total_tokens"] = response.usage.total_tokens
if response.model:
llm_output["model"] = response.model
llm_output["model_name"] = response.model
return ChatResult(generations=generations, llm_output=llm_output)
def _extract_response_usage_from_chunk(
self, chunk: Any, stream_usage: bool
) -> Optional[ResponseUsage | Dict[str, int]]:
"""Extract usage information from a chunk if available.
Args:
chunk: The chunk to extract usage from
stream_usage: Whether to extract usage information
Returns:
Dictionary with usage info or None if not available
"""
if hasattr(chunk, "response"):
response = chunk.response
if (
hasattr(response, "usage")
and response.usage is not None
and stream_usage
and isinstance(response.usage, ResponseUsage)
):
return response.usage
if not stream_usage or not hasattr(chunk, "usage") or not chunk.usage:
return None
input_tokens = getattr(chunk.usage, "prompt_tokens", None)
output_tokens = getattr(chunk.usage, "completion_tokens", None)
if input_tokens is not None and output_tokens is not None:
return {
"input_tokens": input_tokens,
"output_tokens": output_tokens,
"total_tokens": input_tokens + output_tokens,
}
return None
def _extract_completion_usage_from_chunk(
self, chunk: Any, stream_usage: bool
) -> Optional[CompletionUsage | Dict[str, int]]:
if not stream_usage or not hasattr(chunk, "usage") or not chunk.usage:
return None
if isinstance(chunk.usage, CompletionUsage):
return chunk.usage
input_tokens = getattr(chunk.usage, "prompt_tokens", None)
output_tokens = getattr(chunk.usage, "completion_tokens", None)
if input_tokens is not None and output_tokens is not None:
return {
"input_tokens": input_tokens,
"output_tokens": output_tokens,
"total_tokens": input_tokens + output_tokens,
}
return None
def _build_usage_chunk_from_completions(
self, usage: CompletionUsage | Dict[str, int]
) -> ChatGenerationChunk:
"""Build a usage metadata chunk.
Args:
usage: Dictionary containing input_tokens, output_tokens, and total_tokens
Returns:
ChatGenerationChunk with usage metadata
"""
if isinstance(usage, CompletionUsage):
return ChatGenerationChunk(
message=AIMessageChunk(
content="",
usage_metadata=ChatDatabricks._convert_completion_usage_to_usage_metadata(
usage
),
)
)
else:
return ChatGenerationChunk(
message=AIMessageChunk(
content="",
usage_metadata=UsageMetadata(
input_tokens=usage["input_tokens"],
output_tokens=usage["output_tokens"],
total_tokens=usage["total_tokens"],
),
)
)
def _build_usage_chunk_from_responses(
self, usage: ResponseUsage | Dict[str, int]
) -> ChatGenerationChunk:
"""Build a usage metadata chunk.
Args:
usage: Dictionary containing input_tokens, output_tokens, and total_tokens
Returns:
ChatGenerationChunk with usage metadata
"""
if isinstance(usage, ResponseUsage):
return ChatGenerationChunk(
message=AIMessageChunk(
content="",
usage_metadata=ChatDatabricks._convert_responses_usage_to_usage_metadata(usage),
)
)
else:
return ChatGenerationChunk(
message=AIMessageChunk(
content="",
usage_metadata=UsageMetadata(
input_tokens=usage["input_tokens"],
output_tokens=usage["output_tokens"],
total_tokens=usage["total_tokens"],
),
)
)
def _stream(
self,
messages: List[BaseMessage],
stop: Optional[List[str]] = None,
run_manager: Optional[CallbackManagerForLLMRun] = None,
*,
stream_usage: Optional[bool] = None,
custom_inputs: Optional[Dict[str, Any]] = None,
**kwargs: Any,
) -> Iterator[ChatGenerationChunk]:
if stream_usage is None:
stream_usage = self.stream_usage
data = self._prepare_inputs(
messages, stop, stream=True, custom_inputs=custom_inputs, **kwargs
)
usage_chunk_emitted = False
final_usage: ResponseUsage | CompletionUsage | dict[str, int] | None = None
if self.use_responses_api:
prev_chunk = None
stream: Stream[ResponseStreamEvent] = self.client.responses.create(**data)
for chunk in stream:
chunk_message = _convert_responses_api_chunk_to_lc_chunk(chunk, prev_chunk)
prev_chunk = chunk
if chunk_message:
yield ChatGenerationChunk(message=chunk_message)
# Check for usage in the chunk if available
usage = self._extract_response_usage_from_chunk(chunk, stream_usage)
if usage:
final_usage = usage
# Emit special usage chunk at end of stream
if stream_usage and final_usage and not usage_chunk_emitted:
yield self._build_usage_chunk_from_responses(final_usage)
usage_chunk_emitted = True
else:
first_chunk_role = None
stream: Stream[ChatCompletionChunk] = self.client.chat.completions.create(**data)
for chunk in stream:
# Handle ChatAgent chunks that don't have choices but have delta
if hasattr(chunk, "choices") and chunk.choices is None and hasattr(chunk, "delta"):
delta = chunk.delta
chunk_delta_dict = {
"role": delta.get("role"),
"content": delta.get("content", ""),
}
if hasattr(chunk, "custom_outputs"):
chunk_delta_dict["custom_outputs"] = chunk.custom_outputs
chunk_message = _convert_dict_to_message_chunk(
chunk_delta_dict, first_chunk_role
)
generation_chunk = ChatGenerationChunk(message=chunk_message)
if run_manager:
run_manager.on_llm_new_token(
generation_chunk.text,
chunk=generation_chunk,
)
yield generation_chunk
elif chunk.choices:
choice = chunk.choices[0]
chunk_delta = choice.delta
if first_chunk_role is None:
first_chunk_role = chunk_delta.role
usage = None
# Collect usage info only if both are present
usage = self._extract_completion_usage_from_chunk(chunk, stream_usage)
if usage:
final_usage = usage # store for usage chunk at end
# Use model_dump instead of manual dict reconstruction
chunk_delta_dict = chunk_delta.model_dump(exclude_unset=True)
chunk_message = _convert_dict_to_message_chunk(
chunk_delta_dict, first_chunk_role, usage=usage
)
generation_info = {}
if choice.finish_reason:
generation_info["finish_reason"] = choice.finish_reason
if choice.logprobs:
generation_info["logprobs"] = choice.logprobs
generation_chunk = ChatGenerationChunk(
message=chunk_message, generation_info=generation_info or None
)
if run_manager:
run_manager.on_llm_new_token(
generation_chunk.text,
chunk=generation_chunk,
logprobs=generation_info.get("logprobs"),
)
yield generation_chunk
elif chunk.usage and stream_usage:
# Some models send a final chunk that does not have
# a delta or choices, but does have usage info
if not usage_chunk_emitted:
usage = self._extract_completion_usage_from_chunk(chunk, stream_usage)
if usage:
final_usage = usage
# Emit special usage chunk at end of stream
if stream_usage and final_usage and not usage_chunk_emitted:
yield self._build_usage_chunk_from_completions(final_usage)
usage_chunk_emitted = True
async def _astream(
self,
messages: List[BaseMessage],
stop: Optional[List[str]] = None,
run_manager: Optional[AsyncCallbackManagerForLLMRun] = None,
*,
stream_usage: Optional[bool] = None,
custom_inputs: Optional[Dict[str, Any]] = None,
**kwargs: Any,
) -> AsyncIterator[ChatGenerationChunk]:
if stream_usage is None:
stream_usage = self.stream_usage
data = self._prepare_inputs(
messages, stop, stream=True, custom_inputs=custom_inputs, **kwargs
)
usage_chunk_emitted = False
final_usage: ResponseUsage | CompletionUsage | dict[str, int] | None = None
if self.use_responses_api:
prev_chunk = None
stream = cast(
AsyncStream[ResponseStreamEvent],
await self.async_client.responses.create(**data),
)
async for chunk in stream:
chunk_message = _convert_responses_api_chunk_to_lc_chunk(chunk, prev_chunk)
prev_chunk = chunk
if chunk_message:
yield ChatGenerationChunk(message=chunk_message)
# Check for usage in the chunk if available
usage = self._extract_response_usage_from_chunk(chunk, stream_usage)
if usage:
final_usage = usage
# Emit special usage chunk at end of stream
if stream_usage and final_usage and not usage_chunk_emitted:
yield self._build_usage_chunk_from_responses(final_usage)
usage_chunk_emitted = True
else:
first_chunk_role = None
stream = cast(
AsyncStream[ChatCompletionChunk],
await self.async_client.chat.completions.create(**data),
)
async for chunk in stream:
# Handle ChatAgent chunks that don't have choices but have delta
if hasattr(chunk, "choices") and chunk.choices is None and hasattr(chunk, "delta"):
delta = chunk.delta
chunk_delta_dict = {
"role": delta.get("role"),
"content": delta.get("content", ""),
}
if hasattr(chunk, "custom_outputs"):