Self-evolving Context Database for AI Agents. Unify Agent Memory, Knowledge RAG and Skills.
Python agent-contextagent-memoryagent-pluginsagentic-ragcontext-databasedsh-pluginknowledge-basememorymemory-managementself-evolvingvector-database
fix(session): respect configured thinking in patch merge and repair budget-exhausted extraction (#6104)
akushonkamenc973ad1c4f0f
diff --git a/openviking/models/vlm/backends/litellm_vlm.py b/openviking/models/vlm/backends/litellm_vlm.pyindex 917046e6e..60330f86e 100644--- a/openviking/models/vlm/backends/litellm_vlm.py+++ b/openviking/models/vlm/backends/litellm_vlm.py@@ -473,8 +473,11 @@ class LiteLLMVLMProvider(VLMBase):elapsed = time.perf_counter() - t0self._update_token_usage_from_response(response, duration_seconds=elapsed)tracer.info(f"response={response}")- if tools:- return self._build_vlm_response(response, has_tools=True)+ if tools is not None:+ result = self._build_vlm_response(response, has_tools=True)+ if not tools:+ result.content = self._clean_response(result.content or "")+ return resultreturn self._clean_response(self._extract_content_from_response(response))return _call()@@ -505,8 +508,11 @@ class LiteLLMVLMProvider(VLMBase):elapsed = time.perf_counter() - t0self._update_token_usage_from_response(response, duration_seconds=elapsed)tracer.info(f"response={response}")- if tools:- return self._build_vlm_response(response, has_tools=True)+ if tools is not None:+ result = self._build_vlm_response(response, has_tools=True)+ if not tools:+ result.content = self._clean_response(result.content or "")+ return resultreturn self._clean_response(self._extract_content_from_response(response))return await _call()@@ -529,8 +535,11 @@ class LiteLLMVLMProvider(VLMBase):response = completion(**kwargs)elapsed = time.perf_counter() - t0self._update_token_usage_from_response(response, duration_seconds=elapsed)- if tools:- return self._build_vlm_response(response, has_tools=True)+ if tools is not None:+ result = self._build_vlm_response(response, has_tools=True)+ if not tools:+ result.content = self._clean_response(result.content or "")+ return resultreturn self._clean_response(self._extract_content_from_response(response))return _call()@@ -553,8 +562,11 @@ class LiteLLMVLMProvider(VLMBase):response = await acompletion(**kwargs)elapsed = time.perf_counter() - t0self._update_token_usage_from_response(response, duration_seconds=elapsed)- if tools:- return self._build_vlm_response(response, has_tools=True)+ if tools is not None:+ result = self._build_vlm_response(response, has_tools=True)+ if not tools:+ result.content = self._clean_response(result.content or "")+ return resultreturn self._clean_response(self._extract_content_from_response(response))return await _call()diff --git a/openviking/models/vlm/backends/openai_vlm.py b/openviking/models/vlm/backends/openai_vlm.pyindex b6686a850..a9d92ccd3 100644--- a/openviking/models/vlm/backends/openai_vlm.py+++ b/openviking/models/vlm/backends/openai_vlm.py@@ -386,7 +386,10 @@ class OpenAIVLM(VLMBase):elapsed = time.perf_counter() - t0if tools is not None:self._update_token_usage_from_response(response, duration_seconds=elapsed)- return self._build_vlm_response(response, has_tools=True)+ result = self._build_vlm_response(response, has_tools=True)+ if not tools:+ result.content = self._clean_response(result.content or "")+ return resultreturn await self._extract_completion_content_async(response, elapsed)# 用 tracer.info 打印请求(人类可读格式)diff --git a/openviking/models/vlm/backends/volcengine_vlm.py b/openviking/models/vlm/backends/volcengine_vlm.pyindex 38460a363..d94c71aaa 100644--- a/openviking/models/vlm/backends/volcengine_vlm.py+++ b/openviking/models/vlm/backends/volcengine_vlm.py@@ -231,9 +231,12 @@ class VolcEngineVLM(OpenAIVLM):raiseelapsed = time.perf_counter() - t0self._update_token_usage_from_response(response, duration_seconds=elapsed)- result = self._build_vlm_response(response, has_tools=bool(tools))- if tools:+ if tools is not None:+ result = self._build_vlm_response(response, has_tools=True)+ if not tools:+ result.content = self._clean_response(result.content or "")return result+ result = self._build_vlm_response(response, has_tools=False)return self._clean_response(str(result))@model_error_boundary@@ -292,9 +295,12 @@ class VolcEngineVLM(OpenAIVLM):raiseelapsed = time.perf_counter() - t0self._update_token_usage_from_response(response, duration_seconds=elapsed)- result = self._build_vlm_response(response, has_tools=bool(tools))- if tools:+ if tools is not None:+ result = self._build_vlm_response(response, has_tools=True)+ if not tools:+ result.content = self._clean_response(result.content or "")return result+ result = self._build_vlm_response(response, has_tools=False)content = self._clean_response(str(result))if content:tracer.info(f"message.content={content}")@@ -462,9 +468,12 @@ class VolcEngineVLM(OpenAIVLM):raiseelapsed = time.perf_counter() - t0self._update_token_usage_from_response(response, duration_seconds=elapsed)- result = self._build_vlm_response(response, has_tools=bool(tools))- if tools:+ if tools is not None:+ result = self._build_vlm_response(response, has_tools=True)+ if not tools:+ result.content = self._clean_response(result.content or "")return result+ result = self._build_vlm_response(response, has_tools=False)return self._clean_response(str(result))@model_error_boundary@@ -513,7 +522,10 @@ class VolcEngineVLM(OpenAIVLM):raiseelapsed = time.perf_counter() - t0self._update_token_usage_from_response(response, duration_seconds=elapsed)- result = self._build_vlm_response(response, has_tools=bool(tools))- if tools:+ if tools is not None:+ result = self._build_vlm_response(response, has_tools=True)+ if not tools:+ result.content = self._clean_response(result.content or "")return result+ result = self._build_vlm_response(response, has_tools=False)return self._clean_response(str(result))diff --git a/openviking/models/vlm/base.py b/openviking/models/vlm/base.pyindex d8755526d..35a1c973f 100644--- a/openviking/models/vlm/base.py+++ b/openviking/models/vlm/base.py@@ -204,7 +204,8 @@ class VLMBase(ABC):f"VLM provider {self.provider!r} does not support audio/video inputs")- def _clean_response(self, content: str) -> str:+ @staticmethod+ def _clean_response(content: str) -> str:"""Strip reasoning tags (e.g. ``<think>...</think>``) from model output."""return _THINK_TAG_RE.sub("", content).strip()diff --git a/openviking/session/memory/extract_loop.py b/openviking/session/memory/extract_loop.pyindex a00f97c40..b6451a3d6 100644--- a/openviking/session/memory/extract_loop.py+++ b/openviking/session/memory/extract_loop.py@@ -134,7 +134,7 @@ class ExtractLoop:ctx: Optional[RequestContext] = None,context_provider: Optional[Any] = None, # ExtractContextProviderisolation_handler: MemoryIsolationHandler = None,- thinking: bool = False,+ thinking: Optional[bool] = None,max_output_tokens: Optional[int] = None,):"""@@ -147,7 +147,9 @@ class ExtractLoop:max_iterations: Maximum number of ReAct iterations (default: 5)ctx: Request contextcontext_provider: ExtractContextProvider - 必须提供(由 provider 加载 schema)- thinking: Whether to explicitly enable model thinking for this extraction loop.+ thinking: Per-call thinking override for this extraction loop. True/False+ force the mode for every call; None (default) defers to the VLM+ backend's configured thinking policy.max_output_tokens: Per-call output cap for the extraction LLM. When None, theconfigured vlm.max_tokens is used, falling back to a value large enough forfull memory rewrites so providers do not apply a small server-side default@@ -159,7 +161,7 @@ class ExtractLoop:self.max_iterations = max_iterationsself.ctx = ctxself.context_provider = context_provider- self.thinking = bool(thinking)+ self.thinking = thinkingself.max_output_tokens = max_output_tokens# Resolved in run() via _resolve_effective_max_output_tokens(); default to# the extraction floor so a direct _call_llm() before run() stays safe.@@ -402,10 +404,21 @@ class ExtractLoop:parse_error = self._last_parse_error# Add format error message if parse failed (max 1 retry). This may raise# max_iterations, granting one more attempt after this failure.+ if failure_kind == "budget_exhausted":+ # Truncation is not an ordinary format mistake: a same-cap format+ # retry would only hit the budget again, and replaying the+ # truncated output just grows the prompt. Fail fast with the+ # dedicated error recorded by _call_llm().+ raise RuntimeError(+ f"Memory extraction aborted: {parse_error or failure_kind}"+ )+if self._format_retry_count == 0:self._format_retry_count += 1max_iterations += 1- retry_reason = "refusal_text" if failure_kind == "refusal_text" else "format_retry"+ retry_reason = (+ "refusal_text" if failure_kind == "refusal_text" else "format_retry"+ )tracer.info(f"Extended max_iterations to {max_iterations} for {retry_reason}")self._add_format_error_message(messages)@@ -479,6 +492,25 @@ class ExtractLoop:configured if configured is not None else _DEFAULT_EXTRACTION_MAX_OUTPUT_TOKENS)+ def _budget_exhausted_error(self, response: Any, content: str) -> str:+ """Build the dedicated, actionable error for a truncated response.++ Truncation is detected only from the backend's explicit+ ``finish_reason == "length"``; token counters are never used to infer it.+ """+ usage = getattr(response, "usage", None)+ completion_tokens = usage.get("completion_tokens") if isinstance(usage, dict) else None+ details = (+ f"finish_reason='length', output cap={self._effective_max_output_tokens} tokens"+ )+ if completion_tokens:+ details += f", completion_tokens={completion_tokens}"+ return (+ "Response was cut off by the output-token budget "+ f"({details}), response_preview={_preview_text(content)!r}. "+ "Raise vlm.max_tokens in ov.conf or reduce the memory context before retrying."+ )+def _retryable_resolution_issues(self, operations: ResolvedOperations) -> List[Dict[str, Any]]:issues: List[Dict[str, Any]] = []for operation in operations.upsert_operations:@@ -1173,8 +1205,11 @@ class ExtractLoop:Returns:Tuple of (tool_calls, operations) - one will be None, the other set"""- # Call LLM with tools - use tools from strategy- tools = None+ # Call LLM with tools - use tools from strategy. Pass tools=[] (not None)+ # when tools are disabled so backends following the OpenAI backend's+ # `tools is not None` convention still return a VLMResponse carrying+ # finish_reason and usage instead of a bare string.+ tools: Optional[List[Dict[str, Any]]] = []tool_choice = Noneif not self._disable_tools_for_iteration and self._tool_schemas:tools = self._tool_schemas@@ -1219,6 +1254,21 @@ class ExtractLoop:f"[KVCache] prompt_tokens={prompt_tokens}, cached_tokens={cached_tokens}")+ # Reject explicit truncation before handling tool calls or parsing:+ # neither a partial tool call nor a parseable program is safe to use.+ # run() treats budget_exhausted as terminal, without a format retry.+ if getattr(response, "finish_reason", None) == "length":+ content = getattr(response, "content", None) or ""+ self._last_llm_failure_kind = "budget_exhausted"+ self._last_llm_failure_content = content+ self._last_parse_error = self._budget_exhausted_error(response, content)+ tracer.set("memory.extraction.parse_error", self._last_parse_error)+ logger.debug(+ "Response truncated by output-token budget "+ f"failure_kind=budget_exhausted error={self._last_parse_error}"+ )+ return (None, None)+# Case 0: Handle string response (when tools are not provided) or Noneif response is None:content = ""@@ -1236,6 +1286,9 @@ class ExtractLoop:# Case 2: VLMResponse without tool calls - get content from responsecontent = response.content or ""+ # No tool calls (Case 0 & 2): strip reasoning tags in the text before parsing.+ content = VLMBase._clean_response(content)+# Parse operations from contentif content:try:diff --git a/openviking/session/train/components/policy_optimizer.py b/openviking/session/train/components/policy_optimizer.pyindex ec2f3397b..a36d8688d 100644--- a/openviking/session/train/components/policy_optimizer.py+++ b/openviking/session/train/components/policy_optimizer.py@@ -51,6 +51,15 @@ class PatchMergePolicyOptimizer:memory_type: str = "experiences"memory_registry: MemoryTypeRegistry | None = Nonevlm_resolver: VLMResolver | None = None+ thinking: bool | None = None+ """Per-call thinking override for the merge extract loop.++ None (default) defers to the VLM backend's configured ``thinking`` policy.+ True/False force the mode for every merge call, overriding the backend+ configuration. The optimizer never forces thinking on by itself: forcing+ ``thinking=True`` for experiences/trajectories merges made reasoning consume+ the whole completion budget and truncate the emitted program mid-string.+ """@tracer("train.policy_optimizer.patch_merge.plan",@@ -183,7 +192,7 @@ class PatchMergePolicyOptimizer:context_provider=provider,isolation_handler=isolation_handler,max_iterations=1,- thinking=self.memory_type in {"trajectories", "experiences"},+ thinking=self.thinking,)operations, _ = await orchestrator.run()return operationsdiff --git a/tests/session/memory/test_extract_loop_budget_recovery.py b/tests/session/memory/test_extract_loop_budget_recovery.pynew file mode 100644index 000000000..7665de7d9--- /dev/null+++ b/tests/session/memory/test_extract_loop_budget_recovery.py@@ -0,0 +1,370 @@+# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.+# SPDX-License-Identifier: AGPL-3.0+"""Tests for ExtractLoop truncation handling and thinking passthrough.++Regression tests for https://github.com/volcengine/issues/6096, reworked after+review of PR #6104: truncation is detected only from an explicit+``finish_reason == "length"``, checked before parsing; ``tools=[]`` is passed so+real backends still return a ``VLMResponse`` with finish_reason and usage on the+patch-merge path (where ``PatchMergeContextProvider.get_tools() == []``); and+budget exhaustion is terminal — no cap doubling, no replay of the truncated+output, and no completion_tokens-based truncation inference.+"""++from types import SimpleNamespace+from unittest.mock import AsyncMock, MagicMock, Mock, patch++import pytest++from openviking.models.vlm.base import ToolCall, VLMResponse+from openviking.session.memory.dataclass import MemoryTypeSchema+from openviking.session.memory.extract_loop import ExtractLoop+from openviking.session.memory.page_id_map import PageIdMap++_DEFAULT_CAP = 32768++_TRUNCATED_PROGRAM = (+ "sdk.upsert_preference(\n"+ ' topic="booking",\n'+ ' content="""The agent should deduplicate requests because\n'+)+++class FakeContextProvider:+ read_file_contents = {}++ def get_memory_schemas(self, ctx):+ return [+ MemoryTypeSchema(+ memory_type="preferences",+ description="Preferences",+ directory="viking://user/{user_space}/memories/preferences",+ filename_template="{topic}.md",+ fields=[],+ )+ ]++ def get_tools(self):+ # The real patch-merge path returns [] — this is what forced _call_llm+ # down the tools-less branch under review.+ return []++ def get_extract_context(self):+ return SimpleNamespace(page_id_map=PageIdMap())++ def get_output_language(self):+ return "en"++ def instruction(self):+ return "Extract memory operations."++ async def prefetch(self):+ return []+++def _length_response(+ completion_tokens: int = _DEFAULT_CAP,+ finish_reason: str = "length",+ content: str = _TRUNCATED_PROGRAM,+) -> VLMResponse:+ return VLMResponse(+ content=content,+ finish_reason=finish_reason,+ usage={"prompt_tokens": 100, "completion_tokens": completion_tokens},+ )+++class ScriptedVLM:+ """Fake VLM that records per-call kwargs and replays scripted responses."""++ model = "test-model"++ def __init__(self, responses):+ self.responses = iter(responses)+ self.calls = []++ async def get_completion_async(self, **kwargs):+ self.calls.append(kwargs)+ return next(self.responses)+++def _user_contents(messages):+ return [message.get("content", "") for message in messages if message.get("role") == "user"]+++def _assistant_contents(messages):+ return [+ message.get("content", "") for message in messages if message.get("role") == "assistant"+ ]+++def _make_loop(vlm, **kwargs):+ isolation_handler = Mock()+ isolation_handler.get_read_scope.return_value = None+ isolation_handler.fill_identity_fields.side_effect = lambda item, **kwargs: item+ return ExtractLoop(+ vlm=vlm,+ viking_fs=MagicMock(),+ context_provider=FakeContextProvider(),+ isolation_handler=isolation_handler,+ max_iterations=1,+ **kwargs,+ )+++async def _run_loop(loop):+ config = SimpleNamespace(+ memory=SimpleNamespace(link_enabled=False, extraction_output_format="python")+ )+ with (+ patch(+ "openviking.session.memory.extract_loop.get_openviking_config",+ return_value=config,+ ),+ patch(+ "openviking_cli.utils.config.get_openviking_config",+ return_value=config,+ ),+ ):+ loop._check_unread_existing_files = _async_return({})+ loop._validate_patch_operations = _async_return([])+ loop.finalize_operations = _async_return(None)+ # Await inside the patch context: run() is a coroutine, so returning it+ # would let the patches expire before the code under test executes.+ return await loop.run()+++def _async_return(value):+ async def _call(*args, **kwargs):+ return value++ return _call+++class TestThinkingPassthrough:+ @pytest.mark.asyncio+ @pytest.mark.parametrize("thinking", [None, True, False])+ async def test_thinking_kwarg_is_forwarded_verbatim(self, thinking):+ vlm = ScriptedVLM(["sdk.commit()"])+ loop = _make_loop(vlm, thinking=thinking)+ await _run_loop(loop)++ assert len(vlm.calls) == 1+ assert vlm.calls[0]["thinking"] is thinking+++class TestToolsDisabledStillUsesVLMResponse:+ @pytest.mark.asyncio+ async def test_tools_is_empty_list_not_none(self):+ vlm = ScriptedVLM(["sdk.commit()"])+ loop = _make_loop(vlm)+ await _run_loop(loop)++ assert len(vlm.calls) == 1+ assert vlm.calls[0]["tools"] == []++ @pytest.mark.asyncio+ async def test_empty_tools_response_from_real_volcengine_backend(self):+ """On the patch-merge path (tools=[]) the real volcengine backend must+ still return a VLMResponse carrying finish_reason/usage, with the+ inline thinking stripped from the content."""+ volcengine_vlm = pytest.importorskip(+ "openviking.models.vlm.backends.volcengine_vlm"+ ).VolcEngineVLM+ raw = SimpleNamespace(+ choices=[+ SimpleNamespace(+ message=SimpleNamespace(+ content="<think>reasoning</think>sdk.commit()", tool_calls=None+ ),+ finish_reason="stop",+ )+ ],+ usage=SimpleNamespace(+ prompt_tokens=10,+ completion_tokens=5,+ total_tokens=15,+ prompt_tokens_details=None,+ completion_tokens_details=None,+ ),+ )++ async def create(**_kwargs):+ return raw++ vlm = volcengine_vlm({"provider": "volcengine", "model": "test-model"})+ vlm.get_async_client = lambda: SimpleNamespace(+ chat=SimpleNamespace(completions=SimpleNamespace(create=create))+ )+ loop = _make_loop(vlm)++ operations, _tools = await _run_loop(loop)++ assert operations is not None+ # Backend-level check: with tools=[] the backend still returns a+ # VLMResponse (finish_reason/usage preserved) whose content had the+ # inline thinking stripped by _clean_response.+ response = await vlm.get_completion_async(+ messages=[{"role": "user", "content": "hi"}], tools=[]+ )+ assert isinstance(response, VLMResponse)+ assert response.finish_reason == "stop"+ assert response.usage["completion_tokens"] == 5+ assert response.content == "sdk.commit()"+++class TestTruncationDetection:+ @pytest.mark.asyncio+ async def test_length_finish_reason_is_terminal_even_when_program_parses(self):+ """A truncated program that still parses must NOT be accepted as+ operations — trailing writes/deletes would be silently lost."""+ vlm = ScriptedVLM(+ [_length_response(content="sdk.commit() # actually truncated upstream")]+ )+ loop = _make_loop(vlm)++ with pytest.raises(RuntimeError, match="output-token budget"):+ await _run_loop(loop)++ # Fail fast: exactly one call, no same-cap format retry.+ assert len(vlm.calls) == 1+ assert vlm.calls[0]["max_tokens"] == _DEFAULT_CAP++ @pytest.mark.asyncio+ async def test_length_finish_reason_error_names_cap_usage_and_preview(self):+ vlm = ScriptedVLM([_length_response(completion_tokens=32768)])+ loop = _make_loop(vlm)++ with pytest.raises(RuntimeError) as exc_info:+ await _run_loop(loop)++ message = str(exc_info.value)+ assert "finish_reason='length'" in message+ assert f"output cap={_DEFAULT_CAP}" in message+ assert "completion_tokens=32768" in message+ assert "vlm.max_tokens" in message++ @pytest.mark.asyncio+ async def test_length_through_real_volcengine_backend_is_budget_exhausted(self):+ """The reviewer's main repro: with the real volcengine backend and+ tools=[], finish_reason='length' used to be classified as parse_error+ because the backend returned a bare str."""+ volcengine_vlm = pytest.importorskip(+ "openviking.models.vlm.backends.volcengine_vlm"+ ).VolcEngineVLM+ raw = SimpleNamespace(+ choices=[+ SimpleNamespace(+ message=SimpleNamespace(+ content=_TRUNCATED_PROGRAM, tool_calls=None+ ),+ finish_reason="length",+ )+ ],+ usage=SimpleNamespace(+ prompt_tokens=20214,+ completion_tokens=32768,+ total_tokens=52982,+ prompt_tokens_details=None,+ completion_tokens_details=None,+ ),+ )++ async def create(**_kwargs):+ return raw++ vlm = volcengine_vlm({"provider": "volcengine", "model": "test-model"})+ vlm.get_async_client = lambda: SimpleNamespace(+ chat=SimpleNamespace(completions=SimpleNamespace(create=create))+ )+ loop = _make_loop(vlm)++ with pytest.raises(RuntimeError, match="finish_reason='length'"):+ await _run_loop(loop)+++class TestNoTokenCounterInference:+ @pytest.mark.asyncio+ async def test_stop_at_cap_is_not_truncation(self):+ """finish_reason='stop' that lands exactly on the cap is a complete+ response, not budget exhaustion: an ordinary format error gets the+ regular single retry with the cap unchanged and no assistant replay."""+ vlm = ScriptedVLM(+ [_length_response(finish_reason="stop"), "sdk.commit()"]+ )+ loop = _make_loop(vlm)++ operations, _tools = await _run_loop(loop)++ assert operations is not None+ assert len(vlm.calls) == 2+ # No cap doubling: the retry reused the same output budget.+ assert vlm.calls[1]["max_tokens"] == _DEFAULT_CAP+ # No replay of the failed output as an assistant message.+ assert _assistant_contents(vlm.calls[1]["messages"]) == []++ @pytest.mark.asyncio+ async def test_ordinary_format_error_retry_keeps_cap_and_no_assistant_program(self):+ vlm = ScriptedVLM(["this is not a python program", "sdk.commit()"])+ loop = _make_loop(vlm)++ await _run_loop(loop)++ assert len(vlm.calls) == 2+ assert vlm.calls[1]["max_tokens"] == _DEFAULT_CAP+ assert _assistant_contents(vlm.calls[1]["messages"]) == []+++class TestExtractionContentBoundary:+ @pytest.mark.asyncio+ @pytest.mark.parametrize("with_tools", [False, True])+ @pytest.mark.parametrize("structured", [False, True])+ async def test_extraction_cleans_local_text_without_mutating_response(+ self, with_tools, structured+ ):+ raw_content = "<think>internal reasoning</think>\n sdk.commit() "+ usage = {"prompt_tokens": 10, "completion_tokens": 5, "total_tokens": 15}+ response = (+ VLMResponse(content=raw_content, finish_reason="stop", usage=usage.copy())+ if structured+ else raw_content+ )+ vlm = ScriptedVLM([response])+ loop = _make_loop(vlm)+ loop.context_provider.get_tools = lambda: ["read"] if with_tools else []++ operations, _ = await _run_loop(loop)++ assert operations is not None+ assert len(vlm.calls) == 1+ assert bool(vlm.calls[0]["tools"]) is with_tools+ if structured:+ assert response.content == raw_content+ assert response.finish_reason == "stop"+ assert response.usage == usage++ @pytest.mark.asyncio+ @pytest.mark.parametrize("finish_reason", ["tool_calls", "length"])+ async def test_tool_call_respects_finish_reason(self, finish_reason):+ response = VLMResponse(+ content="<think>planning</think>I will read the file.",+ tool_calls=[ToolCall(id="read-1", name="read", arguments={"uri": "viking://user/test"})],+ finish_reason=finish_reason,+ )+ vlm = ScriptedVLM([response, VLMResponse(content="<think>done</think>sdk.commit()")])+ loop = _make_loop(vlm)+ loop.context_provider.get_tools = lambda: ["read"]+ execute = AsyncMock(return_value={"content": "test"})+ loop.context_provider.execute_tool = execute++ if finish_reason == "length":+ with pytest.raises(RuntimeError, match="output-token budget"):+ await _run_loop(loop)+ execute.assert_not_awaited()+ assert len(vlm.calls) == 1+ else:+ operations, _ = await _run_loop(loop)+ assert operations is not None+ execute.assert_awaited_once()+ assert len(vlm.calls) == 2+ assert response.content == "<think>planning</think>I will read the file."diff --git a/tests/session/train/test_train_components.py b/tests/session/train/test_train_components.pyindex 0fdc1d7d3..3cc0d5ac8 100644--- a/tests/session/train/test_train_components.py+++ b/tests/session/train/test_train_components.py@@ -751,6 +751,85 @@ async def test_patch_merge_policy_optimizer_runs_patch_merge_extract_loop(monkeyassert "+merged content" in captured["prefetch_messages"][-1]["content"]+async def test_patch_merge_policy_optimizer_thinking_defaults_to_config_passthrough(+ monkeypatch,+):+ """The optimizer must not force per-call thinking for experiences/trajectories.++ Regression test for issue #6096: an operator-configured ``thinking=False`` VLM+ still received ``thinking=True`` on every patch-merge call.+ """+ from openviking.session.memory.dataclass import ResolvedOperations++ captured = {}++ class FakeExtractLoop:+ def __init__(self, **kwargs):+ captured.update(kwargs)++ async def run(self):+ return ResolvedOperations(upsert_operations=[], delete_file_contents=[], errors=[]), []++ monkeypatch.setattr(+ "openviking.session.train.components.policy_optimizer.ExtractLoop",+ FakeExtractLoop,+ )++ policy_set = _experience_set()+ gradient = _patch_gradient(+ uri=policy_set.policies[0].uri,+ before="stale content",+ after="merged content",+ )+ await PatchMergePolicyOptimizer(viking_fs=FakeVikingFS({}), vlm=object()).plan(+ [gradient],+ policy_set,+ PatchMergePolicyOptimizerContext(request_context=fake_request_context()),+ )++ assert captured["thinking"] is None++[email protected]("thinking", [True, False])+async def test_patch_merge_policy_optimizer_explicit_thinking_is_forwarded(monkeypatch, thinking):+ from openviking.session.memory.dataclass import ResolvedOperations++ captured = {}++ class FakeExtractLoop:+ def __init__(self, **kwargs):+ captured.update(kwargs)++ async def run(self):+ return ResolvedOperations(upsert_operations=[], delete_file_contents=[], errors=[]), []++ monkeypatch.setattr(+ "openviking.session.train.components.policy_optimizer.ExtractLoop",+ FakeExtractLoop,+ )++ policy_set = _experience_set()+ gradient = _patch_gradient(+ uri=policy_set.policies[0].uri,+ before="stale content",+ after="merged content",+ )+ optimizer = PatchMergePolicyOptimizer(+ viking_fs=FakeVikingFS({}),+ vlm=object(),+ thinking=thinking,+ )+ await optimizer.plan(+ [gradient],+ policy_set,+ PatchMergePolicyOptimizerContext(request_context=fake_request_context()),+ )++ assert captured["thinking"] is thinking++@pytest.mark.asyncioasync def test_patch_merge_policy_optimizer_merges_all_patch_gradients_once(monkeypatch):from openviking.session.memory.dataclass import (diff --git a/tests/unit/test_vikingbot_vlm_adapter_retry.py b/tests/unit/test_vikingbot_vlm_adapter_retry.pyindex 9232c84d4..dab2461ae 100644--- a/tests/unit/test_vikingbot_vlm_adapter_retry.py+++ b/tests/unit/test_vikingbot_vlm_adapter_retry.py@@ -16,6 +16,7 @@ from volcenginesdkarkruntime._exceptions import (from volcenginesdkarkruntime._streaming import AsyncStreamfrom openviking.models.model_error import ModelError, ModelErrorKind, model_error_kind+from openviking.models.vlm.backends.litellm_vlm import LiteLLMVLMProviderfrom openviking.models.vlm.backends.openai_vlm import OpenAIVLMfrom openviking.models.vlm.backends.volcengine_vlm import (VOLCENGINE_CLIENT_REQUEST_ID,@@ -157,12 +158,17 @@ async def test_chat_accepts_string_response_from_openai_backend_with_tools(monke@pytest.mark.asyncio-async def test_chat_without_tools_preserves_usage_from_openai_backend(monkeypatch):[email protected]("vlm_type", [OpenAIVLM, VolcEngineVLM, LiteLLMVLMProvider])[email protected]("finish_reason", ["stop", "length"])+async def test_chat_without_tools_preserves_clean_content_and_metadata(+ monkeypatch, vlm_type, finish_reason+):+ raw_content = "<think>internal reasoning</think>\nplain response"raw_response = SimpleNamespace(choices=[SimpleNamespace(- message=SimpleNamespace(content="plain response", tool_calls=None),- finish_reason="stop",+ message=SimpleNamespace(content=raw_content, tool_calls=None),+ finish_reason=finish_reason,)],usage=SimpleNamespace(@@ -181,15 +187,19 @@ async def test_chat_without_tools_preserves_usage_from_openai_backend(monkeypatcclient = SimpleNamespace(chat=SimpleNamespace(completions=SimpleNamespace(create=create)),)- vlm = OpenAIVLM({"provider": "openai", "model": "gpt-5.6-terra"})- monkeypatch.setattr(vlm, "get_async_client", lambda: client)+ vlm = vlm_type({"model": "gpt-5.6-terra", "api_key": "test-key"})+ if vlm_type is LiteLLMVLMProvider:+ monkeypatch.setattr("openviking.models.vlm.backends.litellm_vlm.acompletion", create)+ else:+ monkeypatch.setattr(vlm, "get_async_client", lambda: client)adapter = VLMProviderAdapter(vlm, "gpt-5.6-terra", langfuse_client=_DisabledLangfuse())response = await adapter.chat(messages=[{"role": "user", "content": "hello"}])assert response.content == "plain response"assert response.tool_calls == []- assert response.finish_reason == "stop"+ assert response.finish_reason == finish_reason+ assert raw_response.choices[0].message.content == raw_contentassert response.usage == {"prompt_tokens": 13,"completion_tokens": 5,