Repository navigation
fix: provider request fixes for OpenAI tool fallback, Anthropic caching, context accounting and audio input - #11303
liquidtoy001 wants to merge 9 commits into
Conversation
Linked issuesChecked at commit 5199e27 #9864 [Bug] AstrBot ChatUI 长对话在上下文占用很低时却被提前压缩/截断,导致严重的对话失忆。 · 1 of 1 met
|
There was a problem hiding this comment.
Hey - I've found 14 issues
Prompt for AI Agents
Please address the comments from this code review:
## Individual Comments
### Comment 1
<location path="astrbot/core/astr_agent_runtime/execution.py" line_range="67" />
<code_context>
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"]
</code_context>
<issue_to_address>
**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.
</issue_to_address>
### Comment 2
<location path="astrbot/core/llm_error_messages.py" line_range="72-73" />
<code_context>
+# 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),
+ ),
+ (
</code_context>
<issue_to_address>
**Provider failures get misleading advice**
When a provider error mentions `/v1/responses` without indicating a tool/API compatibility problem, `classify_provider_failure` matches the endpoint text before other failure details, so connection, authentication, endpoint, and other unrelated errors are classified as `providerToolsRequireResponses` and users see the wrong remediation.
Require evidence of a tool/API compatibility problem before classifying an error as `providerToolsRequireResponses`.
</issue_to_address>
### Comment 3
<location path="astrbot/core/provider/sources/openai_source.py" line_range="1173-1174" />
<code_context>
+ # 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)",
</code_context>
<issue_to_address>
**Unsupported tools do not trigger retry**
When an OpenAI-compatible provider says it does not support the quoted `tools` parameter, the fallback regex requires a tool term immediately after `support`, so `_handle_api_error` does not recognize the error and re-raises it without retrying with tools disabled.
Allow intervening parameter wording, including quotes and the word `parameter`, between `support` and the tool term.
</issue_to_address>
### Comment 4
<location path="astrbot/core/provider/sources/openai_source.py" line_range="1183-1185" />
<code_context>
- 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,
</code_context>
<issue_to_address>
**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.
</issue_to_address>
### Comment 5
<location path="astrbot/core/agent/runners/tool_loop_agent_runner.py" line_range="471" />
<code_context>
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}
</code_context>
<issue_to_address>
**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`.
</issue_to_address>
### Comment 6
<location path="astrbot/core/provider/sources/anthropic_source.py" line_range="1126" />
<code_context>
+ # 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})
# 如果只有主文本且没有额外内容块和图片,返回简单格式以保持向后兼容
</code_context>
<issue_to_address>
**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.
</issue_to_address>
### Comment 7
<location path="astrbot/core/astr_agent_runtime/execution.py" line_range="215-217" />
<code_context>
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,
</code_context>
<issue_to_address>
**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).
</issue_to_address>
### Comment 8
<location path="astrbot/core/provider/sources/openai_source.py" line_range="1181" />
<code_context>
- # openai, ollama, gemini openai, siliconcloud 的错误提示与 code 不统一,只能通过字符串匹配
logger.warning(
- f"{self.get_model()} 不支持函数工具调用,已自动去除,不影响使用。如需永久关闭,可前往 WebUI 中关闭工具调用。",
+ f"{self.get_model()} 不支持函数工具调用,已自动去除,不影响使用。如需永久关闭,可前往 WebUI 中关闭工具调用。原始错误: {e}",
)
payloads.pop("tools", None)
</code_context>
<issue_to_address>
**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.
</issue_to_address>
### Comment 9
<location path="astrbot/core/agent/runners/tool_loop_agent_runner.py" line_range="1229" />
<code_context>
+ 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:]
</code_context>
<issue_to_address>
**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.
</issue_to_address>
### Comment 10
<location path="astrbot/core/agent/runners/tool_loop_agent_runner.py" line_range="1233" />
<code_context>
+ # 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)
</code_context>
<issue_to_address>
**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.
</issue_to_address>
### Comment 11
<location path="astrbot/core/agent/runners/tool_loop_agent_runner.py" line_range="425-426" />
<code_context>
+ 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
</code_context>
<issue_to_address>
**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.
</issue_to_address>
### Comment 12
<location path="astrbot/core/provider/modalities.py" line_range="13" />
<code_context>
+# 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 "
</code_context>
<issue_to_address>
**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`.
</issue_to_address>
### Comment 13
<location path="astrbot/core/provider/sources/anthropic_source.py" line_range="1126" />
<code_context>
+ # 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})
# 如果只有主文本且没有额外内容块和图片,返回简单格式以保持向后兼容
</code_context>
<issue_to_address>
**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.
</issue_to_address>
### Comment 14
<location path="tests/test_anthropic_source.py" line_range="547-629" />
<code_context>
+@pytest.mark.asyncio
</code_context>
<issue_to_address>
**Regression tests are added**
When the PR adds regression tests and new test modules, the patch adds regression tests to three existing test files and creates three new test modules, contrary to the repository rule; the change therefore includes prohibited test additions.
Remove the added test code and test modules, or update the repository guidance if test additions are now allowed.
Also at `tests/test_openai_source.py:2264-2340`, `tests/test_tool_loop_agent_runner.py:2880-3008`, `tests/unit/test_anthropic_cache_breakpoints.py:1-89`, `tests/unit/test_native_context_limit.py:1-53`, `tests/unit/test_provider_failure_codes.py:1-49`.
</issue_to_address>Sourcery assessment
Needs a human reviewer. 13 findings to address first, and the new Anthropic cache breakpoints change which prompt tokens the provider bills as cache writes or cache reads. If the markers cause unexpected charges, reverting stops the behavior on later requests but cannot undo costs already incurred.
Blocking findings: astrbot/core/astr_agent_runtime/execution.py:67, astrbot/core/llm_error_messages.py:73, astrbot/core/provider/sources/openai_source.py:1174, astrbot/core/provider/sources/openai_source.py:1185, astrbot/core/agent/runners/tool_loop_agent_runner.py:471, and 8 more
| 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()) |
There was a problem hiding this comment.
🟡 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.| payloads.pop("tools", None) | ||
| # tool_choice without tools is rejected by OpenAI-compatible APIs. | ||
| payloads.pop("tool_choice", None) |
There was a problem hiding this comment.
🟡 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.| 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}) |
There was a problem hiding this comment.
🟡 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`.| # The reply to the measured request is already counted. | ||
| added = added[1:] | ||
| token_usage = tokens + ( | ||
| self.request_context_manager.token_counter.count_tokens(added) |
There was a problem hiding this comment.
🟡 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._usage_baseline: tuple[int, int] | None = ( | ||
| (conversation_usage, len(messages) - int(new_user_message)) |
There was a problem hiding this comment.
🟡 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.|
|
||
| # 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 = ( |
There was a problem hiding this comment.
🟡 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`.| # 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}) |
There was a problem hiding this comment.
🟡 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.| @pytest.mark.asyncio | ||
| async def test_assemble_context_explains_unreceived_audio(): | ||
| 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 |
There was a problem hiding this comment.
⚪ Low · Regression tests are added
When the PR adds regression tests and new test modules, the patch adds regression tests to three existing test files and creates three new test modules, contrary to the repository rule; the change therefore includes prohibited test additions.
Remove the added test code and test modules, or update the repository guidance if test additions are now allowed.
Also at tests/test_openai_source.py:2264-2340, tests/test_tool_loop_agent_runner.py:2880-3008, tests/unit/test_anthropic_cache_breakpoints.py:1-89, tests/unit/test_native_context_limit.py:1-53, tests/unit/test_provider_failure_codes.py:1-49.
Prompt for AI agents
In `tests/test_anthropic_source.py` at lines 547-629:
**Regression tests are added**
When the PR adds regression tests and new test modules, the patch adds regression tests to three existing test files and creates three new test modules, contrary to the repository rule; the change therefore includes prohibited test additions.
Remove the added test code and test modules, or update the repository guidance if test additions are now allowed.
Also at `tests/test_openai_source.py:2264-2340`, `tests/test_tool_loop_agent_runner.py:2880-3008`, `tests/unit/test_anthropic_cache_breakpoints.py:1-89`, `tests/unit/test_native_context_limit.py:1-53`, `tests/unit/test_provider_failure_codes.py:1-49`.From .github/copilot-instructions.md L27:
Do not generate test files for now.…ce 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.
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.
…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.
…dget 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.
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.
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".
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.
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.
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.
0b4d665 to
5199e27
Compare
Related PRs
Independent of my other open PRs (#11283, #11304) and of the ChatUI branches in my fork (
liquidtoy001/AstrBot): it merges cleanly with each of them, in any order. Based on currentmaster(ccd78fc). Size: 19 files; source +218/−20, tests +519/−1, docs and changelog +23/−2.Relation to recent upstream changes: #11167 (token estimation performance) does not overlap; this PR changes how the runner feeds the token count and window into the context manager. #11170 transcribes ChatUI dictation through its own endpoint; an uploaded audio file still reaches the model as audio unless speech recognition is enabled, so the audio hint still applies. #11168 (OpenRouter reasoning details) and the Gemini 4 thinking levels (#11219, #11251) touch other sources. #11259 added ChatUI error cards keyed by error code; the last commit gives failed model requests codes those cards can act on (see below).
Four small, independent fixes in how AstrBot builds and retries model requests, plus stable error codes for failed requests. Each commit stands on its own and has regression tests that fail without the fix.
tool_choicewas kept after removingtools, which OpenAI-compatible APIs reject.custom_extra_body.[Audio]. With speech recognition off, a model without the audio modality, or any Anthropic model (the Messages API has no audio input block), got[Audio], so it claimed to have received the attachment and then said it could not listen to it. It now receives a note asking it to tell the user to enable speech recognition or switch to an audio-capable model.provider_error, so feat: show actionable ChatUI error cards #11259's error cards could only show a generic message. Failures the user can fix now get a stable code:providerAuth(API key rejected, 401/403),providerRateLimit(quota or rate limit, 429),providerToolsRequireResponses(the model needs the Responses API for tools, e.g. "Function tools with reasoning_effort are not supported ... use /v1/responses"),providerModelNotFound(404). Everything else keepsprovider_error; other platforms still get the same plain text.Modifications / 改动点
astrbot/core/provider/sources/openai_source.py: narrow regex for "tools unsupported" errors, only when tools were sent; it still matches the real messages (a quoted'tools', "does not support the 'tools' parameter", "Function call is not supported", OpenRouter's "No endpoints found that support tool use"); droptool_choicetogether withtools; include the original error in the warning.astrbot/core/agent/runners/tool_loop_agent_runner.py,astrbot/core/astr_agent_runtime/execution.py: look up the context window forrequest.model; keep the reported usage as a baseline for the messages it covers and estimate only newer messages; drop the baseline when compression rewrites the history.astrbot/core/provider/sources/anthropic_source.py: tail cache breakpoint within the four-marker budget, applied after sanitizing; audio hint inassemble_context.astrbot/core/provider/modalities.py:AUDIO_NOT_RECEIVED_HINT, also used by the runner when the provider lacks the audio modality.astrbot/core/llm_error_messages.py:classify_provider_failure()(the Responses code only when the error itself says to use/v1/responses);astrbot/core/astr_agent_runtime/execution.pyuses it for the failed turn's error code, andastrbot/core/agent_output.pykeeps the localized model error text for everyprovider*code.docs/{zh,en}/use/context-compress.md(how usage is counted, window follows the selected model),docs/{zh,en}/providers/deepseek-stt.md(what a model without audio input receives when speech recognition is off),changelogs/unreleased.md(bilingual entries).No WebUI navigation, page structure or labels change.
Screenshots or Test Results / 运行截图或测试结果
Verification (Windows 11, Python 3.12):
Regression check: with the five source files restored to
v4.30.0-alpha.1and the new tests kept, 19 tests fail (OpenAI fallback 6, cache breakpoints 8, context accounting 3, audio hint 2), covering every fix.ruff checkpasses on all changed files;ruff format --checkpasses on all changed files excepttests/test_tool_loop_agent_runner.py, which is already unformatted upstream and is intentionally left as is (only new tests are appended).cd docs && pnpm run docs:build: build complete. Checked pages: Context Compression and DeepSeek Speech Recognition (zh and en).Relation to #9865
#9865 drops
conversation.token_usageat turn start and reuses a provider prompt snapshot within the tool loop while message-prefix and tool-schema fingerprints match. This PR keeps the stored usage as the baseline for the history it covers and estimates only messages added since, dropping the baseline after compression. If maintainers prefer #9865's approach, the token-count part of the context commit can be dropped and only the selected-model window lookup (execution.py, one line, plustests/unit/test_native_context_limit.py) kept.Checklist / 检查清单
docs/zhanddocs/enagainst the changed navigation, page structure, and labels, and updated them in this PR (or explained why no documentation update is needed). / 已核对并更新相关文档(无界面入口变化)。Models used: Claude Fable 5.2, Claude Opus 5.5 (Claude Code), GPT-6 Astra (Codex).
Summary by Sourcery
Fix provider request handling, context accounting, caching, audio fallback behavior, and actionable error reporting across model integrations.
Bug Fixes:
Enhancements:
Documentation:
Tests:
Chores: