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
42 changes: 40 additions & 2 deletions astrbot/core/agent/runners/tool_loop_agent_runner.py
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,7 @@
ToolCallsResult,
)
from astrbot.core.provider.modalities import (
AUDIO_NOT_RECEIVED_HINT,
log_context_sanitize_stats,
sanitize_contexts_by_modalities,
)
Expand Down Expand Up @@ -371,6 +372,7 @@ async def reset(

# append existing messages in the run context
messages = load_messages(request.contexts or [])
new_user_message = False
if (
request.prompt is not None
or request.image_urls
Expand All @@ -379,12 +381,25 @@ async def reset(
):
m = await self._assemble_request_context_for_provider(request)
messages.append(Message.model_validate(m))
new_user_message = True
if request.system_prompt:
messages.insert(
0,
Message(role="system", content=request.system_prompt),
)
self.run_context.messages = messages
# Provider-reported tokens of the last request (input + output) and the
# number of leading messages it covers; messages added after it are
# estimated on top. The stored conversation usage covers the history
# and system prompt, but not the new user message.
conversation_usage = (
request.conversation.token_usage if request.conversation else 0
)
self._usage_baseline: tuple[int, int] | None = (
(conversation_usage, len(messages) - int(new_user_message))
Comment on lines +398 to +399

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Medium · Changed system prompts go uncounted

When a later request in the same conversation has a changed system prompt, _usage_baseline treats the current leading messages as covered by the previous request's usage, even though the current system_prompt may differ from the one that was measured; the changed prompt is therefore not estimated and context compression can start too late.

Track whether the measured system prompt matches the current one and estimate the current prompt when it does not.

Prompt for AI agents
In `astrbot/core/agent/runners/tool_loop_agent_runner.py` at lines 425-426:

**Changed system prompts go uncounted**

When a later request in the same conversation has a changed system prompt, `_usage_baseline` treats the current leading messages as covered by the previous request's usage, even though the current `system_prompt` may differ from the one that was measured; the changed prompt is therefore not estimated and context compression can start too late.

Track whether the measured system prompt matches the current one and estimate the current prompt when it does not.

if conversation_usage
else None
)

self.stats = AgentStats()
self.stats.start_time = time.time()
Expand Down Expand Up @@ -426,7 +441,7 @@ async def _assemble_request_context_for_provider(
content_blocks.append({"type": "text", "text": "[Image]"})
if not supports_audio:
for _ in request.audio_urls:
content_blocks.append({"type": "text", "text": "[Audio]"})
content_blocks.append({"type": "text", "text": AUDIO_NOT_RECEIVED_HINT})

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Medium · Extra audio reaches unsupported models

When a caller supplies an AudioURLPart in extra_user_content_parts while the model does not support audio, the runner handles request.audio_urls but leaves the extra audio part on the adjusted request; the provider can receive unsupported audio or reduce it to a bare [Audio] placeholder without guidance.

Remove or replace unsupported audio parts in extra_user_content_parts with AUDIO_NOT_RECEIVED_HINT.

Also at astrbot/core/provider/sources/anthropic_source.py:1126-1127.

Prompt for AI agents
In `astrbot/core/agent/runners/tool_loop_agent_runner.py` at line 471:

**Extra audio reaches unsupported models**

When a caller supplies an `AudioURLPart` in `extra_user_content_parts` while the model does not support audio, the runner handles `request.audio_urls` but leaves the extra audio part on the adjusted request; the provider can receive unsupported audio or reduce it to a bare `[Audio]` placeholder without guidance.

Remove or replace unsupported audio parts in `extra_user_content_parts` with `AUDIO_NOT_RECEIVED_HINT`.

Also at `astrbot/core/provider/sources/anthropic_source.py:1126-1127`.


return {"role": "user", "content": content_blocks}

Expand Down Expand Up @@ -1254,7 +1269,21 @@ async def _step(self) -> T.AsyncGenerator[RunnerEventPayload | AgentResponse, No
await self._append_pending_follow_ups()

# Process request-time context before sending it to the provider.
token_usage = self.req.conversation.token_usage if self.req.conversation else 0
# The last reported usage (input and output) covers the messages that
# existed then plus the reply; only messages added since (tool results,
# a new user message) are estimated on top. Without a usable report, 0
# lets the context manager estimate the whole context.
token_usage = 0
if self._usage_baseline:
tokens, count = self._usage_baseline
if count <= len(self.run_context.messages):
added = self.run_context.messages[count:]
if added and added[0].role == "assistant":

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Medium · Missing usage skips new reply tokens

When a request with a usage report is followed in the tool loop by a response without one, such as a tool-call response whose provider omits usage, the previous _usage_baseline remains in place when a later response has no usage report, so _step treats that response’s assistant message as already counted and excludes it from the estimate. Context compression can then undercount the history and send an oversized request.

Clear or otherwise invalidate the baseline when a response lacks usage, and estimate all messages added since the last valid report.

Prompt for AI agents
In `astrbot/core/agent/runners/tool_loop_agent_runner.py` at line 1229:

**Missing usage skips new reply tokens**

When a request with a usage report is followed in the tool loop by a response without one, such as a tool-call response whose provider omits usage, the previous `_usage_baseline` remains in place when a later response has no usage report, so `_step` treats that response’s assistant message as already counted and excludes it from the estimate. Context compression can then undercount the history and send an oversized request.

Clear or otherwise invalidate the baseline when a response lacks usage, and estimate all messages added since the last valid report.

# The reply to the measured request is already counted.
added = added[1:]
token_usage = tokens + (
self.request_context_manager.token_counter.count_tokens(added)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Medium · Truncated history is overcounted

When turn-limit truncation removes messages covered by the usage baseline, ContextManager.process truncates the history, but the runner still passes the baseline calculated from the full history; EstimateTokenCounter.count_tokens treats that stale value as the whole count, triggering unnecessary compression and discarding more turns.

Reconcile the trusted usage baseline with the messages remaining after turn-limit truncation.

Prompt for AI agents
In `astrbot/core/agent/runners/tool_loop_agent_runner.py` at line 1233:

**Truncated history is overcounted**

When turn-limit truncation removes messages covered by the usage baseline, `ContextManager.process` truncates the history, but the runner still passes the baseline calculated from the full history; `EstimateTokenCounter.count_tokens` treats that stale value as the whole count, triggering unnecessary compression and discarding more turns.

Reconcile the trusted usage baseline with the messages remaining after turn-limit truncation.

)
self._simple_print_message_role("[BefCompact]", self.run_context.messages)
previous_messages = self.run_context.messages
context_revision = self.request_context_manager.revision
Expand All @@ -1267,6 +1296,11 @@ async def _step(self) -> T.AsyncGenerator[RunnerEventPayload | AgentResponse, No
if processed_messages is None:
await self._finalize_aborted_step()
return
if processed_messages is not previous_messages or (
self.request_context_manager.revision != context_revision
):
# Compression rewrote the history; the reported usage no longer applies.
self._usage_baseline = None
self.run_context.messages = processed_messages
if self._conversation_event_sink is not None and (
processed_messages is not previous_messages
Expand Down Expand Up @@ -1336,6 +1370,10 @@ async def _step(self) -> T.AsyncGenerator[RunnerEventPayload | AgentResponse, No
self.stats.current_context_tokens = llm_response.usage.input
if self.req.conversation:
self.req.conversation.token_usage = llm_response.usage.total
self._usage_baseline = (
llm_response.usage.total,
len(self.run_context.messages),
)
# Preserve legacy statistics for history and plugin readers.
self.stats.end_time = time.time()
break # got final response
Expand Down
4 changes: 3 additions & 1 deletion astrbot/core/agent_output.py
Original file line number Diff line number Diff line change
Expand Up @@ -177,7 +177,9 @@ async def present_turn(
detail=result.error.message
or translate("unknown_error", locale),
)
if result.error and result.error.code == "provider_error"
# Provider failures may carry a specific code, e.g.
# "providerAuth" (see classify_provider_failure).
if result.error and result.error.code.startswith("provider")
else f"Error occurred during AI execution.\n{result.error.message if result.error else 'Unknown error'}"
)
if event.get_platform_name() == "webchat":
Expand Down
9 changes: 7 additions & 2 deletions astrbot/core/astr_agent_runtime/execution.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
from astrbot.core.agent_output_content import content_from_chain
from astrbot.core.astr_agent_runtime.history import ConversationHistoryObserver
from astrbot.core.astr_agent_runtime.runner import AgentRunner, _watch_agent_stop_signal
from astrbot.core.llm_error_messages import classify_provider_failure

if TYPE_CHECKING:
from astrbot.core.agent.conversation_events import ConversationEventWriter
Expand Down Expand Up @@ -62,7 +63,8 @@ async def create_native_runner(

max_context_tokens = provider.provider_config.get("max_context_tokens", 0)
if max_context_tokens <= 0:
model_info = LLM_METADATAS.get(provider.get_model())
# Use the model selected for this request, not the provider's default.
model_info = LLM_METADATAS.get(request.model or provider.get_model())

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Medium · Fallback requests exceed context limits

When the selected primary model has a larger context window than a configured fallback's default model, and the primary request fails, create_native_runner sizes the context manager for the primary model, but _iter_llm_responses_with_fallback uses the fallback provider's default model; its smaller window then rejects the uncompressed history.

Size or re-compress the context for each fallback provider's selected model before sending its request.

Prompt for AI agents
In `astrbot/core/astr_agent_runtime/execution.py` at line 67:

**Fallback requests exceed context limits**

When the selected primary model has a larger context window than a configured fallback's default model, and the primary request fails, `create_native_runner` sizes the context manager for the primary model, but `_iter_llm_responses_with_fallback` uses the fallback provider's default model; its smaller window then rejects the uncompressed history.

Size or re-compress the context for each fallback provider's selected model before sending its request.

max_context_tokens = (
model_info["limit"]["context"]
if model_info
Expand Down Expand Up @@ -209,7 +211,10 @@ async def execute_native_loop(
if error
else TurnStatus.COMPLETED,
content=content if not error else (),
error=RuntimeErrorInfo(code="provider_error", message=response.completion_text)
error=RuntimeErrorInfo(
code=classify_provider_failure(response.completion_text),
message=response.completion_text,
)
Comment on lines +215 to +217

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Medium · Request failures keep generic codes

When a client uses the public request.finished event to display a provider failure, execute_native_loop classifies the final TurnResult, but the runner separately emits RequestFinished.error as provider_error; clients consuming the per-request event still receive the generic code for these provider failures.

Apply the same classifier when constructing RequestFinished.error (and any corresponding per-request message.appended error).

Prompt for AI agents
In `astrbot/core/astr_agent_runtime/execution.py` at lines 215-217:

**Request failures keep generic codes**

When a client uses the public `request.finished` event to display a provider failure, `execute_native_loop` classifies the final `TurnResult`, but the runner separately emits `RequestFinished.error` as `provider_error`; clients consuming the per-request event still receive the generic code for these provider failures.

Apply the same classifier when constructing `RequestFinished.error` (and any corresponding per-request `message.appended` error).

if error and response is not None
else None,
reason=runner.run_context.run_end_reason or "completed",
Expand Down
51 changes: 51 additions & 0 deletions astrbot/core/llm_error_messages.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
from __future__ import annotations

import re
from typing import TYPE_CHECKING

if TYPE_CHECKING:
Expand Down Expand Up @@ -61,3 +62,53 @@ def set_llm_error_message(event: AstrMessageEvent, key: str, **params: str) -> N
messages = LLM_ERROR_MESSAGES.get(locale, LLM_ERROR_MESSAGES["zh-CN"])
event.set_extra(LLM_ERROR_CODE_EXTRA_KEY, key)
event.set_extra(LLM_ERROR_MESSAGE_EXTRA_KEY, messages[key].format(**params))


# Provider failures reach the turn result only as text (exception class and
# message, e.g. "All chat models failed: AuthenticationError: Error code: 401").
# These patterns give ChatUI a stable code for the failures a user can fix.
_PROVIDER_FAILURE_CODES = (
(
"providerToolsRequireResponses",
# The advice in OpenAI's error, not any mention of the path: a proxy
# 404 for "POST /v1/responses" is not this case.
re.compile(r"use /v1/responses", re.IGNORECASE),
),
(
"providerAuth",
re.compile(
r"AuthenticationError|PermissionDeniedError|Error code: 40[13]\b"
r"|\b40[13] (?:UNAUTHENTICATED|PERMISSION_DENIED)\b"
r"|invalid[ _-]?api[ _-]?key|incorrect api key",
re.IGNORECASE,
),
),
(
"providerRateLimit",
re.compile(
r"RateLimitError|Error code: 429\b|\b429 RESOURCE_EXHAUSTED\b"
r"|insufficient_quota",
re.IGNORECASE,
),
),
(
"providerModelNotFound",
re.compile(r"NotFoundError|Error code: 404\b", re.IGNORECASE),
),
)


def classify_provider_failure(text: str) -> str:
"""Return a stable code for a failed model request.

Args:
text: Error text of the failed request.

Returns:
One of the provider failure codes, or ``provider_error`` when the
failure has no specific user action.
"""
for code, pattern in _PROVIDER_FAILURE_CODES:
if pattern.search(text or ""):
return code
return "provider_error"
10 changes: 10 additions & 0 deletions astrbot/core/provider/modalities.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,16 @@
from astrbot import logger
from astrbot.core.agent.message import Message

# Stands in for audio the current model cannot receive, so the model tells the
# user how to fix it instead of pretending it heard the attachment.
AUDIO_NOT_RECEIVED_HINT = (

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Medium · Old audio history misleads the model

When conversation history contains audio and a later request uses a model without audio support, sanitize_contexts_by_modalities still replaces historical audio with [Audio] instead of AUDIO_NOT_RECEIVED_HINT, so the model is not told that it never received the attachment.

Use AUDIO_NOT_RECEIVED_HINT when sanitizing unsupported audio in conversation history.

Also at astrbot/core/agent/runners/tool_loop_agent_runner.py:471.

Prompt for AI agents
In `astrbot/core/provider/modalities.py` at line 13:

**Old audio history misleads the model**

When conversation history contains audio and a later request uses a model without audio support, `sanitize_contexts_by_modalities` still replaces historical audio with `[Audio]` instead of `AUDIO_NOT_RECEIVED_HINT`, so the model is not told that it never received the attachment.

Use `AUDIO_NOT_RECEIVED_HINT` when sanitizing unsupported audio in conversation history.

Also at `astrbot/core/agent/runners/tool_loop_agent_runner.py:471`.

"[Audio attachment not received: this model cannot take audio input and the "
"audio was not transcribed. Tell the user you cannot hear it, and that they "
"can enable speech recognition in the AstrBot WebUI (Config > AI > Model > "
"Speech recognition) and choose a speech-to-text model, or switch to a model "
"that accepts audio.]"
)


@dataclass(slots=True)
class ContextSanitizeStats:
Expand Down
96 changes: 87 additions & 9 deletions astrbot/core/provider/sources/anthropic_source.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@
)

from ..headers import build_conversation_headers, build_provider_headers
from ..modalities import AUDIO_NOT_RECEIVED_HINT
from ..register import register_provider_adapter
from .request_retry import retry_provider_request, retry_provider_request_context

Expand All @@ -38,6 +39,10 @@
)
class ProviderAnthropic(Provider):
_PROMPT_CACHE_CONTROL = {"type": "ephemeral"}
_MAX_CACHE_BREAKPOINTS = 4
_CACHEABLE_BLOCK_TYPES = frozenset(
{"text", "image", "document", "tool_use", "tool_result"}
)

@staticmethod
def _ensure_usable_response(
Expand Down Expand Up @@ -507,14 +512,84 @@ def _normalize_tool_choice(tool_choice) -> dict:
return {"type": "auto"}

@classmethod
def _apply_explicit_prompt_cache_breakpoints(cls, payloads: dict) -> None:
def _apply_explicit_prompt_cache_breakpoints(
cls, payloads: dict, extra_tools: list | None = None
) -> None:
"""Mark the system prompt and the conversation tail as cache breakpoints.

The system breakpoint caches the tool definitions and system prompt.
The tail breakpoint caches the whole conversation so far, so the next
request (a tool result or the next user turn) reads the history from
the cache instead of paying for it again. Only cache markers are
added; the content sent to the model is unchanged.

Args:
payloads: Anthropic request payload, modified in place.
extra_tools: Tool definitions supplied through the SDK extra body.
"""
system_blocks = payloads.get("system")
if not isinstance(system_blocks, list) or not system_blocks:
messages = payloads.get("messages")
tools = extra_tools if isinstance(extra_tools, list) else payloads.get("tools")
blocks = [
*(system_blocks if isinstance(system_blocks, list) else []),
*(tools if isinstance(tools, list) else []),
*(
part
for message in (messages if isinstance(messages, list) else [])
if isinstance(message, dict)
and isinstance(message.get("content"), list)
for part in message["content"]
),
]
# The API's four-breakpoint budget includes tool definitions.
count = sum(
isinstance(block, dict) and "cache_control" in block for block in blocks
)
if count >= cls._MAX_CACHE_BREAKPOINTS:
return

last_block = system_blocks[-1]
if isinstance(last_block, dict) and "cache_control" not in last_block:
last_block["cache_control"] = dict(cls._PROMPT_CACHE_CONTROL)
if isinstance(system_blocks, list) and system_blocks:
last_block = system_blocks[-1]
if isinstance(last_block, dict) and "cache_control" not in last_block:
last_block["cache_control"] = dict(cls._PROMPT_CACHE_CONTROL)
count += 1
if (
count >= cls._MAX_CACHE_BREAKPOINTS
or not isinstance(messages, list)
or not messages
):
return
last_message = messages[-1]
if not isinstance(last_message, dict):
return
content = last_message.get("content")
if isinstance(content, str):
if content:
last_message["content"] = [
{
"type": "text",
"text": content,
"cache_control": dict(cls._PROMPT_CACHE_CONTROL),
}
]
return
if not isinstance(content, list):
return
for index in range(len(content) - 1, -1, -1):
block = content[index]
if not isinstance(block, dict) or "cache_control" in block:
return
if block.get("type") in cls._CACHEABLE_BLOCK_TYPES and (
block.get("type") != "text" or block.get("text")
):
# A new list and block dict keep the marker out of the
# caller's message history.
content = list(content)
content[index] = {
**block,
"cache_control": dict(cls._PROMPT_CACHE_CONTROL),
}
last_message["content"] = content
return

async def _query(
self,
Expand Down Expand Up @@ -553,9 +628,10 @@ async def _query(

if "max_tokens" not in payloads:
payloads["max_tokens"] = 65536
self._apply_explicit_prompt_cache_breakpoints(payloads)
self._apply_thinking_config(payloads)
self._sanitize_assistant_messages(payloads)
# Mark the final, sanitized blocks so a dropped block cannot take a marker.
self._apply_explicit_prompt_cache_breakpoints(payloads, extra_body.get("tools"))

try:
completion = await retry_provider_request(
Expand Down Expand Up @@ -677,9 +753,10 @@ async def _query_stream(

if "max_tokens" not in payloads:
payloads["max_tokens"] = 65536
self._apply_explicit_prompt_cache_breakpoints(payloads)
self._apply_thinking_config(payloads)
self._sanitize_assistant_messages(payloads)
# Mark the final, sanitized blocks so a dropped block cannot take a marker.
self._apply_explicit_prompt_cache_breakpoints(payloads, extra_body.get("tools"))

async with retry_provider_request_context(
"Anthropic",
Expand Down Expand Up @@ -1044,8 +1121,9 @@ async def resolve_image_url(image_url: str) -> dict | None:
if image_dict:
content.append(image_dict)
if audio_urls:
# The Anthropic Messages API has no audio input block.
for _audio_path in audio_urls:
content.append({"type": "text", "text": "[Audio]"})
content.append({"type": "text", "text": AUDIO_NOT_RECEIVED_HINT})

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟠 High · Native Anthropic requests still send audio

When an audio attachment reaches the native Anthropic runner while its modalities setting is unset or empty, the native runner bypasses ProviderAnthropic.assemble_context and, when modalities are unset or empty, calls ProviderRequest.assemble_context instead. That builds an audio_url block, which the Anthropic Messages API cannot accept, so the request fails without the new guidance reaching the model.

Route native request assembly through provider-specific audio handling, or ensure Anthropic requests receive the hint even when modalities are unset.

Prompt for AI agents
In `astrbot/core/provider/sources/anthropic_source.py` at line 1126:

**Native Anthropic requests still send audio**

When an audio attachment reaches the native Anthropic runner while its modalities setting is unset or empty, the native runner bypasses `ProviderAnthropic.assemble_context` and, when modalities are unset or empty, calls `ProviderRequest.assemble_context` instead. That builds an `audio_url` block, which the Anthropic Messages API cannot accept, so the request fails without the new guidance reaching the model.

Route native request assembly through provider-specific audio handling, or ensure Anthropic requests receive the hint even when modalities are unset.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Medium · Audio-only requests retain bare placeholder

When an Anthropic request contains audio URLs but no text, assemble_context first adds [Audio] when text is empty and audio_urls is nonempty, then appends AUDIO_NOT_RECEIVED_HINT for each URL; the model therefore receives both the misleading placeholder and the explanation.

Replace the audio-only placeholder with the hint, or omit the placeholder when the hint is appended.

Prompt for AI agents
In `astrbot/core/provider/sources/anthropic_source.py` at line 1126:

**Audio-only requests retain bare placeholder**

When an Anthropic request contains audio URLs but no text, `assemble_context` first adds `[Audio]` when `text` is empty and `audio_urls` is nonempty, then appends `AUDIO_NOT_RECEIVED_HINT` for each URL; the model therefore receives both the misleading placeholder and the explanation.

Replace the audio-only placeholder with the hint, or omit the placeholder when the hint is appended.


# 如果只有主文本且没有额外内容块和图片,返回简单格式以保持向后兼容
if (
Expand Down
26 changes: 20 additions & 6 deletions astrbot/core/provider/sources/openai_source.py
Original file line number Diff line number Diff line change
Expand Up @@ -1223,16 +1223,30 @@ async def _handle_api_error(
image_fallback_used=True,
)

if (
"Function calling is not enabled" in str(e)
or ("tool" in str(e).lower() and "support" in str(e).lower())
or ("function" in str(e).lower() and "support" in str(e).lower())
# OpenAI, Ollama, Gemini (OpenAI-compatible) and SiliconCloud report this
# with different codes, so only the message text can be matched.
if func_tool and re.search(
# Only match messages that say tools themselves are unsupported, so
# unrelated errors (e.g. "function tools with reasoning_effort are
# not supported", invalid tool schemas) are surfaced instead of
# silently dropping every tool.
r"function calling is not enabled"
r"|(?:does not|doesn't|do not|don't|not) support (?:the )?['\"]?"
r"(?:function calling|function calls?|functions|tools|tool use"
r"|tool calling|tool calls)\b"
r"|['\"]?(?:tools|tool use|tool calling|function calling|function calls?)"
r"['\"]? (?:is|are) not supported"
r"|no endpoints found that support tool use"
r"|不支持.{0,6}(?:工具|函数|function|tool)",
str(e),
re.IGNORECASE,
):
# openai, ollama, gemini openai, siliconcloud 的错误提示与 code 不统一,只能通过字符串匹配
logger.warning(
f"{self.get_model()} 不支持函数工具调用,已自动去除,不影响使用。如需永久关闭,可前往 WebUI 中关闭工具调用。",
f"{self.get_model()} 不支持函数工具调用,已自动去除,不影响使用。如需永久关闭,可前往 WebUI 中关闭工具调用。原始错误: {e}",

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Medium · Provider errors enter dashboard logs

When a configured OpenAI-compatible endpoint returns an unsupported-tools error whose message contains sensitive request data, the warning logs the provider-controlled exception verbatim, so an OpenAI-compatible endpoint that includes prompt content or credentials in its unsupported-tools error places that data in AstrBot's log cache and persistent logs, where dashboard users with system scope can read it.

Log a sanitized error summary or redact the exception before including it in the warning.

Prompt for AI agents
In `astrbot/core/provider/sources/openai_source.py` at line 1181:

**Provider errors enter dashboard logs**

When a configured OpenAI-compatible endpoint returns an unsupported-tools error whose message contains sensitive request data, the warning logs the provider-controlled exception verbatim, so an OpenAI-compatible endpoint that includes prompt content or credentials in its unsupported-tools error places that data in AstrBot's log cache and persistent logs, where dashboard users with system scope can read it.

Log a sanitized error summary or redact the exception before including it in the warning.

)
payloads.pop("tools", None)
# tool_choice without tools is rejected by OpenAI-compatible APIs.
payloads.pop("tool_choice", None)
Comment on lines 1247 to +1249

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Medium · Custom tools survive fallback retry

When custom_extra_body contains tools or tool_choice and the request also has function tools that trigger the unsupported-tools fallback, _query merges custom_extra_body after extracting request fields, so removing tools and tool_choice from payloads does not remove those keys from the configured extra body. The retry therefore still sends them and the tools-unsupported fallback fails instead of retrying without tools.

Remove or filter the custom extra-body tool fields for the retry as well, while preserving unrelated extra-body settings.

Prompt for AI agents
In `astrbot/core/provider/sources/openai_source.py` at lines 1183-1185:

**Custom tools survive fallback retry**

When `custom_extra_body` contains `tools` or `tool_choice` and the request also has function tools that trigger the unsupported-tools fallback, `_query` merges `custom_extra_body` after extracting request fields, so removing `tools` and `tool_choice` from `payloads` does not remove those keys from the configured extra body. The retry therefore still sends them and the tools-unsupported fallback fails instead of retrying without tools.

Remove or filter the custom extra-body tool fields for the retry as well, while preserving unrelated extra-body settings.

return (
False,
chosen_key,
Expand Down
Loading
Loading