Coverage for app / tools / clarify.py: 99%
194 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"""
2ask_user — let an agent put a question back to the person before answering.
4An agent that has misread an ambiguous prompt produces a confident, wrong,
5expensive answer. This tool gives it a way to stop and ask instead, without
6falling back to a free-text "what did you mean?" turn that the user then has
7to compose an answer to.
9The agent supplies structured questions; the frontend renders them as real
10controls — radio buttons (with the agent's recommended option marked),
11checkboxes, and typed input fields (text, number, date) — and returns the
12answers. One question and a multi-question form are the same mechanism — a
13form is just a longer ``questions`` list — so there is no separate code path
14for either.
16Every clarification is asked in one place: the graph's ``__clarify__`` node
17(``agents/graph.py``), whether the request's scope was checked up front or an
18agent called ``ask_user`` mid-task; ``source`` tells the two apart.
20──────────────────────────────────────────────────────────────────────────────
21How it suspends
22──────────────────────────────────────────────────────────────────────────────
24The tool never pauses itself. It raises :class:`ClarificationRequested`
25carrying the questions; the agent's step ends there, and the graph routes to
26``__clarify__``, which calls LangGraph's ``interrupt()``. The engine
27checkpoints the graph, emits a ``hitl_interrupt`` SSE frame carrying the
28questions, and ends the stream. Once the person answers, ``__clarify__`` folds
29the answers into the request and the agent's step starts again — with the
30tool calls it had made listed for it, so it does not repeat them.
32It used to call ``interrupt()`` itself, inside the agent's step, and the
33step's own error handling caught the pause as a failure: no mid-task question
34ever reached the person. A question set the person could not answer was
35refused back to the model, which then wrote the questions into its answer
36instead. Now what can be asked is asked (:func:`usable_questions`), and the
37questions never go in the answer.
39──────────────────────────────────────────────────────────────────────────────
40When an agent may ask, and what
41──────────────────────────────────────────────────────────────────────────────
43Once a turn, whoever asks: a turn whose scope was checked with the person, or
44that has asked mid-task already, asks nothing more; nor does a quality-check
45revision, whose gaps are the agent's to fix. Where an agent may not ask,
46``ask_user`` is not offered at all (:func:`may_ask`, read by the tool loop) —
47a refusal left the model writing "I've asked you…" to someone who was never
48asked. And it asks only what the person alone can answer: CHAINR Bot, three
49images short in a PDF of illusions, asked the person to choose image links
50for it — a form of links is refused, and a written-out "Other" option is
51dropped for the form's own box (the person picked it, and every answer came
52back the literal value "other").
53"""
55from __future__ import annotations
57import logging
58import re
59from collections.abc import Iterator
60from contextlib import contextmanager
61from contextvars import ContextVar
62from typing import Any, Literal
64from langchain_core.tools import StructuredTool
65from langgraph.errors import GraphBubbleUp
66from pydantic import BaseModel, Field
68from app.util import vocab
69from app.util.schema import openai_schema_from_model
71logger = logging.getLogger(__name__)
73#: Interrupt discriminator. Travels as ``interrupt_type`` on the SSE frame so a
74#: client can tell a clarification apart from an approval request.
75CLARIFICATION_INTERRUPT = "clarification_request"
77#: Who raised a clarification: an agent calling ``ask_user`` mid-task, or the
78#: pipeline's ``__clarify__`` node checking the request's scope up front.
79SOURCE_TOOL = "tool"
80SOURCE_SCOPE = "scope"
82QuestionKind = Literal["single", "multi", "text", "number", "date"]
84#: What each kind of question is, as a model is told it — the ``kind`` field,
85#: the ``ask_user`` description and the scope check all render from this.
86QUESTION_KINDS: dict[str, str] = {
87 "single": "pick exactly one option (radio buttons)",
88 "multi": "pick any number (checkboxes)",
89 "text": "a free-text field",
90 "number": "a numeric field",
91 "date": "a date field (answered as YYYY-MM-DD)",
92}
93vocab.check(QUESTION_KINDS, QuestionKind)
95#: Kinds answered by picking from ``options``.
96CHOICE_KINDS: tuple[str, ...] = vocab.members(QuestionKind, ("single", "multi"))
97#: Kinds answered by typing — the fields of an input form. They carry no
98#: options; the answer is the value entered.
99INPUT_KINDS: tuple[str, ...] = tuple(
100 kind for kind in vocab.values(QuestionKind) if kind not in CHOICE_KINDS
101)
102_CHOICE_KINDS_QUOTED = vocab.listing(CHOICE_KINDS, sep="/", quote="'")
103_SINGLE = vocab.member(QuestionKind, "single")
104_TEXT = vocab.member(QuestionKind, "text")
106# Caps: a clarification is meant to unblock a turn, not become a survey. An
107# agent that wants more than this has misunderstood the task, and a user faced
108# with it will abandon the conversation.
109MAX_QUESTIONS = 6
110MAX_OPTIONS = 10
111MIN_CHOICE_OPTIONS = 2
113#: The tool's name.
114ASK_USER = "ask_user"
116#: A choice that is a web link: something the agent found, for it to choose.
117_LINK = re.compile(r"https?://|\bwww\.", re.IGNORECASE)
118#: An option that is the form's own free-text box ('allow_other') written out
119#: again — "Other", "Other (specify)", "Something else: …" — which, chosen,
120#: answers with its value, never the person's words. "Other teams" is a choice.
121_WRITTEN_OTHER = re.compile(
122 r"^\s*(?:other|something else)\s*(?:$|[(\[:\-–—,.…])", re.IGNORECASE
123)
126class ClarifyOption(BaseModel):
127 """One selectable answer."""
129 value: str = Field(description="Value returned when this option is chosen.")
130 label: str = Field(description="Short text shown on the control.")
131 description: str | None = Field(
132 default=None,
133 description="Optional one-line hint shown beneath the label.",
134 )
135 recommended: bool = Field(
136 default=False,
137 description=(
138 "Mark the option you would choose if the user has no preference. "
139 f"At most one per '{_SINGLE}' question; only when one is genuinely "
140 "the better default."
141 ),
142 )
145class ClarifyQuestion(BaseModel):
146 """A single question to put to the user."""
148 id: str = Field(
149 description="Short unique identifier, e.g. 'environment'. Answers come "
150 "back keyed by this."
151 )
152 question: str = Field(description="The question, phrased for a person.")
153 kind: QuestionKind = Field(
154 default=_SINGLE,
155 description=(
156 vocab.guide(
157 QUESTION_KINDS,
158 QuestionKind,
159 indent="",
160 quote="'",
161 align=False,
162 end=".",
163 joiner=" ",
164 ) # fmt: skip
165 + f" Several {vocab.listing(INPUT_KINDS, sep='/')} questions together "
166 "make an input form."
167 ),
168 )
169 options: list[ClarifyOption] = Field(
170 default_factory=list,
171 description=(
172 f"Choices for {_CHOICE_KINDS_QUOTED}. "
173 "Omit entirely for "
174 f"{vocab.one_of(INPUT_KINDS, quote='', conjunction='and')}."
175 ),
176 )
177 placeholder: str | None = Field(
178 default=None,
179 description=(
180 "Example value shown in an empty "
181 f"{vocab.one_of(INPUT_KINDS, quote='')} field."
182 ),
183 )
184 multiline: bool = Field(
185 default=False,
186 description=f"For '{_TEXT}': expect a longer answer (a paragraph, not a phrase).",
187 )
188 allow_other: bool = Field(
189 default=True,
190 description=(
191 "Offer an 'Other' free-text box alongside the options, so the user "
192 "is never forced into a choice that does not fit. Ignored for "
193 f"{vocab.one_of(INPUT_KINDS, quote='', conjunction='and')}."
194 ),
195 )
196 required: bool = Field(
197 default=True,
198 description="Whether the user must answer before submitting.",
199 )
202class AskUserArgs(BaseModel):
203 """Arguments for ``ask_user``."""
205 questions: list[ClarifyQuestion] = Field(
206 description=(
207 f"The questions to ask — between 1 and {MAX_QUESTIONS}, each with "
208 f"{MIN_CHOICE_OPTIONS} to {MAX_OPTIONS} options when it offers "
209 "choices. Ask only what genuinely changes your answer."
210 )
211 )
212 title: str | None = Field(
213 default=None,
214 description="Optional heading shown above the questions.",
215 )
216 intro: str | None = Field(
217 default=None,
218 description=(
219 "Optional one-line explanation of why you are asking. Helps the "
220 "user answer well."
221 ),
222 )
225ASK_USER_SCHEMA: dict[str, Any] = openai_schema_from_model(
226 ASK_USER,
227 "Ask the user clarifying questions and wait for their answers before continuing",
228 AskUserArgs,
229)
232class ClarifyValidationError(ValueError):
233 """Raised when the model's proposed questions are not answerable."""
236def _question_problem(question: ClarifyQuestion, seen: set[str]) -> str | None:
237 """Why ``question`` cannot be put to a person, or None. ``seen`` holds the
238 ids of the questions before it."""
239 if not question.id.strip():
240 return "Every question needs a non-empty 'id'."
241 if question.id in seen:
242 return (
243 f"Duplicate question id {question.id!r} — ids must be unique so "
244 "answers can be matched back to their question."
245 )
246 if not question.question.strip():
247 return f"Question {question.id!r} has empty question text."
248 if question.kind in INPUT_KINDS:
249 if question.options:
250 return (
251 f"Question {question.id!r} is kind {question.kind!r} and must "
252 f"not carry options. Use {vocab.one_of(CHOICE_KINDS)} to offer "
253 "choices."
254 )
255 return None
256 if any(_LINK.search(f"{o.value} {o.label}") for o in question.options):
257 return (
258 f"Question {question.id!r} offers links as its choices. Finding "
259 "and choosing what the request needs — a file, an image, a page, "
260 "a source — is your work, not the person's: pick the best "
261 "yourself, or leave it out and say so."
262 )
263 if len(question.options) < MIN_CHOICE_OPTIONS:
264 return (
265 f"Question {question.id!r} is kind {question.kind!r} and needs at "
266 f"least {MIN_CHOICE_OPTIONS} options. Use kind '{_TEXT}' to ask an "
267 "open question."
268 )
269 if len(question.options) > MAX_OPTIONS:
270 return (
271 f"Question {question.id!r} has {len(question.options)} options; the "
272 f"maximum is {MAX_OPTIONS}."
273 )
274 values = [option.value for option in question.options]
275 if len(set(values)) != len(values):
276 return f"Question {question.id!r} has duplicate option values."
277 recommended = sum(1 for option in question.options if option.recommended)
278 if question.kind == _SINGLE and recommended > 1:
279 return (
280 f"Question {question.id!r} recommends {recommended} options; a "
281 f"'{_SINGLE}' question can recommend at most one."
282 )
283 return None
286def _validate(questions: list[ClarifyQuestion]) -> None:
287 """Reject question sets a user could not sensibly answer."""
288 if not questions:
289 raise ClarifyValidationError("'questions' must contain at least one question.")
290 if len(questions) > MAX_QUESTIONS:
291 raise ClarifyValidationError(
292 f"Too many questions ({len(questions)}); the maximum is "
293 f"{MAX_QUESTIONS}. Ask only what changes your answer."
294 )
295 seen: set[str] = set()
296 for question in questions:
297 problem = _question_problem(question, seen)
298 if problem:
299 raise ClarifyValidationError(problem)
300 seen.add(question.id)
303def _without_written_other(question: ClarifyQuestion) -> ClarifyQuestion:
304 """``question`` without options that are the form's own 'Other' box
305 written out ("Other (specify)"), and with that box on."""
306 if question.kind not in CHOICE_KINDS:
307 return question
308 kept = [
309 o
310 for o in question.options
311 if not (_WRITTEN_OTHER.match(o.label) or _WRITTEN_OTHER.match(o.value))
312 ]
313 if len(kept) == len(question.options):
314 return question
315 return question.model_copy(update={"options": kept, "allow_other": True})
318def _within_option_limit(question: ClarifyQuestion) -> ClarifyQuestion:
319 """``question`` with no more than :data:`MAX_OPTIONS` choices: the
320 recommended ones always, then the first of the rest, in the order the
321 model gave them. The person can still type anything else ('Other')."""
322 if question.kind not in CHOICE_KINDS or len(question.options) <= MAX_OPTIONS:
323 return question
324 room = max(0, MAX_OPTIONS - sum(o.recommended for o in question.options))
325 kept = []
326 for option in question.options:
327 if option.recommended or room > 0:
328 kept.append(option)
329 room -= 0 if option.recommended else 1
330 return question.model_copy(
331 update={"options": kept[:MAX_OPTIONS], "allow_other": True}
332 )
335def usable_questions(
336 questions: list[Any], *, limit: int = MAX_QUESTIONS
337) -> tuple[list[ClarifyQuestion], list[str]]:
338 """The model-proposed questions that can be put to a person, and why any
339 others were not.
341 Each question stands alone: one that cannot be read or answered is left
342 out, not the set (a scope check used to lose all its questions to one
343 bad one). A written-out 'Other' option goes, for the form's own box; too
344 many choices are cut to :data:`MAX_OPTIONS`, keeping the recommended
345 ones; past ``limit`` questions, the rest are left out.
346 """
347 if not questions:
348 return [], ["'questions' must contain at least one question."]
349 kept: list[ClarifyQuestion] = []
350 problems: list[str] = []
351 seen: set[str] = set()
352 for raw in questions:
353 try:
354 question = ClarifyQuestion.model_validate(raw)
355 except Exception as exc: # noqa: BLE001 — a malformed question is left out
356 problems.append(
357 f"A question could not be read ({type(exc).__name__}): each needs "
358 f"an 'id', a 'question', and a 'kind' of "
359 f"{vocab.one_of(QuestionKind, quote='')}."
360 )
361 continue
362 question = _within_option_limit(_without_written_other(question))
363 problem = _question_problem(question, seen)
364 if problem:
365 problems.append(problem)
366 continue
367 seen.add(question.id)
368 kept.append(question)
369 if len(kept) > limit:
370 problems.append(f"Only the first {limit} questions are asked.")
371 kept = kept[:limit]
372 return kept, problems
375def validate_questions(questions: list[Any]) -> list[ClarifyQuestion]:
376 """Parse and check model-proposed questions.
378 Raises ``ClarifyValidationError`` with a message the model can act on —
379 the same checks whether the questions came from ``ask_user`` or from the
380 ``__clarify__`` node's scope check, since both reach the same form.
381 """
382 try:
383 parsed = [ClarifyQuestion.model_validate(q) for q in questions]
384 except Exception as exc: # malformed question objects from the model
385 raise ClarifyValidationError(
386 f"Could not read 'questions': {exc}. Each question needs an 'id', "
387 f"a 'question', and a 'kind' of {vocab.one_of(QuestionKind, quote='')}."
388 ) from exc
389 _validate(parsed)
390 return parsed
393def clarification_payload(
394 questions: list[ClarifyQuestion],
395 *,
396 source: str,
397 title: str | None = None,
398 intro: str | None = None,
399 reason: str | None = None,
400) -> dict[str, Any]:
401 """The interrupt payload a client renders as the clarification form."""
402 payload: dict[str, Any] = {
403 "type": CLARIFICATION_INTERRUPT,
404 "source": source,
405 "title": title,
406 "intro": intro,
407 "questions": [q.model_dump() for q in questions],
408 }
409 if reason:
410 payload["reason"] = reason
411 return payload
414def answers_from_resume(response: Any) -> dict[str, Any]:
415 """The ``answers`` map out of a resume payload, tolerating any shape."""
416 answers = response.get("answers", {}) if isinstance(response, dict) else {}
417 return answers if isinstance(answers, dict) else {}
420def was_skipped(answers: dict[str, Any]) -> bool:
421 """True when the person dismissed the form without answering anything."""
422 return not any(
423 str(v).strip()
424 for raw in answers.values()
425 for v in (raw if isinstance(raw, list) else [raw])
426 if v is not None
427 )
430def format_answers(
431 questions: list[ClarifyQuestion],
432 answers: dict[str, Any],
433) -> str:
434 """Render the user's answers back to the model as readable text.
436 Answers arrive keyed by question id, each a list of values (a list even for
437 'single', so both kinds share one shape). An option's label is preferred
438 over its raw value — the model wrote the labels and reads them better —
439 while free-text and 'Other' entries pass through verbatim.
441 A question the user skipped is reported as skipped rather than omitted, so
442 the model knows it was declined rather than never asked.
443 """
444 lines: list[str] = []
445 for question in questions:
446 rendered = _answered(question, answers)
447 answer_text = ", ".join(rendered) if rendered else "(skipped)"
448 lines.append(f"{question.question}\n → {answer_text}")
449 return "The user answered:\n\n" + "\n".join(lines)
452def _answered(question: ClarifyQuestion, answers: dict[str, Any]) -> list[str]:
453 """What the person answered to ``question``: each chosen option's label
454 (or the value, when no option has it), free text verbatim; nothing when
455 they skipped it."""
456 raw = answers.get(question.id)
457 values = raw if isinstance(raw, list) else ([] if raw is None else [raw])
458 labels_by_value = {option.value: option.label for option in question.options}
459 return [
460 labels_by_value.get(str(value), str(value))
461 for value in values
462 if str(value).strip()
463 ]
466def answer_labels(clarifications: list[dict[str, Any]]) -> list[str]:
467 """Every answer given to the scope clarifications ``GraphState`` records
468 (``{"questions", "answers", "skipped"}`` each), in the order asked, as
469 :func:`format_answers` renders them. A skipped clarification or question
470 gives nothing, and an entry that no longer reads is passed over."""
471 out: list[str] = []
472 for entry in clarifications or []:
473 if not isinstance(entry, dict) or entry.get("skipped"):
474 continue
475 answers = entry.get("answers")
476 if not isinstance(answers, dict):
477 continue
478 for raw in entry.get("questions") or []:
479 try:
480 question = ClarifyQuestion.model_validate(raw)
481 except ValueError:
482 continue
483 out.extend(a.strip() for a in _answered(question, answers))
484 return list(dict.fromkeys(a for a in out if a))
487class ClarificationRequested(GraphBubbleUp):
488 """An agent's ``ask_user`` call: the questions it wants put to the person.
490 Not a pause itself. A ``GraphBubbleUp``, so ``ToolNode`` passes it up
491 rather than turning it into an error result; the agent's step catches it,
492 ends, and leaves the questions for the graph's ``__clarify__`` node to ask
493 (``agents/graph.py``). ``messages`` is the step's trace up to the call.
494 """
496 def __init__(self, payload: dict[str, Any]) -> None:
497 super().__init__("clarification requested")
498 self.payload = payload
499 self.messages: list[Any] = []
502#: Whether the code running may ask the person. Off unless a graph step turns
503#: it on (``asking_allowed``): the step's agent may ask only once a turn and
504#: never on a revision (``AgentGraphBuilder._may_ask``), and nothing outside a
505#: step can pause for an answer at all.
506_ASKING: ContextVar[bool] = ContextVar("chainr_asking_allowed", default=False)
508#: What the model is told if it calls ``ask_user`` where it may not ask — a
509#: backstop: there the tool is not offered (``may_ask``).
510NOT_NOW = (
511 "[ask_user] The person cannot be asked now. Do not tell them you asked. "
512 "Finish the task with what you have, and say what you assumed or could "
513 "not do."
514)
517@contextmanager
518def asking_allowed(allowed: bool) -> Iterator[None]:
519 """Run a step with ``ask_user`` allowed to ask, or not."""
520 token = _ASKING.set(allowed)
521 try:
522 yield
523 finally:
524 _ASKING.reset(token)
527def may_ask() -> bool:
528 """Whether the code running may ask the person — when not, the tool loop
529 leaves ``ask_user`` out of the tools it offers."""
530 return _ASKING.get()
533def ask_user_tool_factory(config: dict[str, Any]) -> StructuredTool:
534 """Build the ``ask_user`` tool.
536 ``config`` is accepted for registry uniformity; the tool takes no options.
537 """
539 def ask_user(
540 questions: list[dict[str, Any]],
541 title: str | None = None,
542 intro: str | None = None,
543 ) -> str:
544 if not may_ask():
545 return NOT_NOW
546 parsed, problems = usable_questions(questions)
547 if not parsed:
548 return (
549 f"[ask_user] No question could be asked: {' '.join(problems)} "
550 "Fix them and call ask_user again — never write the questions "
551 "in your answer."
552 )
553 logger.info(
554 "[ask_user] asking %d question(s), %d left out",
555 len(parsed),
556 len(problems),
557 )
558 raise ClarificationRequested(
559 clarification_payload(parsed, source=SOURCE_TOOL, title=title, intro=intro)
560 )
562 return StructuredTool.from_function(
563 func=ask_user,
564 name=ASK_USER,
565 description=(
566 "Ask the person one or more questions, as a form they answer, when "
567 "you cannot go on without them: the request is genuinely ambiguous "
568 "and the readings would lead to materially different answers, or a "
569 "step needs a detail only they know. Not for anything you can "
570 "reasonably decide, assume or infer yourself — decide it, and say "
571 "so. Never write questions for the person in your answer: ask them "
572 "here, all in one form, once a turn.\n\n"
573 "Ask only what the person alone can decide or knows: what they "
574 "want, which of several meanings they intend, a detail of their "
575 "own (an account, a date, a budget). Never ask them to find, "
576 "choose or fix what they asked you for — a file, an image, a "
577 "link, a source, a fact, a search that failed: do it yourself, or "
578 "leave it out and say so. Links are never choices. Never ask what "
579 "the request or the conversation already says (it gave the time, "
580 "the budget, lunch: they are settled), and never ask them to "
581 "choose among things you found — venues, rooms, products, "
582 "options: choose one, and say why.\n\n"
583 f"Prefer offering options ({vocab.one_of(CHOICE_KINDS)}, "
584 f"{MIN_CHOICE_OPTIONS} to {MAX_OPTIONS} each) over open text: they "
585 "are faster to answer and easier to answer well. Mark the option you "
586 "would pick as 'recommended' when one is a sensible default. Leave "
587 "'allow_other' on so the person is never forced into a choice that "
588 "does not fit. For values only they know (a budget, a deadline, a "
589 f"name) use {vocab.one_of(INPUT_KINDS)} fields — several of them "
590 "together make a short form.\n\n"
591 "Your step ends when you call this. Once they answer, it starts "
592 "again with their answers, and the tool calls you made are listed "
593 "for you to reuse — so ask as soon as you know you need to."
594 ),
595 args_schema=AskUserArgs,
596 )