agent-zero icon indicating copy to clipboard operation
agent-zero copied to clipboard

Chat Completions mode: plain-text final answer is never logged — model answers, turn completes, UI silently shows nothing

Open nico7master opened this issue 3 months ago • 4 comments

Summary

In Chat Completions mode, when a model returns its final answer as plain prose (no JSON tool call), the answer is fully generated, the turn completes cleanly, the history is updated, memory extensions still run — but no type="response" log entry is ever created, so the WebUI never displays the answer. The chat silently returns to idle, indistinguishable from a hang. No warning, no exception, no diagnostic trail.

This was observed with a custom preset pointing a glm-5.3 Chat Completions endpoint at a coding-assistant API (z.ai coding plan) that answers conversational requests in plain text instead of emitting the {"tool_name":"response",...} JSON protocol. Any provider/model that answers in prose for simple conversational prompts will trigger this.

Related prior work (not duplicates):

  • #1812 (closed) fixed the return message shortcut in process_llm_result_tools() — that code path no longer exists in v2.10; plain text now always reaches process_tools(). But the logging half was never covered for chat mode.
  • #1729 (open) proposes a monologue_end fallback for the same family of symptom. This issue provides a root-cause trace and a narrower fix at the hist_add_ai_response hook that reuses the generating log item (so the response bubbles into the existing stream position).

Reproduction

  1. Run Agent Zero v2.10 with any Chat Completions mode preset whose model answers a trivial prompt in plain prose (e.g. a coding-assistant endpoint, or any model that ignores the JSON tool protocol for conversational questions).
  2. Open a new chat, send: say READY.
  3. Observe:
    • the LLM call completes (debug trace: turn_end response="READY"),
    • process_tools() runs and returns the message,
    • message_loop_end fires, memorize extensions run in the finally,
    • the chat goes idle — no response bubble, no warning.

Instrumented trace from a live v2.10 instance (extension hooks on call_chat_model_turn, process_tools, message_loop_end):

turn_end:         response_len=5, response_head="READY"
process_tools:     message="READY"  (plain prose, not a tool request)
process_tools_end: result="READY"   (returned cleanly)
message_loop_end:  last_response_len=5
→ no response log entry anywhere ✗

Root cause

Three logging paths exist for a final answer, and plain prose in Chat Completions mode falls through all of them:

  1. extensions/python/response_stream/_20_live_response.py — only creates log_item_response when it sees a response tool request in the stream (via normalize_tool_request(parsed)). Plain prose is never a tool request, so no entry is created during streaming.
  2. tools/response.py (before_execution) — response logging is intentionally disabled:
    # don't log here anymore, we have the live_response extension now
    pass
    
    and after_execution only updates loop_data.params_temporary["log_item_response"] if it already exists — it never creates one.
  3. extensions/python/_functions/agent/Agent/hist_add_ai_response/end/_10_log_plain_responses.py — this is exactly the backstop for plain-text answers, but it early-returns unless the call was Responses-API mode:
    llm_result = call_kwargs.get("llm_result")
    if getattr(llm_result, "mode", "") != "responses":
        return
    

Meanwhile the framework does anticipate plain-text finals — but only for Responses mode: agent.py process_llm_result_tools() treats plain text as a response tool call when llm_result.mode == "responses" (agent.py:1124-1135), and the _10_log_plain_responses backstop covers its logging. Chat Completions mode never got the equivalent pair, so a valid, fully-generated answer disappears silently.

The model is not at fault and neither is the stream: chunk deltas arrive, the monologue completes, hist_add_ai_response runs — only the log entry is missing.

Proposed fix

Minimal, conservative fix: a chat-mode sibling of _10_log_plain_responses at the same hook point (hist_add_ai_response/end), which converts the existing log_item_generating into a finished response entry when the message is plain prose and no response entry exists yet:

# extensions/python/_functions/agent/Agent/hist_add_ai_response/end/_20_log_plain_chat_responses.py
class LogPlainChatResponses(Extension):
    def execute(self, data=None, **kwargs):          # SYNC — hook point runs via call_extensions_sync
        call_kwargs = data.get("kwargs") or {}
        llm_result = call_kwargs.get("llm_result")
        if getattr(llm_result, "mode", "") == "responses":
            return                                   # core _10 already handles Responses mode
        message = call_kwargs.get("message") or (data.get("args")[1] if ...)
        if not isinstance(message, str) or not message:
            return
        if extract_tools.extract_tool_request(message) is not None:
            return                                   # proper tool call — normal path
        if extract_tools.is_misformatted_tool_request(message):
            return                                   # repair/warning path stays intact
        params = self.agent.loop_data.params_temporary
        if "log_item_response" in params or "log_item_generating" not in params:
            return
        params["log_item_response"] = params["log_item_generating"]
        params["log_item_generating"].update(
            type="response", heading="", content=message,
            finished=True, update_progress="none",
        )

