-
Notifications
You must be signed in to change notification settings - Fork 88
Expand file tree
/
Copy path_openai_model.py
More file actions
1784 lines (1509 loc) · 80.5 KB
/
Copy path_openai_model.py
File metadata and controls
1784 lines (1509 loc) · 80.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
# Tencent is pleased to support the open source community by making tRPC-Agent-Python available.
#
# Copyright (C) 2026 Tencent. All rights reserved.
#
# tRPC-Agent-Python is licensed under Apache-2.0.
"""OpenAI model implementation module.
This module provides the OpenAIModel class which implements the BaseModel interface
for interacting with OpenAI's API. It supports both streaming and non-streaming
responses, tool calls, and various OpenAI-specific features.
"""
import base64
import json
import uuid
from enum import Enum
from typing import Any
from typing import AsyncGenerator
from typing import Dict
from typing import List
from typing import Optional
from typing_extensions import override
import httpx
import openai
from pydantic import BaseModel
from trpc_agent_sdk.common import check_enum
from trpc_agent_sdk.context import InvocationContext
from trpc_agent_sdk.log import logger
from trpc_agent_sdk.types import Content
from trpc_agent_sdk.types import FunctionResponse
from trpc_agent_sdk.types import GenerateContentConfig
from trpc_agent_sdk.types import GenerateContentResponseUsageMetadata
from trpc_agent_sdk.types import Part
from trpc_agent_sdk.types import Schema
from trpc_agent_sdk.types import Tool
from trpc_agent_sdk.utils import json_loads_repair
from . import _constants as const
from ._llm_model import LLMModel
from ._llm_request import LlmRequest
from ._llm_response import LlmResponse
from ._registry import register_model
from ._httpx_client import BaseHttpClientProvider
from ._httpx_client import HttpClientProviderFactory
from ._httpx_client import temporary_http_client_provider_factory
from .openai_adapter import get_openai_adapter
from .tool_prompt import ToolPromptFactory
from .tool_prompt import get_factory
from .tool_prompt import ToolPrompt
class ToolCall(BaseModel):
"""Represents a tool call made by the model."""
id: str
name: str
arguments: Dict[str, Any]
thought_signature: Optional[str] = None
class FinishReason(str, Enum):
"""Reasons why model generation finished."""
STOP = "stop"
LENGTH = "length"
ERROR = "error"
TOOL_CALLS = const.TOOL_CALLS
class ToolKey(str, Enum):
"""Tool keys for tool calls."""
ID = "id"
TYPE = "type"
NAME = "name"
FUNCTION = "function"
ARGUMENTS = "arguments"
THOUGHT_SIGNATURE = "thought_signature"
PROVIDER_SPECIFIC_FIELDS = "provider_specific_fields"
class ApiParamsKey(str, Enum):
"""Tool keys for tool calls."""
MODEL = const.MODEL
MESSAGES = "messages"
STREAM = "stream"
MAX_TOKENS = "max_tokens"
TEMPERATURE = "temperature"
TOP_P = "top_p"
STOP = "stop"
TOOLS = "tools"
TOOL_CHOICE = "tool_choice"
STREAM_OPTS = "stream_options"
INCLUDE_USAGE = "include_usage"
# Additional OpenAI parameters for better configuration support
FREQUENCY_PENALTY = "frequency_penalty"
PRESENCE_PENALTY = "presence_penalty"
SEED = "seed"
LOGPROBS = "logprobs"
TOP_LOGPROBS = "top_logprobs"
N = "n"
RESPONSE_FORMAT = "response_format"
MAX_COMPLETION_TOKENS = "max_completion_tokens"
REASONING_EFFORT = "reasoning_effort"
PARALLEL_TOOL_CALLS = "parallel_tool_calls"
PROMPT_CACHE_KEY = "prompt_cache_key"
PROMPT_CACHE_RETENTION = "prompt_cache_retention"
@register_model(model_name="OpenAIModel", supported_models=[r"gpt-.*", r"o1-.*", r"deepseek-.*", r"hy3-.*"])
class OpenAIModel(LLMModel):
"""OpenAI model implementation using the abstract model interface.
This class provides integration with OpenAI's API, supporting features like:
- Streaming and non-streaming responses
- Tool/function calling (both native and via text prompts)
- Vision API for image inputs
- Default configuration via generate_content_config
Args:
model_name: The OpenAI model name (e.g., "gpt-4", "gpt-3.5-turbo")
filters_name: Optional list of filter names to apply
add_tools_to_prompt: If True, tools are added to the system prompt as text
instead of using OpenAI's native function calling
tool_prompt: Tool prompt format to use when add_tools_to_prompt=True
(default: "xml")
generate_content_config: Default configuration for all requests. This config
will be used as the base, with per-request configs
overriding specific fields. Useful for maintaining
consistent model behavior across multiple calls.
**kwargs: Additional arguments passed to parent LLMModel class
(e.g., api_key, base_url, etc.)
Example:
>>> # Create model with default config
>>> default_config = GenerateContentConfig(
... temperature=0.7,
... max_output_tokens=1000,
... top_p=0.9
... )
>>> model = OpenAIModel(
... model_name="gpt-4",
... api_key="your-api-key",
... generate_content_config=default_config
... )
>>>
>>> # Request without config uses defaults
>>> request1 = LlmRequest(
... contents=[Content(parts=[Part.from_text(text="Hello")])],
... config=None # Will use temperature=0.7, max_output_tokens=1000, etc.
... )
>>>
>>> # Request with partial config overrides specific fields
>>> request2 = LlmRequest(
... contents=[Content(parts=[Part.from_text(text="Hello")])],
... config=GenerateContentConfig(temperature=0.3) # Override only temperature
... )
"""
def __init__(
self,
model_name: str,
filters_name: Optional[list[str]] = None,
add_tools_to_prompt: bool = False,
tool_prompt: str = "xml",
generate_content_config: Optional[GenerateContentConfig] = None,
http_client_provider_factory: HttpClientProviderFactory = temporary_http_client_provider_factory,
**kwargs,
):
super().__init__(model_name, filters_name, **kwargs)
self._adapter = get_openai_adapter(self._model_name, self._base_url)
# Extract OpenAI-specific config
self.organization: str = kwargs.get(const.ORGANIZATION, "")
self.client_args = kwargs.get(const.CLIENT_ARGS, {})
# Allow callers to inject a tuned httpx client
http_client_provider_factory = http_client_provider_factory or temporary_http_client_provider_factory
self._http_client_provider: BaseHttpClientProvider = http_client_provider_factory()
# Tool prompt configuration
self.add_tools_to_prompt = add_tools_to_prompt
self.tool_prompt = tool_prompt
# Default generation config that can be overridden per request
self.generate_content_config = generate_content_config
# Optional hard cap for tool-response payload injected into model context.
# Disabled by default; callers can opt in.
self._tool_response_clip_chars = int(kwargs.get("tool_response_clip_chars", 0) or 0)
# Validate tool_prompt parameter
if isinstance(self.tool_prompt, str):
# Validate that the string is registered in factory
factory: ToolPromptFactory = get_factory()
try:
factory.create(self.tool_prompt) # Test creation to validate
except Exception as ex: # pylint: disable=broad-except
raise ValueError(f"Invalid tool_prompt string '{self.tool_prompt}': {ex}")
elif not (isinstance(self.tool_prompt, type) and issubclass(self.tool_prompt, ToolPrompt)):
raise ValueError(f"tool_prompt must be a string or ToolPrompt class, got {type(self.tool_prompt)}")
def _refresh_adapter(self) -> None:
"""Refresh provider adapter after model or endpoint changes."""
self._adapter = get_openai_adapter(self._model_name, self._base_url)
def is_retriable_status_code(self, status_code: int) -> Optional[bool]:
return status_code in {408, 409, 429} or status_code >= 500
def is_retriable_exception(self, ex: Exception) -> bool:
if isinstance(ex, httpx.TimeoutException):
return True
if isinstance(ex, openai.OpenAIError):
return False
return True
@override
def set_base_url(self, value: str) -> None:
super().set_base_url(value)
self._refresh_adapter()
@override
def set_model_name(self, value: str) -> None:
super().set_model_name(value)
self._refresh_adapter()
def _create_async_client(self) -> openai.AsyncOpenAI:
"""Create a new async client instance."""
# Disable httpx logging to prevent HTTP request logs
import logging
logging.getLogger("httpx").setLevel(logging.WARNING)
client_args = self.client_args.copy()
client_args['http_client'] = self._http_client_provider.create_http_client()
return openai.AsyncOpenAI(
api_key=self._api_key,
max_retries=0, # disable retries
organization=self.organization,
base_url=self._base_url,
**client_args,
)
def _create_tool_prompt(self) -> ToolPrompt:
"""Create a tool prompt instance from the blueprint."""
if isinstance(self.tool_prompt, str):
# Get tool prompt from factory
factory: ToolPromptFactory = get_factory()
return factory.create(self.tool_prompt)
return self.tool_prompt()
def _get_part_thought_signature(self, part: Part) -> str:
"""Get thought_signature from Part as str; return dummy if missing.
See https://ai.google.dev/gemini-api/docs/thought-signatures (Gemini 3+).
"""
raw = getattr(part, "thought_signature", None)
if not raw:
return base64.b64encode(b"skip_thought_signature_validator").decode("utf-8")
if isinstance(raw, bytes):
return base64.b64encode(raw).decode("utf-8")
return raw
def _set_part_thought_signature(self, function_part: Part, thought_signature: Optional[str]) -> None:
"""Attach thought_signature to Part for next request.
Store as bytes to match Part schema and avoid serialization warnings.
"""
if not thought_signature:
return
sig = thought_signature
try:
setattr(
function_part,
"thought_signature",
base64.b64decode(sig) if isinstance(sig, str) else sig,
)
except Exception: # pylint: disable=broad-except
setattr(
function_part,
"thought_signature",
sig.encode("utf-8") if isinstance(sig, str) else sig,
)
def _format_messages(self, request: LlmRequest) -> List[Dict[str, Any]]:
"""Format contents for OpenAI API as messages."""
formatted_messages = []
# Add system message if provided in config
system_text = ""
if request.config and request.config.system_instruction:
# Convert system_instruction to string if it's not already
system_text = str(request.config.system_instruction)
# Add tool prompt to system message if enabled and tools are available
if self.add_tools_to_prompt and request.config and request.config.tools:
tool_prompt = self._create_tool_prompt()
tool_prompt_str = tool_prompt.build_prompt(request.config.tools) # type: ignore
if tool_prompt_str:
if system_text:
system_text += f"\n\n{tool_prompt_str}"
else:
system_text = tool_prompt_str
# Add system message if we have any system content
if system_text:
request.config.system_instruction = system_text # type: ignore
formatted_messages.append({const.ROLE: const.SYSTEM, const.CONTENT: system_text})
# Convert Contents to OpenAI message format
for content in request.contents:
# Determine role - map different roles for OpenAI compatibility
role = content.role
if role == const.MODEL:
role = const.ASSISTANT # OpenAI uses const.ASSISTANT instead of const.MODEL
elif not role:
# Default role based on content type
role = const.USER # Default to user if no role specified
parts: list[Part] = content.parts # type: ignore
conditions_iter = [
len(parts) == 1, parts[0].text, parts[0].function_call, parts[0].function_response,
parts[0].code_execution_result, parts[0].executable_code, parts[0].inline_data
]
# Handle different content structures
if all(conditions_iter):
# Simple text message
message = {const.ROLE: role, const.CONTENT: parts[0].text}
if self._adapter.should_backfill_reasoning_content(role, message):
message[const.REASONING_CONTENT] = ""
formatted_messages.append(message)
else:
# Complex message with multiple parts or function calls/responses
# Separate function responses from other content
function_responses: list[FunctionResponse] = []
text_parts = []
image_parts = []
tool_calls = []
for part in parts: # type: ignore
if part.text:
if part.thought:
continue
text_parts.append(part.text)
elif part.inline_data and part.inline_data.mime_type:
# Handle image data - convert to OpenAI vision format
base64_string = base64.b64encode(part.inline_data.data).decode("utf-8") # type: ignore
data_uri = f"data:{part.inline_data.mime_type};base64,{base64_string}"
image_parts.append({"type": "image_url", "image_url": {"url": data_uri, "detail": "high"}})
elif part.function_call:
# Only convert function call to OpenAI tool call format if add_tools_to_prompt is disabled
if not self.add_tools_to_prompt:
tool_call = {
"id": getattr(part.function_call, "id", None) or f"call_{uuid.uuid4().hex[:24]}",
"type": "function",
"function": {
"name":
part.function_call.name,
"arguments": (part.function_call.args if isinstance(part.function_call.args, str)
else json.dumps(part.function_call.args, ensure_ascii=False)),
},
}
if self._adapter.should_include_thought_signature():
tool_call["thought_signature"] = self._get_part_thought_signature(part)
tool_calls.append(tool_call)
# If add_tools_to_prompt is enabled, skip tool calls (they're handled via text prompts)
elif part.function_response:
# Collect function responses to be added as separate tool messages
function_responses.append(part.function_response)
elif part.code_execution_result:
# Handle code execution results - add to text parts
execution_result = f"{part.code_execution_result.outcome.value}"
if part.code_execution_result.output:
execution_result += f": {part.code_execution_result.output}"
result_text = f"CODE EXECUTION RESULT(DON'T SHOW THIS TEXT): {execution_result}\n"
text_parts.append(result_text)
elif part.executable_code:
# Handle executable code - add to text parts
if part.executable_code.language:
language = part.executable_code.language.value.lower()
code_text = f"```{language}\n{part.executable_code.code}\n```"
else:
code_text = f"```text\n{part.executable_code.code}\n```"
text_parts.append(code_text)
# Handle function responses - role depends on add_tools_to_prompt setting
if self.add_tools_to_prompt:
# merge tool responses to correctly mach the qa pair
content = ""
for func_response in function_responses:
content += f"invoke {func_response.name}, get rsp: "
if isinstance(func_response.response, dict):
content += json.dumps(func_response.response, ensure_ascii=False)
else:
content += str(func_response.response)
content += "\n"
content = self._clip_tool_response_text(content, "tool_response_merged")
if len(content) > 0:
tool_message = {
const.ROLE: const.USER,
const.CONTENT: content,
}
formatted_messages.append(tool_message)
else:
for func_response in function_responses:
# Standard tool message format for OpenAI API
raw_text = (json.dumps(func_response.response, ensure_ascii=False) if isinstance(
func_response.response, dict) else str(func_response.response))
clipped_text = self._clip_tool_response_text(
raw_text,
getattr(func_response, "name", "tool"),
)
tool_message = {
const.ROLE: const.TOOL,
const.TOOL_CALL_ID: getattr(func_response, "id", "unknown"),
const.CONTENT: clipped_text,
}
formatted_messages.append(tool_message)
# Create the main message (assistant/user) if it has content or tool calls
if text_parts or image_parts or tool_calls:
message: dict = {const.ROLE: role}
# Handle content based on what we have
if image_parts or (text_parts and image_parts):
# Use array format for vision API when we have images
content_array = []
# Add text parts first
if text_parts:
content_array.append({"type": "text", "text": " ".join(text_parts)})
# Add image parts
content_array.extend(image_parts)
message[const.CONTENT] = content_array
elif text_parts:
# Simple text content when no images
message[const.CONTENT] = " ".join(text_parts)
else:
message[const.CONTENT] = "" # Empty content if no text or tools
# Add tool calls if any (only when add_tools_to_prompt is disabled)
if tool_calls and not self.add_tools_to_prompt:
message[const.TOOL_CALLS] = tool_calls
if self._adapter.should_backfill_reasoning_content(role, message):
message[const.REASONING_CONTENT] = ""
formatted_messages.append(message)
# Validate and fix message sequence for OpenAI compatibility
return self._validate_and_fix_openai_messages(formatted_messages)
def _validate_and_fix_openai_messages(self, messages: List[Dict[str, Any]]) -> List[Dict[str, Any]]:
"""Validate and fix message sequence to ensure OpenAI compatibility.
OpenAI requires that assistant messages with tool_calls are immediately
followed by tool messages responding to each tool_call_id.
Args:
messages: List of formatted messages
Returns:
List of validated and potentially fixed messages
"""
if not messages:
return messages
fixed_messages = []
pending_tool_calls = [] # Track tool calls that need responses
for message in messages:
role = message.get(const.ROLE, "")
if role == const.ASSISTANT:
# Check if this assistant message has tool_calls
tool_calls = message.get(const.TOOL_CALLS, [])
if tool_calls:
# If there are pending tool calls from a previous assistant message,
# we need to add dummy tool responses first
if pending_tool_calls:
logger.warning("Adding dummy tool responses for %s pending tool calls", len(pending_tool_calls))
for pending_call in pending_tool_calls:
dummy_response = {
const.ROLE: const.TOOL,
const.TOOL_CALL_ID: pending_call["id"],
const.CONTENT: json.dumps({
"status": "completed",
"note": "Tool call completed by system"
}),
}
fixed_messages.append(dummy_response)
# Add the current assistant message
fixed_messages.append(message)
# Update pending tool calls
pending_tool_calls = tool_calls
else:
# Assistant message without tool calls
if pending_tool_calls:
# Need to add dummy responses for pending tool calls
logger.warning("Adding dummy tool responses for %s pending tool calls before assistant message",
len(pending_tool_calls))
for pending_call in pending_tool_calls:
dummy_response = {
const.ROLE: const.TOOL,
const.TOOL_CALL_ID: pending_call["id"],
const.CONTENT: json.dumps({
"status": "completed",
"note": "Tool call completed by system"
}),
}
fixed_messages.append(dummy_response)
pending_tool_calls = []
# Add the assistant message
fixed_messages.append(message)
elif role == const.TOOL:
# Tool message - remove matching tool call from pending
tool_call_id = message.get(const.TOOL_CALL_ID)
if tool_call_id and pending_tool_calls:
# Remove the matching pending tool call
pending_tool_calls = [tc for tc in pending_tool_calls if tc["id"] != tool_call_id]
fixed_messages.append(message)
else:
# User or system message
if pending_tool_calls:
# Add dummy responses for any pending tool calls before user/system message
logger.warning("Adding dummy tool responses for %s pending tool calls before %s message",
len(pending_tool_calls), role)
for pending_call in pending_tool_calls:
dummy_response = {
const.ROLE: const.TOOL,
const.TOOL_CALL_ID: pending_call["id"],
const.CONTENT: json.dumps({
"status": "completed",
"note": "Tool call completed by system"
}),
}
fixed_messages.append(dummy_response)
pending_tool_calls = []
fixed_messages.append(message)
# Handle any remaining pending tool calls at the end
if pending_tool_calls:
logger.warning("Adding dummy tool responses for %s remaining pending tool calls", len(pending_tool_calls))
for pending_call in pending_tool_calls:
dummy_response = {
const.ROLE: const.TOOL,
const.TOOL_CALL_ID: pending_call["id"],
const.CONTENT: json.dumps({
"status": "completed",
"note": "Tool call completed by system"
}),
}
fixed_messages.append(dummy_response)
return fixed_messages
def _parse_finish_reason(self, finish_reason: str) -> FinishReason:
"""Convert OpenAI finish reason to our enum."""
if not check_enum(finish_reason, FinishReason):
return FinishReason.ERROR
return FinishReason(finish_reason)
def _verify_text_content_in_delta_response(self, response: dict) -> bool:
"""Verify if the text content exists in the streaming response.
Args:
response (`dict`):
The JSON-format response (After calling `model_dump` function)
Returns:
`bool`: If the text content exists and is not empty
"""
choices: list[dict] = response.get(const.CHOICES, [{}])
# Handle case where choices could be None (e.g., DeepSeek thinking events)
if choices is None or not choices:
return False
delta: dict = choices[0].get(const.DELTA, {})
if delta is None:
return False
# Check if regular content exists and is not None/empty
content = delta.get(const.CONTENT)
has_content = content is not None and content != ""
# Check if reasoning content exists and is not None/empty
reasoning_content = delta.get(const.REASONING_CONTENT)
has_reasoning_content = reasoning_content is not None and reasoning_content != ""
# Return True if either regular content or reasoning content exists
return has_content or has_reasoning_content
def _is_thinking_event(self, response: dict) -> bool:
"""Check if this is a thinking event from the model.
Args:
response (`dict`): The JSON-format response
Returns:
`bool`: True if this is a thinking event
"""
return (response.get("object", "") == "stream_server.event"
and response.get("event", {}).get("name", "") == "thinking")
def _set_thinking(self, request: LlmRequest, http_options: dict):
"""Set thinking parameters from request config."""
# Check if thinking config is available in the request
if not request.config or not request.config.thinking_config:
return
thinking_config = request.config.thinking_config
if self._adapter.apply_thinking(request, http_options):
return
# Only set thinking parameters if include_thoughts is True
if not thinking_config.include_thoughts:
return
if "extra_body" not in http_options:
http_options["extra_body"] = {}
processed_extra_body = http_options["extra_body"]
# Enable thinking
processed_extra_body[const.THINKING_ENABLED] = True
# Set thinking budget if specified
if thinking_config.thinking_budget is not None:
max_output_tokens = request.config.max_output_tokens or 0
if not max_output_tokens:
raise ValueError("max_output_tokens must be set when thinking is enabled")
# Handle different thinking budget values
if thinking_config.thinking_budget == 0:
# 0 means disabled, so don't enable thinking
processed_extra_body[const.THINKING_ENABLED] = False
return
elif thinking_config.thinking_budget == -1:
# -1 means automatic, let the model decide
# Don't set thinking_tokens, let the model use its default
pass
elif thinking_config.thinking_budget > 0:
# Positive value means specific token budget
if thinking_config.thinking_budget <= max_output_tokens:
processed_extra_body[const.THINKING_TOKENS] = thinking_config.thinking_budget
else:
raise ValueError(f"thinking_budget: {thinking_config.thinking_budget} "
f"must be between 1024 and {max_output_tokens}")
else:
raise ValueError(f"Invalid thinking_budget value: {thinking_config.thinking_budget}. "
"Must be 0 (disabled), -1 (automatic), or positive integer.")
def _get_thinking_state(self, response: dict) -> int:
"""Get the thinking state from a thinking event.
Args:
response (`dict`): The JSON-format response
Returns:
`int`: The thinking state (0=start, 2=end, -1=not a thinking event)
"""
if self._is_thinking_event(response):
return response.get("event", {}).get("state", -1)
return -1
def _process_tool_call_delta(self, tool_call_delta: dict, accumulated_tool_calls: list[dict]) -> None:
"""Process a single tool call delta and update accumulated tool calls.
Args:
tool_call_delta (`dict`): The tool call delta to process
accumulated_tool_calls (`list`): The list of accumulated tool calls
"""
# Get the index of the tool call, handle None case
index = tool_call_delta.get(const.INDEX, 0)
if index is None:
index = 0
# Ensure we have enough slots in accumulated_tool_calls
while len(accumulated_tool_calls) <= index:
accumulated_tool_calls.append({
ToolKey.ID: "",
ToolKey.TYPE: ToolKey.FUNCTION,
ToolKey.FUNCTION: {
ToolKey.NAME: "",
ToolKey.ARGUMENTS: ""
},
ToolKey.THOUGHT_SIGNATURE: "",
})
# Capture thought_signature from delta or provider_specific_fields for next-round pass-through
thought_sig = tool_call_delta.get(ToolKey.THOUGHT_SIGNATURE)
if not thought_sig and isinstance(tool_call_delta.get(ToolKey.PROVIDER_SPECIFIC_FIELDS), dict):
thought_sig = tool_call_delta[ToolKey.PROVIDER_SPECIFIC_FIELDS].get(ToolKey.THOUGHT_SIGNATURE)
if thought_sig:
accumulated_tool_calls[index][ToolKey.THOUGHT_SIGNATURE] = thought_sig
# Update the tool call with new information, preserving existing data
# Only update if the field exists and is not None in the delta
# For ID, preserve existing value if delta contains None or empty string (handles streaming inconsistencies)
if ToolKey.ID in tool_call_delta:
delta_id = tool_call_delta[ToolKey.ID]
if delta_id is not None and delta_id != "":
accumulated_tool_calls[index][ToolKey.ID] = delta_id
# If tool_call_delta[ToolKey.ID] is None or empty string, keep the existing ID value
if ToolKey.FUNCTION in tool_call_delta:
function_delta = tool_call_delta[ToolKey.FUNCTION]
if (ToolKey.NAME in function_delta and function_delta[ToolKey.NAME] is not None
and function_delta[ToolKey.NAME] != ""):
accumulated_tool_calls[index][ToolKey.FUNCTION][ToolKey.NAME] = function_delta[ToolKey.NAME]
# If function_delta[ToolKey.NAME] is None or empty, keep the existing name value
if ToolKey.ARGUMENTS in function_delta and function_delta[ToolKey.ARGUMENTS] is not None:
accumulated_tool_calls[index][ToolKey.FUNCTION][ToolKey.ARGUMENTS] += function_delta[ToolKey.ARGUMENTS]
@staticmethod
def _build_usage_metadata(usage_data: dict) -> GenerateContentResponseUsageMetadata:
"""Build ``GenerateContentResponseUsageMetadata`` from a raw usage dict.
``cache_read_input_tokens`` prefers Anthropic/LiteLLM-style top-level fields;
falls back to OpenAI-style ``prompt_tokens_details.cached_tokens``.
"""
completion_details = usage_data.get("completion_tokens_details") or {}
cache_read = usage_data.get("cache_read_input_tokens")
if cache_read is None:
details = usage_data.get("prompt_tokens_details")
cache_read = details.get("cached_tokens") if isinstance(details, dict) else None
return GenerateContentResponseUsageMetadata(
prompt_token_count=usage_data.get("prompt_tokens", 0),
candidates_token_count=usage_data.get("completion_tokens", 0),
thoughts_token_count=completion_details.get("reasoning_tokens"),
total_token_count=usage_data.get("total_tokens", 0),
cache_read_input_tokens=cache_read,
cache_creation_input_tokens=usage_data.get("cache_creation_input_tokens"),
)
def _process_usage(self, chunk_dict: dict) -> Optional[GenerateContentResponseUsageMetadata]:
"""Extract usage metadata from a streaming chunk dict."""
usage_data = chunk_dict.get(const.USAGE)
return self._build_usage_metadata(usage_data) if usage_data is not None else None
def _process_chunk_without_content(
self, chunk_dict: dict, accumulated_tool_calls: list[dict]
) -> tuple[Optional[FinishReason], Optional[GenerateContentResponseUsageMetadata], dict[int, str]]:
"""Process a chunk that doesn't contain content.
Args:
chunk_dict (`dict`): The chunk dictionary to process
accumulated_tool_calls (`list`): The list of accumulated tool calls
Returns:
Tuple of (finish_reason, usage_metadata, delta_arguments).
delta_arguments maps tool index to this chunk's argument delta string.
"""
choices = chunk_dict.get(const.CHOICES, [{}])
# Handle case where choices could be None (e.g., DeepSeek thinking events)
if choices is None or not choices:
# Return early with only usage data if available
usage = self._process_usage(chunk_dict)
return None, usage, {}
choice: dict = choices[0]
delta: dict = choice.get(const.DELTA, {})
if delta is None:
return None, None, {}
finish_reason = None
# Handle finish reason
if choice.get(const.FINISH_REASON):
finish_reason = self._parse_finish_reason(choice[const.FINISH_REASON])
# Handle usage
usage = self._process_usage(chunk_dict)
# Handle tool calls in chunks without content (this is where streaming tool calls happen)
tool_calls_data = delta.get(const.TOOL_CALLS)
# Track delta arguments from this chunk
delta_arguments: dict[int, str] = {}
if tool_calls_data and tool_calls_data is not None:
for tool_call_delta in tool_calls_data:
if tool_call_delta is None:
continue
try:
# Extract delta arguments before processing (for delta mode)
index = tool_call_delta.get(const.INDEX, 0) or 0
function_delta = tool_call_delta.get(ToolKey.FUNCTION, {})
if function_delta and ToolKey.ARGUMENTS in function_delta:
delta_arg = function_delta.get(ToolKey.ARGUMENTS)
if delta_arg is not None:
delta_arguments[index] = delta_arg
self._process_tool_call_delta(tool_call_delta, accumulated_tool_calls)
except Exception as ex: # pylint: disable=broad-except
logger.error("Error processing tool call delta: %s", ex)
continue
return finish_reason, usage, delta_arguments
def _create_complete_tool_calls(self, accumulated_tool_calls: list[dict]) -> Optional[List[ToolCall]]:
"""Create ToolCall objects only for complete tool calls with valid data.
Args:
accumulated_tool_calls (`list`): The list of accumulated tool calls
Returns:
`Optional[List[ToolCall]]`: List of complete tool calls or None
"""
if not accumulated_tool_calls:
return None
complete_tool_calls = []
for i, tool_call_data in enumerate(accumulated_tool_calls):
# Only create ToolCall if we have complete data
function_map: dict = tool_call_data.get(ToolKey.FUNCTION, {})
# Check if we have the essential fields (name and arguments)
has_name = ToolKey.NAME in function_map and function_map[ToolKey.NAME]
has_arguments = ToolKey.ARGUMENTS in function_map
if has_name and has_arguments:
try:
# Streaming tool-call accumulator: keep STRICT json.loads here.
# Incomplete deltas (e.g. ``{"foo":``) must raise so the loop
# can wait for the next chunk; using a repair-style parser
# would prematurely emit half-formed tool calls.
arguments_str: str = function_map[ToolKey.ARGUMENTS].strip()
if arguments_str:
arguments = json.loads(arguments_str)
else:
arguments = {}
# Handle missing or empty ID by generating a fallback
tool_call_id = tool_call_data.get(ToolKey.ID, "")
if not tool_call_id:
# Generate a fallback ID if missing
tool_call_id = f"call_{uuid.uuid4().hex[:24]}"
logger.warning("Generated fallback ID '%s' for tool call with missing ID", tool_call_id)
thought_sig = tool_call_data.get(ToolKey.THOUGHT_SIGNATURE) or None
logger.debug("Creating tool call: id=%s, name=%s, arguments=%s", tool_call_id,
function_map[ToolKey.NAME], arguments)
complete_tool_calls.append(
ToolCall(
id=tool_call_id,
name=function_map[ToolKey.NAME],
arguments=arguments,
thought_signature=thought_sig,
))
except json.JSONDecodeError as ex:
# Arguments not complete yet, skip this tool call
logger.debug("JSON decode error for tool call %s: %s", i, ex)
continue
except Exception as ex: # pylint: disable=broad-except
logger.warning("Failed to create complete tool call: %s, error: %s", tool_call_data, ex)
continue
return complete_tool_calls if complete_tool_calls else None
def _create_streaming_tool_call_response(
self,
accumulated_tool_calls: list[dict],
delta_arguments: Optional[dict[int, str]] = None,
streaming_tool_names: Optional[set] = None,
) -> Optional[LlmResponse]:
"""Create a streaming tool call response with delta arguments.
This method creates LlmResponse events for streaming tool call arguments,
allowing real-time display of tool call arguments as they are generated.
Only the delta (new content from this chunk) is included in the response.
The agent layer is responsible for accumulating deltas.
Args:
accumulated_tool_calls: The accumulated tool calls so far (used to get name/id)
delta_arguments: Dict mapping tool index to this chunk's delta arguments.
streaming_tool_names: Set of tool names that should receive streaming events.
If None, all tools receive streaming events.
Returns:
LlmResponse with delta tool call information, or None if no valid data
"""
if not accumulated_tool_calls:
return None
parts = []
for idx, tool_call_data in enumerate(accumulated_tool_calls):
function_map: dict = tool_call_data.get(ToolKey.FUNCTION, {})
name = function_map.get(ToolKey.NAME, "")
tool_call_id = tool_call_data.get(ToolKey.ID, "")
if not name:
continue
# Only process tools that are in the streaming_tool_names set
if streaming_tool_names is not None and name not in streaming_tool_names:
continue
# Only process tool calls that have delta updates in this chunk
if delta_arguments is None or idx not in delta_arguments:
continue
delta = delta_arguments[idx]
# Delta mode: send only the delta for this chunk
# Agent layer accumulates deltas to build complete JSON
function_part = Part.from_function_call(name=name, args={const.TOOL_STREAMING_ARGS: delta})
if tool_call_id:
function_part.function_call.id = tool_call_id # type: ignore
parts.append(function_part)
if not parts:
return None
streaming_content = Content(parts=parts, role=const.MODEL)
return LlmResponse(
content=streaming_content,
partial=True,
)
def _verify_text_content_in_openai_message_response(
self,
response: dict,
allow_content_none: bool = False,
) -> bool:
"""Verify if the text content exists in the openai message response.
Args:
response (`dict`):
The JSON-format OpenAI response (After calling `model_dump`
function)
allow_content_none (`bool`, defaults to `False`):
If the content can be `None`
Returns:
`bool`: If the text content exists
"""
choices: list[dict] = response.get(const.CHOICES, [{}])
# Handle case where choices could be None (e.g., DeepSeek thinking events)
if choices is None or not choices:
return False
if const.MESSAGE not in choices[0]:
return False
if not allow_content_none:
return const.CONTENT in choices[0][const.MESSAGE]
return True
def _process_tool_calls_from_message(self, message: dict) -> Optional[List[ToolCall]]:
"""Process tool calls from a message.
Args:
message (`dict`): The message containing tool calls
Returns:
`Optional[List[ToolCall]]`: List of processed tool calls or None
"""
tool_calls_data = message.get(const.TOOL_CALLS, [])
if not tool_calls_data:
return None
tool_calls = []
for tool_call in tool_calls_data:
if tool_call is None:
continue
try:
thought_sig = tool_call.get(ToolKey.THOUGHT_SIGNATURE)
if not thought_sig and isinstance(tool_call.get(ToolKey.PROVIDER_SPECIFIC_FIELDS), dict):
thought_sig = tool_call[ToolKey.PROVIDER_SPECIFIC_FIELDS].get(ToolKey.THOUGHT_SIGNATURE)
arguments = json_loads_repair(tool_call[ToolKey.FUNCTION][ToolKey.ARGUMENTS])
if not isinstance(arguments, dict):
# json_repair can turn unrecoverable text (e.g. "NOT_JSON")
# into an empty string or list. Skip those so we never feed
# ToolCall a non-dict ``arguments`` value.
logger.warning(
"Skipping tool call with non-dict repaired arguments: %s -> %r",
tool_call,
arguments,
)
continue
tool_calls.append(
ToolCall(
id=tool_call[ToolKey.ID],
name=tool_call[ToolKey.FUNCTION][ToolKey.NAME],
arguments=arguments,
thought_signature=thought_sig,
))
except (KeyError, json.JSONDecodeError, TypeError) as ex: