Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
167 changes: 122 additions & 45 deletions astrbot/core/provider/sources/gemini_source.py
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,13 @@
"gemini-4-hydrogen": ("LOW", "MEDIUM", "HIGH", "XHIGH"),
}

_SERVER_SIDE_PART_ATTRS = (
"tool_call",
"tool_response",
"executable_code",
"code_execution_result",
)


class SuppressNonTextPartsWarning(logging.Filter):
"""过滤 Gemini SDK 中的非文本部分警告"""
Expand Down Expand Up @@ -269,6 +276,7 @@ async def _prepare_query_config(
if url_context:
tool_list.append(types.Tool(url_context=types.UrlContext()))

has_builtin_tool = bool(tool_list)
if tools:
func_desc = tools.get_func_desc_google_genai_style()
tool_list.append(
Expand All @@ -281,15 +289,34 @@ async def _prepare_query_config(
tool_config = None
has_func_decl = tool_list and any(t.function_declarations for t in tool_list)
if has_func_decl:
tool_config = types.ToolConfig(
function_calling_config=types.FunctionCallingConfig(
mode=(
types.FunctionCallingConfigMode.ANY
if tool_choice == "required"
else types.FunctionCallingConfigMode.AUTO
)
)
# Built-in tools + function calling on Gemini 3/4 require server-side
# tool invocations and VALIDATED (or ANY) mode instead of AUTO.
combines_tools = has_builtin_tool and (
is_gemini_4 or model_name.startswith(("gemini-3-", "gemini-3."))
)
if tool_choice == "required":
mode = types.FunctionCallingConfigMode.ANY
elif combines_tools:
mode = types.FunctionCallingConfigMode.VALIDATED
else:
mode = types.FunctionCallingConfigMode.AUTO
tool_config_kwargs = {
"function_calling_config": types.FunctionCallingConfig(mode=mode),
}
if combines_tools:
# google-genai<1.68.0 lacks this field and rejects unknown kwargs.
if (
"include_server_side_tool_invocations"
in types.ToolConfig.model_fields
):
tool_config_kwargs["include_server_side_tool_invocations"] = True
else:
logger.warning(
"Gemini built-in tool combination with function calling "
"requires google-genai>=1.68.0; the installed SDK does not "
"support it."
)
tool_config = types.ToolConfig(**tool_config_kwargs)

extra_body = self.provider_config.get("custom_extra_body")
if extra_body is None:
Expand Down Expand Up @@ -461,6 +488,8 @@ def append_or_extend(
contents.append(content_cls(parts=part))

gemini_contents: list[types.Content] = []
# Map tool call IDs to function names for later tool result matching.
tool_id_to_name: dict[str, str] = {}
for message in payloads["messages"]:
role, content = message["role"], message.get("content")

Expand All @@ -480,6 +509,38 @@ def append_or_extend(

elif role == "assistant":
parts = []
tool_parts: list[types.Part] = []
if "tool_calls" in message:
for tool in message["tool_calls"]:
extra_content = tool.get("extra_content") or {}
google_extra = extra_content.get("google") or {}
function_name = tool["function"]["name"]
if tool.get("id"):
tool_id_to_name[tool["id"]] = function_name
# Replay server-side tool parts unchanged (with their thought signatures).
for server_side_part in google_extra.get("server_parts") or []:
try:
tool_parts.append(
types.Part.model_validate(server_side_part)
)
except Exception as e:
logger.warning(
"Failed to restore Gemini server-side tool part: %s",
e,
exc_info=True,
)
part = types.Part.from_function_call(
name=function_name,
args=json.loads(tool["function"]["arguments"]),
)
# we should set thought_signature back to part if exists
# for more info about thought_signature, see:
# https://ai.google.dev/gemini-api/docs/thought-signatures
ts_bs64 = google_extra.get("thought_signature")
if ts_bs64:
part.thought_signature = base64.b64decode(ts_bs64)
tool_parts.append(part)

Comment thread
sourcery-ai[bot] marked this conversation as resolved.
Resolved
if isinstance(content, str):
parts.append(types.Part.from_text(text=content))
elif isinstance(content, list):
Comment thread
sourcery-ai[bot] marked this conversation as resolved.
Resolved
Expand All @@ -502,21 +563,17 @@ def append_or_extend(
)
thinking_signature = None

if (
not text
and thinking_signature
and "tool_calls" in message
has_duplicate_thought_signature = bool(
thinking_signature
and any(
isinstance(tool, dict)
and isinstance(tool.get("extra_content"), dict)
and isinstance(tool["extra_content"].get("google"), dict)
and tool["extra_content"]["google"].get("thought_signature")
for tool in message["tool_calls"]
tool_part.thought_signature == thinking_signature
for tool_part in tool_parts
)
):
# If the main content is empty but tool calls have thought signatures,
# skip adding an empty text part to deduplicate the thinking signature in the main content and tool calls.
pass
)
if has_duplicate_thought_signature:
# Omit duplicate thought_signature already carried by a tool/server part.
if text:
parts.append(types.Part(text=text))
Comment thread
DOTBave marked this conversation as resolved.
Resolved
else:
parts.append(
types.Part(
Expand All @@ -525,32 +582,19 @@ def append_or_extend(
)
)

if "tool_calls" in message:
for tool in message["tool_calls"]:
part = types.Part.from_function_call(
name=tool["function"]["name"],
args=json.loads(tool["function"]["arguments"]),
)
# we should set thought_signature back to part if exists
# for more info about thought_signature, see:
# https://ai.google.dev/gemini-api/docs/thought-signatures
if "extra_content" in tool and tool["extra_content"]:
ts_bs64 = (
tool["extra_content"]
.get("google", {})
.get("thought_signature")
)
if ts_bs64:
part.thought_signature = base64.b64decode(ts_bs64)
parts.append(part)
parts.extend(tool_parts)

if not parts:
parts = [types.Part.from_text(text=" ")]

append_or_extend(gemini_contents, parts, types.ModelContent)

elif role == "tool":
func_name = message.get("name", message["tool_call_id"])
tool_call_id = message["tool_call_id"]
# Resolve function name from preceding assistant tool calls via call ID.
func_name = message.get("name") or tool_id_to_name.get(
tool_call_id, tool_call_id
)
part = types.Part.from_function_response(
name=func_name,
response={
Expand Down Expand Up @@ -673,6 +717,7 @@ def _process_content_parts(
for part in result_parts
):
chain.append(Comp.Plain("这是图片"))
server_side_parts: list[dict] = []
for part in result_parts:
# Skip thinking parts — their text is already captured via
# _extract_reasoning_content above. Including them here would
Expand Down Expand Up @@ -707,9 +752,23 @@ def _process_content_parts(
):
chain.append(Comp.Image.fromBytes(part.inline_data.data))

if ts := part.thought_signature:
# only keep the last thinking signature
if any(getattr(part, attr, None) for attr in _SERVER_SIDE_PART_ATTRS):
server_side_parts.append(
part.model_dump(exclude_none=True, mode="json")
)
elif ts := part.thought_signature:
# Only keep the last thinking signature from non-server-side parts.
llm_response.reasoning_signature = base64.b64encode(ts).decode("utf-8")

# Store server-side parts on the first custom tool call for replay.
if server_side_parts and llm_response.tools_call_ids:
Comment thread
DOTBave marked this conversation as resolved.
Resolved
Comment thread
sourcery-ai[bot] marked this conversation as resolved.
Resolved
Comment thread
sourcery-ai[bot] marked this conversation as resolved.
Resolved
Comment thread
sourcery-ai[bot] marked this conversation as resolved.
Resolved
Comment thread
sourcery-ai[bot] marked this conversation as resolved.
Resolved
google_extra = llm_response.tools_call_extra_content.setdefault(
llm_response.tools_call_ids[0], {}
).setdefault("google", {})
google_extra["server_parts"] = [
*server_side_parts,
Comment thread
DOTBave marked this conversation as resolved.
Resolved
*(google_extra.get("server_parts") or []),
Comment thread
sourcery-ai[bot] marked this conversation as resolved.
Resolved
]
chain_result = MessageChain(chain=chain)
Comment thread
DOTBave marked this conversation as resolved.
Resolved
llm_response.result_chain = chain_result
if validate_output:
Expand Down Expand Up @@ -880,6 +939,8 @@ async def _query_stream(
accumulated_text = ""
accumulated_reasoning = ""
final_response = None
# Buffer server-side tool parts until a custom tool call is emitted.
pending_server_side_parts: list[dict] = []

async with self._conversation_header(conversation_id):
async for chunk in result:
Expand All @@ -892,16 +953,25 @@ async def _query_stream(
logger.warning(f"Gemini stream chunk has empty content: {chunk}")
continue

if chunk.candidates[0].content.parts and any(
part.function_call for part in chunk.candidates[0].content.parts
):
chunk_parts = chunk.candidates[0].content.parts or []

if chunk_parts and any(part.function_call for part in chunk_parts):
llm_response = LLMResponse("assistant", is_chunk=False)
Comment thread
sourcery-ai[bot] marked this conversation as resolved.
Resolved
llm_response.raw_completion = chunk
llm_response.result_chain = self._process_content_parts(
chunk.candidates[0],
llm_response,
validate_output=False,
)
# Prepend earlier server-side parts so replay keeps response order.
if pending_server_side_parts and llm_response.tools_call_ids:
google_extra = llm_response.tools_call_extra_content.setdefault(
llm_response.tools_call_ids[0], {}
).setdefault("google", {})
google_extra["server_parts"] = [
*pending_server_side_parts,
*(google_extra.get("server_parts") or []),
]
# This response replaces the whole turn in conversation
# history, so keep the narration and reasoning that were
# already streamed before the tool call. Dropping them made
Expand All @@ -924,6 +994,13 @@ async def _query_stream(
yield llm_response
return

pending_server_side_parts.extend(
part.model_dump(exclude_none=True, mode="json")
for part in chunk_parts
if any(
getattr(part, attr, None) for attr in _SERVER_SIDE_PART_ATTRS
)
)
Comment thread
sourcery-ai[bot] marked this conversation as resolved.
Resolved
_f = False

# 提取 reasoning content
Expand Down
Loading
Loading