(Full tested file below.) Notes:

  • execute() must stay sync — hist_add_ai_response is a sync def (agent.py:758) and its /end point runs call_extensions_sync, which raises ValueError: Extension ... returned awaitable in sync mode for async extensions. That failure mode itself silently kills every turn after the LLM answered — worth documenting in the extension developer docs.
  • Never raises (whole body wrapped), so the backstop cannot become a new kill switch.
  • Reusing log_item_generating keeps the response attached to the same stream position/branch id the UI already tracks.

Alternative (more conservative, no new core file): extend the gate in the existing core _10_log_plain_responses.py from mode != "responses" to also run for chat mode. Functionally identical; keeps everything in one file.

Full locally-tested extension (click to expand)
"""Log plain-text responses in Chat Completions mode."""
import sys, traceback
from typing import Any
from helpers import extract_tools
from helpers.extension import Extension


class LogPlainChatResponses(Extension):
    def execute(self, data: dict[str, Any] | None = None, **kwargs):
        try:
            if not self.agent or not isinstance(data, dict):
                return
            call_kwargs = data.get("kwargs")
            if not isinstance(call_kwargs, dict):
                call_kwargs = {}
            llm_result = call_kwargs.get("llm_result")
            if getattr(llm_result, "mode", "") == "responses":
                return  # core _10 handles Responses API mode
            message = call_kwargs.get("message")
            call_args = data.get("args")
            if message is None and isinstance(call_args, tuple) and len(call_args) > 1:
                message = call_args[1]
            if not isinstance(message, str) or not message:
                return
            if (
                extract_tools.extract_tool_request(message) is not None
                or extract_tools.is_misformatted_tool_request(message)
            ):
                return
            params = getattr(getattr(self.agent, "loop_data", None), "params_temporary", None)
            if not isinstance(params, dict) or "log_item_response" in params:
                return
            log_item = params.get("log_item_generating")
            if log_item is None:
                return
            params["log_item_response"] = log_item
            log_item.update(
                type="response", heading="", content=message,
                finished=True, update_progress="none",
            )
        except Exception:
            try:
                traceback.print_exc(file=sys.stderr)
            except Exception:
                pass

Before / after

Scenario Before After
Chat Completions model returns plain-prose final answer No response entry; UI silently idle Response logged & displayed
Chat Completions model returns proper response tool JSON Logged by LiveResponse in-stream Unchanged (backstop skips: log_item_response exists)
Responses-API plain text Logged by core _10_log_plain_responses Unchanged (mode gate)
Misformatted tool request (fenced/concatenated JSON) Warning + repair path Unchanged (is_misformatted_tool_request guard)
Empty response (reasoning only) Retry path Unchanged (empty-message guard)

Environment

  • Agent Zero v2.10 (git tag), Docker deployment
  • Custom preset: Chat Completions mode, api_base=https://api.z.ai/api/coding/paas/v4, model glm-5.3 (coding-assistant persona → plain-prose answers)
  • Same model via a gateway that emits the JSON protocol works fine — the failure is purely the chat-mode logging gap, not the model
  • Fix verified live on three chats (incl. two long-running production chats) after applying the user-space extension above; trace captured with temporary call_chat_model_turn / process_tools / message_loop_end hooks

Happy to turn this into a PR against development if the approach looks right — the tested extension is ready to drop into extensions/python/_functions/agent/Agent/hist_add_ai_response/end/ with a regression test alongside tests/test_plain_response_logging.py.

nico7master avatar Aug 27 '26 11:08 nico7master

Refinement discovered in production (running this backstop live on a GLM Chat Completions endpoint today, ~1,600-message chats):

The proposed guard is not strict enough. Models frequently emit tool requests that are almost valid JSON but contain an invalid escape (typical for large code_execution_tool payloads with heredocs). Those messages:

  • fail extract_tool_request() (invalid JSON),
  • fail is_misformatted_tool_request() (its patterns only cover fenced / concatenated / truncated envelopes),
  • yet are still recoverable downstream — our repair extension (json_parse_dirty / DirtyJson.parse_string) rebuilds them and the tool executes normally.

