Coverage for app / memory / turn_outcome.py: 98%
49 statements
« prev ^ index » next coverage.py v7.13.4, created at 2026-10-31 11:23 +0000
« prev ^ index » next coverage.py v7.13.4, created at 2026-10-31 11:23 +0000
1"""Whether a turn's answer is kept in its episode, from what its tools did.
3An episode keeps the gist of the answer so that a later conversation can
4pick up where this one left off. Two kinds of answer must not be kept that
5way:
7* **What the tools could not do.** CHAINR Bot answered "whats in the news"
8 with "the searches found nothing" while the search engine was out of
9 credit (25 October 2026). The quality check passed it, since an honest
10 limitation is no gap, and memory kept it. The next time the question was
11 asked, recall brought that answer back beside it, and the agent repeated
12 it without searching.
13* **What is true only today.** Headlines, prices, results: an answer built
14 on a news search, or a search held to a recent window, is stale by the
15 next conversation, and recalled it reads as current. So is one resting on
16 the agent's temporal knowledge (``app/knowledge/categories.py``): the
17 dated passages retrieval handed on, or a knowledge search of it.
19Either way the episode keeps only what was asked (``text.episode(request,
20None)``), so a later conversation still knows the subject came up.
21"""
23from __future__ import annotations
25from collections.abc import Iterable
26from enum import StrEnum
27from typing import Any
30class AnswerKept(StrEnum):
31 """What becomes of a turn's answer in its episode, and why."""
33 #: Kept: nothing its tools did makes it unsafe to recall.
34 kept = "kept"
35 #: A web tool ran and the web gave the answer nothing: the search
36 #: failed, found nothing, or ran out of calls.
37 web_failed = "web_failed"
38 #: Every tool the turn called failed.
39 tools_failed = "tools_failed"
40 #: The answer rests on a news search or one held to a recent window.
41 time_sensitive = "time_sensitive"
42 #: The answer rests on dated knowledge: the agent's temporal knowledge.
43 dated_knowledge = "dated_knowledge"
46def _tool_calls(messages: Iterable[Any]) -> list[tuple[str, dict[str, Any]]]:
47 """Every tool call the turn's messages made: its name and arguments."""
48 calls: list[tuple[str, dict[str, Any]]] = []
49 for msg in messages:
50 for call in getattr(msg, "tool_calls", None) or []:
51 if isinstance(call, dict):
52 name, args = call.get("name"), call.get("args")
53 else:
54 name, args = getattr(call, "name", None), getattr(call, "args", None)
55 calls.append((str(name or ""), args if isinstance(args, dict) else {}))
56 return calls
59def _time_sensitive(name: str, args: dict[str, Any]) -> bool:
60 """Whether a ``web_search`` call asked for news, or for results from a
61 month or less. A year is no recent window: a build-or-buy answer that
62 searched the past year's comparisons is as good next month, and was
63 not remembered."""
64 from app.tools.web.models import Freshness, SearchType
66 if name != "web_search":
67 return False
68 if str(args.get("search_type") or "").strip().lower() == SearchType.NEWS.value:
69 return True
70 return Freshness.parse(args.get("freshness")) in (
71 Freshness.DAY,
72 Freshness.WEEK,
73 Freshness.MONTH,
74 )
77def _searched_dated_knowledge(results: Iterable[Any]) -> bool:
78 """Whether a knowledge search's results came from temporal knowledge:
79 they open with its line (``categories.DATED_RESULTS_LINE``)."""
80 from app.knowledge.categories import DATED_RESULTS_LINE
82 return any(
83 isinstance(getattr(m, "content", None), str) and DATED_RESULTS_LINE in m.content
84 for m in results
85 )
88def of_turn(messages: Iterable[Any], *, dated: bool = False) -> AnswerKept:
89 """What becomes of the answer, from this turn's messages: the tool calls
90 its nodes made and the results that came back. ``dated``: retrieval
91 handed on dated passages (temporal knowledge). A turn that called no
92 tool and was handed no dated passages keeps its answer."""
93 from app.agents import source_ledger
95 messages = list(messages or [])
96 results = [m for m in messages if getattr(m, "tool_call_id", None) is not None]
97 if not results:
98 return AnswerKept.dated_knowledge if dated else AnswerKept.kept
99 names = [str(getattr(m, "name", "") or "") for m in results]
100 if any(
101 source_ledger.tool_kind(n) == "web" for n in names
102 ) and not source_ledger.web_answered(results):
103 return AnswerKept.web_failed
105 def failed(msg: Any) -> bool:
106 content = getattr(msg, "content", "")
107 return getattr(msg, "status", "success") == "error" or (
108 isinstance(content, str) and source_ledger.tool_failed(content)
109 )
111 if all(failed(m) for m in results):
112 return AnswerKept.tools_failed
113 if any(_time_sensitive(name, args) for name, args in _tool_calls(messages)):
114 return AnswerKept.time_sensitive
115 if dated or _searched_dated_knowledge(results):
116 return AnswerKept.dated_knowledge
117 return AnswerKept.kept
120__all__ = ["AnswerKept", "of_turn"]