diff --git a/application/agents/base.py b/application/agents/base.py index 061b726c..2137982c 100644 --- a/application/agents/base.py +++ b/application/agents/base.py @@ -14,7 +14,10 @@ from application.core.json_schema_utils import ( normalize_json_schema_payload, ) from application.core.settings import settings -from application.llm.handlers.base import ToolCall +from application.llm.handlers.base import ( + ToolCall, + _bound_tool_response_for_llm, +) from application.llm.handlers.handler_creator import LLMHandlerCreator from application.llm.llm_creator import LLMCreator from application.logging import build_stack_data, log_activity, LogContext @@ -316,6 +319,9 @@ class BaseAgent(ABC): except StopIteration as e: tool_response, _ = e.value break + # Same per-result cap as the in-loop path + # (handle_tool_calls); the journal keeps the full result. + tool_response = _bound_tool_response_for_llm(tool_response) messages.append( self.llm_handler.create_tool_message(tc, tool_response) ) @@ -355,7 +361,11 @@ class BaseAgent(ABC): id=call_id, name=pending["name"], arguments=args ) messages.append( - self.llm_handler.create_tool_message(tc, result_str) + self.llm_handler.create_tool_message( + # Client-supplied results get the same per-result + # cap as server-side tool executions. + tc, _bound_tool_response_for_llm(result_str) + ) ) yield { "type": "tool_call", @@ -483,6 +493,10 @@ class BaseAgent(ABC): end_chars = int(target_chars * 0.4) truncation_marker = "\n\n[... content truncated to fit context limit ...]\n\n" + if end_chars <= 0: + # ``text[-0:]`` returns the WHOLE string — a "truncation" that + # grows the text by the marker length. + return truncation_marker.strip() truncated = text[:start_chars] + truncation_marker + text[-end_chars:] logger.info( @@ -491,6 +505,53 @@ class BaseAgent(ABC): ) return truncated + def _enforce_context_window(self, messages: List[Dict]) -> List[Dict]: + """Hard pre-send gate: never dispatch a payload that cannot fit. + + ``_validate_context_size`` only logs; an over-window payload used to + go straight to the provider, get rejected (context-length 400 / + capacity cap), take the fallback down with it, and still record its + full estimated prompt as usage. Called immediately before an LLM + dispatch: progressively middle-truncates the largest tool results + (the usual culprit) and raises when even that cannot fit — BEFORE + the usage decorators run, so a hopeless payload costs nothing. + """ + from application.core.model_utils import get_token_limit + from application.utils import num_tokens_from_string + + context_limit = get_token_limit( + self.model_id, user_id=self.model_user_id or self.user + ) + current_tokens = self._calculate_current_context_tokens(messages) + if current_tokens < context_limit: + return messages + + logger.warning( + f"Context ({current_tokens:,} tokens) exceeds the model's window " + f"({context_limit:,}). Shrinking tool results before dispatch." + ) + for per_message_cap in (8000, 2000, 500): + for message in messages: + content = message.get("content") + if ( + message.get("role") == "tool" + and isinstance(content, str) + and num_tokens_from_string(content) > per_message_cap + ): + message["content"] = self._truncate_text_middle( + content, per_message_cap + ) + current_tokens = self._calculate_current_context_tokens(messages) + if current_tokens < context_limit: + return messages + + raise ValueError( + f"Conversation context ({current_tokens:,} tokens) exceeds the " + f"model's context window ({context_limit:,} tokens) even after " + f"shrinking tool results. Start a new conversation or remove " + f"large attachments." + ) + # ---- Message building ---- def _build_messages( @@ -695,6 +756,9 @@ class BaseAgent(ABC): preserve_responses_state: bool = False, ): self._validate_context_size(messages) + # Hard gate: refuse/shrink instead of dispatching a payload the + # provider is guaranteed to reject (see _enforce_context_window). + messages = self._enforce_context_window(messages) if not preserve_responses_state: starter = getattr(self.llm, "start_responses_turn", None) diff --git a/application/api/answer/routes/stream.py b/application/api/answer/routes/stream.py index 080687bf..064474dc 100644 --- a/application/api/answer/routes/stream.py +++ b/application/api/answer/routes/stream.py @@ -10,6 +10,7 @@ from application.api.answer.routes.base import answer_ns, BaseAnswerResource from application.api.answer.services.persistence_policy import resolve_persistence from application.api.answer.services.stream_processor import StreamProcessor +from application.streaming.sse_keepalive import with_sse_keepalive logger = logging.getLogger(__name__) @@ -113,24 +114,26 @@ class StreamResource(Resource, BaseAnswerResource): if error := self.check_usage(processor.agent_config): return error return Response( - self.complete_stream( - question="", - agent=agent, - conversation_id=processor.conversation_id, - user_api_key=processor.agent_config.get("user_api_key"), - decoded_token=processor.decoded_token, - agent_id=processor.agent_id, - model_id=processor.model_id, - model_user_id=processor.model_user_id, - _continuation={ - "messages": messages, - "tools_dict": tools_dict, - "pending_tool_calls": pending_tool_calls, - "tool_actions": tool_actions, - "reserved_message_id": processor.reserved_message_id, - "request_id": processor.request_id, - "reasoning_content": reasoning_content, - }, + with_sse_keepalive( + self.complete_stream( + question="", + agent=agent, + conversation_id=processor.conversation_id, + user_api_key=processor.agent_config.get("user_api_key"), + decoded_token=processor.decoded_token, + agent_id=processor.agent_id, + model_id=processor.model_id, + model_user_id=processor.model_user_id, + _continuation={ + "messages": messages, + "tools_dict": tools_dict, + "pending_tool_calls": pending_tool_calls, + "tool_actions": tool_actions, + "reserved_message_id": processor.reserved_message_id, + "request_id": processor.request_id, + "reasoning_content": reasoning_content, + }, + ), ), mimetype="text/event-stream", ) @@ -151,22 +154,24 @@ class StreamResource(Resource, BaseAnswerResource): persist_flag=data.get("persist"), ) return Response( - self.complete_stream( - question=data["question"], - agent=agent, - conversation_id=processor.conversation_id, - user_api_key=processor.agent_config.get("user_api_key"), - decoded_token=processor.decoded_token, - isNoneDoc=data.get("isNoneDoc"), - index=data.get("index"), - should_persist=should_persist, - visibility=visibility, - attachment_ids=data.get("attachments", []), - agent_id=processor.agent_id, - is_shared_usage=processor.is_shared_usage, - shared_token=processor.shared_token, - model_id=processor.model_id, - model_user_id=processor.model_user_id, + with_sse_keepalive( + self.complete_stream( + question=data["question"], + agent=agent, + conversation_id=processor.conversation_id, + user_api_key=processor.agent_config.get("user_api_key"), + decoded_token=processor.decoded_token, + isNoneDoc=data.get("isNoneDoc"), + index=data.get("index"), + should_persist=should_persist, + visibility=visibility, + attachment_ids=data.get("attachments", []), + agent_id=processor.agent_id, + is_shared_usage=processor.is_shared_usage, + shared_token=processor.shared_token, + model_id=processor.model_id, + model_user_id=processor.model_user_id, + ), ), mimetype="text/event-stream", ) diff --git a/application/api/answer/services/compression/service.py b/application/api/answer/services/compression/service.py index 3af3ac63..2934d79e 100644 --- a/application/api/answer/services/compression/service.py +++ b/application/api/answer/services/compression/service.py @@ -131,6 +131,18 @@ class CompressionService: original_tokens / compressed_tokens if compressed_tokens > 0 else 0 ) + # Port of the in-memory path's guard: a "successful" summary + # that isn't smaller than what it replaces must never become a + # compression point — it would make every later rebuild WORSE + # while reporting success (observed in prod: "successful" + # compressions with negative savings). + if compressed_tokens >= original_tokens: + raise ValueError( + f"Compression did not reduce token count " + f"({original_tokens} → {compressed_tokens}); " + f"keeping original history" + ) + logger.info( f"Compression complete: {original_tokens} → {compressed_tokens} tokens " f"({compression_ratio:.1f}x compression)" @@ -244,7 +256,7 @@ class CompressionService: f"(messages {last_compressed_index + 1}-{total_queries - 1})" ) - return compressed_summary, recent_queries + return compressed_summary, self._bound_recent_queries(recent_queries) except Exception as e: logger.error( @@ -255,6 +267,90 @@ class CompressionService: return None, [] return None, queries + def _truncate_middle_tokens(self, text: str, max_tokens: int) -> str: + """Middle-truncate ``text`` to roughly ``max_tokens`` tokens.""" + from application.utils import num_tokens_from_string + + current = num_tokens_from_string(text) + if current <= max_tokens: + return text + chars_per_token = len(text) / current if current > 0 else 4 + target_chars = int(max_tokens * chars_per_token * 0.95) + keep = int(target_chars * 0.4) + marker = "\n\n[... trimmed to fit context after compression ...]\n\n" + if keep <= 0: + # ``text[-0:]`` would return the WHOLE string, not nothing. + return marker.strip() + return text[:keep] + marker + text[-keep:] + + def _bound_recent_queries( + self, queries: List[Dict[str, Any]] + ) -> List[Dict[str, Any]]: + """Cap oversized verbatim fields in the post-compression-point tail. + + Compression summarizes everything up to the compression point, but + the tail rides along verbatim — a single giant prompt / response / + tool result there can defeat the whole compression (measured in + prod: half of compressions produced no reduction in the next + call's prompt). Returns copies; the caller's conversation dict is + never mutated. + """ + max_tokens = int( + getattr(settings, "COMPRESSION_RECENT_FIELD_MAX_TOKENS", 8000) or 0 + ) + if max_tokens <= 0: + return queries + from application.utils import num_tokens_from_string + + bounded: List[Dict[str, Any]] = [] + trimmed = 0 + for query in queries: + if not isinstance(query, dict): + bounded.append(query) + continue + out = query + for field in ("prompt", "response"): + value = query.get(field) + if ( + isinstance(value, str) + and num_tokens_from_string(value) > max_tokens + ): + if out is query: + out = dict(query) + out[field] = self._truncate_middle_tokens(value, max_tokens) + trimmed += 1 + tool_calls = query.get("tool_calls") + if isinstance(tool_calls, list): + new_calls = None + for idx, tc in enumerate(tool_calls): + if not isinstance(tc, dict): + continue + result = tc.get("result") + if ( + isinstance(result, str) + and num_tokens_from_string(result) > max_tokens + ): + if new_calls is None: + new_calls = [ + dict(c) if isinstance(c, dict) else c + for c in tool_calls + ] + new_calls[idx]["result"] = self._truncate_middle_tokens( + result, max_tokens + ) + trimmed += 1 + if new_calls is not None: + if out is query: + out = dict(query) + out["tool_calls"] = new_calls + bounded.append(out) + if trimmed: + logger.info( + f"Bounded {trimmed} oversized field(s) in recent " + f"uncompressed queries (cap: {max_tokens} tokens each)" + ) + return bounded + def _extract_summary(self, llm_response: str) -> str: """ Extract clean summary from LLM response. diff --git a/application/api/v1/routes.py b/application/api/v1/routes.py index 52bb3483..620f15a1 100644 --- a/application/api/v1/routes.py +++ b/application/api/v1/routes.py @@ -39,6 +39,7 @@ from application.api.v1.translator import ( from application.storage.db.repositories.agents import AgentsRepository from application.storage.db.repositories.conversations import ConversationsRepository from application.storage.db.session import db_readonly +from application.streaming.sse_keepalive import with_sse_keepalive logger = logging.getLogger(__name__) @@ -353,19 +354,21 @@ def chat_completions(): # b2b client is non-streaming), so a streaming request never # claims a key. This is a known, accepted limitation. return Response( - _stream_response( - helper, - question, - agent, - processor, - model_name, - continuation, - should_persist, - visibility, - strip_reasoning_leak, - bool((data.get("stream_options") or {}).get("include_usage")), - client_session, - finalize_stateless_tool_pause, + with_sse_keepalive( + _stream_response( + helper, + question, + agent, + processor, + model_name, + continuation, + should_persist, + visibility, + strip_reasoning_leak, + bool((data.get("stream_options") or {}).get("include_usage")), + client_session, + finalize_stateless_tool_pause, + ), ), mimetype="text/event-stream", headers={ diff --git a/application/core/settings.py b/application/core/settings.py index ce0230af..a10f90df 100644 --- a/application/core/settings.py +++ b/application/core/settings.py @@ -2,7 +2,7 @@ import os from pathlib import Path from typing import Optional -from pydantic import field_validator +from pydantic import Field, field_validator from pydantic_settings import BaseSettings, SettingsConfigDict current_dir = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) @@ -248,6 +248,7 @@ class Settings(BaseSettings): # reasoning is carried across the in-turn tool loop via encrypted # reasoning items instead. OPENAI_RESPONSES_STORE: bool = False + OPENAI_REASONING_SUMMARY: str = "auto" # OpenAI-compatible clients can identify a logical chat with session # headers even though chat-completions itself has no conversation field. @@ -272,6 +273,8 @@ class Settings(BaseSettings): COMPRESSION_MODEL_OVERRIDE: Optional[str] = None # Use different model for compression COMPRESSION_PROMPT_VERSION: str = "v1.0" # Track prompt iterations COMPRESSION_MAX_HISTORY_POINTS: int = 3 # Keep only last N compression points to prevent DB bloat + COMPRESSION_RECENT_FIELD_MAX_TOKENS: int = 8000 # Per-field cap on the verbatim tail kept after a compression point (0 disables) + TOOL_RESULT_MAX_TOKENS: int = 20000 # Cap on a single tool result entering the LLM context (0 disables); journal/DB keep the full result # Internal SSE push channel (notifications + durable replay journal) # Master switch — when False, /api/events emits a "push_disabled" comment @@ -285,9 +288,7 @@ class Settings(BaseSettings): # Used by gunicorn_worker.BoundedDrainUvicornWorker. GRACEFUL_SHUTDOWN_TIMEOUT_SECONDS: int = 30 WSGI_THREADPOOL_WORKERS: int = 96 - # SSE keepalive comment cadence. Must sit under Cloudflare's 100s idle - # close and iOS Safari's ~60s — 15s gives generous headroom. - SSE_KEEPALIVE_SECONDS: int = 15 + SSE_KEEPALIVE_SECONDS: int = Field(default=15, ge=1) # Cap on simultaneous SSE connections per user. Each connection holds # one WSGI thread (32 per gunicorn worker) and one Redis pub/sub # connection. 8 covers normal multi-tab use without letting one user diff --git a/application/llm/base.py b/application/llm/base.py index 79c8397b..7399320b 100644 --- a/application/llm/base.py +++ b/application/llm/base.py @@ -142,6 +142,44 @@ class BaseLLM(ABC): return args_dict return {k: v for k, v in args_dict.items() if v is not None} + @staticmethod + def _fallback_payload_fits(fallback, kwargs) -> bool: + """Whether the failed request's payload can fit the fallback model. + + A primary rejected for size (context-length 400, capacity cap) hands + the *same* oversized payload to the fallback, which then rejects it + too — one guaranteed-failed provider call plus one estimated-prompt + ``token_usage`` row for nothing. Skip the attempt when the estimated + prompt already exceeds the fallback's context window. Estimation + errors never block the attempt. + """ + messages = kwargs.get("messages") + if not messages: + return True + try: + from application.core.model_utils import get_token_limit + from application.usage import _count_prompt_tokens + + estimated = _count_prompt_tokens(messages, tools=kwargs.get("tools")) + limit = get_token_limit( + fallback.model_id, + user_id=getattr(fallback, "model_user_id", None), + ) + # 10% slack: the tiktoken estimate over-counts vs provider + # tokenizers (and ``get_token_limit`` returns a conservative + # default for unregistered models) — only skip when the payload + # is decisively over, never on a borderline estimate. + if estimated > int(limit * 1.1): + logger.warning( + f"Skipping fallback to {fallback.model_id}: estimated " + f"prompt (~{estimated} tokens) cannot fit its context " + f"window ({limit} tokens)." + ) + return False + except Exception: + logger.debug("Fallback payload size estimation failed", exc_info=True) + return True + def _execute_with_fallback( self, method_name: str, decorators: list, *args, **kwargs ): @@ -186,6 +224,8 @@ class BaseLLM(ABC): logger.error(f"Primary LLM failed and no fallback configured: {str(e)}") raise fallback = self.fallback_llm + if not self._fallback_payload_fits(fallback, kwargs): + raise self._responding_provider = fallback.provider_name logger.warning( f"Primary LLM failed. Falling back to " @@ -232,12 +272,26 @@ class BaseLLM(ABC): try: yield from decorated_method() except Exception as e: + if getattr(self, "_stream_reached_finish", False): + # The primary already delivered a finish signal — only + # trailing frames (usage chunk, [DONE]) failed. Restreaming + # from the fallback would duplicate the entire answer the + # user already received (and re-run tool calls). Re-raise; + # the streaming handler treats post-finish failures as + # non-fatal. + logger.warning( + f"Primary LLM failed after delivering its finish signal; " + f"not engaging fallback. Error: {str(e)}" + ) + raise if not self.fallback_llm: logger.error( f"Primary LLM failed and no fallback configured: {str(e)}" ) raise fallback = self.fallback_llm + if not self._fallback_payload_fits(fallback, kwargs): + raise self._responding_provider = fallback.provider_name logger.warning( f"Primary LLM failed mid-stream. Falling back to " diff --git a/application/llm/handlers/base.py b/application/llm/handlers/base.py index aa00177b..44cb558d 100644 --- a/application/llm/handlers/base.py +++ b/application/llm/handlers/base.py @@ -22,6 +22,44 @@ _FINALIZE_INSTRUCTION = ( ) +def _bound_tool_response_for_llm(tool_response: Any) -> Any: + """Cap a single tool result before it enters the LLM message array. + + One uncapped web page / API response has produced multi-hundred-KB tool + results that get re-sent in every subsequent round of the tool loop — + blowing conversations past every model's context window (observed in + prod up to a 14M-token estimated prompt). The durability journal and + the persisted conversation keep the FULL result (bounded separately at + persistence); only the copy handed to the model is truncated here. + """ + from application.core.settings import settings + from application.utils import num_tokens_from_string + + max_tokens = int(getattr(settings, "TOOL_RESULT_MAX_TOKENS", 20000) or 0) + if max_tokens <= 0: + return tool_response + text = tool_response if isinstance(tool_response, str) else str(tool_response) + tokens = num_tokens_from_string(text) + if tokens <= max_tokens: + return tool_response + chars_per_token = len(text) / tokens if tokens > 0 else 4 + target_chars = int(max_tokens * chars_per_token * 0.95) + keep = int(target_chars * 0.4) + marker = ( + f"\n\n[... tool result truncated: {tokens:,} tokens exceeded the " + f"{max_tokens:,}-token per-result limit ...]\n\n" + ) + if keep <= 0: + # ``text[-0:]`` would return the WHOLE string, not nothing. + return marker.strip() + logger.warning( + "Tool result truncated from %s to ~%s tokens before LLM handoff", + tokens, + max_tokens, + ) + return text[:keep] + marker + text[-keep:] + + @dataclass class ToolCall: """Represents a tool/function call from the LLM.""" @@ -697,13 +735,20 @@ class LLMHandler(ABC): logger.warning("Not enough queries to compress in-memory context") return False, None - metadata = compression_service.compress_conversation( - conversation, - compress_up_to_index=compress_up_to, - ) + try: + metadata = compression_service.compress_conversation( + conversation, + compress_up_to_index=compress_up_to, + ) + except ValueError: + # compress_conversation raises when the summary is not + # smaller than the original (negative-savings guard). For + # the in-memory path that is not fatal — fall back to + # minimal pruning and keep the tool loop running. + metadata = None # If compression doesn't reduce tokens, fall back to minimal pruning - if ( + if metadata is None or ( metadata.compressed_token_count >= metadata.original_token_count ): @@ -1014,6 +1059,9 @@ class LLMHandler(ABC): except StopIteration as e: tool_response, call_id = e.value break + # The journal / persisted conversation received the full + # result inside the executor; the model gets a bounded copy. + tool_response = _bound_tool_response_for_llm(tool_response) # Standard internal format: assistant message with tool_calls array args_str = ( @@ -1236,8 +1284,58 @@ class LLMHandler(ABC): buffer = "" tool_calls = {} reasoning_buffer = "" + finish_reason = None - for chunk in self._iterate_stream(response): + # Consume the provider stream to exhaustion before acting on its + # finish reason. Acting mid-iteration (as this loop used to) left + # every tool round's generator abandoned until request teardown, + # where all their usage-decorator ``finally`` blocks fired at once + # and mis-billed each round with the shared ``_last_usage`` of the + # final round (duplicate token_usage rows). Exhausting the stream + # also delivers the terminal usage-only chunk (Chat Completions + # ``stream_options.include_usage``), which arrives *after* the + # finish_reason chunk — so provider-exact counts land before the + # decorator persists this round's row. + stream_iter = self._iterate_stream(response) + while True: + try: + chunk = next(stream_iter) + except StopIteration: + break + except Exception: + # A failure in the trailing frames (usage chunk, [DONE]) + # after the round already finished must not fail — or + # fallback-restream — an answer the user has fully + # received. GeneratorExit/KeyboardInterrupt are + # BaseException and still propagate. + # + # The handler-local ``finish_reason`` only ever sees + # tool-call finishes (providers don't surface a parseable + # "stop" chunk — content arrives as bare strings), so the + # final answer round is covered by the LLM-level + # ``_stream_reached_finish`` flag instead — checked on the + # primary AND its fallback (whichever actually served the + # stream). + llm = getattr(agent, "llm", None) + provider_finished = bool( + getattr(llm, "_stream_reached_finish", False) + or getattr( + getattr(llm, "_fallback_llm", None), + "_stream_reached_finish", + False, + ) + ) + if finish_reason is not None or provider_finished: + logger.warning( + "Provider stream failed after finish " + "(finish_reason=%s, provider_finished=%s); " + "ignoring trailing-frame failure", + finish_reason, + provider_finished, + exc_info=True, + ) + break + raise if isinstance(chunk, dict) and chunk.get("type") == "thought": reasoning_buffer += chunk.get("thought") or "" yield chunk @@ -1251,6 +1349,13 @@ class LLMHandler(ABC): if parsed.tool_calls: for call in parsed.tool_calls: + if call.index is None: + # Providers like Google emit each parallel call as + # a COMPLETE, index-less ToolCall per chunk. They + # must never be merged into one another (dict + # arguments would even raise on ``+=``). + tool_calls[("complete", len(tool_calls))] = call + continue if call.index not in tool_calls: tool_calls[call.index] = call else: @@ -1262,88 +1367,104 @@ class LLMHandler(ABC): if call.arguments: if existing.arguments is None: existing.arguments = call.arguments - else: + elif isinstance(existing.arguments, str) and isinstance( + call.arguments, str + ): existing.arguments += call.arguments + else: + # Complete (non-delta) payloads: latest wins. + existing.arguments = call.arguments # Preserve thought_signature for Google Gemini 3 models if call.thought_signature: existing.thought_signature = call.thought_signature if parsed.finish_reason == "tool_calls": - tool_handler_gen = self.handle_tool_calls( - agent, - list(tool_calls.values()), - tools_dict, - messages, - reasoning_content=reasoning_buffer, - ) - while True: - try: - yield next(tool_handler_gen) - except StopIteration as e: - messages, pending_actions = e.value - break - tool_calls = {} - pause_reasoning = reasoning_buffer - reasoning_buffer = "" - - # If tools need approval or client execution, pause the loop - if pending_actions: - agent._pending_continuation = { - "messages": messages, - "pending_tool_calls": pending_actions, - "tools_dict": tools_dict, - "reasoning_content": pause_reasoning, - } - yield { - "type": "tool_calls_pending", - "data": {"pending_tool_calls": pending_actions}, - } - return - - next_iteration = _iteration + 1 - cap_reached = next_iteration >= MAX_TOOL_ITERATIONS - - # Check if context limit was reached during tool execution - if hasattr(agent, 'context_limit_reached') and agent.context_limit_reached: - # Add system message warning about context limit - messages.append({ - "role": "system", - "content": ( - "WARNING: Context window limit has been reached. " - "Please provide a final response to the user without making additional tool calls. " - "Summarize the work completed so far." - ) - }) - logger.info("Context limit reached - instructing agent to wrap up") - elif cap_reached: - logger.warning( - "agent tool loop hit cap (%d); forcing finalize", - MAX_TOOL_ITERATIONS, - ) - messages.append( - {"role": "system", "content": _FINALIZE_INSTRUCTION}, - ) - - # See note above on agent.model_id vs llm.model_id. - response = agent.llm.gen_stream( - model=getattr(agent.llm, "model_id", None) or agent.model_id, - messages=messages, - tools=( - None - if cap_reached - or getattr(agent, "context_limit_reached", False) - else agent.tools - ), - ) - self.llm_calls.append(build_stack_data(agent.llm)) - - yield from self.handle_streaming( - agent, response, tools_dict, messages, - _iteration=next_iteration, - ) - return + finish_reason = "tool_calls" + continue if parsed.content: buffer += parsed.content yield buffer buffer = "" - if parsed.finish_reason == "stop": - return + if parsed.finish_reason == "stop" and finish_reason is None: + finish_reason = "stop" + + if finish_reason != "tool_calls": + return + + tool_handler_gen = self.handle_tool_calls( + agent, + list(tool_calls.values()), + tools_dict, + messages, + reasoning_content=reasoning_buffer, + ) + while True: + try: + yield next(tool_handler_gen) + except StopIteration as e: + messages, pending_actions = e.value + break + pause_reasoning = reasoning_buffer + + # If tools need approval or client execution, pause the loop + if pending_actions: + agent._pending_continuation = { + "messages": messages, + "pending_tool_calls": pending_actions, + "tools_dict": tools_dict, + "reasoning_content": pause_reasoning, + } + yield { + "type": "tool_calls_pending", + "data": {"pending_tool_calls": pending_actions}, + } + return + + next_iteration = _iteration + 1 + cap_reached = next_iteration >= MAX_TOOL_ITERATIONS + + # Check if context limit was reached during tool execution + if hasattr(agent, 'context_limit_reached') and agent.context_limit_reached: + # Add system message warning about context limit + messages.append({ + "role": "system", + "content": ( + "WARNING: Context window limit has been reached. " + "Please provide a final response to the user without making additional tool calls. " + "Summarize the work completed so far." + ) + }) + logger.info("Context limit reached - instructing agent to wrap up") + elif cap_reached: + logger.warning( + "agent tool loop hit cap (%d); forcing finalize", + MAX_TOOL_ITERATIONS, + ) + messages.append( + {"role": "system", "content": _FINALIZE_INSTRUCTION}, + ) + + # Hard pre-send gate: tool results appended this round may have + # pushed the payload past the model's window — shrink or refuse + # BEFORE the usage decorators run (a rejected dispatch would still + # bill its full estimated prompt). + enforce = getattr(agent, "_enforce_context_window", None) + if callable(enforce): + messages = enforce(messages) + + # See note above on agent.model_id vs llm.model_id. + response = agent.llm.gen_stream( + model=getattr(agent.llm, "model_id", None) or agent.model_id, + messages=messages, + tools=( + None + if cap_reached + or getattr(agent, "context_limit_reached", False) + else agent.tools + ), + ) + self.llm_calls.append(build_stack_data(agent.llm)) + + yield from self.handle_streaming( + agent, response, tools_dict, messages, + _iteration=next_iteration, + ) diff --git a/application/llm/openai.py b/application/llm/openai.py index d2d2ec9a..75555546 100644 --- a/application/llm/openai.py +++ b/application/llm/openai.py @@ -160,6 +160,14 @@ class OpenAILLM(BaseLLM): self._last_response_id = None self._last_reasoning_items = [] self._last_usage = None + # One-shot guard consumed by ``_prefer_provider_usage``: fresh + # provider usage flips it False, the first billing read flips it + # True, so no two token_usage rows share one reported usage. + self._last_usage_claimed = False + # True once the current stream delivered a finish signal — only + # trailing frames remain, so a failure there must not trigger a + # fallback restream of the already-delivered answer. + self._stream_reached_finish = False self._imported_response_id = None def responses_chain_key(self) -> str: @@ -443,6 +451,7 @@ class OpenAILLM(BaseLLM): if response_format: request_params["response_format"] = response_format self._last_usage = None + self._stream_reached_finish = False response = self.client.chat.completions.create(**request_params) logging.debug("OpenAI request completed") self._record_chat_usage(getattr(response, "usage", None)) @@ -515,6 +524,7 @@ class OpenAILLM(BaseLLM): stream_options.setdefault("include_usage", True) request_params["stream_options"] = stream_options self._last_usage = None + self._stream_reached_finish = False response = self.client.chat.completions.create(**request_params) try: @@ -537,6 +547,12 @@ class OpenAILLM(BaseLLM): has_tool_calls = bool(getattr(delta, "tool_calls", None)) finish_reason = getattr(choice, "finish_reason", None) + if finish_reason: + # The answer is complete; only trailing frames (usage + # chunk, [DONE]) remain. ``_stream_with_fallback`` reads + # this to refuse restreaming a delivered answer when a + # trailing frame fails. + self._stream_reached_finish = True # Yield non-content chunks only when needed for tool-call handling. if has_tool_calls or finish_reason == "tool_calls": @@ -596,29 +612,77 @@ class OpenAILLM(BaseLLM): parts.append(file_part) return parts - def _to_responses_input(self, messages): + def _to_responses_input(self, messages, chained=False): """Translate cleaned Chat-Completions messages into a Responses ``input`` item list. Reasoning items captured during the in-turn tool loop are re-injected ahead of the function calls they belong to (deduped by id) so the model keeps its chain-of-thought across the round-trip. + + Pairing invariant: the Responses API 400s on a ``function_call`` + without a matching ``function_call_output`` ("No tool output found + for function call …") and on an output without its call. History + rebuilds (compression, pause/resume) can produce either orphan, so + both directions are dropped here rather than sent to certain + rejection — along with any reasoning items that would then precede + a dropped call with no following item. A call is only "paired" when + its output appears LATER in the list (an output *before* its call + is malformed history; both sides are dropped). + + ``chained=True`` (store-mode ``previous_response_id`` requests) + disables the guard entirely: ``_trim_for_previous_response`` + deliberately sends bare ``function_call_output`` items whose calls + live server-side in the previous response — dropping those breaks + every tool round. """ input_items = [] emitted_reasoning = set() - for message in messages: + # First position (message index) at which each call_id's output + # appears — used to require call-before-output ordering. + output_positions: dict = {} + for position, m in enumerate(messages): + if m.get("role") == "tool" and m.get("tool_call_id") is not None: + output_positions.setdefault(m["tool_call_id"], position) + emitted_call_ids = set() + for position, message in enumerate(messages): role = message.get("role") message_reasoning = message.get("responses_reasoning_items") or [] - for item in message_reasoning: - item_id = item.get("id") if isinstance(item, dict) else None - if item_id and item_id in emitted_reasoning: - continue - if item_id: - emitted_reasoning.add(item_id) - input_items.append(item) tool_calls = message.get("tool_calls") if tool_calls and role == "assistant": - for tc in tool_calls: + kept_calls = [ + tc + for tc in tool_calls + if chained + or output_positions.get(tc.get("id", ""), -1) > position + ] + if len(kept_calls) < len(tool_calls): + kept_ids = {id(tc) for tc in kept_calls} + dropped = [ + tc.get("id", "") + for tc in tool_calls + if id(tc) not in kept_ids + ] + logging.warning( + "Dropping %d function_call item(s) without a matching " + "later function_call_output (call_ids=%s) from " + "Responses input", + len(dropped), + dropped, + ) + if not kept_calls: + # Nothing left to emit for this message; its reasoning + # items must not be emitted either (a trailing reasoning + # item with no following item is itself rejected). + continue + for item in message_reasoning: + item_id = item.get("id") if isinstance(item, dict) else None + if item_id and item_id in emitted_reasoning: + continue + if item_id: + emitted_reasoning.add(item_id) + input_items.append(item) + for tc in kept_calls: call_id = tc.get("id", "") for item in self._reasoning_for_calls.get(call_id, []): item_id = item.get("id") @@ -634,9 +698,24 @@ class OpenAILLM(BaseLLM): "name": func.get("name", ""), "arguments": func.get("arguments", "") or "{}", }) + emitted_call_ids.add(call_id) continue + for item in message_reasoning: + item_id = item.get("id") if isinstance(item, dict) else None + if item_id and item_id in emitted_reasoning: + continue + if item_id: + emitted_reasoning.add(item_id) + input_items.append(item) tool_call_id = message.get("tool_call_id") if role == "tool" and tool_call_id is not None: + if not chained and tool_call_id not in emitted_call_ids: + logging.warning( + "Dropping orphaned function_call_output (call_id=%s) " + "with no preceding function_call from Responses input", + tool_call_id, + ) + continue tool_content = message.get("content") input_items.append({ "type": "function_call_output", @@ -740,7 +819,8 @@ class OpenAILLM(BaseLLM): else None ) if effort: - params["reasoning"] = {"effort": effort, "summary": "auto"} + summary = settings.OPENAI_REASONING_SUMMARY or "auto" + params["reasoning"] = {"effort": effort, "summary": summary} if response_format: fmt = self._responses_text_format(response_format) @@ -827,6 +907,7 @@ class OpenAILLM(BaseLLM): if reasoning: result["completion_tokens_details"] = {"reasoning_tokens": reasoning} self._last_usage = result + self._last_usage_claimed = False def _record_responses_metadata(self, response): rid = getattr(response, "id", None) @@ -850,6 +931,7 @@ class OpenAILLM(BaseLLM): if reasoning: result["completion_tokens_details"] = {"reasoning_tokens": reasoning} self._last_usage = result + self._last_usage_claimed = False @staticmethod def _responses_status_error(response) -> str | None: @@ -924,9 +1006,10 @@ class OpenAILLM(BaseLLM): self._last_response_id = None self._last_usage = None self._last_finish_reason = None - if previous_response_id and settings.OPENAI_RESPONSES_STORE: + chained = bool(previous_response_id and settings.OPENAI_RESPONSES_STORE) + if chained: messages = self._trim_for_previous_response(messages) - input_items = self._to_responses_input(messages) + input_items = self._to_responses_input(messages, chained=chained) params = self._build_responses_params( model, input_items, @@ -993,9 +1076,11 @@ class OpenAILLM(BaseLLM): self._last_response_id = None self._last_usage = None self._last_finish_reason = None - if previous_response_id and settings.OPENAI_RESPONSES_STORE: + self._stream_reached_finish = False + chained = bool(previous_response_id and settings.OPENAI_RESPONSES_STORE) + if chained: messages = self._trim_for_previous_response(messages) - input_items = self._to_responses_input(messages) + input_items = self._to_responses_input(messages, chained=chained) params = self._build_responses_params( model, input_items, @@ -1069,6 +1154,7 @@ class OpenAILLM(BaseLLM): status_error = self._responses_status_error(completed_response) if status_error: raise RuntimeError(status_error) + self._stream_reached_finish = True self._record_responses_metadata(completed_response) self._last_reasoning_items = reasoning_items self._last_finish_reason = "tool_calls" if func_calls else "stop" diff --git a/application/streaming/sse_keepalive.py b/application/streaming/sse_keepalive.py new file mode 100644 index 00000000..9d716ac0 --- /dev/null +++ b/application/streaming/sse_keepalive.py @@ -0,0 +1,72 @@ +"""Wire-level keepalive wrapper for synchronous SSE streaming routes.""" + +import contextvars +import logging +import queue +import threading +from typing import Generator, Optional + +from application.core.settings import settings + +logger = logging.getLogger(__name__) + + +def with_sse_keepalive( + inner: Generator[str, None, None], + interval_seconds: Optional[float] = None, +) -> Generator[str, None, None]: + """Yield from ``inner``, emitting ``: keepalive`` SSE comments whenever it + stays quiet for ``interval_seconds`` (defaults to + ``settings.SSE_KEEPALIVE_SECONDS``). + + Long tool-argument generations, summary-less reasoning stretches, and + server-side tool runs keep the origin busy for minutes without producing + a single chunk; proxies in front of the API then cut the byte-silent + connection (Cloudflare read-times-out at ~100s) while the origin + finishes into a dead socket. SSE comment frames keep bytes flowing and + are ignored by every SSE/OpenAI-compatible client — the same + ``: keepalive`` convention used by + ``application/streaming/async_event_replay.py``. + + ``inner`` is pumped from a daemon thread so this wrapper can time out on + silence. Callers must pass generators that don't rely on Flask's request + context (both chat stream routes return bare generators without + ``stream_with_context``). The pump runs in a copy of the caller's + contextvars context so request-scoped log bindings survive the thread + hop. The queue is unbounded and the thread is a daemon: if the consumer + disconnects mid-stream, the pump drains the upstream generator to + completion — matching the production ASGI adapter's pre-existing + disconnect behavior, where the WSGI iterable is drained before close(). + """ + if interval_seconds is None: + interval_seconds = float(settings.SSE_KEEPALIVE_SECONDS) + frames: queue.Queue = queue.Queue() + + def _pump() -> None: + try: + for item in inner: + frames.put(("item", item)) + except BaseException as exc: + # Logged here because after a client disconnect the consumer + # loop is gone and nothing ever dequeues (or re-raises) this. + logger.exception("SSE keepalive pump: upstream stream failed") + frames.put(("error", exc)) + else: + frames.put(("end", None)) + + ctx = contextvars.copy_context() + threading.Thread( + target=ctx.run, args=(_pump,), daemon=True, name="sse-keepalive-pump" + ).start() + while True: + try: + kind, payload = frames.get(timeout=interval_seconds) + except queue.Empty: + yield ": keepalive\n\n" + continue + if kind == "item": + yield payload + elif kind == "error": + raise payload + else: + return diff --git a/application/usage.py b/application/usage.py index 5f7c55c5..a1d31d08 100644 --- a/application/usage.py +++ b/application/usage.py @@ -155,10 +155,25 @@ def _prefer_provider_usage(llm: Any, call_usage: Dict[str, int]) -> Dict[str, in reported = getattr(llm, "_last_usage", None) if not isinstance(reported, dict): return call_usage + # ``_last_usage`` is shared instance state overwritten by every call on + # this LLM. Each reported usage may be billed to exactly ONE call: the + # provider clears ``_last_usage_claimed`` when it records fresh usage, + # and the first decorator ``finally`` to read it claims it. Without + # this, a generator finalized late (abandoned round, GC) would adopt a + # *different* call's provider counts. ``_last_usage`` itself is left in + # place for read-only consumers (client-facing usage metadata). + if getattr(llm, "_last_usage_claimed", False): + return call_usage prompt = reported.get("prompt_tokens") completion = reported.get("completion_tokens") if prompt is None or completion is None: return call_usage + try: + llm._last_usage_claimed = True + except AttributeError: + # Slotted/immutable LLM stand-ins can't record the claim; this + # call still gets the provider counts, which is correct for them. + pass return { "prompt_tokens": int(prompt or 0), "generated_tokens": int(completion or 0), diff --git a/frontend/src/locale/en.json b/frontend/src/locale/en.json index d474b801..f25b028b 100644 --- a/frontend/src/locale/en.json +++ b/frontend/src/locale/en.json @@ -344,6 +344,7 @@ "stats": { "messages": "Messages", "tokens": "Tokens", + "tokensHint": "All LLM-billed tokens. Agents re-send the conversation context on every tool step, so tool-heavy chats use many times more tokens than the visible messages suggest.", "toolCalls": "Tool Calls", "runSuccess": "Run Success", "feedback": "Feedback" diff --git a/frontend/src/settings/Analytics.tsx b/frontend/src/settings/Analytics.tsx index 47b4e135..1183f2af 100644 --- a/frontend/src/settings/Analytics.tsx +++ b/frontend/src/settings/Analytics.tsx @@ -336,7 +336,7 @@ export default function Analytics({ agentId }: AnalyticsProps) { ? `${Math.round((scheduleTotals.completed / scheduleRunsTotal) * 100)}%` : '—'; - const statCards = [ + const statCards: { label: string; value: string; hint?: string }[] = [ { label: t('settings.analytics.stats.messages'), value: totalMessages.toLocaleString(), @@ -344,6 +344,7 @@ export default function Analytics({ agentId }: AnalyticsProps) { { label: t('settings.analytics.stats.tokens'), value: totalTokens.toLocaleString(), + hint: t('settings.analytics.stats.tokensHint'), }, { label: t('settings.analytics.stats.toolCalls'), @@ -410,7 +411,8 @@ export default function Analytics({ agentId }: AnalyticsProps) { {statCards.map((card) => (
{card.label}
diff --git a/tests/api/answer/services/compression/test_service.py b/tests/api/answer/services/compression/test_service.py
index 99042780..6145a168 100644
--- a/tests/api/answer/services/compression/test_service.py
+++ b/tests/api/answer/services/compression/test_service.py
@@ -421,3 +421,128 @@ class TestLogToolCallStats:
}
]
svc._log_tool_call_stats(queries)
+
+
+@pytest.mark.unit
+class TestNegativeSavingsGuard:
+ """A summary that isn't smaller than the original must never be saved
+ as a compression point."""
+
+ def test_growing_compression_raises(self, mock_llm, sample_conversation):
+ mock_llm.gen.return_value = (
+ "