With the backstop as proposed, such messages get logged as type="response" (raw JSON envelope shown to the user as the assistant's answer) before the repair path recovers them — a false positive: the user sees raw JSON and the tool result. We observed 18 such polluted entries in one working session before catching it.

Guard to add (mirrors what our misformat_guard plugin uses for the same decision):

stripped = message.strip()
if stripped.startswith("{") or stripped.startswith("```"):
    return  # botched tool-call attempt, not an answer meant for the user

Rationale: a genuine plain-prose answer never starts with a bare { or fence. Messages that do are either valid tool requests (already handled by the strict check), repairable envelopes (handled by the repair path), or unrecoverable (handled by the misformat warning retry path) — in all three cases the backstop must stay silent.

Same guard would apply to widening the gate in core _10_log_plain_responses.py instead.

nico7master avatar Aug 27 '26 21:08 nico7master

I can reproduce a closely related failure mode on Agent Zero v2.13 with OpenRouter / GLM-5.3 Flash.

Environment

  • Agent Zero: v2.13 (updated from the WebUI)
  • Main model: OpenRouter GLM-5.3 Flash
  • Utility model: DeepSeek V4 Flash 0423 (confirmed from OpenRouter logs)
  • Context usage when observed: about 22% (no obvious compaction had occurred)
  • Same project, new chat: still reproducible
  • Switching the main model only to GLM-5.2 in the same project allowed the request to complete normally

Observed behavior

With GLM-5.3 Flash, even a simple request such as:

Hello. Please tell me the current project progress.

can repeatedly enter:

A0: Plain-text reply was kept as thoughts. Retrying with ...
A0: Receiving...
A0: Plain-text reply was kept as thoughts. Retrying with ...
...
Agent stopped after 5 consecutive unusable model responses to prevent further API charges.

This is reproducible in a newly created chat within the same project, so it does not look like a single corrupted chat history.

I also observed a related failure in a longer-running chat: after the same plain-text retry path, Agent Zero sometimes ignored the latest user request and replayed an older task context (release/handoff work) instead. I am not sure whether this stale-task replay is the same root cause or a secondary effect of the response-repair path, but it happened in the same GLM-5.3 Flash setup.

A/B observation

Under the same project context:

  • Main: GLM-5.3 Flash + Utility: DeepSeek V4 Flash 0423 -> repeated plain-text retries -> 5 consecutive unusable responses / stop
  • Main: GLM-5.2 + Utility: DeepSeek V4 Flash 0423 -> normal tool execution and final response

This makes the failure look more isolated to the main-model response / repair path, rather than to the utility model, compaction, or a permanently corrupted project context.

OpenRouter logs around the failure also show GLM-5.3 Flash requests being routed through multiple providers (including Z.ai and Open Inference), while utility calls went to DeepSeek V4 Flash 0423 via providers such as Baidu Qianfan, Relace, and SiliconFlow.

I have screenshots of:

  1. repeated Plain-text reply was kept as thoughts retries ending in the 5-response circuit breaker;
  2. the same project succeeding immediately after switching the main model to GLM-5.2;
  3. the stale-task replay case after repair retries;
  4. OpenRouter logs confirming that the utility model was DeepSeek V4 Flash 0423 rather than GLM-5.3 Flash.

Happy to provide additional logs or run a provider-pinned OpenRouter test if that would help narrow down whether this is specific to GLM-5.3 Flash itself or to a particular OpenRouter provider implementation.

Marble-GP avatar Sep 26 '26 02:09 Marble-GP

@nico7master I could not reproduce this on stock v2.10 or on current ready (0efb0d4f). There, a plain-prose answer is retried, and the agent stops after 5 unusable responses. This is by design: root AGENTS.md says plain Chat Completions text "enters repair".

The trace in the issue can only come from a non-stock extension. Could you please check whether it still happens on a stock install? If not, I think this issue can be closed.

@Marble-GP your 5-retry stop with GLM-5.3 Flash is this intended limit, not the silent idle. If the model leaks <tool_call> markup, #1920 targets that case.

Details

A plain-prose answer in Chat Completions mode:

  • Context Doctor on (default on ready): 4 × "Plain-text reply was kept as thoughts. Retrying…", then the stop.
  • Context Doctor off, or v2.10: "Message misformat" warnings, then the same stop.

Why the trace needs an extension:

  • Stock process_tools returns a result only when a tool sets break_loop. Plain prose runs no tool, so process_tools_end: result="READY" cannot happen on stock code.
  • I get exactly this silent idle when an extension turns the prose into a response call. Nothing streamed a response JSON, so no response bubble exists yet. tools/response.py never creates the bubble itself, so the turn ends with nothing shown.
  • Open PR #1920 has the same gap when Context Doctor is off.

gf239 avatar Sep 29 '26 16:09 gf239

Thanks for the detailed reports everyone.

We’ve now merged #1920 into ready, including a fix for the missing answer discussed here.

When a model outputs a complete tool call in an unexpected format, Agent Zero can now recover it and show the final answer correctly, including with Context Doctor disabled. We tested this live with Codex and Opus (Responses with native tool calling vs. Chat Completions with the usual JSON format), with Context Doctor both on and off.

Plain prose in Chat Completions still follows the existing repair/retry behavior, so this doesn’t necessarily resolve every case reported above. We haven’t tested the exact GLM configurations mentioned here yet.

@nico7master @Marble-GP, I will follow up whenever I'll release v2.15 so we can verify if you still see the problem. You can also test by going in the Advanced tab and updating to ready branch. If it persists, a short chat log and the active extensions would help us follow up.

Let’s keep this open until we’ve confirmed the original case is resolved. With original case I mean the silent-idle scenario.

3clyp50 avatar Oct 24 '26 16:10 3clyp50