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
1735 lines (1465 loc) · 52.8 KB
/
lite_llm.py
File metadata and controls
1735 lines (1465 loc) · 52.8 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 2025 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 copy
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 TypedDict
from typing import Union
from urllib.parse import urlparse
import uuid
import warnings
from google.genai import types
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 OpenAIMessageContent
from opentelemetry import trace
from pydantic import BaseModel
from pydantic import Field
from typing_extensions import override
from .base_llm import BaseLlm
from .llm_request import LlmRequest
from .llm_response import LlmResponse
# This will add functions to prompts if functions are provided.
litellm.add_function_to_prompt = True
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 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"})
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 _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 _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 _convert_reasoning_value_to_parts(reasoning_value: Any) -> List[types.Part]:
"""Converts provider reasoning payloads into Gemini thought parts."""
return [
types.Part(text=text, thought=True)
for text in _iter_reasoning_texts(reasoning_value)
if text
]
def _extract_reasoning_value(message: Message | Dict[str, Any]) -> Any:
"""Fetches the reasoning payload from a LiteLLM message or dict."""
if message is None:
return None
if hasattr(message, "reasoning_content"):
return getattr(message, "reasoning_content")
if isinstance(message, dict):
return message.get("reasoning_content")
return None
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
class LiteLLMClient:
"""Provides acompletion method (for better testability)."""
@staticmethod
def _build_traceparent() -> Optional[str]:
span_context = trace.get_current_span().get_span_context()
if not span_context.is_valid:
return None
trace_id = f"{span_context.trace_id:032x}"
span_id = f"{span_context.span_id:016x}"
trace_flags = f"{int(span_context.trace_flags):02x}"
return f"00-{trace_id}-{span_id}-{trace_flags}"
@classmethod
def _maybe_add_traceparent_header(
cls, extra_headers: Optional[dict[str, str]]
) -> Optional[dict[str, str]]:
traceparent = cls._build_traceparent()
if not traceparent:
return extra_headers
headers_with_trace = dict(extra_headers) if extra_headers else {}
headers_with_trace["traceparent"] = traceparent
return headers_with_trace
@classmethod
def _attach_traceparent_header(cls, kwargs: Dict[str, Any]) -> None:
updated_headers = cls._maybe_add_traceparent_header(
kwargs.get("extra_headers")
)
if updated_headers is None:
kwargs.pop("extra_headers", None)
else:
kwargs["extra_headers"] = updated_headers
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.
"""
self._attach_traceparent_header(kwargs)
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.
"""
self._attach_traceparent_header(kwargs)
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
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
async def _content_to_message_param(
content: types.Content,
*,
provider: 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").
Returns:
A litellm Message, a list of litellm Messages.
"""
tool_messages = []
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,
)
)
if tool_messages:
return tool_messages if len(tool_messages) > 1 else tool_messages[0]
# Handle user or assistant messages
role = _to_litellm_role(content.role)
message_content = await _get_content(content.parts, provider=provider) or None
if role == "user":
return ChatCompletionUserMessage(role="user", content=message_content)
else: # assistant/model
tool_calls = []
content_present = False
for part in content.parts:
if part.function_call:
tool_calls.append(
ChatCompletionAssistantToolCall(
type="function",
id=part.function_call.id,
function=Function(
name=part.function_call.name,
arguments=_safe_json_serialize(part.function_call.args),
),
)
)
elif part.text or part.inline_data:
content_present = True
final_content = message_content if content_present 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
)
return ChatCompletionAssistantMessage(
role=role,
content=final_content,
tool_calls=tool_calls or None,
)
async def _get_content(
parts: Iterable[types.Part],
*,
provider: str = "",
) -> Union[OpenAIMessageContent, str]:
"""Converts a list of parts to litellm content.
Args:
parts: The parts to convert.
provider: The LLM provider name (e.g., "openai", "azure").
Returns:
The litellm content.
"""
content_objects = []
for part in parts:
if part.text:
if len(parts) == 1:
return part.text
content_objects.append({
"type": "text",
"text": part.text,
})
elif (
part.inline_data
and part.inline_data.data
and part.inline_data.mime_type
):
if part.inline_data.mime_type.startswith("text/"):
decoded_text = _decode_inline_text_data(part.inline_data.data)
if len(parts) == 1:
return decoded_text
content_objects.append({
"type": "text",
"text": decoded_text,
})
continue
base64_string = base64.b64encode(part.inline_data.data).decode("utf-8")
data_uri = f"data:{part.inline_data.mime_type};base64,{base64_string}"
# LiteLLM providers extract the MIME type from the data URI; avoid
# passing a separate `format` field that some backends reject.
if part.inline_data.mime_type.startswith("image"):
content_objects.append({
"type": "image_url",
"image_url": {"url": data_uri},
})
elif part.inline_data.mime_type.startswith("video"):
content_objects.append({
"type": "video_url",
"video_url": {"url": data_uri},
})
elif part.inline_data.mime_type.startswith("audio"):
content_objects.append({
"type": "audio_url",
"audio_url": {"url": data_uri},
})
elif part.inline_data.mime_type in _SUPPORTED_FILE_CONTENT_MIME_TYPES:
# OpenAI/Azure require file_id from uploaded file, not inline data
if provider in _FILE_ID_REQUIRED_PROVIDERS:
file_response = await litellm.acreate_file(
file=part.inline_data.data,
purpose="assistants",
custom_llm_provider=provider,
)
content_objects.append({
"type": "file",
"file": {"file_id": file_response.id},
})
else:
content_objects.append({
"type": "file",
"file": {"file_data": data_uri},
})
else:
raise ValueError(
"LiteLlm(BaseLlm) does not support content part with MIME type "
f"{part.inline_data.mime_type}."
)
elif part.file_data and part.file_data.file_uri:
file_object: ChatCompletionFileUrlObject = {
"file_id": part.file_data.file_uri,
}
# Determine MIME type: use explicit value, infer from URI, or use default
mime_type = part.file_data.mime_type
if not mime_type:
mime_type = _infer_mime_type_from_uri(part.file_data.file_uri)
if not mime_type and part.file_data.display_name:
guessed_mime_type, _ = mimetypes.guess_type(part.file_data.display_name)
mime_type = guessed_mime_type
if not mime_type:
# LiteLLM's Vertex AI backend requires format for GCS URIs
mime_type = _DEFAULT_MIME_TYPE
logger.debug(
"Could not determine MIME type for file_uri %s, using default: %s",
part.file_data.file_uri,
mime_type,
)
file_object["format"] = mime_type
content_objects.append({
"type": "file",
"file": file_object,
})
return content_objects
def _is_ollama_chat_provider(
model: Optional[str], custom_llm_provider: Optional[str]
) -> bool:
"""Returns True when requests should be normalized for ollama_chat."""
if custom_llm_provider and custom_llm_provider.lower() == "ollama_chat":
return True
if model and model.lower().startswith("ollama_chat"):
return True
return False
def _flatten_ollama_content(
content: OpenAIMessageContent | str | None,
) -> str | OpenAIMessageContent | None:
"""Flattens multipart content to text for ollama_chat compatibility.
Ollama's chat endpoint rejects arrays for `content`. We keep textual parts,
join them with newlines, and fall back to a JSON string for non-text content.
If both text and non-text parts are present, only the text parts are kept.
"""
if not isinstance(content, list):
return content
text_parts = []
for block in content:
if isinstance(block, dict) and block.get("type") == "text":
text_value = block.get("text")
if text_value:
text_parts.append(text_value)
if text_parts:
return _NEW_LINE.join(text_parts)
try:
return json.dumps(content)
except TypeError:
return str(content)
def _normalize_ollama_chat_messages(
messages: list[Message],
*,
model: Optional[str] = None,
custom_llm_provider: Optional[str] = None,
) -> list[Message]:
"""Normalizes message payloads for ollama_chat provider.
The provider expects string content. Convert multipart content to text while
leaving other providers untouched.
"""
if not _is_ollama_chat_provider(model, custom_llm_provider):
return messages
normalized_messages: list[Message] = []
for message in messages:
if isinstance(message, dict):
message_copy = dict(message)
message_copy["content"] = _flatten_ollama_content(
message_copy.get("content")
)
normalized_messages.append(message_copy)
continue
message_copy = (
message.model_copy()
if hasattr(message, "model_copy")
else copy.copy(message)
)
if hasattr(message_copy, "content"):
flattened_content = _flatten_ollama_content(
getattr(message_copy, "content")
)
try:
setattr(message_copy, "content", flattened_content)
except AttributeError as e:
logger.debug(
"Failed to set 'content' attribute on message of type %s: %s",
type(message_copy).__name__,
e,
)
normalized_messages.append(message_copy)
return normalized_messages
def _build_tool_call_from_json_dict(
candidate: Any, *, index: int
) -> Optional[ChatCompletionMessageToolCall]:
"""Creates a tool call object from JSON content embedded in text."""
if not isinstance(candidate, dict):
return None
name = candidate.get("name")
args = candidate.get("arguments")
if not isinstance(name, str) or args is None:
return None
if isinstance(args, str):
arguments_payload = args
else:
try:
arguments_payload = json.dumps(args, ensure_ascii=False)
except (TypeError, ValueError):
arguments_payload = _safe_json_serialize(args)
call_id = candidate.get("id") or f"adk_tool_call_{uuid.uuid4().hex}"
call_index = candidate.get("index")
if isinstance(call_index, int):
index = call_index
function = Function(
name=name,
arguments=arguments_payload,
)
# Some LiteLLM types carry an `index` field only in streaming contexts,
# so guard the assignment to stay compatible with older versions.
if hasattr(function, "index"):
function.index = index # type: ignore[attr-defined]
tool_call = ChatCompletionMessageToolCall(
type="function",
id=str(call_id),
function=function,
)
# Same reasoning as above: not every ChatCompletionMessageToolCall exposes it.
if hasattr(tool_call, "index"):
tool_call.index = index # type: ignore[attr-defined]
return tool_call
def _parse_tool_calls_from_text(
text_block: str,
) -> tuple[list[ChatCompletionMessageToolCall], Optional[str]]:
"""Extracts inline JSON tool calls from LiteLLM text responses."""
tool_calls = []
if not text_block:
return tool_calls, None
remainder_segments = []
cursor = 0
text_length = len(text_block)
while cursor < text_length:
brace_index = text_block.find("{", cursor)
if brace_index == -1:
remainder_segments.append(text_block[cursor:])
break
remainder_segments.append(text_block[cursor:brace_index])
try:
candidate, end = _JSON_DECODER.raw_decode(text_block, brace_index)
except json.JSONDecodeError:
remainder_segments.append(text_block[brace_index])
cursor = brace_index + 1
continue
tool_call = _build_tool_call_from_json_dict(
candidate, index=len(tool_calls)
)
if tool_call:
tool_calls.append(tool_call)
else:
remainder_segments.append(text_block[brace_index:end])
cursor = end
remainder = "".join(segment for segment in remainder_segments if segment)
remainder = remainder.strip()
return tool_calls, remainder or None
def _split_message_content_and_tool_calls(
message: Message,
) -> tuple[Optional[OpenAIMessageContent], list[ChatCompletionMessageToolCall]]:
"""Returns message content and tool calls, parsing inline JSON when needed."""
existing_tool_calls = message.get("tool_calls") or []
normalized_tool_calls = (
list(existing_tool_calls) if existing_tool_calls else []
)
content = message.get("content")
# LiteLLM responses either provide structured tool_calls or inline JSON, not
# both. When tool_calls are present we trust them and skip the fallback parser.
if normalized_tool_calls or not isinstance(content, str):
return content, normalized_tool_calls
fallback_tool_calls, remainder = _parse_tool_calls_from_text(content)
if fallback_tool_calls:
return remainder, fallback_tool_calls
return content, []
def _to_litellm_role(role: Optional[str]) -> Literal["user", "assistant"]:
"""Converts a types.Content role to a litellm role.
Args:
role: The types.Content role.
Returns:
The litellm role.
"""
if role in ["model", "assistant"]:
return "assistant"
return "user"
TYPE_LABELS = {
"STRING": "string",
"NUMBER": "number",
"BOOLEAN": "boolean",
"OBJECT": "object",
"ARRAY": "array",
"INTEGER": "integer",
}
def _schema_to_dict(schema: types.Schema | dict[str, Any]) -> dict:
"""Recursively converts a schema object or dict to a pure-python dict.
Args:
schema: The schema to convert.
Returns:
The dictionary representation of the schema.
"""
schema_dict = (
schema.model_dump(exclude_none=True)
if isinstance(schema, types.Schema)
else dict(schema)
)
enum_values = schema_dict.get("enum")
if isinstance(enum_values, (list, tuple)):
schema_dict["enum"] = [value for value in enum_values if value is not None]
if "type" in schema_dict and schema_dict["type"] is not None:
t = schema_dict["type"]
schema_dict["type"] = (
t.value if isinstance(t, types.Type) else str(t)
).lower()
if "items" in schema_dict:
items = schema_dict["items"]
schema_dict["items"] = (
_schema_to_dict(items)
if isinstance(items, (types.Schema, dict))
else items
)
if "properties" in schema_dict:
new_props = {}
for key, value in schema_dict["properties"].items():
if isinstance(value, (types.Schema, dict)):
new_props[key] = _schema_to_dict(value)
else:
new_props[key] = value
schema_dict["properties"] = new_props
return schema_dict
def _function_declaration_to_tool_param(
function_declaration: types.FunctionDeclaration,
) -> dict:
"""Converts a types.FunctionDeclaration to an openapi spec dictionary.
Args:
function_declaration: The function declaration to convert.
Returns:
The openapi spec dictionary representation of the function declaration.
"""
assert function_declaration.name
parameters = {
"type": "object",
"properties": {},
}
if (
function_declaration.parameters
and function_declaration.parameters.properties
):
properties = {}
for key, value in function_declaration.parameters.properties.items():
properties[key] = _schema_to_dict(value)
parameters = {
"type": "object",
"properties": properties,
}
elif function_declaration.parameters_json_schema:
parameters = function_declaration.parameters_json_schema
tool_params = {
"type": "function",
"function": {
"name": function_declaration.name,
"description": function_declaration.description or "",
"parameters": parameters,
},
}
required_fields = (
getattr(function_declaration.parameters, "required", None)
if function_declaration.parameters
else None
)
if required_fields:
tool_params["function"]["parameters"]["required"] = required_fields
return tool_params
def _model_response_to_chunk(
response: ModelResponse,
) -> Generator[
Tuple[
Optional[
Union[
TextChunk,
FunctionChunk,
UsageMetadataChunk,
ReasoningChunk,
]
],
Optional[str],
],
None,
None,
]: