forked from google/adk-python
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlite_llm.py
More file actions
2500 lines (2124 loc) · 78.1 KB
/
lite_llm.py
File metadata and controls
2500 lines (2124 loc) · 78.1 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
# Copyright 2026 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from __future__ import annotations
import base64
import binascii
import copy
import importlib.util
import json
import logging
import mimetypes
import os
import re
import sys
from typing import Any
from typing import AsyncGenerator
from typing import cast
from typing import Dict
from typing import Generator
from typing import Iterable
from typing import List
from typing import Literal
from typing import Optional
from typing import Tuple
from typing import TYPE_CHECKING
from typing import TypedDict
from typing import Union
from urllib.parse import urlparse
import uuid
import warnings
from google.genai import types
if not TYPE_CHECKING and importlib.util.find_spec("litellm") is None:
raise ImportError(
"LiteLLM support requires: pip install google-adk[extensions]"
)
from pydantic import BaseModel
from pydantic import Field
from typing_extensions import override
from ..utils._google_client_headers import merge_tracking_headers
from .base_llm import BaseLlm
from .llm_request import LlmRequest
from .llm_response import LlmResponse
if TYPE_CHECKING:
import litellm
from litellm import acompletion
from litellm import ChatCompletionAssistantMessage
from litellm import ChatCompletionAssistantToolCall
from litellm import ChatCompletionMessageToolCall
from litellm import ChatCompletionSystemMessage
from litellm import ChatCompletionToolMessage
from litellm import ChatCompletionUserMessage
from litellm import completion
from litellm import CustomStreamWrapper
from litellm import Function
from litellm import Message
from litellm import ModelResponse
from litellm import ModelResponseStream
from litellm import OpenAIMessageContent
from litellm.types.utils import Delta
else:
litellm = None
acompletion = None
ChatCompletionAssistantMessage = None
ChatCompletionAssistantToolCall = None
ChatCompletionMessageToolCall = None
ChatCompletionSystemMessage = None
ChatCompletionToolMessage = None
ChatCompletionUserMessage = None
completion = None
CustomStreamWrapper = None
Function = None
Message = None
ModelResponse = None
Delta = None
OpenAIMessageContent = None
ModelResponseStream = None
logger = logging.getLogger("google_adk." + __name__)
_NEW_LINE = "\n"
_EXCLUDED_PART_FIELD = {"inline_data": {"data"}}
_LITELLM_STRUCTURED_TYPES = {"json_object", "json_schema"}
_JSON_DECODER = json.JSONDecoder()
# Mapping of major MIME type prefixes to LiteLLM content types for URL blocks.
_MEDIA_URL_CONTENT_TYPE_BY_MAJOR_MIME_TYPE = {
"image": "image_url",
"video": "video_url",
"audio": "audio_url",
}
# Mapping of LiteLLM finish_reason strings to FinishReason enum values
# Note: tool_calls/function_call map to STOP because:
# 1. FinishReason.TOOL_CALL enum does not exist (as of google-genai 0.8.0)
# 2. Tool calls represent normal completion (model stopped to invoke tools)
# 3. Gemini native responses use STOP for tool calls (see lite_llm.py:910)
_FINISH_REASON_MAPPING = {
"length": types.FinishReason.MAX_TOKENS,
"stop": types.FinishReason.STOP,
"tool_calls": (
types.FinishReason.STOP
), # Normal completion with tool invocation
"function_call": types.FinishReason.STOP, # Legacy function call variant
"content_filter": types.FinishReason.SAFETY,
}
# File MIME types supported for upload as file content (not decoded as text).
# Note: text/* types are handled separately and decoded as text content.
# These types are uploaded as files to providers that support it.
_SUPPORTED_FILE_CONTENT_MIME_TYPES = frozenset({
# Documents
"application/pdf",
"application/msword", # .doc
"application/vnd.openxmlformats-officedocument.wordprocessingml.document", # .docx
"application/vnd.openxmlformats-officedocument.presentationml.presentation", # .pptx
# Data formats
"application/json",
# Scripts (when not detected as text/*)
"application/x-sh", # .sh (Python mimetypes returns this)
})
# Providers that require file_id instead of inline file_data
_FILE_ID_REQUIRED_PROVIDERS = frozenset({"openai", "azure"})
_MISSING_TOOL_RESULT_MESSAGE = (
"Error: Missing tool result (tool execution may have been interrupted "
"before a response was recorded)."
)
# Separator LiteLLM uses to embed thought_signature in tool call IDs.
# Gemini's thoughtSignature requirement is documented here:
# https://ai.google.dev/gemini-api/docs/thought-signatures
_THOUGHT_SIGNATURE_SEPARATOR = "__thought__"
_LITELLM_IMPORTED = False
_LITELLM_GLOBAL_SYMBOLS = (
"ChatCompletionAssistantMessage",
"ChatCompletionAssistantToolCall",
"ChatCompletionMessageToolCall",
"ChatCompletionSystemMessage",
"ChatCompletionToolMessage",
"ChatCompletionUserMessage",
"CustomStreamWrapper",
"Function",
"Message",
"ModelResponse",
"ModelResponseStream",
"OpenAIMessageContent",
"acompletion",
"completion",
)
def _ensure_litellm_imported() -> None:
"""Imports LiteLLM with safe defaults.
LiteLLM defaults to DEV mode, which autoloads a local `.env` at import time.
ADK should not implicitly load `.env` just because LiteLLM is installed.
Users can opt into LiteLLM's default behavior by setting LITELLM_MODE=DEV.
"""
global _LITELLM_IMPORTED
if _LITELLM_IMPORTED:
return
# https://github.com/BerriAI/litellm/blob/main/litellm/__init__.py#L80-L82
os.environ.setdefault("LITELLM_MODE", "PRODUCTION")
import litellm as litellm_module
litellm_module.add_function_to_prompt = True
globals()["litellm"] = litellm_module
for symbol in _LITELLM_GLOBAL_SYMBOLS:
globals()[symbol] = getattr(litellm_module, symbol)
_redirect_litellm_loggers_to_stdout()
_LITELLM_IMPORTED = True
def _map_finish_reason(
finish_reason: Any,
) -> types.FinishReason | None:
"""Maps a LiteLLM finish_reason value to a google-genai FinishReason enum."""
if not finish_reason:
return None
if isinstance(finish_reason, types.FinishReason):
return finish_reason
finish_reason_str = str(finish_reason).lower()
return _FINISH_REASON_MAPPING.get(finish_reason_str, types.FinishReason.OTHER)
def _get_provider_from_model(model: str) -> str:
"""Extracts the provider name from a LiteLLM model string.
Args:
model: The model string (e.g., "openai/gpt-4o", "azure/gpt-4").
Returns:
The provider name or empty string if not determinable.
"""
if not model:
return ""
# LiteLLM uses "provider/model" format
if "/" in model:
provider, _ = model.split("/", 1)
return provider.lower()
# Fallback heuristics for common patterns
model_lower = model.lower()
if "azure" in model_lower:
return "azure"
# Note: The 'openai' check is based on current naming conventions (e.g., gpt-, o1).
# This might need updates if OpenAI introduces new model families with different prefixes.
if model_lower.startswith("gpt-") or model_lower.startswith("o1"):
return "openai"
return ""
# Default MIME type when none can be inferred
_DEFAULT_MIME_TYPE = "application/octet-stream"
def _infer_mime_type_from_uri(uri: str) -> Optional[str]:
"""Attempts to infer MIME type from a URI's path extension.
Args:
uri: A URI string (e.g., 'gs://bucket/file.pdf' or
'https://example.com/doc.json')
Returns:
The inferred MIME type, or None if it cannot be determined.
"""
try:
parsed = urlparse(uri)
# Get the path component and extract filename
path = parsed.path
if not path:
return None
# Many artifact URIs are versioned (for example, ".../filename/0" or
# ".../filename/versions/0"). If the last path segment looks like a numeric
# version, infer from the preceding filename instead.
segments = [segment for segment in path.split("/") if segment]
if not segments:
return None
candidate = segments[-1]
if candidate.isdigit():
segments = segments[:-1]
if segments and segments[-1].lower() in ("versions", "version"):
segments = segments[:-1]
if not segments:
return None
candidate = segments[-1]
mime_type, _ = mimetypes.guess_type(candidate)
return mime_type
except (ValueError, AttributeError) as e:
logger.debug("Could not infer MIME type from URI %s: %s", uri, e)
return None
def _looks_like_openai_file_id(file_uri: str) -> bool:
"""Returns True when file_uri resembles an OpenAI/Azure file id."""
return file_uri.startswith("file-")
def _is_http_url(uri: str) -> bool:
"""Returns True when `uri` is an HTTP(S) URL."""
try:
parsed = urlparse(uri)
except ValueError:
return False
return parsed.scheme in ("http", "https")
def _redact_file_uri_for_log(
file_uri: str, *, display_name: str | None = None
) -> str:
"""Returns a privacy-preserving identifier for logs."""
if display_name:
return display_name
if _looks_like_openai_file_id(file_uri):
return "file-<redacted>"
try:
parsed = urlparse(file_uri)
except ValueError:
return "<unparseable>"
if not parsed.scheme:
return "<unknown>"
segments = [segment for segment in parsed.path.split("/") if segment]
tail = segments[-1] if segments else ""
if tail:
return f"{parsed.scheme}://<redacted>/{tail}"
return f"{parsed.scheme}://<redacted>"
def _requires_file_uri_fallback(
provider: str, model: str, file_uri: str
) -> bool:
"""Returns True when `file_uri` should not be sent as a file content block."""
if provider in _FILE_ID_REQUIRED_PROVIDERS:
return not _looks_like_openai_file_id(file_uri)
if provider == "anthropic":
return True
if provider == "vertex_ai" and not _is_litellm_gemini_model(model):
return True
return False
def _decode_inline_text_data(raw_bytes: bytes) -> str:
"""Decodes inline file bytes that represent textual content."""
try:
return raw_bytes.decode("utf-8")
except UnicodeDecodeError:
logger.debug("Falling back to latin-1 decoding for inline file bytes.")
return raw_bytes.decode("latin-1", errors="replace")
def _normalize_mime_type(mime_type: str) -> str:
"""Normalizes MIME types for comparisons."""
return mime_type.split(";", 1)[0].strip().lower()
def _media_url_content_type(mime_type: str) -> str | None:
"""Returns the LiteLLM URL content type for known media MIME types."""
major_mime_type = _normalize_mime_type(mime_type).split("/", 1)[0]
return _MEDIA_URL_CONTENT_TYPE_BY_MAJOR_MIME_TYPE.get(major_mime_type)
def _iter_reasoning_texts(reasoning_value: Any) -> Iterable[str]:
"""Yields textual fragments from provider specific reasoning payloads."""
if reasoning_value is None:
return
if isinstance(reasoning_value, types.Content):
if not reasoning_value.parts:
return
for part in reasoning_value.parts:
if part and part.text:
yield part.text
return
if isinstance(reasoning_value, str):
yield reasoning_value
return
if isinstance(reasoning_value, list):
for value in reasoning_value:
yield from _iter_reasoning_texts(value)
return
if isinstance(reasoning_value, dict):
# LiteLLM currently nests “reasoning” text under a few known keys.
# (Documented in https://docs.litellm.ai/docs/openai#reasoning-outputs)
for key in ("text", "content", "reasoning", "reasoning_content"):
text_value = reasoning_value.get(key)
if isinstance(text_value, str):
yield text_value
return
text_attr = getattr(reasoning_value, "text", None)
if isinstance(text_attr, str):
yield text_attr
elif isinstance(reasoning_value, (int, float, bool)):
yield str(reasoning_value)
def _is_thinking_blocks_format(reasoning_value: Any) -> bool:
"""Returns True if reasoning_value is Anthropic thinking_blocks format.
Anthropic thinking_blocks is a list of dicts, each with 'type', 'thinking',
and 'signature' keys.
"""
if not isinstance(reasoning_value, list) or not reasoning_value:
return False
first = reasoning_value[0]
return isinstance(first, dict) and "signature" in first
def _convert_reasoning_value_to_parts(reasoning_value: Any) -> List[types.Part]:
"""Converts provider reasoning payloads into Gemini thought parts.
Handles Anthropic thinking_blocks (list of dicts with type/thinking/signature)
by preserving the signature on each part's thought_signature field. This is
required for Anthropic to maintain thinking across tool call boundaries.
"""
if _is_thinking_blocks_format(reasoning_value):
parts: List[types.Part] = []
for block in reasoning_value:
if not isinstance(block, dict):
continue
block_type = block.get("type", "")
if block_type == "redacted":
continue
thinking_text = block.get("thinking", "")
signature = block.get("signature", "")
if not thinking_text:
continue
part = types.Part(text=thinking_text, thought=True)
if signature:
part.thought_signature = signature.encode("utf-8")
parts.append(part)
return parts
return [
types.Part(text=text, thought=True)
for text in _iter_reasoning_texts(reasoning_value)
if text
]
def _extract_reasoning_value(message: Message | Delta | None) -> Any:
"""Fetches the reasoning payload from a LiteLLM message.
Checks for 'thinking_blocks' (Anthropic structured format with signatures),
'reasoning_content' (LiteLLM standard, used by Azure/Foundry, Ollama via
LiteLLM) and 'reasoning' (used by LM Studio, vLLM).
Prioritizes 'thinking_blocks' when present (Anthropic models), then
'reasoning_content', then 'reasoning'.
"""
if message is None:
return None
# Anthropic models return thinking_blocks with type/thinking/signature fields.
# This must be preserved to maintain thinking across tool call boundaries.
thinking_blocks = message.get("thinking_blocks")
if thinking_blocks is not None:
return thinking_blocks
reasoning_content = message.get("reasoning_content")
if reasoning_content is not None:
return reasoning_content
return message.get("reasoning")
class ChatCompletionFileUrlObject(TypedDict, total=False):
file_data: str
file_id: str
format: str
class FunctionChunk(BaseModel):
id: Optional[str]
name: Optional[str]
args: Optional[str]
index: Optional[int] = 0
class TextChunk(BaseModel):
text: str
class ReasoningChunk(BaseModel):
parts: List[types.Part]
class UsageMetadataChunk(BaseModel):
prompt_tokens: int
completion_tokens: int
total_tokens: int
cached_prompt_tokens: int = 0
reasoning_tokens: int = 0
class LiteLLMClient:
"""Provides acompletion method (for better testability)."""
async def acompletion(
self, model, messages, tools, **kwargs
) -> Union[ModelResponse, CustomStreamWrapper]:
"""Asynchronously calls acompletion.
Args:
model: The model name.
messages: The messages to send to the model.
tools: The tools to use for the model.
**kwargs: Additional arguments to pass to acompletion.
Returns:
The model response as a message.
"""
_ensure_litellm_imported()
return await acompletion(
model=model,
messages=messages,
tools=tools,
**kwargs,
)
def completion(
self, model, messages, tools, stream=False, **kwargs
) -> Union[ModelResponse, CustomStreamWrapper]:
"""Synchronously calls completion. This is used for streaming only.
Args:
model: The model to use.
messages: The messages to send.
tools: The tools to use for the model.
stream: Whether to stream the response.
**kwargs: Additional arguments to pass to completion.
Returns:
The response from the model.
"""
_ensure_litellm_imported()
return completion(
model=model,
messages=messages,
tools=tools,
stream=stream,
**kwargs,
)
def _safe_json_serialize(obj) -> str:
"""Convert any Python object to a JSON-serializable type or string.
Args:
obj: The object to serialize.
Returns:
The JSON-serialized object string or string.
"""
try:
# Try direct JSON serialization first
return json.dumps(obj, ensure_ascii=False)
except (TypeError, OverflowError):
return str(obj)
def _part_has_payload(part: types.Part) -> bool:
"""Checks whether a Part contains usable payload for the model."""
if part.text:
return True
if part.inline_data and part.inline_data.data:
return True
if part.file_data and (part.file_data.file_uri or part.file_data.data):
return True
if part.function_response:
return True
return False
def _append_fallback_user_content_if_missing(
llm_request: LlmRequest,
) -> None:
"""Ensures there is a user message with content for LiteLLM backends.
Args:
llm_request: The request that may need a fallback user message.
"""
for content in reversed(llm_request.contents):
if content.role == "user":
parts = content.parts or []
if any(_part_has_payload(part) for part in parts):
return
if not parts:
content.parts = []
content.parts.append(
types.Part.from_text(
text="Handle the requests as specified in the System Instruction."
)
)
return
llm_request.contents.append(
types.Content(
role="user",
parts=[
types.Part.from_text(
text=(
"Handle the requests as specified in the System"
" Instruction."
)
),
],
)
)
def _extract_cached_prompt_tokens(usage: Any) -> int:
"""Extracts cached prompt tokens from LiteLLM usage.
Providers expose cached token metrics in different shapes. Common patterns:
- usage["prompt_tokens_details"]["cached_tokens"] (OpenAI/Azure style)
- usage["prompt_tokens_details"] is a list of dicts with cached_tokens
- usage["cached_prompt_tokens"] (LiteLLM-normalized for some providers)
- usage["cached_tokens"] (flat)
Args:
usage: Usage dictionary from LiteLLM response.
Returns:
Integer number of cached prompt tokens if present; otherwise 0.
"""
try:
usage_dict = usage
if hasattr(usage, "model_dump"):
usage_dict = usage.model_dump()
elif isinstance(usage, str):
try:
usage_dict = json.loads(usage)
except json.JSONDecodeError:
return 0
if not isinstance(usage_dict, dict):
return 0
details = usage_dict.get("prompt_tokens_details")
if isinstance(details, dict):
value = details.get("cached_tokens")
if isinstance(value, int):
return value
elif isinstance(details, list):
total = sum(
item.get("cached_tokens", 0)
for item in details
if isinstance(item, dict)
and isinstance(item.get("cached_tokens"), int)
)
if total > 0:
return total
for key in ("cached_prompt_tokens", "cached_tokens"):
value = usage_dict.get(key)
if isinstance(value, int):
return value
except (TypeError, AttributeError) as e:
logger.debug("Error extracting cached prompt tokens: %s", e)
return 0
def _decode_thought_signature(value: Any) -> Optional[bytes]:
"""Safely decodes a thought_signature value to bytes.
Args:
value: A base64 string or raw bytes thought_signature.
Returns:
The decoded bytes, or None if decoding fails.
"""
if isinstance(value, bytes):
return value
try:
return base64.b64decode(value, validate=True)
except (binascii.Error, TypeError, ValueError):
logger.debug(
"Failed to decode thought_signature of type %s.",
type(value).__name__,
)
return None
def _extract_reasoning_tokens(usage: Any) -> int:
"""Extracts reasoning tokens from LiteLLM usage.
Providers expose reasoning token metrics under completion_tokens_details.
Args:
usage: Usage dictionary or object from LiteLLM response.
Returns:
Integer number of reasoning tokens if present; otherwise 0.
"""
try:
usage_dict = usage
if hasattr(usage, "model_dump"):
usage_dict = usage.model_dump()
elif isinstance(usage, str):
try:
usage_dict = json.loads(usage)
except json.JSONDecodeError:
return 0
if not isinstance(usage_dict, dict):
return 0
details = usage_dict.get("completion_tokens_details")
if isinstance(details, dict):
value = details.get("reasoning_tokens")
if isinstance(value, int):
return value
except (TypeError, AttributeError) as e:
logger.debug("Error extracting reasoning tokens: %s", e)
return 0
def _extract_thought_signature_from_tool_call(
tool_call: ChatCompletionMessageToolCall,
) -> Optional[bytes]:
"""Extracts thought_signature from a litellm tool call if present.
Gemini thinking models attach a thought_signature to function call parts.
See https://ai.google.dev/gemini-api/docs/thought-signatures.
This signature may appear in several locations depending on the
provider path:
1. extra_content.google.thought_signature (OpenAI-compatible API).
2. provider_specific_fields on the tool call or function (Vertex).
3. Embedded in the tool call ID via __thought__ separator.
Args:
tool_call: A litellm tool call object.
Returns:
The thought_signature as bytes, or None if not present.
"""
# Check extra_content.google.thought_signature (OpenAI format)
extra_content = tool_call.get("extra_content")
if isinstance(extra_content, dict):
google_fields = extra_content.get("google")
if isinstance(google_fields, dict):
signature = google_fields.get("thought_signature")
if signature:
return _decode_thought_signature(signature)
# Check provider_specific_fields on the tool call
provider_fields = tool_call.get("provider_specific_fields")
if isinstance(provider_fields, dict):
signature = provider_fields.get("thought_signature")
if signature:
return _decode_thought_signature(signature)
# Check provider_specific_fields on the function
function = tool_call.get("function")
if function:
func_provider_fields = None
if isinstance(function, dict):
func_provider_fields = function.get("provider_specific_fields")
elif hasattr(function, "provider_specific_fields"):
func_provider_fields = function.provider_specific_fields
if isinstance(func_provider_fields, dict):
signature = func_provider_fields.get("thought_signature")
if signature:
return _decode_thought_signature(signature)
# Check if thought signature is embedded in the tool call ID
tool_call_id = tool_call.get("id") or ""
if _THOUGHT_SIGNATURE_SEPARATOR in tool_call_id:
parts = tool_call_id.split(_THOUGHT_SIGNATURE_SEPARATOR, 1)
if len(parts) == 2:
return _decode_thought_signature(parts[1])
return None
async def _content_to_message_param(
content: types.Content,
*,
provider: str = "",
model: str = "",
) -> Union[Message, list[Message]]:
"""Converts a types.Content to a litellm Message or list of Messages.
Handles multipart function responses by returning a list of
ChatCompletionToolMessage objects if multiple function_response parts exist.
Args:
content: The content to convert.
provider: The LLM provider name (e.g., "openai", "azure").
model: The LiteLLM model string, used for provider-specific behavior.
Returns:
A litellm Message, a list of litellm Messages.
"""
_ensure_litellm_imported()
tool_messages: list[Message] = []
non_tool_parts: list[types.Part] = []
for part in content.parts:
if part.function_response:
response = part.function_response.response
response_content = (
response
if isinstance(response, str)
else _safe_json_serialize(response)
)
tool_messages.append(
ChatCompletionToolMessage(
role="tool",
tool_call_id=part.function_response.id,
content=response_content,
)
)
else:
non_tool_parts.append(part)
if tool_messages and not non_tool_parts:
return tool_messages if len(tool_messages) > 1 else tool_messages[0]
if tool_messages and non_tool_parts:
follow_up = await _content_to_message_param(
types.Content(role=content.role, parts=non_tool_parts),
provider=provider,
)
follow_up_messages = (
follow_up if isinstance(follow_up, list) else [follow_up]
)
return tool_messages + follow_up_messages
# Handle user or assistant messages
role = _to_litellm_role(content.role)
if role == "user":
user_parts = [part for part in content.parts if not part.thought]
message_content = (
await _get_content(user_parts, provider=provider, model=model) or None
)
return ChatCompletionUserMessage(role="user", content=message_content)
else: # assistant/model
tool_calls = []
content_parts: list[types.Part] = []
reasoning_parts: list[types.Part] = []
for part in content.parts:
if part.function_call:
tool_call_id = part.function_call.id or ""
tool_call_dict: Dict[str, Any] = {
"type": "function",
"id": tool_call_id,
"function": {
"name": part.function_call.name,
"arguments": _safe_json_serialize(part.function_call.args),
},
}
# Preserve thought_signature for Gemini thinking models.
# LiteLLM's Gemini prompt conversion reads provider_specific_fields,
# while the OpenAI-compatible Gemini endpoint path expects the
# extra_content.google.thought_signature payload to survive.
# See https://ai.google.dev/gemini-api/docs/thought-signatures.
if part.thought_signature:
sig = part.thought_signature
if isinstance(sig, bytes):
sig = base64.b64encode(sig).decode("utf-8")
tool_call_dict["provider_specific_fields"] = {
"thought_signature": sig
}
tool_call_dict["extra_content"] = {
"google": {"thought_signature": sig}
}
tool_calls.append(tool_call_dict)
elif part.thought:
reasoning_parts.append(part)
else:
content_parts.append(part)
final_content = (
await _get_content(content_parts, provider=provider, model=model)
if content_parts
else None
)
if final_content and isinstance(final_content, list):
# when the content is a single text object, we can use it directly.
# this is needed for ollama_chat provider which fails if content is a list
final_content = (
final_content[0].get("text", "")
if final_content[0].get("type", None) == "text"
else final_content
)
# For Anthropic models, rebuild thinking_blocks with signatures so that
# thinking is preserved across tool call boundaries. Without this,
# Anthropic silently drops thinking after the first turn.
if model and _is_anthropic_model(model) and reasoning_parts:
thinking_blocks = []
for part in reasoning_parts:
if part.text and part.thought_signature:
sig = part.thought_signature
if isinstance(sig, bytes):
sig = sig.decode("utf-8")
thinking_blocks.append({
"type": "thinking",
"thinking": part.text,
"signature": sig,
})
if thinking_blocks:
msg = ChatCompletionAssistantMessage(
role=role,
content=final_content,
tool_calls=tool_calls or None,
)
msg["thinking_blocks"] = thinking_blocks # type: ignore[typeddict-unknown-key]
return msg
reasoning_texts = []
for part in reasoning_parts:
if part.text:
reasoning_texts.append(part.text)
elif (
part.inline_data
and part.inline_data.data
and part.inline_data.mime_type
and part.inline_data.mime_type.startswith("text/")
):
reasoning_texts.append(_decode_inline_text_data(part.inline_data.data))
reasoning_content = _NEW_LINE.join(text for text in reasoning_texts if text)
return ChatCompletionAssistantMessage(
role=role,
content=final_content,
tool_calls=tool_calls or None,
reasoning_content=reasoning_content or None,
)
def _ensure_tool_results(messages: List[Message]) -> List[Message]:
"""Insert placeholder tool messages for missing tool results.
LiteLLM-backed providers like OpenAI and Anthropic reject histories where an
assistant tool call is not followed by tool responses before the next
non-tool message. This helps recover from interrupted tool execution.
"""
if not messages:
return messages
_ensure_litellm_imported()
healed_messages: List[Message] = []
pending_tool_call_ids: List[str] = []
for message in messages:
role = message.get("role")
if pending_tool_call_ids and role != "tool":
logger.warning(
"Missing tool results for tool_call_id(s): %s",
pending_tool_call_ids,
)
healed_messages.extend(
ChatCompletionToolMessage(
role="tool",
tool_call_id=tool_call_id,
content=_MISSING_TOOL_RESULT_MESSAGE,
)
for tool_call_id in pending_tool_call_ids
)
pending_tool_call_ids = []
if role == "assistant":
tool_calls = message.get("tool_calls") or []
pending_tool_call_ids = [
tool_call.get("id") for tool_call in tool_calls if tool_call.get("id")
]
elif role == "tool":
tool_call_id = message.get("tool_call_id")
if tool_call_id in pending_tool_call_ids:
pending_tool_call_ids.remove(tool_call_id)
healed_messages.append(message)
if pending_tool_call_ids:
logger.warning(
"Missing tool results for tool_call_id(s): %s",
pending_tool_call_ids,
)
healed_messages.extend(
ChatCompletionToolMessage(
role="tool",
tool_call_id=tool_call_id,
content=_MISSING_TOOL_RESULT_MESSAGE,
)
for tool_call_id in pending_tool_call_ids
)
return healed_messages
async def _get_content(
parts: Iterable[types.Part],
*,
provider: str = "",
model: str = "",
) -> OpenAIMessageContent:
"""Converts a list of parts to litellm content.
Callers may need to filter out thought parts before calling this helper if
thought parts are not needed.
Args:
parts: The parts to convert.
provider: The LLM provider name (e.g., "openai", "azure").
model: The LiteLLM model string (e.g., "openai/gpt-4o",
"vertex_ai/gemini-2.5-flash").