上下文窗口的修改

This commit is contained in:
2026-03-13 21:51:15 +08:00
parent efbd4214a7
commit f476022968
18 changed files with 1451 additions and 36 deletions
+351 -16
View File
@@ -3,19 +3,38 @@
from __future__ import annotations
from dataclasses import dataclass
import json
from typing import Any
from voidbot.config import AppConfig
from voidbot.context import ContextBuilder
from voidbot.context_window import (
ContextWindowResolution,
estimate_message_tokens,
estimate_prompt_tokens,
is_context_overflow_error_text,
resolve_context_window,
)
from voidbot.gateway.messages import InboundMessageContext
from voidbot.i18n import t
from voidbot.models import RunTurnResult
from voidbot.models import LLMResponse, RunTurnResult
from voidbot.providers.manager import ProviderManager
from voidbot.providers.registry import get_provider_spec
from voidbot.runtime_env import detect_runtime_execution
from voidbot.session import SessionState, SessionStore
from voidbot.tools.base import ToolRegistry
@dataclass(frozen=True, slots=True)
class PreparedContext:
"""Resolved prompt context for one turn."""
messages: list[dict[str, Any]]
provider_summary: str
limits: ContextWindowResolution
estimated_prompt_tokens: int
@dataclass(slots=True)
class AgentRuntime:
"""Session-aware runtime."""
@@ -42,24 +61,32 @@ class AgentRuntime:
return command_result
active_provider_id = session_state.provider_id or self.config.default_provider
provider_description = self.providers.describe(active_provider_id)
history = self.session.load_history(
limit=self.config.history_limit,
session_id=inbound.session_id,
provider_profile = self.providers.get_profile(active_provider_id)
provider_spec = get_provider_spec(provider_profile.preset)
limits = resolve_context_window(self.config, provider_profile, provider_spec)
self.session.update_context_metrics(
inbound.session_id,
resolved_context_window_tokens=limits.context_window_tokens,
max_output_tokens=limits.max_output_tokens,
input_budget_tokens=limits.input_budget_tokens,
)
tool_summaries = self.tools.summaries()
provider_description = self.providers.describe(active_provider_id)
provider_summary = (
f"{provider_description['id']} / "
f"{provider_description['label']} / "
f"{provider_description['model']}"
)
messages = self.context_builder.build_messages(
history,
inbound,
tool_summaries,
provider_summary,
)
tool_summaries = self.tools.summaries()
provider = self.providers.build(active_provider_id)
prepared = self._prepare_context(
inbound=inbound,
provider_id=active_provider_id,
provider=provider,
provider_summary=provider_summary,
limits=limits,
tool_summaries=tool_summaries,
)
self.session.append(
{
@@ -74,13 +101,61 @@ class AgentRuntime:
session_id=inbound.session_id,
)
tool_events: list[dict] = []
tool_events: list[dict[str, Any]] = []
final_reply = "No reply produced."
iteration = 0
messages = [dict(item) for item in prepared.messages]
overflow_retries = 0
while iteration < self.config.max_iterations:
iteration += 1
estimated_for_iteration = self._estimate_prompt_tokens(
provider,
messages,
self.tools.schemas(),
)
self.session.update_context_metrics(
inbound.session_id,
estimated_prompt_tokens=estimated_for_iteration,
needs_compaction=(
estimated_for_iteration >= prepared.limits.compact_threshold_tokens
),
)
response = provider.chat(messages=messages, tools=self.tools.schemas())
actual_prompt_tokens = self._extract_actual_prompt_tokens(response)
self.session.update_context_metrics(
inbound.session_id,
actual_prompt_tokens=actual_prompt_tokens,
needs_compaction=(
actual_prompt_tokens is not None
and actual_prompt_tokens >= prepared.limits.compact_threshold_tokens
),
)
if response.finish_reason == "error":
if (
overflow_retries < 2
and is_context_overflow_error_text(response.content)
and self._compact_session(
inbound=inbound,
provider=provider,
provider_id=active_provider_id,
provider_summary=prepared.provider_summary,
tool_summaries=tool_summaries,
limits=prepared.limits,
aggressive=True,
)
):
overflow_retries += 1
messages = self._rebuild_messages(
inbound=inbound,
provider_summary=prepared.provider_summary,
tool_summaries=tool_summaries,
)
continue
final_reply = response.content or final_reply
break
assistant_message = {
"role": "assistant",
@@ -158,6 +233,268 @@ class AgentRuntime:
metadata["channel_capabilities"] = list(inbound.capabilities)
return metadata
def _prepare_context(
self,
*,
inbound: InboundMessageContext,
provider_id: str,
provider: Any,
provider_summary: str,
limits: ContextWindowResolution,
tool_summaries: list[str],
) -> PreparedContext:
rounds = 0
messages = self._rebuild_messages(
inbound=inbound,
provider_summary=provider_summary,
tool_summaries=tool_summaries,
)
estimated_tokens = self._estimate_prompt_tokens(
provider,
messages,
self.tools.schemas(),
)
self.session.update_context_metrics(
inbound.session_id,
estimated_prompt_tokens=estimated_tokens,
needs_compaction=estimated_tokens >= limits.compact_threshold_tokens,
)
while (
estimated_tokens >= limits.compact_threshold_tokens
and rounds < self.config.context_compaction_max_rounds
):
did_compact = self._compact_session(
inbound=inbound,
provider=provider,
provider_id=provider_id,
provider_summary=provider_summary,
tool_summaries=tool_summaries,
limits=limits,
aggressive=False,
)
if not did_compact:
break
rounds += 1
messages = self._rebuild_messages(
inbound=inbound,
provider_summary=provider_summary,
tool_summaries=tool_summaries,
)
estimated_tokens = self._estimate_prompt_tokens(
provider,
messages,
self.tools.schemas(),
)
self.session.update_context_metrics(
inbound.session_id,
estimated_prompt_tokens=estimated_tokens,
needs_compaction=estimated_tokens >= limits.compact_threshold_tokens,
)
return PreparedContext(
messages=messages,
provider_summary=provider_summary,
limits=limits,
estimated_prompt_tokens=estimated_tokens,
)
def _rebuild_messages(
self,
*,
inbound: InboundMessageContext,
provider_summary: str,
tool_summaries: list[str],
) -> list[dict[str, Any]]:
history = self.session.load_active_history(session_id=inbound.session_id)
compaction_summary = self.session.load_compaction_summary(inbound.session_id)
return self.context_builder.build_messages(
history,
inbound,
tool_summaries,
provider_summary,
compaction_summary=compaction_summary,
)
def _compact_session(
self,
*,
inbound: InboundMessageContext,
provider: Any,
provider_id: str,
provider_summary: str,
tool_summaries: list[str],
limits: ContextWindowResolution,
aggressive: bool,
) -> bool:
candidates = self.session.list_compaction_candidates(session_id=inbound.session_id)
chunk = self._pick_compaction_chunk(
candidates,
limits=limits,
aggressive=aggressive,
)
if not chunk:
return False
previous_summary = self.session.load_compaction_summary(inbound.session_id)
summary_messages = self._build_compaction_prompt(previous_summary, chunk)
summary_response = provider.chat(messages=summary_messages, tools=None)
if summary_response.finish_reason == "error":
return False
summary_text = (summary_response.content or "").strip()
if not summary_text:
return False
self.session.record_compaction(
session_id=inbound.session_id,
start_message_id=chunk[0]["_message_id"],
end_message_id=chunk[-1]["_message_id"],
summary=summary_text,
message_count=len(chunk),
estimated_tokens=sum(
estimate_message_tokens(message)
for message in [
converted
for converted in (
self.session._to_llm_message(row) for row in chunk
)
if converted is not None
]
),
provider_id=provider_id,
model_name=getattr(provider, "model_name", None),
)
self.session.update_context_metrics(
inbound.session_id,
needs_compaction=False,
input_budget_tokens=limits.input_budget_tokens,
)
return True
def _pick_compaction_chunk(
self,
candidates: list[dict[str, Any]],
*,
limits: ContextWindowResolution,
aggressive: bool,
) -> list[dict[str, Any]]:
visible = [row for row in candidates if row.get("role") in {"user", "assistant", "tool"}]
if not visible:
return []
preserve_turns = self._resolve_preserve_recent_turns(aggressive=aggressive)
user_indexes = [
index for index, row in enumerate(visible) if row.get("role") == "user"
]
if len(user_indexes) <= preserve_turns:
return []
preserve_start = user_indexes[-preserve_turns]
max_chunk_tokens = max(1024, limits.input_budget_tokens // 2)
chunk: list[dict[str, Any]] = []
accumulated_tokens = 0
for row in visible[:preserve_start]:
converted = self.session._to_llm_message(row)
estimated = estimate_message_tokens(converted) if converted is not None else 64
if chunk and accumulated_tokens + estimated > max_chunk_tokens:
break
chunk.append(row)
accumulated_tokens += estimated
while chunk and chunk[-1].get("role") != "assistant":
chunk = chunk[:-1]
return chunk
def _resolve_preserve_recent_turns(self, *, aggressive: bool) -> int:
base = max(1, self.config.history_limit // 4)
capped = min(6, base)
if aggressive:
return max(1, min(2, capped))
return max(2, capped)
@staticmethod
def _build_compaction_prompt(
previous_summary: str | None,
chunk: list[dict[str, Any]],
) -> list[dict[str, Any]]:
lines = []
for row in chunk:
role = str(row.get("role") or "unknown").upper()
content = row.get("content")
rendered = content if isinstance(content, str) else json.dumps(
content, ensure_ascii=False
)
if row.get("tool_calls"):
rendered = (
f"{rendered}\nTool Calls: "
f"{json.dumps(row['tool_calls'], ensure_ascii=False)}"
)
if row.get("tool_call_id"):
rendered = (
f"{rendered}\nTool Call ID: {row.get('tool_call_id')}\n"
f"Tool Name: {row.get('name')}"
)
lines.append(f"[message_id={row['_message_id']}] {role}: {rendered}")
prior = previous_summary.strip() if previous_summary else "(none)"
prompt = (
"Merge the older conversation history into one compact continuation summary.\n"
"Preserve:\n"
"- the latest user goals and pending asks\n"
"- important decisions and constraints\n"
"- exact file paths, command names, IDs, model names, and channel details\n"
"- unresolved tool results or failures\n"
"- active implementation status\n\n"
"Be concise but do not lose durable context.\n\n"
"## Previous Summary\n"
f"{prior}\n\n"
"## Messages To Compact\n"
f"{chr(10).join(lines)}"
)
return [
{
"role": "system",
"content": (
"You summarize older agent conversation history so the active "
"context window can stay small without losing continuity."
),
},
{"role": "user", "content": prompt},
]
@staticmethod
def _estimate_prompt_tokens(
provider: Any,
messages: list[dict[str, Any]],
tools: list[dict[str, Any]] | None,
) -> int:
estimator = getattr(provider, "estimate_prompt_tokens", None)
if callable(estimator):
try:
estimated = estimator(messages, tools)
if isinstance(estimated, tuple):
tokens = estimated[0]
else:
tokens = estimated
if isinstance(tokens, int) and tokens > 0:
return tokens
except Exception:
pass
return estimate_prompt_tokens(messages, tools)
@staticmethod
def _extract_actual_prompt_tokens(response: LLMResponse) -> int | None:
usage = response.usage
if not isinstance(usage, dict):
return None
for key in (
"prompt_tokens",
"input_tokens",
"promptTokens",
"input",
):
value = usage.get(key)
if isinstance(value, int) and value > 0:
return value
return None
def _handle_control_command(
self,
inbound: InboundMessageContext,
@@ -206,9 +543,7 @@ class AgentRuntime:
try:
profile = self.providers.get_profile(provider_id)
except ValueError as exc:
provider_description = self.providers.describe(
session_state.provider_id
)
provider_description = self.providers.describe(session_state.provider_id)
return RunTurnResult(
reply=str(exc),
iterations=0,
+13 -10
View File
@@ -3,7 +3,6 @@
from __future__ import annotations
import asyncio
from concurrent.futures import ThreadPoolExecutor
import logging
import threading
from typing import Any
@@ -13,6 +12,7 @@ from voidbot.channels.base import BaseChannel, InboundChannelMessage
from voidbot.channels.typing import create_reply_indicator_callbacks
from voidbot.config import ChannelsConfig
from voidbot.gateway.messages import InboundMessageContext
from voidbot.gateway.run_queue import InMemoryRunQueue
LOGGER = logging.getLogger(__name__)
@@ -26,10 +26,12 @@ class ChannelManager:
channels_config: ChannelsConfig,
*,
channel_factories: dict[str, type[BaseChannel]] | None = None,
run_queue: InMemoryRunQueue | None = None,
) -> None:
self.runtime = runtime
self.channels_config = channels_config
self.channel_factories = channel_factories or self._default_channel_factories()
self.run_queue = run_queue or InMemoryRunQueue()
self.channels: dict[str, BaseChannel] = {}
self._loop: asyncio.AbstractEventLoop | None = None
self._thread: threading.Thread | None = None
@@ -97,16 +99,12 @@ class ChannelManager:
)
await reply_indicator.on_reply_start()
try:
loop = asyncio.get_running_loop()
with ThreadPoolExecutor(
max_workers=1,
thread_name_prefix="voidbot-channel-turn",
) as executor:
result = await loop.run_in_executor(
executor,
self.runtime.run_turn,
inbound,
result = await asyncio.wrap_future(
self.run_queue.enqueue(
inbound.session_id,
lambda: self.runtime.run_turn(inbound),
)
)
reply = result.reply.strip()
if not reply:
return
@@ -265,3 +263,8 @@ class ChannelManager:
}
for name, channel in self.channels.items()
}
def shutdown(self) -> None:
"""Stop channel listeners and release queue workers."""
self.stop_background()
self.run_queue.shutdown(wait=False)
+62
View File
@@ -49,6 +49,8 @@ class ProviderConfig:
api_base: str | None = None
model: str | None = None
label: str | None = None
context_window_tokens: int | None = None
max_output_tokens: int | None = None
@classmethod
def from_mapping(
@@ -64,6 +66,16 @@ class ProviderConfig:
api_base=str(data["api_base"]) if data.get("api_base") else None,
model=str(data["model"]) if data.get("model") else None,
label=str(data["label"]) if data.get("label") else None,
context_window_tokens=(
int(data["context_window_tokens"])
if data.get("context_window_tokens") not in (None, "")
else None
),
max_output_tokens=(
int(data["max_output_tokens"])
if data.get("max_output_tokens") not in (None, "")
else None
),
)
@@ -141,6 +153,8 @@ def build_example_config() -> dict[str, Any]:
"api_key": "YOUR_API_KEY",
"api_base": "https://open.bigmodel.cn/api/coding/paas/v4",
"model": "glm-4.7",
"context_window_tokens": 128000,
"max_output_tokens": 8192,
},
{
"id": "2",
@@ -148,6 +162,8 @@ def build_example_config() -> dict[str, Any]:
"preset": "openai_chatgpt",
"api_key": "YOUR_OPENAI_API_KEY",
"model": "gpt-4.1-mini",
"context_window_tokens": 128000,
"max_output_tokens": 8192,
},
{
"id": "3",
@@ -156,12 +172,20 @@ def build_example_config() -> dict[str, Any]:
"api_key": "YOUR_SILICONFLOW_API_KEY",
"api_base": "https://api.siliconflow.cn/v1",
"model": "deepseek-ai/DeepSeek-V3",
"context_window_tokens": 128000,
"max_output_tokens": 8192,
},
],
"workspace": ".",
"database_path": "~/.voidbot/voidbot.db",
"max_iterations": 8,
"history_limit": 24,
"context_window_tokens": 16384,
"max_output_tokens": 4096,
"context_compact_threshold_ratio": 0.88,
"context_warn_threshold_ratio": 0.8,
"context_safety_margin_tokens": 1024,
"context_compaction_max_rounds": 3,
"system_prompt": (
"You are VoidBot, a concise coding agent. "
"Use tools when needed, cite tool results plainly, "
@@ -304,6 +328,12 @@ class AppConfig:
session_file: Path | None = None
max_iterations: int = 8
history_limit: int = 24
context_window_tokens: int = 16384
max_output_tokens: int = 4096
context_compact_threshold_ratio: float = 0.88
context_warn_threshold_ratio: float = 0.8
context_safety_margin_tokens: int = 1024
context_compaction_max_rounds: int = 3
system_prompt: str | None = None
request_timeout: int = 120
gateway_host: str = "127.0.0.1"
@@ -352,6 +382,20 @@ class AppConfig:
session_file=database_path.resolve(),
max_iterations=int(data.get("max_iterations") or 8),
history_limit=int(data.get("history_limit") or 24),
context_window_tokens=int(data.get("context_window_tokens") or 16384),
max_output_tokens=int(data.get("max_output_tokens") or 4096),
context_compact_threshold_ratio=float(
data.get("context_compact_threshold_ratio") or 0.88
),
context_warn_threshold_ratio=float(
data.get("context_warn_threshold_ratio") or 0.8
),
context_safety_margin_tokens=int(
data.get("context_safety_margin_tokens") or 1024
),
context_compaction_max_rounds=int(
data.get("context_compaction_max_rounds") or 3
),
system_prompt=str(data["system_prompt"])
if data.get("system_prompt")
else None,
@@ -433,6 +477,10 @@ def _provider_to_mapping(provider: ProviderConfig) -> dict[str, Any]:
payload["api_base"] = provider.api_base
if provider.model:
payload["model"] = provider.model
if provider.context_window_tokens is not None:
payload["context_window_tokens"] = provider.context_window_tokens
if provider.max_output_tokens is not None:
payload["max_output_tokens"] = provider.max_output_tokens
return payload
@@ -481,6 +529,20 @@ def load_config(
"session_file": os.getenv("VOIDBOT_SESSION_FILE"),
"max_iterations": os.getenv("VOIDBOT_MAX_ITERATIONS"),
"history_limit": os.getenv("VOIDBOT_HISTORY_LIMIT"),
"context_window_tokens": os.getenv("VOIDBOT_CONTEXT_WINDOW_TOKENS"),
"max_output_tokens": os.getenv("VOIDBOT_MAX_OUTPUT_TOKENS"),
"context_compact_threshold_ratio": os.getenv(
"VOIDBOT_CONTEXT_COMPACT_THRESHOLD_RATIO"
),
"context_warn_threshold_ratio": os.getenv(
"VOIDBOT_CONTEXT_WARN_THRESHOLD_RATIO"
),
"context_safety_margin_tokens": os.getenv(
"VOIDBOT_CONTEXT_SAFETY_MARGIN_TOKENS"
),
"context_compaction_max_rounds": os.getenv(
"VOIDBOT_CONTEXT_COMPACTION_MAX_ROUNDS"
),
"system_prompt": os.getenv("VOIDBOT_SYSTEM_PROMPT"),
"request_timeout": os.getenv("VOIDBOT_REQUEST_TIMEOUT"),
"gateway_host": os.getenv("VOIDBOT_GATEWAY_HOST"),
+18 -4
View File
@@ -30,9 +30,10 @@ class ContextBuilder:
inbound: InboundMessageContext,
tool_summaries: list[str],
provider_summary: str,
compaction_summary: str | None = None,
) -> list[dict]:
"""Build a chat completion message array."""
return [
messages: list[dict] = [
{
"role": "system",
"content": self._build_system_prompt(
@@ -40,10 +41,23 @@ class ContextBuilder:
tool_summaries=tool_summaries,
provider_summary=provider_summary,
),
},
*history,
{"role": "user", "content": inbound.body_for_agent},
}
]
if compaction_summary:
messages.append(
{
"role": "system",
"content": (
"## Compacted Session Summary\n"
"The following summary replaces older session turns that were "
"compacted to stay within the context window.\n\n"
f"{compaction_summary}"
),
}
)
messages.extend(history)
messages.append({"role": "user", "content": inbound.body_for_agent})
return messages
def _build_system_prompt(
self,
+171
View File
@@ -0,0 +1,171 @@
"""Context window resolution, estimation, and overflow helpers."""
from __future__ import annotations
from dataclasses import dataclass
import json
import math
from typing import TYPE_CHECKING, Any
if TYPE_CHECKING:
from voidbot.config import AppConfig, ProviderConfig
from voidbot.providers.base import ProviderSpec
_SAFE_FALLBACK_CONTEXT_WINDOW_TOKENS = 16384
_SAFE_FALLBACK_MAX_OUTPUT_TOKENS = 4096
_OVERFLOW_KEYWORDS = (
"maximum context length",
"context length exceeded",
"context_length_exceeded",
"too many tokens",
"prompt is too long",
"prompt too long",
"input is too long",
"context window",
"exceeds the context",
"token limit exceeded",
"上下文长度",
"超出上下文",
"超出最大长度",
)
@dataclass(frozen=True, slots=True)
class ContextWindowResolution:
"""Resolved limits for one provider/model profile."""
context_window_tokens: int
max_output_tokens: int
compact_threshold_tokens: int
warn_threshold_tokens: int
input_budget_tokens: int
source: str
def resolve_context_window(
config: "AppConfig",
profile: "ProviderConfig",
spec: "ProviderSpec",
) -> ContextWindowResolution:
"""Resolve usable context limits for one provider profile."""
context_window_tokens = _first_positive_int(
profile.context_window_tokens,
spec.default_context_window_tokens,
config.context_window_tokens,
fallback=_SAFE_FALLBACK_CONTEXT_WINDOW_TOKENS,
)
max_output_tokens = _first_positive_int(
profile.max_output_tokens,
spec.default_max_output_tokens,
config.max_output_tokens,
fallback=_SAFE_FALLBACK_MAX_OUTPUT_TOKENS,
)
warn_ratio = _normalize_ratio(config.context_warn_threshold_ratio, fallback=0.8)
compact_ratio = _normalize_ratio(
config.context_compact_threshold_ratio, fallback=0.88
)
if compact_ratio < warn_ratio:
compact_ratio = warn_ratio
safety_margin_tokens = max(0, int(config.context_safety_margin_tokens))
input_budget_tokens = max(
1,
context_window_tokens - max_output_tokens - safety_margin_tokens,
)
warn_threshold_tokens = max(1, math.floor(input_budget_tokens * warn_ratio))
compact_threshold_tokens = max(1, math.floor(input_budget_tokens * compact_ratio))
source = "profile" if profile.context_window_tokens else (
"preset" if spec.default_context_window_tokens else "config"
)
return ContextWindowResolution(
context_window_tokens=context_window_tokens,
max_output_tokens=max_output_tokens,
compact_threshold_tokens=compact_threshold_tokens,
warn_threshold_tokens=warn_threshold_tokens,
input_budget_tokens=input_budget_tokens,
source=source,
)
def estimate_prompt_tokens(
messages: list[dict[str, Any]],
tools: list[dict[str, Any]] | None = None,
) -> int:
"""Estimate full prompt token usage conservatively."""
total = 0
for message in messages:
total += estimate_message_tokens(message)
if tools:
total += estimate_json_tokens(tools)
return max(1, total)
def estimate_message_tokens(message: dict[str, Any]) -> int:
"""Estimate one chat message's prompt contribution."""
payload_parts: list[str] = [str(message.get("role") or "message")]
content = message.get("content")
if isinstance(content, str):
payload_parts.append(content)
elif isinstance(content, list):
for item in content:
if isinstance(item, dict) and item.get("type") == "text":
payload_parts.append(str(item.get("text") or ""))
else:
payload_parts.append(json.dumps(item, ensure_ascii=False))
elif content is not None:
payload_parts.append(json.dumps(content, ensure_ascii=False))
for key in ("name", "tool_call_id"):
value = message.get(key)
if value:
payload_parts.append(str(value))
tool_calls = message.get("tool_calls")
if tool_calls:
payload_parts.append(json.dumps(tool_calls, ensure_ascii=False))
return estimate_text_tokens("\n".join(part for part in payload_parts if part))
def estimate_json_tokens(value: Any) -> int:
"""Estimate tokens for a JSON payload."""
return estimate_text_tokens(json.dumps(value, ensure_ascii=False, sort_keys=True))
def estimate_text_tokens(text: str) -> int:
"""Estimate text tokens conservatively across ASCII and CJK-heavy payloads."""
if not text:
return 1
ascii_count = sum(1 for char in text if char.isascii())
non_ascii_count = max(0, len(text) - ascii_count)
whitespace_count = sum(1 for char in text if char.isspace())
visible_ascii = max(0, ascii_count - whitespace_count)
estimated = (
visible_ascii / 3.2
+ whitespace_count / 12
+ non_ascii_count * 1.15
)
return max(1, math.ceil(estimated))
def is_context_overflow_error_text(text: str | None) -> bool:
"""Return True when provider error text looks like a context overflow."""
if not text:
return False
lowered = text.strip().lower()
return any(keyword in lowered for keyword in _OVERFLOW_KEYWORDS)
def _first_positive_int(*values: int | None, fallback: int) -> int:
for value in values:
if isinstance(value, int) and value > 0:
return value
return fallback
def _normalize_ratio(value: float | int, *, fallback: float) -> float:
if not isinstance(value, (float, int)):
return fallback
normalized = float(value)
if normalized <= 0:
return fallback
return min(0.99, normalized)
+8 -1
View File
@@ -24,6 +24,7 @@ from voidbot.config import (
)
from voidbot.gateway.client import GatewayClient
from voidbot.gateway.messages import InboundMessageContext
from voidbot.gateway.run_queue import InMemoryRunQueue
from voidbot.gateway.server import GatewayApplication, run_gateway_server
from voidbot.gateway.ui import render_single_turn, run_terminal_loop
from voidbot.i18n import t
@@ -292,13 +293,19 @@ def run_gateway_command(
"""Run the standalone gateway server."""
config = load_config(config_path, require_api_key=True)
app = build_app(config)
channel_manager = ChannelManager(app.runtime, config.channels)
run_queue = InMemoryRunQueue()
channel_manager = ChannelManager(
app.runtime,
config.channels,
run_queue=run_queue,
)
bind_host = host or config.gateway_host
bind_port = port or config.gateway_port
run_gateway_server(
application=GatewayApplication(
runtime=app.runtime,
channel_manager=channel_manager,
run_queue=run_queue,
),
host=bind_host,
port=bind_port,
+111
View File
@@ -0,0 +1,111 @@
"""In-memory run queue for gateway-driven agent turns."""
from __future__ import annotations
from collections import deque
from concurrent.futures import Future, ThreadPoolExecutor
from dataclasses import dataclass
import threading
from typing import Callable, Generic, TypeVar
T = TypeVar("T")
@dataclass(slots=True)
class _QueueEntry(Generic[T]):
future: Future[T]
task: Callable[[], T]
class InMemoryRunQueue:
"""Serialize agent turns per session with a global concurrency cap."""
def __init__(self, *, max_concurrent: int = 1) -> None:
self.max_concurrent = max(1, int(max_concurrent))
self._lock = threading.RLock()
self._executor = ThreadPoolExecutor(
max_workers=self.max_concurrent,
thread_name_prefix="voidbot-run-queue",
)
self._queues: dict[str, deque[_QueueEntry[object]]] = {}
self._ready_sessions: deque[str] = deque()
self._ready_session_set: set[str] = set()
self._active_sessions: set[str] = set()
self._active_count = 0
self._shutdown = False
def enqueue(self, session_id: str, task: Callable[[], T]) -> Future[T]:
"""Queue one synchronous task and return a future for its result."""
future: Future[T] = Future()
cleaned_session_id = (session_id or "main").strip() or "main"
with self._lock:
if self._shutdown:
future.set_exception(RuntimeError("run queue is shut down"))
return future
queue = self._queues.setdefault(cleaned_session_id, deque())
queue.append(_QueueEntry(future=future, task=task))
if (
cleaned_session_id not in self._active_sessions
and cleaned_session_id not in self._ready_session_set
):
self._ready_sessions.append(cleaned_session_id)
self._ready_session_set.add(cleaned_session_id)
self._dispatch_locked()
return future
def snapshot(self) -> dict[str, object]:
"""Return queue activity counters for diagnostics."""
with self._lock:
return {
"active_count": self._active_count,
"active_sessions": sorted(self._active_sessions),
"queued_count": sum(len(items) for items in self._queues.values()),
"queued_by_session": {
session_id: len(items)
for session_id, items in sorted(self._queues.items())
if items
},
"max_concurrent": self.max_concurrent,
}
def shutdown(self, *, wait: bool = True) -> None:
"""Stop accepting new jobs and close worker threads."""
with self._lock:
self._shutdown = True
self._executor.shutdown(wait=wait, cancel_futures=False)
def _dispatch_locked(self) -> None:
while self._active_count < self.max_concurrent and self._ready_sessions:
session_id = self._ready_sessions.popleft()
self._ready_session_set.discard(session_id)
queue = self._queues.get(session_id)
if not queue:
self._queues.pop(session_id, None)
continue
entry = queue.popleft()
if not queue:
self._queues.pop(session_id, None)
else:
self._queues[session_id] = queue
self._active_sessions.add(session_id)
self._active_count += 1
self._executor.submit(self._run_entry, session_id, entry)
def _run_entry(self, session_id: str, entry: _QueueEntry[object]) -> None:
try:
result = entry.task()
except Exception as exc:
if not entry.future.done():
entry.future.set_exception(exc)
else:
if not entry.future.done():
entry.future.set_result(result)
finally:
with self._lock:
self._active_sessions.discard(session_id)
self._active_count = max(0, self._active_count - 1)
if session_id in self._queues and session_id not in self._ready_session_set:
self._ready_sessions.append(session_id)
self._ready_session_set.add(session_id)
self._dispatch_locked()
+21 -3
View File
@@ -10,6 +10,7 @@ from typing import Any
from voidbot.agent import AgentRuntime
from voidbot.channels.manager import ChannelManager
from voidbot.gateway.messages import InboundMessageContext
from voidbot.gateway.run_queue import InMemoryRunQueue
from voidbot.i18n import t
@@ -19,6 +20,13 @@ class GatewayApplication:
runtime: AgentRuntime
channel_manager: ChannelManager | None = None
run_queue: InMemoryRunQueue | None = None
def __post_init__(self) -> None:
if self.run_queue is None and self.channel_manager is not None:
self.run_queue = self.channel_manager.run_queue
if self.run_queue is None:
self.run_queue = InMemoryRunQueue()
def health(self) -> dict[str, Any]:
"""Return gateway health."""
@@ -32,6 +40,7 @@ class GatewayApplication:
"channels": self.channel_manager.get_status()
if self.channel_manager
else {},
"queue": self.run_queue.snapshot() if self.run_queue else {},
}
def run_agent(self, payload: dict[str, Any]) -> dict[str, Any]:
@@ -64,7 +73,10 @@ class GatewayApplication:
if payload.get("python_executable")
else None,
)
result = self.runtime.run_turn(inbound)
result = self.run_queue.enqueue(
inbound.session_id,
lambda: self.runtime.run_turn(inbound),
).result()
return {
"ok": True,
"session_id": inbound.session_id,
@@ -78,6 +90,13 @@ class GatewayApplication:
"model_name": result.model_name,
}
def shutdown(self) -> None:
"""Release queue workers owned by the gateway application."""
if self.channel_manager:
self.channel_manager.stop_background()
if self.run_queue:
self.run_queue.shutdown(wait=False)
def create_gateway_handler(
application: GatewayApplication,
@@ -148,5 +167,4 @@ def run_gateway_server(
pass
finally:
server.server_close()
if application.channel_manager:
application.channel_manager.stop_background()
application.shutdown()
+1
View File
@@ -35,6 +35,7 @@ class LLMResponse:
content: str | None = None
tool_calls: list[ToolCall] = field(default_factory=list)
finish_reason: str = "stop"
usage: dict[str, Any] | None = None
raw: dict[str, Any] | None = None
@property
+9 -1
View File
@@ -1,15 +1,23 @@
"""Provider helpers."""
from __future__ import annotations
from typing import TYPE_CHECKING
from voidbot.config import ProviderConfig
from voidbot.providers.openai_compatible import OpenAICompatibleProvider
from voidbot.providers.manager import ProviderManager
from voidbot.providers.registry import get_provider_spec
if TYPE_CHECKING:
from voidbot.providers.openai_compatible import OpenAICompatibleProvider
def build_provider(
profile: ProviderConfig, *, timeout: int = 120
) -> OpenAICompatibleProvider:
"""Build one configured provider client."""
from voidbot.providers.openai_compatible import OpenAICompatibleProvider
spec = get_provider_spec(profile.preset)
return OpenAICompatibleProvider(
spec=spec,
+8
View File
@@ -16,6 +16,8 @@ class ProviderSpec:
label: str
default_base_url: str
default_model: str
default_context_window_tokens: int | None = None
default_max_output_tokens: int | None = None
class LLMProvider(ABC):
@@ -27,6 +29,12 @@ class LLMProvider(ABC):
) -> LLMResponse:
"""Execute one chat completion call."""
def estimate_prompt_tokens(
self, messages: list[dict], tools: list[dict] | None = None
) -> tuple[int, str] | None:
"""Estimate prompt usage for one request if supported."""
return None
@property
@abstractmethod
def model_name(self) -> str:
+6 -1
View File
@@ -3,12 +3,15 @@
from __future__ import annotations
from dataclasses import dataclass
from typing import TYPE_CHECKING
from voidbot.config import AppConfig, ProviderConfig
from voidbot.i18n import t
from voidbot.providers.openai_compatible import OpenAICompatibleProvider
from voidbot.providers.registry import get_provider_spec
if TYPE_CHECKING:
from voidbot.providers.openai_compatible import OpenAICompatibleProvider
@dataclass(slots=True)
class ProviderManager:
@@ -38,6 +41,8 @@ class ProviderManager:
def build(self, provider_id: str | None = None) -> OpenAICompatibleProvider:
"""Build a provider client for the given profile."""
from voidbot.providers.openai_compatible import OpenAICompatibleProvider
profile = self.get_profile(provider_id)
spec = get_provider_spec(profile.preset)
return OpenAICompatibleProvider(
@@ -9,6 +9,7 @@ import uuid
from dataclasses import dataclass
from typing import Any
from voidbot.context_window import estimate_prompt_tokens
from voidbot.models import LLMResponse, ToolCall
from voidbot.providers.base import LLMProvider, ProviderSpec
from voidbot.providers.compat import build_request_payload
@@ -28,6 +29,11 @@ class OpenAICompatibleProvider(LLMProvider):
def model_name(self) -> str:
return self._model_name
def estimate_prompt_tokens(
self, messages: list[dict], tools: list[dict] | None = None
) -> tuple[int, str] | None:
return estimate_prompt_tokens(messages, tools), "voidbot_estimator"
def chat(
self, messages: list[dict], tools: list[dict] | None = None
) -> LLMResponse:
@@ -93,6 +99,7 @@ class OpenAICompatibleProvider(LLMProvider):
content=content if isinstance(content, str) else None,
tool_calls=tool_calls,
finish_reason=str(choice.get("finish_reason") or "stop"),
usage=raw.get("usage") if isinstance(raw.get("usage"), dict) else None,
raw=raw,
)
+8
View File
@@ -11,24 +11,32 @@ PROVIDERS: dict[str, ProviderSpec] = {
label="OpenAI ChatGPT",
default_base_url="https://api.openai.com/v1",
default_model="gpt-4.1-mini",
default_context_window_tokens=128000,
default_max_output_tokens=8192,
),
"zhipu_coding_plan": ProviderSpec(
name="zhipu_coding_plan",
label="Zhipu Coding Plan",
default_base_url="https://open.bigmodel.cn/api/coding/paas/v4",
default_model="glm-4.7",
default_context_window_tokens=128000,
default_max_output_tokens=8192,
),
"siliconflow": ProviderSpec(
name="siliconflow",
label="SiliconFlow",
default_base_url="https://api.siliconflow.cn/v1",
default_model="deepseek-ai/DeepSeek-V3",
default_context_window_tokens=128000,
default_max_output_tokens=8192,
),
"custom_openai_compatible": ProviderSpec(
name="custom_openai_compatible",
label="Custom OpenAI-Compatible",
default_base_url="http://localhost:8000/v1",
default_model="default",
default_context_window_tokens=16384,
default_max_output_tokens=4096,
),
}
+327
View File
@@ -27,6 +27,22 @@ class SessionState:
updated_at: str | None = None
@dataclass(slots=True)
class SessionCompaction:
"""Stored session compaction summary."""
id: int
session_id: str
start_message_id: int | None
end_message_id: int
summary: str
message_count: int
estimated_tokens: int | None = None
provider_id: str | None = None
model_name: str | None = None
created_at: str | None = None
@dataclass(slots=True)
class SessionStore:
"""SQLite-backed chat history and session metadata."""
@@ -71,6 +87,35 @@ class SessionStore:
)
"""
)
connection.execute(
"""
CREATE TABLE IF NOT EXISTS session_compactions (
id INTEGER PRIMARY KEY AUTOINCREMENT,
session_id TEXT NOT NULL,
start_message_id INTEGER,
end_message_id INTEGER NOT NULL,
summary TEXT NOT NULL,
message_count INTEGER NOT NULL,
estimated_tokens INTEGER,
provider_id TEXT,
model_name TEXT,
created_at TEXT NOT NULL
)
"""
)
connection.execute(
"""
CREATE INDEX IF NOT EXISTS idx_messages_session_id_id
ON messages (session_id, id)
"""
)
connection.execute(
"""
CREATE INDEX IF NOT EXISTS idx_session_compactions_session_id_id
ON session_compactions (session_id, id)
"""
)
connection.commit()
def ensure_session(
self,
@@ -221,6 +266,223 @@ class SessionStore:
)
connection.commit()
def load_active_history(
self,
*,
session_id: str = "main",
) -> list[dict[str, Any]]:
"""Load all uncompacted messages for one session."""
self.ensure_session(session_id)
compacted_until_id = self._get_compacted_until_message_id(session_id)
with self._lock:
with closing(self._connect()) as connection:
rows = connection.execute(
"""
SELECT payload_json
FROM messages
WHERE session_id = ?
AND (? IS NULL OR id > ?)
ORDER BY id ASC
""",
(session_id, compacted_until_id, compacted_until_id),
).fetchall()
messages: list[dict[str, Any]] = []
for row in rows:
payload = json.loads(row["payload_json"])
message = self._to_llm_message(payload)
if message is not None:
messages.append(message)
return messages
def list_compaction_candidates(
self,
*,
session_id: str = "main",
) -> list[dict[str, Any]]:
"""Return uncompacted stored messages including database ids."""
self.ensure_session(session_id)
compacted_until_id = self._get_compacted_until_message_id(session_id)
with self._lock:
with closing(self._connect()) as connection:
rows = connection.execute(
"""
SELECT id, payload_json
FROM messages
WHERE session_id = ?
AND (? IS NULL OR id > ?)
ORDER BY id ASC
""",
(session_id, compacted_until_id, compacted_until_id),
).fetchall()
payloads: list[dict[str, Any]] = []
for row in rows:
payload = json.loads(row["payload_json"])
payload["_message_id"] = int(row["id"])
payloads.append(payload)
return payloads
def get_latest_compaction(self, session_id: str) -> SessionCompaction | None:
"""Return the latest compaction summary for one session."""
with self._lock:
with closing(self._connect()) as connection:
row = connection.execute(
"""
SELECT
id,
session_id,
start_message_id,
end_message_id,
summary,
message_count,
estimated_tokens,
provider_id,
model_name,
created_at
FROM session_compactions
WHERE session_id = ?
ORDER BY id DESC
LIMIT 1
""",
(session_id,),
).fetchone()
if row is None:
return None
return SessionCompaction(
id=int(row["id"]),
session_id=str(row["session_id"]),
start_message_id=(
int(row["start_message_id"])
if row["start_message_id"] is not None
else None
),
end_message_id=int(row["end_message_id"]),
summary=str(row["summary"]),
message_count=int(row["message_count"]),
estimated_tokens=(
int(row["estimated_tokens"])
if row["estimated_tokens"] is not None
else None
),
provider_id=str(row["provider_id"]) if row["provider_id"] else None,
model_name=str(row["model_name"]) if row["model_name"] else None,
created_at=str(row["created_at"]),
)
def load_compaction_summary(self, session_id: str = "main") -> str | None:
"""Return the latest compaction summary text, if any."""
latest = self.get_latest_compaction(session_id)
if latest is None:
return None
return latest.summary
def record_compaction(
self,
*,
session_id: str,
start_message_id: int | None,
end_message_id: int,
summary: str,
message_count: int,
estimated_tokens: int | None = None,
provider_id: str | None = None,
model_name: str | None = None,
) -> SessionCompaction:
"""Persist one compaction snapshot and advance the active cursor."""
now = _utc_now()
with self._lock:
with closing(self._connect()) as connection:
cursor = connection.execute(
"""
INSERT INTO session_compactions (
session_id,
start_message_id,
end_message_id,
summary,
message_count,
estimated_tokens,
provider_id,
model_name,
created_at
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
""",
(
session_id,
start_message_id,
end_message_id,
summary,
message_count,
estimated_tokens,
provider_id,
model_name,
now,
),
)
connection.commit()
compaction_id = int(cursor.lastrowid)
state = self.get_session_state(session_id)
metadata = dict(state.metadata if state else {})
metadata.update(
{
"compacted_until_message_id": end_message_id,
"last_compaction_id": compaction_id,
"last_compaction_at": now,
"needs_compaction": False,
"context_compaction_count": int(
metadata.get("context_compaction_count") or 0
)
+ 1,
}
)
self.update_session_state(session_id, metadata=metadata)
latest = self.get_latest_compaction(session_id)
if latest is not None:
return latest
return SessionCompaction(
id=compaction_id,
session_id=session_id,
start_message_id=start_message_id,
end_message_id=end_message_id,
summary=summary,
message_count=message_count,
estimated_tokens=estimated_tokens,
provider_id=provider_id,
model_name=model_name,
created_at=now,
)
def update_context_metrics(
self,
session_id: str,
*,
resolved_context_window_tokens: int | None = None,
max_output_tokens: int | None = None,
estimated_prompt_tokens: int | None = None,
actual_prompt_tokens: int | None = None,
input_budget_tokens: int | None = None,
needs_compaction: bool | None = None,
) -> SessionState:
"""Persist latest context-control metrics."""
metadata: dict[str, Any] = {}
if resolved_context_window_tokens is not None:
metadata["resolved_context_window_tokens"] = resolved_context_window_tokens
if max_output_tokens is not None:
metadata["resolved_max_output_tokens"] = max_output_tokens
if estimated_prompt_tokens is not None:
metadata["last_estimated_prompt_tokens"] = estimated_prompt_tokens
if actual_prompt_tokens is not None:
metadata["last_actual_prompt_tokens"] = actual_prompt_tokens
if input_budget_tokens is not None:
metadata["input_budget_tokens"] = input_budget_tokens
if needs_compaction is not None:
metadata["needs_compaction"] = needs_compaction
if not metadata:
return self.get_session_state(session_id) or SessionState(session_id=session_id)
metadata["context_metrics_updated_at"] = _utc_now()
return self.update_session_state(session_id, metadata=metadata)
def load_history(
self,
limit: int = 24,
@@ -336,8 +598,61 @@ class SessionStore:
"database_path": str(self.path),
"sessions": sessions,
"messages": self.list_messages(session_id=session_id, limit=limit),
"compactions": self.list_compactions(session_id=session_id),
}
def list_compactions(
self,
*,
session_id: str | None = None,
) -> list[dict[str, Any]]:
"""Return stored compaction snapshots."""
query = """
SELECT
id,
session_id,
start_message_id,
end_message_id,
summary,
message_count,
estimated_tokens,
provider_id,
model_name,
created_at
FROM session_compactions
"""
params: list[Any] = []
if session_id:
query += " WHERE session_id = ?"
params.append(session_id)
query += " ORDER BY id ASC"
with self._lock:
with closing(self._connect()) as connection:
rows = connection.execute(query, params).fetchall()
return [
{
"id": int(row["id"]),
"session_id": str(row["session_id"]),
"start_message_id": (
int(row["start_message_id"])
if row["start_message_id"] is not None
else None
),
"end_message_id": int(row["end_message_id"]),
"summary": str(row["summary"]),
"message_count": int(row["message_count"]),
"estimated_tokens": (
int(row["estimated_tokens"])
if row["estimated_tokens"] is not None
else None
),
"provider_id": str(row["provider_id"]) if row["provider_id"] else None,
"model_name": str(row["model_name"]) if row["model_name"] else None,
"created_at": str(row["created_at"]),
}
for row in rows
]
@staticmethod
def _to_llm_message(row: dict[str, Any]) -> dict[str, Any] | None:
role = row.get("role")
@@ -351,3 +666,15 @@ class SessionStore:
message["tool_call_id"] = row.get("tool_call_id")
message["name"] = row.get("name")
return message
def _get_compacted_until_message_id(self, session_id: str) -> int | None:
state = self.get_session_state(session_id)
if state is None:
return None
value = state.metadata.get("compacted_until_message_id")
if value in (None, ""):
return None
try:
return int(value)
except (TypeError, ValueError):
return None
+182
View File
@@ -8,6 +8,7 @@ from unittest.mock import patch
from voidbot.agent import AgentRuntime
from voidbot.config import AppConfig, ProviderConfig
from voidbot.context import ContextBuilder
from voidbot.context_window import estimate_prompt_tokens
from voidbot.gateway.messages import InboundMessageContext
from voidbot.models import LLMResponse, ToolCall
from voidbot.runtime_env import RuntimeExecutionInfo
@@ -79,6 +80,70 @@ class FakeProviderManager:
return FakeProvider(profile.model or "(default)", self)
class CompactionAwareProvider:
def __init__(
self,
model_name: str,
manager: "CompactionProviderManager",
*,
overflow_once: bool = False,
) -> None:
self.model_name = model_name
self.manager = manager
self.overflow_once = overflow_once
self.overflow_emitted = False
def estimate_prompt_tokens(
self, messages: list[dict], tools: list[dict] | None = None
) -> tuple[int, str]:
return estimate_prompt_tokens(messages, tools), "test_estimator"
def chat(
self, messages: list[dict], tools: list[dict] | None = None
) -> LLMResponse:
first_system = str(messages[0]["content"]) if messages else ""
if first_system.startswith("You summarize older agent conversation history"):
self.manager.summary_calls += 1
return LLMResponse(
content=(
"## Decisions\n"
"- Earlier workspace inspection was completed.\n\n"
"## Pending user asks\n"
"- Continue with the latest request."
)
)
self.manager.last_messages = messages
self.manager.regular_calls += 1
if self.overflow_once and not self.overflow_emitted:
self.overflow_emitted = True
return LLMResponse(
content="maximum context length exceeded for this model",
finish_reason="error",
)
return LLMResponse(
content=f"Compaction-safe reply from {self.model_name}.",
usage={"prompt_tokens": 96, "completion_tokens": 12},
)
class CompactionProviderManager(FakeProviderManager):
def __init__(self, *, overflow_once: bool = False) -> None:
super().__init__()
self.last_messages: list[dict] = []
self.regular_calls = 0
self.summary_calls = 0
self.provider = CompactionAwareProvider(
"model-one",
self,
overflow_once=overflow_once,
)
def build(self, provider_id: str | None = None) -> CompactionAwareProvider:
_ = self.get_profile(provider_id)
return self.provider
class AgentRuntimeTests(unittest.TestCase):
def _make_runtime(self, workspace: Path) -> AgentRuntime:
config = AppConfig(
@@ -96,6 +161,36 @@ class AgentRuntimeTests(unittest.TestCase):
context_builder=ContextBuilder(config),
)
def _make_compaction_runtime(
self,
workspace: Path,
*,
overflow_once: bool = False,
context_window_tokens: int = 240,
) -> AgentRuntime:
config = AppConfig(
api_key="test-key",
workspace=workspace,
database_path=workspace / ".voidbot/voidbot.db",
default_provider="1",
max_iterations=4,
history_limit=8,
context_window_tokens=context_window_tokens,
max_output_tokens=32,
context_safety_margin_tokens=0,
context_compaction_max_rounds=2,
)
provider_manager = CompactionProviderManager(overflow_once=overflow_once)
provider_manager.profiles["1"].context_window_tokens = context_window_tokens
provider_manager.profiles["1"].max_output_tokens = 32
return AgentRuntime(
config=config,
providers=provider_manager,
session=SessionStore(config.storage_path),
tools=build_default_tool_registry(workspace),
context_builder=ContextBuilder(config),
)
def test_run_turn_executes_tool_loop(self) -> None:
with tempfile.TemporaryDirectory() as temp_dir:
workspace = Path(temp_dir)
@@ -313,6 +408,93 @@ class AgentRuntimeTests(unittest.TestCase):
self.assertIn("Switched to model 2", switch_result.reply)
self.assertIn("model-two", result.reply)
def test_run_turn_compacts_old_history_before_model_call(self) -> None:
with tempfile.TemporaryDirectory() as temp_dir:
workspace = Path(temp_dir)
runtime = self._make_compaction_runtime(
workspace,
context_window_tokens=120,
)
for index in range(3):
runtime.session.append(
{
"role": "user",
"content": f"user-{index} " + ("A" * 720),
},
session_id="main",
)
runtime.session.append(
{
"role": "assistant",
"content": f"assistant-{index} " + ("B" * 720),
},
session_id="main",
)
result = runtime.run_turn(
InboundMessageContext(
session_id="main",
raw_body="continue",
body_for_agent="continue",
)
)
state = runtime.session.get_session_state("main")
compactions = runtime.session.list_compactions(session_id="main")
provider_manager = runtime.providers
self.assertEqual(result.reply, "Compaction-safe reply from model-one.")
self.assertEqual(len(compactions), 1)
self.assertIsNotNone(state)
self.assertEqual(state.metadata["context_compaction_count"], 1)
self.assertGreater(provider_manager.summary_calls, 0)
self.assertEqual(
provider_manager.last_messages[1]["role"],
"system",
)
self.assertIn(
"Compacted Session Summary",
provider_manager.last_messages[1]["content"],
)
def test_context_overflow_error_triggers_compaction_and_retry(self) -> None:
with tempfile.TemporaryDirectory() as temp_dir:
workspace = Path(temp_dir)
runtime = self._make_compaction_runtime(
workspace,
overflow_once=True,
context_window_tokens=4000,
)
for index in range(3):
runtime.session.append(
{
"role": "user",
"content": f"user-{index} " + ("C" * 240),
},
session_id="main",
)
runtime.session.append(
{
"role": "assistant",
"content": f"assistant-{index} " + ("D" * 240),
},
session_id="main",
)
result = runtime.run_turn(
InboundMessageContext(
session_id="main",
raw_body="retry after overflow",
body_for_agent="retry after overflow",
)
)
compactions = runtime.session.list_compactions(session_id="main")
provider_manager = runtime.providers
self.assertEqual(result.reply, "Compaction-safe reply from model-one.")
self.assertEqual(len(compactions), 1)
self.assertGreaterEqual(provider_manager.regular_calls, 2)
self.assertEqual(provider_manager.summary_calls, 1)
if __name__ == "__main__":
unittest.main()
+74
View File
@@ -3,6 +3,7 @@ from __future__ import annotations
import io
import json
import tempfile
import threading
import unittest
from dataclasses import dataclass
from pathlib import Path
@@ -71,6 +72,79 @@ class GatewayTests(unittest.TestCase):
self.assertEqual(runtime.last_inbound.launch_cwd, "/tmp/demo-launch")
self.assertEqual(runtime.last_inbound.entrypoint_path, "/usr/local/bin/voidbot")
self.assertEqual(runtime.last_inbound.python_executable, "/usr/bin/python3.12")
self.assertIn("queue", application.health())
application.shutdown()
def test_gateway_application_serializes_same_session_requests(self) -> None:
@dataclass
class BlockingRuntime:
config: AppConfig
def __post_init__(self) -> None:
self.active = 0
self.max_active = 0
self.lock = threading.Lock()
self.first_started = threading.Event()
self.second_started = threading.Event()
self.release_first = threading.Event()
self.order: list[str] = []
def run_turn(self, inbound: InboundMessageContext) -> RunTurnResult:
with self.lock:
self.active += 1
self.max_active = max(self.max_active, self.active)
self.order.append(f"start:{inbound.message_id}")
if inbound.message_id == "msg-1":
self.first_started.set()
self.release_first.wait(timeout=2)
else:
self.second_started.set()
with self.lock:
self.active -= 1
self.order.append(f"end:{inbound.message_id}")
return RunTurnResult(
reply=f"echo:{inbound.body_for_agent}",
iterations=1,
provider_id="1",
provider_label="Model One",
model_name="model-one",
)
runtime = BlockingRuntime(config=AppConfig(api_key="test-key"))
application = GatewayApplication(runtime=runtime)
payload_one = {
"session_id": "main",
"message_id": "msg-1",
"body_for_agent": "hello",
}
payload_two = {
"session_id": "main",
"message_id": "msg-2",
"body_for_agent": "again",
}
results: list[dict] = []
thread_one = threading.Thread(
target=lambda: results.append(application.run_agent(payload_one))
)
thread_two = threading.Thread(
target=lambda: results.append(application.run_agent(payload_two))
)
thread_one.start()
self.assertTrue(runtime.first_started.wait(timeout=1))
thread_two.start()
self.assertFalse(runtime.second_started.wait(timeout=0.1))
runtime.release_first.set()
thread_one.join(timeout=2)
thread_two.join(timeout=2)
self.assertEqual(len(results), 2)
self.assertEqual(runtime.max_active, 1)
self.assertEqual(
runtime.order,
["start:msg-1", "end:msg-1", "start:msg-2", "end:msg-2"],
)
application.shutdown()
def test_gateway_mode_calls_gateway_client(self) -> None:
with patch("voidbot.gateway.cli.GatewayClient.run_agent") as run_agent:
+74
View File
@@ -0,0 +1,74 @@
from __future__ import annotations
import threading
import time
import unittest
from voidbot.gateway.run_queue import InMemoryRunQueue
class InMemoryRunQueueTests(unittest.TestCase):
def test_same_session_jobs_run_serially(self) -> None:
queue = InMemoryRunQueue(max_concurrent=2)
first_started = threading.Event()
second_started = threading.Event()
release_first = threading.Event()
order: list[str] = []
def first_job() -> str:
order.append("start-1")
first_started.set()
release_first.wait(timeout=1)
order.append("end-1")
return "one"
def second_job() -> str:
order.append("start-2")
second_started.set()
order.append("end-2")
return "two"
future_one = queue.enqueue("session-a", first_job)
self.assertTrue(first_started.wait(timeout=1))
future_two = queue.enqueue("session-a", second_job)
time.sleep(0.05)
self.assertFalse(second_started.is_set())
release_first.set()
self.assertEqual(future_one.result(timeout=1), "one")
self.assertEqual(future_two.result(timeout=1), "two")
self.assertEqual(order, ["start-1", "end-1", "start-2", "end-2"])
queue.shutdown(wait=False)
def test_global_concurrency_limit_applies_across_sessions(self) -> None:
queue = InMemoryRunQueue(max_concurrent=1)
first_started = threading.Event()
second_started = threading.Event()
release_first = threading.Event()
def first_job() -> str:
first_started.set()
release_first.wait(timeout=1)
return "one"
def second_job() -> str:
second_started.set()
return "two"
future_one = queue.enqueue("session-a", first_job)
self.assertTrue(first_started.wait(timeout=1))
future_two = queue.enqueue("session-b", second_job)
time.sleep(0.05)
self.assertFalse(second_started.is_set())
release_first.set()
self.assertEqual(future_one.result(timeout=1), "one")
self.assertEqual(future_two.result(timeout=1), "two")
snapshot = queue.snapshot()
self.assertEqual(snapshot["active_count"], 0)
self.assertEqual(snapshot["queued_count"], 0)
queue.shutdown(wait=False)
if __name__ == "__main__":
unittest.main()