From eb91b0cd7b8157f9c7f96acb13ac722aaf8a2e48 Mon Sep 17 00:00:00 2001 From: Turino Date: Tue, 17 Nov 2026 13:09:48 +1000 Subject: [PATCH 1/9] fix(openai): narrow the tools-unsupported fallback and drop tool_choice with tools The fallback that retries without tools matched any error mentioning "tool" or "function" together with "support", so unrelated errors such as invalid tool schemas or "function tools with reasoning_effort are not supported" silently removed every tool. It also kept tool_choice after removing tools, which OpenAI-compatible APIs reject. Match only messages saying that tools themselves are unsupported, only when tools were sent, drop tool_choice together with tools, and include the original error in the warning. --- .../core/provider/sources/openai_source.py | 23 ++++-- tests/test_openai_source.py | 79 +++++++++++++++++++ 2 files changed, 96 insertions(+), 6 deletions(-) diff --git a/astrbot/core/provider/sources/openai_source.py b/astrbot/core/provider/sources/openai_source.py index 97e14b7365..9bdfa6078d 100644 --- a/astrbot/core/provider/sources/openai_source.py +++ b/astrbot/core/provider/sources/openai_source.py @@ -1223,16 +1223,27 @@ 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" + r" (?:function calling|functions|tools|tool use|tool calling|tool calls)" + r"|(?:tools|tool use|tool calling|function calling) (?:is|are) not supported" + 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}", ) payloads.pop("tools", None) + # tool_choice without tools is rejected by OpenAI-compatible APIs. + payloads.pop("tool_choice", None) return ( False, chosen_key, diff --git a/tests/test_openai_source.py b/tests/test_openai_source.py index 5c8ae9b450..80bd00d1dd 100644 --- a/tests/test_openai_source.py +++ b/tests/test_openai_source.py @@ -2383,3 +2383,82 @@ async def fake_create(**kwargs): assert messages[1] == {"role": "user", "content": "again"} finally: await provider.terminate() + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + "message", + [ + "Error code: 400 - this model does not support tools", + "Function calling is not enabled for this model", + "tool calling is not supported by the selected model", + "当前模型不支持工具调用", + ], +) +async def test_handle_api_error_tools_unsupported_drops_tools_and_tool_choice( + message, +): + provider = _make_provider() + try: + payloads = { + "messages": [{"role": "user", "content": "hi"}], + "tools": [{"type": "function", "function": {"name": "f"}}], + "tool_choice": "auto", + } + + ( + success, + _key, + _keys, + new_payloads, + _ctx, + new_tools, + _img, + ) = await provider._handle_api_error( + Exception(message), + payloads=payloads, + context_query=payloads["messages"], + func_tool=object(), + chosen_key="test-key", + available_api_keys=["test-key"], + retry_cnt=0, + max_retries=10, + ) + + assert success is False + assert new_tools is None + assert "tools" not in new_payloads + assert "tool_choice" not in new_payloads + finally: + await provider.terminate() + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + "message", + [ + # gpt models on /v1/chat/completions: tools are supported, the + # combination with reasoning_effort is not (should surface, not drop). + "400 - Function tools with reasoning_effort are not supported for " + "gpt-x in /v1/chat/completions. To use function tools, use /v1/responses", + "Invalid schema for function 'lookup': 'format' is not supported", + ], +) +async def test_handle_api_error_unrelated_tool_errors_are_raised(message): + provider = _make_provider() + try: + payloads = {"messages": [], "tools": [{}], "tool_choice": "auto"} + with pytest.raises(Exception, match="not supported"): + await provider._handle_api_error( + Exception(message), + payloads=payloads, + context_query=[], + func_tool=object(), + chosen_key="test-key", + available_api_keys=["test-key"], + retry_cnt=0, + max_retries=10, + ) + assert "tools" in payloads + finally: + await provider.terminate() From 14507da27b3ee3ab2f296e4631ad2a096275bec8 Mon Sep 17 00:00:00 2001 From: Turino Date: Tue, 17 Nov 2026 13:09:49 +1000 Subject: [PATCH 2/9] fix(context): count context against the selected model and new messages The context window was looked up from the provider's default model even when the request selected another model, so a large selected model could be compressed early or a small one too late. Use the request's model. The token count before compression reused the previous request's reported total and ignored messages added since, such as the new user message or tool results. Keep the reported usage as a baseline for the messages it covers, estimate only newer messages on top, and drop the baseline after compression rewrites the history. --- .../agent/runners/tool_loop_agent_runner.py | 39 +++++- astrbot/core/astr_agent_runtime/execution.py | 3 +- tests/test_tool_loop_agent_runner.py | 117 ++++++++++++++++++ tests/unit/test_native_context_limit.py | 55 ++++++++ 4 files changed, 212 insertions(+), 2 deletions(-) create mode 100644 tests/unit/test_native_context_limit.py diff --git a/astrbot/core/agent/runners/tool_loop_agent_runner.py b/astrbot/core/agent/runners/tool_loop_agent_runner.py index ded393c72f..b4ad45c338 100644 --- a/astrbot/core/agent/runners/tool_loop_agent_runner.py +++ b/astrbot/core/agent/runners/tool_loop_agent_runner.py @@ -371,6 +371,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 @@ -379,12 +380,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)) + if conversation_usage + else None + ) self.stats = AgentStats() self.stats.start_time = time.time() @@ -1254,7 +1268,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": + # The reply to the measured request is already counted. + added = added[1:] + token_usage = tokens + ( + self.request_context_manager.token_counter.count_tokens(added) + ) self._simple_print_message_role("[BefCompact]", self.run_context.messages) previous_messages = self.run_context.messages context_revision = self.request_context_manager.revision @@ -1267,6 +1295,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 @@ -1336,6 +1369,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 diff --git a/astrbot/core/astr_agent_runtime/execution.py b/astrbot/core/astr_agent_runtime/execution.py index 378cdfbbba..f3530cf7a0 100644 --- a/astrbot/core/astr_agent_runtime/execution.py +++ b/astrbot/core/astr_agent_runtime/execution.py @@ -62,7 +62,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()) max_context_tokens = ( model_info["limit"]["context"] if model_info diff --git a/tests/test_tool_loop_agent_runner.py b/tests/test_tool_loop_agent_runner.py index e3e6a88a8d..cbd6e5a2ee 100644 --- a/tests/test_tool_loop_agent_runner.py +++ b/tests/test_tool_loop_agent_runner.py @@ -3092,3 +3092,120 @@ async def capture_request(**kwargs): assert len(finished) == 1 and finished[0].status == "completed" assert finished[0].structured_result is None wakeup.assert_not_awaited() + + +@pytest.mark.asyncio +async def test_trusted_context_tokens_add_new_messages_to_reported_usage( + runner, mock_provider, mock_tool_executor, mock_hooks, tool_set +): + """Reported usage covers the history; newer messages are estimated on top.""" + request = ProviderRequest( + prompt="new question " * 20, + system_prompt="system", + contexts=[ + {"role": "user", "content": "old question"}, + {"role": "assistant", "content": "old answer"}, + ], + conversation=SimpleNamespace(token_usage=1000, cid="c1"), + func_tool=tool_set, + ) + await runner.reset( + provider=mock_provider, + request=request, + run_context=ContextWrapper(context=None), + tool_executor=mock_tool_executor, + agent_hooks=mock_hooks, + streaming=False, + ) + manager = runner.request_context_manager + counter = manager.token_counter + seen = [] + process = manager.process + + async def recording_process(messages, trusted_token_usage=0): + seen.append(trusted_token_usage) + return await process(messages, trusted_token_usage=trusted_token_usage) + + manager.process = recording_process + user_tokens = counter.count_tokens([runner.run_context.messages[-1]]) + assert user_tokens > 0 + + # The stored usage covers the history; the new user message is estimated. + # A tool call makes the run take a second step, where the new report + # covers everything so far: only the tool result is estimated (the reply + # that asked for it is output of the measured request). + replies = 0 + + async def text_chat(**kwargs): + nonlocal replies + replies += 1 + return LLMResponse( + role="assistant", + completion_text="first reply" if replies == 1 else "done", + tools_call_name=["test_tool"] if replies == 1 else None, + tools_call_args=[{"query": "q"}] if replies == 1 else None, + tools_call_ids=["call_1"] if replies == 1 else None, + usage=TokenUsage(input_other=1490, output=10), + ) + + mock_provider.text_chat = text_chat + async for _ in runner.step_until_done(3): + pass + tool_result = next( + message for message in runner.run_context.messages if message.role == "tool" + ) + assert seen[0] == 1000 + user_tokens + assert seen[1] == 1500 + counter.count_tokens([tool_result]) + + # Without a usable report the context manager estimates everything. + await runner.reset( + provider=mock_provider, + request=ProviderRequest(prompt="new"), + run_context=ContextWrapper(context=None), + tool_executor=mock_tool_executor, + agent_hooks=mock_hooks, + ) + runner.request_context_manager.process = recording_process + await collect_events(runner.step()) + assert seen[-1] == 0 + + +@pytest.mark.asyncio +async def test_compaction_invalidates_reported_usage_before_next_provider_call( + runner, mock_provider, mock_tool_executor, mock_hooks +): + """Usage reported for the old history must not be reused after compression.""" + observed = [] + + async def reply(**kwargs): + observed.append((len(runner.run_context.messages), runner._usage_baseline)) + return LLMResponse( + role="assistant", + completion_text="done", + usage=TokenUsage(input_other=10, output=2), + ) + + mock_provider.text_chat = reply + request = ProviderRequest( + prompt="next", + contexts=[ + {"role": role, "content": "history " * 100} + for role in ("user", "assistant", "user", "assistant") + ], + conversation=SimpleNamespace(token_usage=4000, cid="c1"), + ) + await runner.reset( + provider=mock_provider, + request=request, + run_context=ContextWrapper(context=None), + tool_executor=mock_tool_executor, + agent_hooks=mock_hooks, + max_context_tokens=100, + truncate_turns=1, + ) + assert runner._usage_baseline == (4000, 4) + await collect_events(runner.step()) + # The history was shortened before the request and the baseline dropped. + assert len(observed) == 1 + assert observed[0][0] < 5 + assert observed[0][1] is None diff --git a/tests/unit/test_native_context_limit.py b/tests/unit/test_native_context_limit.py new file mode 100644 index 0000000000..c53c78e41b --- /dev/null +++ b/tests/unit/test_native_context_limit.py @@ -0,0 +1,55 @@ +from types import SimpleNamespace +from unittest.mock import AsyncMock + +import pytest + +from astrbot.core.agent.runners.tool_loop_agent_runner import ToolLoopAgentRunner +from astrbot.core.astr_agent_runtime import execution +from astrbot.core.astr_agent_runtime.main_agent import providers +from astrbot.core.provider.entities import ProviderRequest +from astrbot.core.utils import llm_metadata + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + ("selected", "expected"), [("big-model", 1_000_000), (None, 32_000)] +) +async def test_context_limit_follows_selected_model(monkeypatch, selected, expected): + monkeypatch.setitem( + llm_metadata.LLM_METADATAS, "small-default", {"limit": {"context": 32_000}} + ) + monkeypatch.setitem( + llm_metadata.LLM_METADATAS, "big-model", {"limit": {"context": 1_000_000}} + ) + monkeypatch.setattr( + providers, "resolve_compression_provider", AsyncMock(return_value=None) + ) + reset = AsyncMock() + monkeypatch.setattr(ToolLoopAgentRunner, "reset", reset) + provider = SimpleNamespace( + provider_config={"id": "p1"}, get_model=lambda: "small-default" + ) + config = SimpleNamespace( + fallback_max_context_tokens=128_000, + context_limit_reached_strategy="truncate_by_turns", + tool_call_timeout=60, + streaming_response=False, + llm_compress_instruction="", + llm_compress_keep_recent_ratio=0.15, + dequeue_context_length=1, + max_context_length=-1, + tool_schema_mode="full", + request_max_retries=1, + ) + await execution.create_native_runner( + SimpleNamespace(), + provider, + ProviderRequest(prompt="hi", model=selected), + config, + # A plain message event: no ChatUI options are set. + SimpleNamespace( + event=SimpleNamespace(get_extra=lambda key, default=None: None) + ), + fallback_providers=[], + ) + assert reset.call_args.kwargs["max_context_tokens"] == expected From 98171919f186c878e67fc9e5d0b5707a07c60992 Mon Sep 17 00:00:00 2001 From: Turino Date: Tue, 17 Nov 2026 13:09:49 +1000 Subject: [PATCH 3/9] fix: tell the model how to enable speech-to-text when it cannot hear audio Audio the current model cannot receive was replaced by a bare "[Audio]" placeholder, so models claimed to have received the attachment and then said they could not listen to it. For models without the audio modality, and for the Anthropic source whose Messages API has no audio input block, send a note asking the model to tell the user to enable speech recognition or switch to a model that accepts audio. --- .../agent/runners/tool_loop_agent_runner.py | 3 ++- astrbot/core/provider/modalities.py | 10 +++++++++ .../core/provider/sources/anthropic_source.py | 4 +++- tests/test_anthropic_source.py | 12 ++++++++++ tests/test_tool_loop_agent_runner.py | 22 +++++++++++++++++++ 5 files changed, 49 insertions(+), 2 deletions(-) diff --git a/astrbot/core/agent/runners/tool_loop_agent_runner.py b/astrbot/core/agent/runners/tool_loop_agent_runner.py index b4ad45c338..15eccc2a24 100644 --- a/astrbot/core/agent/runners/tool_loop_agent_runner.py +++ b/astrbot/core/agent/runners/tool_loop_agent_runner.py @@ -43,6 +43,7 @@ ToolCallsResult, ) from astrbot.core.provider.modalities import ( + AUDIO_NOT_RECEIVED_HINT, log_context_sanitize_stats, sanitize_contexts_by_modalities, ) @@ -440,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}) return {"role": "user", "content": content_blocks} diff --git a/astrbot/core/provider/modalities.py b/astrbot/core/provider/modalities.py index 66ac74e9b7..d40e55af8a 100644 --- a/astrbot/core/provider/modalities.py +++ b/astrbot/core/provider/modalities.py @@ -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 = ( + "[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: diff --git a/astrbot/core/provider/sources/anthropic_source.py b/astrbot/core/provider/sources/anthropic_source.py index f19dfa5cf9..d8faa8efb7 100644 --- a/astrbot/core/provider/sources/anthropic_source.py +++ b/astrbot/core/provider/sources/anthropic_source.py @@ -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 @@ -1044,8 +1045,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}) # 如果只有主文本且没有额外内容块和图片,返回简单格式以保持向后兼容 if ( diff --git a/tests/test_anthropic_source.py b/tests/test_anthropic_source.py index 1d0f7f7078..0d78792d02 100644 --- a/tests/test_anthropic_source.py +++ b/tests/test_anthropic_source.py @@ -541,3 +541,15 @@ async def create(self, **kwargs): response = await provider._query({"model": "claude-test", "messages": []}, None) assert response.completion_text == "Let me search. The answer is 42." + + +@pytest.mark.asyncio +async def test_assemble_context_explains_unreceived_audio(): + from astrbot.core.provider.modalities import AUDIO_NOT_RECEIVED_HINT + + message = await _provider().assemble_context("what was said?", audio_urls=["a.wav"]) + + assert message["content"] == [ + {"type": "text", "text": "what was said?"}, + {"type": "text", "text": AUDIO_NOT_RECEIVED_HINT}, + ] diff --git a/tests/test_tool_loop_agent_runner.py b/tests/test_tool_loop_agent_runner.py index cbd6e5a2ee..29761307cf 100644 --- a/tests/test_tool_loop_agent_runner.py +++ b/tests/test_tool_loop_agent_runner.py @@ -23,6 +23,7 @@ from astrbot.core.exceptions import EmptyModelOutputError from astrbot.core.message.message_event_result import MessageChain from astrbot.core.provider.entities import LLMResponse, ProviderRequest, TokenUsage +from astrbot.core.provider.modalities import AUDIO_NOT_RECEIVED_HINT from astrbot.core.provider.provider import Provider @@ -3209,3 +3210,24 @@ async def reply(**kwargs): assert len(observed) == 1 assert observed[0][0] < 5 assert observed[0][1] is None + + +@pytest.mark.asyncio +async def test_unsupported_audio_is_explained_to_the_model( + runner, mock_hooks, mock_tool_executor +): + """Audio a text-only model cannot receive is replaced by a fix-it hint.""" + provider = CapturingProvider(modalities=["text"]) + + await runner.reset( + provider=provider, + request=ProviderRequest(prompt="what was said?", audio_urls=["voice.wav"]), + run_context=ContextWrapper(context=None), + tool_executor=mock_tool_executor, + agent_hooks=mock_hooks, + streaming=False, + ) + + content = runner.run_context.messages[-1].content + assert TextPart(text=AUDIO_NOT_RECEIVED_HINT) in content + assert TextPart(text="[Audio]") not in content From 05a6e811aa02eedd486b64ca60a0d455f48d1b81 Mon Sep 17 00:00:00 2001 From: Turino Date: Tue, 17 Nov 2026 13:09:50 +1000 Subject: [PATCH 4/9] perf(anthropic): cache the conversation tail within the breakpoint budget Only the system prompt was marked as a cache breakpoint, so every tool-loop step and every new turn paid full price for the whole history. Also mark the last cacheable block of the conversation so the next request reads the history from the cache. Markers are added after assistant messages are sanitized, so a dropped block cannot take one, and the four-breakpoint budget counts markers on tool definitions, including custom tools from the extra body. --- .../core/provider/sources/anthropic_source.py | 92 +++++++++++++++++-- tests/test_anthropic_source.py | 80 +++++++++++++++- .../unit/test_anthropic_cache_breakpoints.py | 89 ++++++++++++++++++ 3 files changed, 251 insertions(+), 10 deletions(-) create mode 100644 tests/unit/test_anthropic_cache_breakpoints.py diff --git a/astrbot/core/provider/sources/anthropic_source.py b/astrbot/core/provider/sources/anthropic_source.py index d8faa8efb7..772175d8e8 100644 --- a/astrbot/core/provider/sources/anthropic_source.py +++ b/astrbot/core/provider/sources/anthropic_source.py @@ -39,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( @@ -508,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, @@ -554,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( @@ -678,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", diff --git a/tests/test_anthropic_source.py b/tests/test_anthropic_source.py index 0d78792d02..4e6c4953ad 100644 --- a/tests/test_anthropic_source.py +++ b/tests/test_anthropic_source.py @@ -8,6 +8,7 @@ from astrbot.core.agent.tool import FunctionTool, ToolSet from astrbot.core.provider.entities import TokenUsage +from astrbot.core.provider.modalities import AUDIO_NOT_RECEIVED_HINT from astrbot.core.provider.sources.anthropic_source import ProviderAnthropic # The SDK bundles its own httpx (``httpx`` before 1.0.0, ``httpx2`` after). @@ -545,11 +546,86 @@ async def create(self, **kwargs): @pytest.mark.asyncio async def test_assemble_context_explains_unreceived_audio(): - from astrbot.core.provider.modalities import AUDIO_NOT_RECEIVED_HINT - message = await _provider().assemble_context("what was said?", audio_urls=["a.wav"]) assert message["content"] == [ {"type": "text", "text": "what was said?"}, {"type": "text", "text": AUDIO_NOT_RECEIVED_HINT}, ] + + +@pytest.mark.asyncio +@pytest.mark.parametrize("streaming", [False, True]) +@pytest.mark.parametrize("tool_marks", [0, 4]) +async def test_cache_breakpoints_apply_to_final_wire_payload( + monkeypatch, streaming, tool_marks +): + captured = [] + + def handle(request): + captured.append(json.loads(request.content)) + return sdk_httpx.Response( + 400, + json={ + "type": "error", + "error": { + "type": "invalid_request_error", + "message": "offline capture", + }, + }, + ) + + monkeypatch.setattr( + ProviderAnthropic, + "_create_http_client", + lambda self, config: sdk_httpx.AsyncClient( + transport=sdk_httpx.MockTransport(handle) + ), + ) + provider = ProviderAnthropic( + { + "id": "test", + "type": "anthropic_chat_completion", + "key": ["test-key"], + "model": "claude-test", + "api_base": "https://offline.invalid", + "custom_extra_body": { + "tools": [ + {"name": str(i), "cache_control": {"type": "ephemeral"}} + for i in range(tool_marks) + ] + }, + }, + {}, + ) + payload = { + "model": "claude-test", + "system": [{"type": "text", "text": "sys"}], + "messages": [ + { + "role": "user", + "content": [ + {"type": "text", "text": "keep"}, + {"type": "tool_result", "tool_use_id": "orphan", "content": "drop"}, + ], + } + ], + } + try: + with pytest.raises(BadRequestError): + if streaming: + async for _ in provider._query_stream( + payload, None, request_max_retries=1 + ): + pass + else: + await provider._query(payload, None, request_max_retries=1) + finally: + await provider.terminate() + wire = captured[0] + content = wire["messages"][-1]["content"] + assert len(content) == 1 and content[0]["text"] == "keep" + blocks = [*wire.get("tools", []), *wire["system"], *content] + assert sum("cache_control" in block for block in blocks) <= 4 + if not tool_marks: + assert content[0]["cache_control"] == {"type": "ephemeral"} diff --git a/tests/unit/test_anthropic_cache_breakpoints.py b/tests/unit/test_anthropic_cache_breakpoints.py new file mode 100644 index 0000000000..b4ec4c05c5 --- /dev/null +++ b/tests/unit/test_anthropic_cache_breakpoints.py @@ -0,0 +1,89 @@ +import copy + +from astrbot.core.provider.sources.anthropic_source import ProviderAnthropic + +apply = ProviderAnthropic._apply_explicit_prompt_cache_breakpoints +MARK = {"type": "ephemeral"} + + +def test_marks_system_and_conversation_tail_without_changing_content(): + tool_result = {"type": "tool_result", "tool_use_id": "t1", "content": "ok"} + history = [ + {"role": "user", "content": "hello"}, + { + "role": "assistant", + "content": [{"type": "tool_use", "id": "t1", "name": "x", "input": {}}], + }, + {"role": "user", "content": [tool_result]}, + ] + payloads = {"system": [{"type": "text", "text": "sys"}], "messages": history} + original = copy.deepcopy(payloads) + apply(payloads) + assert payloads["system"][-1]["cache_control"] == MARK + assert payloads["messages"][-1]["content"][-1]["cache_control"] == MARK + # Only the tail is marked, and the caller's block object is not mutated. + assert "cache_control" not in tool_result + assert payloads["messages"][:2] == original["messages"][:2] + stripped = copy.deepcopy(payloads) + stripped["system"][-1].pop("cache_control") + stripped["messages"][-1]["content"][-1].pop("cache_control") + assert stripped == original + + +def test_string_tail_becomes_marked_text_block(): + payloads = {"messages": [{"role": "user", "content": "hi"}]} + apply(payloads) + assert payloads["messages"][-1]["content"] == [ + {"type": "text", "text": "hi", "cache_control": MARK} + ] + + +def test_skips_uncacheable_blocks_and_respects_limit(): + payloads = { + "messages": [ + { + "role": "assistant", + "content": [ + {"type": "text", "text": "answer"}, + {"type": "thinking", "thinking": "t", "signature": "s"}, + ], + } + ] + } + apply(payloads) + content = payloads["messages"][-1]["content"] + assert content[0]["cache_control"] == MARK + assert "cache_control" not in content[1] + + full = { + "system": [{"type": "text", "text": "s", "cache_control": MARK}], + "messages": [ + { + "role": "user", + "content": [ + {"type": "text", "text": str(i), "cache_control": MARK} + for i in range(3) + ] + + [{"type": "text", "text": "tail"}], + } + ], + } + apply(full) + assert "cache_control" not in full["messages"][-1]["content"][-1] + + +def test_existing_tool_breakpoints_reserve_request_budget(): + # Three marked tools leave room for only one more marker. + tools = [{"name": str(i), "cache_control": MARK} for i in range(3)] + payload = { + "tools": tools, + "system": [{"type": "text", "text": "sys"}], + "messages": [{"role": "user", "content": "hi"}], + } + apply(payload) + blocks = [*payload["tools"], *payload["system"]] + content = payload["messages"][0]["content"] + if isinstance(content, list): + blocks.extend(content) + assert sum("cache_control" in block for block in blocks) <= 4 + assert payload["tools"] == tools From d990ebd4cad9a86e9f3c406a2c80f5b475ac6a57 Mon Sep 17 00:00:00 2001 From: Turino Date: Tue, 17 Nov 2026 13:11:33 +1000 Subject: [PATCH 5/9] docs: document request-time context accounting and the audio hint Describe how context usage is counted before compression and that the context window follows the model used for the request, note what a model without audio input receives when speech recognition is off, and add the changelog entries for the provider request fixes. --- changelogs/unreleased.md | 11 +++++++++++ docs/en/providers/deepseek-stt.md | 2 ++ docs/en/use/context-compress.md | 4 +++- docs/zh/providers/deepseek-stt.md | 2 ++ docs/zh/use/context-compress.md | 4 +++- 5 files changed, 21 insertions(+), 2 deletions(-) diff --git a/changelogs/unreleased.md b/changelogs/unreleased.md index 999d93a8aa..a07462d571 100644 --- a/changelogs/unreleased.md +++ b/changelogs/unreleased.md @@ -53,3 +53,14 @@ - Move view declarations from `Star.chatui_views` to `metadata.yaml` under `views`. Keep default labels in metadata and override them with i18n `views.` (legacy `pages.` remains supported). Existing declarations without a target remain standalone `plugin_page` views. - `chat_workbench` + `launcher=True` → `chat_workbench_with_launcher`:同一视图既能由消息或工具打开,也能从工作台「+」打开。只由插件打开的视图继续使用 `chat_workbench`。 - Replace `chat_workbench` + `launcher=True` with `chat_workbench_with_launcher` for views that can open from messages/tools and from **+**. Keep `chat_workbench` for plugin-opened views without a launcher entry. + +### Model requests / 模型请求 + +- OpenAI 兼容接口:只有报错明确表示模型不支持工具时,才去掉工具重试,同时去掉 `tool_choice`;警告中附带原始报错。其他和工具有关的错误(如工具参数结构不合法)不再被吞掉。 +- OpenAI-compatible APIs: Retry without tools only when the error says the model does not support tools, and drop `tool_choice` together with the tools. The warning includes the original error. Other tool-related errors, such as invalid tool schemas, are no longer hidden. +- Anthropic:除系统提示外,对话末尾也设置缓存断点,工具循环的下一步和下一轮对话可以直接命中历史缓存。断点在清理消息之后设置,并计入工具定义(包括自定义请求体中的工具)上已有的断点,总数不超过 4 个。 +- Anthropic: Mark the end of the conversation as a cache breakpoint in addition to the system prompt, so the next tool-loop step and the next turn read the history from the cache. Breakpoints are placed after messages are sanitized and count existing markers on tool definitions, including tools from the custom request body, staying within the limit of four. +- 上下文压缩按本次请求实际使用的模型查找上下文窗口;压缩前的用量以上一次请求上报的 Token 数为基准,加上之后新增消息的估算。 +- Context compression looks up the context window of the model actually used for the request. Usage before compression starts from the tokens reported for the previous request and adds an estimate for messages added since. +- 当前模型不能接收音频且未开启语音识别时,模型会收到一条说明,提示用户开启语音识别或换用支持音频的模型,而不是只看到 `[Audio]`。 +- When the current model cannot receive audio and speech recognition is off, the model receives a note asking it to tell the user to enable speech recognition or switch to an audio-capable model, instead of a bare `[Audio]` placeholder. diff --git a/docs/en/providers/deepseek-stt.md b/docs/en/providers/deepseek-stt.md index 8a00b1468e..1ff7cd1c42 100644 --- a/docs/en/providers/deepseek-stt.md +++ b/docs/en/providers/deepseek-stt.md @@ -28,6 +28,8 @@ No model name or language parameter is required. The API detects the spoken lang When a voice message arrives, AstrBot transcribes it and sends the resulting text to the current chat model as the user's message. +Without speech recognition, if the current chat model cannot receive audio directly (for example Anthropic Claude, or a model whose modalities do not include audio), the model receives a note instead of the audio and tells the user to enable speech recognition or switch to a model that accepts audio. + ## Audio Requirements and Limits - Uploads are limited to 8 MiB and 120 seconds. Oversized audio must be shortened before sending. diff --git a/docs/en/use/context-compress.md b/docs/en/use/context-compress.md index fd0c712898..0dce1a9c01 100644 --- a/docs/en/use/context-compress.md +++ b/docs/en/use/context-compress.md @@ -46,6 +46,8 @@ The default summary focuses on the user's goal, task progress, conclusions, usef AstrBot checks context **before every model request**, including follow-up requests after an Agent calls tools. The selected strategy is triggered when context usage exceeds approximately **82%** of the model's context window. +Context usage starts from the token count the model reported for the previous request and adds an estimate for content added since, such as the new user message and tool results. After compression rewrites the history, AstrBot estimates the whole context again. + AstrBot checks again after processing. If the context is still too long, it removes complete turns from the oldest first while keeping the latest turn. Tool calls and their results are handled together to avoid leaving incomplete call records. If the latest turn alone is too large, automatic compression may still be unable to fit the request into the model's window. Reduce the size of the input or tool output, or choose a model with a larger context window. @@ -66,7 +68,7 @@ Compression depends on the actual chat model's context window. A value that is t See [Chat Models](../providers/llm.md) for model setup. -When `max_context_tokens` is `0`, AstrBot tries to look up the model ID in its built-in [MODELS.DEV](https://models.dev/) metadata. If the model is unknown, it uses **Fallback context window size**, which defaults to `128000`. Setting the value to `0` therefore does not disable compression, nor does it guarantee recognition of custom model names. +When `max_context_tokens` is `0`, AstrBot tries to look up the ID of the model actually used for the request (the newly selected model if you switched models in the conversation) in its built-in [MODELS.DEV](https://models.dev/) metadata. If the model is unknown, it uses **Fallback context window size**, which defaults to `128000`. Setting the value to `0` therefore does not disable compression, nor does it guarantee recognition of custom model names. For an unrecognized model, set an accurate `max_context_tokens` value instead of relying on the default fallback. diff --git a/docs/zh/providers/deepseek-stt.md b/docs/zh/providers/deepseek-stt.md index b064e1db47..3bb2fe794b 100644 --- a/docs/zh/providers/deepseek-stt.md +++ b/docs/zh/providers/deepseek-stt.md @@ -28,6 +28,8 @@ AstrBot 可通过 [DeepSeek 语音识别接口](https://api-docs.deepseek.com/zh 收到语音消息后,AstrBot 会先把语音转成文字,再将转写结果作为用户消息交给当前对话模型。 +未开启语音识别时,如果当前对话模型不能直接接收音频(例如 Anthropic Claude,或模态中未勾选「音频」的模型),模型收到的不是音频,而是一条说明,会据此提示用户开启语音识别或换用支持音频的模型。 + ## 音频要求与限制 - 上传文件最大为 8 MiB,音频最长为 120 秒。超限音频需要缩短后再发送。 diff --git a/docs/zh/use/context-compress.md b/docs/zh/use/context-compress.md index f45702bf42..238d1befba 100644 --- a/docs/zh/use/context-compress.md +++ b/docs/zh/use/context-compress.md @@ -46,6 +46,8 @@ LLM 压缩会额外调用模型,因此会增加一次请求的时间和费用 AstrBot 会在**每次向模型发送请求之前**检查上下文,包括 Agent 调用工具后再次请求模型的步骤。当上下文 Token 用量超过模型窗口的约 **82%** 时,会触发所选处理方式。 +上下文用量以模型对上一次请求上报的 Token 数为基准,再加上之后新增内容(新的用户消息、工具返回结果)的估算值;压缩改写历史后,改为重新估算整段上下文。 + 处理后会再次检查。如果仍然过长,AstrBot 会从最旧的完整对话轮次开始移除内容,并保留最后一轮。工具调用与对应结果会一起处理,避免只剩下一半的调用记录。 如果最新一轮本身就过大,自动压缩仍可能无法使请求符合模型限制。此时需要减少单次输入或工具返回内容,或者使用上下文窗口更大的模型。 @@ -66,7 +68,7 @@ AstrBot 会在**每次向模型发送请求之前**检查上下文,包括 Agen 更多模型配置方法见[对话模型](../providers/llm.md)。 -当 `max_context_tokens` 为 `0` 时,AstrBot 会尝试根据模型 ID,从内置的 [MODELS.DEV](https://models.dev/) 元数据中获取窗口大小。如果无法识别,则使用「上下文窗口兜底值」,默认 `128000`。因此,设为 `0` 并不等于关闭压缩,也不保证 AstrBot 能识别所有自定义模型名称。 +当 `max_context_tokens` 为 `0` 时,AstrBot 会尝试根据本次请求实际使用的模型 ID(在对话中换了模型时,按换后的模型),从内置的 [MODELS.DEV](https://models.dev/) 元数据中获取窗口大小。如果无法识别,则使用「上下文窗口兜底值」,默认 `128000`。因此,设为 `0` 并不等于关闭压缩,也不保证 AstrBot 能识别所有自定义模型名称。 对未识别的模型,最好填写准确的 `max_context_tokens`,而不是依赖默认兜底值。 From 8d3204ef702b9801c1ca5b02637d8f917b7da03b Mon Sep 17 00:00:00 2001 From: Turino Date: Fri, 20 Nov 2026 15:32:54 +1000 Subject: [PATCH 6/9] feat: give failed model requests a stable error code A failed model request reached the turn result only as text ("All chat models failed: AuthenticationError: Error code: 401 ..."), with the code "provider_error" for every cause. Classify the failures a user can fix: a rejected API key, a quota or rate limit, a model that needs the Responses API for tools, and an unknown model. Other failures keep "provider_error". --- astrbot/core/astr_agent_runtime/execution.py | 6 ++- astrbot/core/llm_error_messages.py | 49 ++++++++++++++++++++ changelogs/unreleased.md | 16 ++++--- tests/unit/test_provider_failure_codes.py | 49 ++++++++++++++++++++ 4 files changed, 112 insertions(+), 8 deletions(-) create mode 100644 tests/unit/test_provider_failure_codes.py diff --git a/astrbot/core/astr_agent_runtime/execution.py b/astrbot/core/astr_agent_runtime/execution.py index f3530cf7a0..3354460389 100644 --- a/astrbot/core/astr_agent_runtime/execution.py +++ b/astrbot/core/astr_agent_runtime/execution.py @@ -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 @@ -210,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, + ) if error and response is not None else None, reason=runner.run_context.run_end_reason or "completed", diff --git a/astrbot/core/llm_error_messages.py b/astrbot/core/llm_error_messages.py index 51875b0a86..b18cd9b9c2 100644 --- a/astrbot/core/llm_error_messages.py +++ b/astrbot/core/llm_error_messages.py @@ -1,5 +1,6 @@ from __future__ import annotations +import re from typing import TYPE_CHECKING if TYPE_CHECKING: @@ -61,3 +62,51 @@ 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", + re.compile(r"/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" diff --git a/changelogs/unreleased.md b/changelogs/unreleased.md index a07462d571..83865bacda 100644 --- a/changelogs/unreleased.md +++ b/changelogs/unreleased.md @@ -47,13 +47,6 @@ - 三类视图教程分别提供 Meme Manager 独立页面、阅读清单消息演示、上下文用量常驻工作台示例,并附实机截图及示例插件。 - Add target-specific examples: Meme Manager for standalone pages, an interactive reading list for messages, and a resident context-usage workbench, with screenshots and example plugins. -### Plugin view registration / 插件视图注册 - -- `Star.chatui_views` → `metadata.yaml` 的 `views`:默认标题和描述随声明保存,i18n 的 `views.`(兼容 `pages.`)按字段覆盖;没有翻译时回退到 metadata。旧的独立页面声明省略 target 时仍为 `plugin_page`。 -- Move view declarations from `Star.chatui_views` to `metadata.yaml` under `views`. Keep default labels in metadata and override them with i18n `views.` (legacy `pages.` remains supported). Existing declarations without a target remain standalone `plugin_page` views. -- `chat_workbench` + `launcher=True` → `chat_workbench_with_launcher`:同一视图既能由消息或工具打开,也能从工作台「+」打开。只由插件打开的视图继续使用 `chat_workbench`。 -- Replace `chat_workbench` + `launcher=True` with `chat_workbench_with_launcher` for views that can open from messages/tools and from **+**. Keep `chat_workbench` for plugin-opened views without a launcher entry. - ### Model requests / 模型请求 - OpenAI 兼容接口:只有报错明确表示模型不支持工具时,才去掉工具重试,同时去掉 `tool_choice`;警告中附带原始报错。其他和工具有关的错误(如工具参数结构不合法)不再被吞掉。 @@ -64,3 +57,12 @@ - Context compression looks up the context window of the model actually used for the request. Usage before compression starts from the tokens reported for the previous request and adds an estimate for messages added since. - 当前模型不能接收音频且未开启语音识别时,模型会收到一条说明,提示用户开启语音识别或换用支持音频的模型,而不是只看到 `[Audio]`。 - When the current model cannot receive audio and speech recognition is off, the model receives a note asking it to tell the user to enable speech recognition or switch to an audio-capable model, instead of a bare `[Audio]` placeholder. +- 模型请求失败时附带稳定的错误代码:API 密钥被拒(401/403)为 `providerAuth`,额度或频率限制(429)为 `providerRateLimit`,模型需要 Responses 接口才能使用工具为 `providerToolsRequireResponses`,模型不存在(404)为 `providerModelNotFound`,其他仍为 `provider_error`。ChatUI 的报错卡片据此给出处理建议。 +- Failed model requests carry a stable error code: `providerAuth` for a rejected API key (401/403), `providerRateLimit` for quota or rate limits (429), `providerToolsRequireResponses` when the model needs the Responses API for tools, `providerModelNotFound` for an unknown model (404), and `provider_error` otherwise. ChatUI error cards use it to suggest a fix. + +### Plugin view registration / 插件视图注册 + +- `Star.chatui_views` → `metadata.yaml` 的 `views`:默认标题和描述随声明保存,i18n 的 `views.`(兼容 `pages.`)按字段覆盖;没有翻译时回退到 metadata。旧的独立页面声明省略 target 时仍为 `plugin_page`。 +- Move view declarations from `Star.chatui_views` to `metadata.yaml` under `views`. Keep default labels in metadata and override them with i18n `views.` (legacy `pages.` remains supported). Existing declarations without a target remain standalone `plugin_page` views. +- `chat_workbench` + `launcher=True` → `chat_workbench_with_launcher`:同一视图既能由消息或工具打开,也能从工作台「+」打开。只由插件打开的视图继续使用 `chat_workbench`。 +- Replace `chat_workbench` + `launcher=True` with `chat_workbench_with_launcher` for views that can open from messages/tools and from **+**. Keep `chat_workbench` for plugin-opened views without a launcher entry. diff --git a/tests/unit/test_provider_failure_codes.py b/tests/unit/test_provider_failure_codes.py new file mode 100644 index 0000000000..6634259408 --- /dev/null +++ b/tests/unit/test_provider_failure_codes.py @@ -0,0 +1,49 @@ +"""Stable codes for failed model requests, used by ChatUI error cards.""" + +import pytest + +from astrbot.core.llm_error_messages import classify_provider_failure + + +@pytest.mark.parametrize( + ("text", "code"), + [ + ( + "All chat models failed: AuthenticationError: Error code: 401 - " + "{'error': {'message': 'Incorrect API key provided'}}", + "providerAuth", + ), + ( + "All chat models failed: PermissionDeniedError: Error code: 403", + "providerAuth", + ), + ("401 UNAUTHENTICATED. API key not valid.", "providerAuth"), + ( + "All chat models failed: RateLimitError: Error code: 429 - " + "{'error': {'code': 'insufficient_quota'}}", + "providerRateLimit", + ), + ("429 RESOURCE_EXHAUSTED. Quota exceeded.", "providerRateLimit"), + ( + "All chat models failed: BadRequestError: Error code: 400 - " + "Function tools with reasoning_effort are not supported for gpt-5 " + "in /v1/chat/completions. Please use /v1/responses instead.", + "providerToolsRequireResponses", + ), + ( + "All chat models failed: NotFoundError: Error code: 404 - " + "The model `gpt-x` does not exist", + "providerModelNotFound", + ), + # Failures without a specific user action keep the generic code. + ( + "All chat models failed: APIConnectionError: Connection error.", + "provider_error", + ), + ("All chat models failed: BadRequestError: Error code: 4013", "provider_error"), + ("All available chat models are unavailable.", "provider_error"), + ("", "provider_error"), + ], +) +def test_failed_requests_get_a_stable_code(text, code): + assert classify_provider_failure(text) == code From fb14588425d36cef5af807999295f2cdd6254e1c Mon Sep 17 00:00:00 2001 From: Turino Date: Thu, 26 Nov 2026 16:08:27 +1000 Subject: [PATCH 7/9] fix: keep the localized model error text for specific provider codes Failed requests now carry codes such as providerAuth, but the turn output still compared the code with provider_error, so those failures showed the generic English "Error occurred during AI execution." on every platform instead of the localized model error. --- astrbot/core/agent_output.py | 4 +++- tests/unit/test_runtime_output.py | 10 +++++++++- 2 files changed, 12 insertions(+), 2 deletions(-) diff --git a/astrbot/core/agent_output.py b/astrbot/core/agent_output.py index 6d5890fb58..1d4e732929 100644 --- a/astrbot/core/agent_output.py +++ b/astrbot/core/agent_output.py @@ -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": diff --git a/tests/unit/test_runtime_output.py b/tests/unit/test_runtime_output.py index b8982f3d09..2d4e372b5d 100644 --- a/tests/unit/test_runtime_output.py +++ b/tests/unit/test_runtime_output.py @@ -199,7 +199,7 @@ async def execute_turn(self, turn): @pytest.mark.parametrize("streaming", [False, True]) @pytest.mark.parametrize("platform", ["webchat", "test"]) @pytest.mark.parametrize( - "code", ["noProvider", "provider_error", "unknown_runtime_error"] + "code", ["noProvider", "provider_error", "providerAuth", "unknown_runtime_error"] ) async def test_failed_turn_preserves_error_identity_and_partial_reply( streaming, platform, code @@ -243,3 +243,11 @@ async def execute_turn(self, turn): else: assert chains[-1].type is None assert "Failure detail" in chains[-1].get_plain_text() + if code.startswith("provider"): + # A specific provider code keeps the localized model error text. + text = ( + chains[-1].chain[0].data["message"] + if platform == "webchat" + else chains[-1].get_plain_text() + ) + assert not text.startswith("Error occurred during AI execution") From fbf1cf00b881fd4bd06c22589ee73c4f1a9278ef Mon Sep 17 00:00:00 2001 From: Turino Date: Thu, 26 Nov 2026 16:08:27 +1000 Subject: [PATCH 8/9] fix(openai): match more tools-unsupported messages The narrowed check missed real messages that the old one retried without tools: a quoted 'tools', "does not support the 'tools' parameter", "Function call is not supported" and OpenRouter's "No endpoints found that support tool use". Unrelated errors about reasoning_effort or tool schemas are still raised. --- astrbot/core/provider/sources/openai_source.py | 9 ++++++--- tests/test_openai_source.py | 5 +++++ 2 files changed, 11 insertions(+), 3 deletions(-) diff --git a/astrbot/core/provider/sources/openai_source.py b/astrbot/core/provider/sources/openai_source.py index 9bdfa6078d..f055295298 100644 --- a/astrbot/core/provider/sources/openai_source.py +++ b/astrbot/core/provider/sources/openai_source.py @@ -1231,9 +1231,12 @@ async def _handle_api_error( # 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" - r" (?:function calling|functions|tools|tool use|tool calling|tool calls)" - r"|(?:tools|tool use|tool calling|function calling) (?:is|are) not supported" + 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, diff --git a/tests/test_openai_source.py b/tests/test_openai_source.py index 80bd00d1dd..044c478355 100644 --- a/tests/test_openai_source.py +++ b/tests/test_openai_source.py @@ -2393,6 +2393,11 @@ async def fake_create(**kwargs): "Function calling is not enabled for this model", "tool calling is not supported by the selected model", "当前模型不支持工具调用", + "Error code: 400 - {'error': {'message': \"'tools' is not supported\"}}", + "This model does not support the 'tools' parameter", + "Function call is not supported for this model", + "No endpoints found that support tool use. To learn more about provider " + "routing, visit: https://openrouter.ai/docs/provider-routing", ], ) async def test_handle_api_error_tools_unsupported_drops_tools_and_tool_choice( From 5199e2738b4a5bea4312c06d35c4560d810000bb Mon Sep 17 00:00:00 2001 From: Turino Date: Fri, 27 Nov 2026 00:22:25 +1000 Subject: [PATCH 9/9] fix: only give the Responses advice when the error asks for it Any error text containing /v1/responses got the "use the OpenAI Responses provider type" code, including a proxy's 404 for POST /v1/responses on a provider that already uses it. Match OpenAI's advice ("use /v1/responses") instead. --- astrbot/core/llm_error_messages.py | 4 +++- tests/unit/test_provider_failure_codes.py | 6 ++++++ 2 files changed, 9 insertions(+), 1 deletion(-) diff --git a/astrbot/core/llm_error_messages.py b/astrbot/core/llm_error_messages.py index b18cd9b9c2..20251ef89c 100644 --- a/astrbot/core/llm_error_messages.py +++ b/astrbot/core/llm_error_messages.py @@ -70,7 +70,9 @@ def set_llm_error_message(event: AstrMessageEvent, key: str, **params: str) -> N _PROVIDER_FAILURE_CODES = ( ( "providerToolsRequireResponses", - re.compile(r"/v1/responses", re.IGNORECASE), + # 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", diff --git a/tests/unit/test_provider_failure_codes.py b/tests/unit/test_provider_failure_codes.py index 6634259408..2f615f3f85 100644 --- a/tests/unit/test_provider_failure_codes.py +++ b/tests/unit/test_provider_failure_codes.py @@ -35,6 +35,12 @@ "The model `gpt-x` does not exist", "providerModelNotFound", ), + # A wrong base URL on a Responses provider is not a tools problem. + ( + "All chat models failed: NotFoundError: Error code: 404 - " + "Invalid URL (POST /v1/responses)", + "providerModelNotFound", + ), # Failures without a specific user action keep the generic code. ( "All chat models failed: APIConnectionError: Connection error.",