mirror of
https://github.com/HKUDS/DeepTutor.git
synced 2026-12-02 04:20:04 +08:00
When a tools snapshot goes away (a session stored before native requests dropped the text manifest, or the turn after a schema-rejection fallback), the generic retraction said the section is now empty, which reads as "no tools" while the request carries native schemas. The tools snapshot now gets its own retraction text, in the Python loop and the TypeScript engine. Refs #2973
231 lines
8.9 KiB
Python
231 lines
8.9 KiB
Python
"""A provider that rejects native tool schemas still gets a tool list.
|
|
|
|
With native tool calling the text ``[Runtime context: tools]`` manifest is not
|
|
sent: the schemas describe every tool. Some providers reject ``tools`` with a
|
|
400 (#708); the loop then retries without schemas and recovers tool calls from
|
|
DSML text. That retry must carry the text manifest again, or the model sees no
|
|
tools at all. The manifest rides as an ordinary append-only snapshot, so it is
|
|
persisted with the turn and replayed — not re-appended — on the next turn.
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
from pathlib import Path
|
|
from types import SimpleNamespace
|
|
from typing import Any
|
|
|
|
import pytest
|
|
|
|
from deeptutor.agents.chat.agentic_pipeline import AgenticChatPipeline
|
|
from deeptutor.core.context import TurnRuntimeContext, UnifiedContext
|
|
from deeptutor.services.session.model_history import model_turn, replay_history
|
|
from tests.agents.chat.test_agent_loop import _async_llm_stream, _llm_chunk, _Registry, _run
|
|
|
|
_MANIFEST = "- `web_search` - Search the web"
|
|
_HEADER = "[Runtime context: tools]"
|
|
_NATIVE_RETRACTION = (
|
|
"Tools are now provided as native function schemas; this list no longer applies."
|
|
)
|
|
|
|
|
|
@pytest.fixture(autouse=True)
|
|
def _isolated_runtime(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None:
|
|
from deeptutor.capabilities.setup.binding import mark_intro_shown
|
|
from deeptutor.services.path_service import PathService
|
|
|
|
monkeypatch.setenv("DEEPTUTOR_HOME", str(tmp_path))
|
|
paths = PathService(workspace_root=tmp_path / "data")
|
|
monkeypatch.setattr(PathService, "_instance", paths)
|
|
paths.ensure_all_directories()
|
|
mark_intro_shown()
|
|
monkeypatch.setattr(
|
|
"deeptutor.agents.loop.pipeline.get_llm_config",
|
|
lambda: SimpleNamespace(
|
|
binding="openai",
|
|
model="gpt-test",
|
|
api_key="k",
|
|
base_url="u",
|
|
api_version=None,
|
|
extra_headers={},
|
|
reasoning_effort=None,
|
|
),
|
|
)
|
|
|
|
|
|
class _Client:
|
|
"""Reject ``tools`` while ``reject`` is set; answer in plain text otherwise."""
|
|
|
|
def __init__(self, *, reject: bool) -> None:
|
|
self.reject = reject
|
|
self.calls: list[dict[str, Any]] = []
|
|
parent = self
|
|
|
|
class _Completions:
|
|
async def create(self, **kwargs):
|
|
parent.calls.append({**kwargs, "messages": list(kwargs["messages"])})
|
|
if parent.reject and kwargs.get("tools"):
|
|
raise ValueError("unsupported parameter: tools")
|
|
return _async_llm_stream([_llm_chunk(content="Answer.")])
|
|
|
|
self.chat = SimpleNamespace(completions=_Completions())
|
|
|
|
|
|
def _pipeline(monkeypatch: pytest.MonkeyPatch, client: _Client) -> AgenticChatPipeline:
|
|
pipeline = AgenticChatPipeline(language="en")
|
|
pipeline.registry = _Registry()
|
|
monkeypatch.setattr(pipeline, "_compose_enabled_tools", lambda _context: ["web_search"])
|
|
monkeypatch.setattr(pipeline, "_build_openai_client", lambda: client)
|
|
return pipeline
|
|
|
|
|
|
def _manifests(messages: list[dict[str, Any]]) -> list[str]:
|
|
return [
|
|
str(message.get("content"))
|
|
for message in messages
|
|
if str(message.get("content") or "").startswith(_HEADER)
|
|
]
|
|
|
|
|
|
def _context(turn: int, rows: list[dict[str, Any]]) -> UnifiedContext:
|
|
return UnifiedContext(
|
|
session_id="fallback-session",
|
|
user_message=f"Question {turn}",
|
|
runtime=TurnRuntimeContext(
|
|
model_history=replay_history(rows) if rows else None,
|
|
previous_model_turn=model_turn(rows[-1]) if rows else None,
|
|
),
|
|
)
|
|
|
|
|
|
async def _turn(
|
|
monkeypatch: pytest.MonkeyPatch, rows: list[dict[str, Any]], *, reject: bool
|
|
) -> tuple[_Client, UnifiedContext]:
|
|
client = _Client(reject=reject)
|
|
context = _context(len(rows) // 2 + 1, rows)
|
|
await _run(_pipeline(monkeypatch, client), context)
|
|
rows.extend(
|
|
[
|
|
{"role": "user", "content": context.user_message},
|
|
{
|
|
"role": "assistant",
|
|
"content": "Answer.",
|
|
"metadata": {"model_turn": context.runtime.model_turn},
|
|
},
|
|
]
|
|
)
|
|
return client, context
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_schema_rejection_retry_carries_the_text_tool_manifest(
|
|
monkeypatch: pytest.MonkeyPatch,
|
|
) -> None:
|
|
client, context = await _turn(monkeypatch, [], reject=True)
|
|
|
|
first, retry = client.calls
|
|
# Native request: schemas, no text manifest.
|
|
assert first["tools"]
|
|
assert _manifests(first["messages"]) == []
|
|
# Retry: no schemas, so the text manifest is back, as the snapshot just
|
|
# before the learner's message (the message stays last).
|
|
assert "tools" not in retry
|
|
assert _manifests(retry["messages"]) == [f"{_HEADER}\n{_MANIFEST}"]
|
|
assert retry["messages"][-2]["content"] == f"{_HEADER}\n{_MANIFEST}"
|
|
assert retry["messages"][-1]["content"].startswith("Question 1")
|
|
# Only the inserted snapshot differs from the rejected request.
|
|
assert retry["messages"][:-2] == first["messages"][:-1]
|
|
assert retry["messages"][-1] == first["messages"][-1]
|
|
# The snapshot is part of the durable turn, tagged like any other.
|
|
record = context.runtime.model_turn
|
|
assert record["tool_schemas_rejected"] is True
|
|
assert {"role": "user", "content": f"{_HEADER}\n{_MANIFEST}", "_context_snapshot": "tools"} in (
|
|
record["messages"]
|
|
)
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_next_rejected_turn_replays_the_manifest_without_another_copy(
|
|
monkeypatch: pytest.MonkeyPatch,
|
|
) -> None:
|
|
rows: list[dict[str, Any]] = []
|
|
first_turn, _ = await _turn(monkeypatch, rows, reject=True)
|
|
second_turn, _ = await _turn(monkeypatch, rows, reject=True)
|
|
|
|
previous_request = first_turn.calls[-1]["messages"]
|
|
for request in second_turn.calls:
|
|
# One manifest, the replayed one; no "now empty" retraction either.
|
|
assert _manifests(request["messages"]) == [f"{_HEADER}\n{_MANIFEST}"]
|
|
assert all(
|
|
"This section is now empty" not in str(message.get("content"))
|
|
for message in request["messages"]
|
|
)
|
|
# The previous turn's request is an exact prefix of this one.
|
|
assert request["messages"][: len(previous_request)] == previous_request
|
|
assert second_turn.calls[0]["tools"]
|
|
assert "tools" not in second_turn.calls[1]
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_accepted_schemas_retire_the_fallback_manifest(
|
|
monkeypatch: pytest.MonkeyPatch,
|
|
) -> None:
|
|
rows: list[dict[str, Any]] = []
|
|
await _turn(monkeypatch, rows, reject=True)
|
|
# The provider accepts schemas again: the replayed manifest stays (no new
|
|
# copy) for this turn, which no longer records a rejection...
|
|
accepted, context = await _turn(monkeypatch, rows, reject=False)
|
|
assert len(accepted.calls) == 1
|
|
assert _manifests(accepted.calls[0]["messages"]) == [f"{_HEADER}\n{_MANIFEST}"]
|
|
assert "tool_schemas_rejected" not in context.runtime.model_turn
|
|
# ...so the next turn retires it, saying the schemas replace it rather
|
|
# than that the model has no tools.
|
|
later, _ = await _turn(monkeypatch, rows, reject=False)
|
|
assert later.calls[0]["tools"]
|
|
tail = later.calls[0]["messages"][-2]["content"]
|
|
assert tail == f"{_HEADER}\n{_NATIVE_RETRACTION}"
|
|
assert "This section is now empty" not in tail
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_session_from_before_native_requests_retracts_its_tool_list(
|
|
monkeypatch: pytest.MonkeyPatch,
|
|
) -> None:
|
|
# A session stored before this change always carried the text manifest as
|
|
# a ``tools`` snapshot, even on native requests.
|
|
rows: list[dict[str, Any]] = [
|
|
{"role": "user", "content": "Question 0"},
|
|
{
|
|
"role": "assistant",
|
|
"content": "Answer.",
|
|
"metadata": {
|
|
"model_turn": {
|
|
"version": 1,
|
|
"route": {"provider": "openai", "model": "gpt-test"},
|
|
"messages": [
|
|
{
|
|
"role": "user",
|
|
"content": f"{_HEADER}\n{_MANIFEST}",
|
|
"_context_snapshot": "tools",
|
|
},
|
|
{"role": "user", "content": "Question 0"},
|
|
{"role": "assistant", "content": "Answer."},
|
|
],
|
|
}
|
|
},
|
|
},
|
|
]
|
|
client, _ = await _turn(monkeypatch, rows, reject=False)
|
|
|
|
(request,) = client.calls
|
|
assert request["tools"]
|
|
messages = request["messages"]
|
|
# The old list is replayed as it was sent, then retracted in favour of the
|
|
# native schemas, just before the learner's new message.
|
|
assert _manifests(messages) == [
|
|
f"{_HEADER}\n{_MANIFEST}",
|
|
f"{_HEADER}\n{_NATIVE_RETRACTION}",
|
|
]
|
|
assert messages[-2]["content"] == f"{_HEADER}\n{_NATIVE_RETRACTION}"
|
|
assert messages[-1]["content"].startswith("Question 2")
|
|
assert all("This section is now empty" not in str(m.get("content")) for m in messages)
|