File size: 3,448 Bytes
23d418f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
"""Step 9b (owner, 2026-11-24): follow-up questions in the chat.

A, B and C answer ONE self-contained question (they are frozen as the held-out test
measured them). A follow-up ("and if he is 70?") means nothing on its own, so before
the system runs, one small call rewrites it into a standalone question from the last
few turns; the system then answers that question exactly as tested. This is the
standard fix for multi-turn RAG ("history-aware retriever", query rewriting): rewrite
only to resolve references and ellipsis, return a clear question unchanged, never add
facts, never answer. The first question of a conversation makes no call.
"""

from pydantic import BaseModel, ConfigDict, Field

from coveragecheck import config
from coveragecheck.llm import LLM, Usage

REWRITE_PROMPT = """\
You rewrite the last question of a conversation between an insurance broker and an \
assistant (about Ontario auto insurance documents) so that it can be understood \
without the conversation.

Rules:
1. If the question is already clear on its own, return it unchanged.
2. Otherwise resolve only what depends on the conversation: pronouns ("he", "it", \
"that form"), omitted subjects ("and if he's 70?"), references to earlier answers \
("the second option"). Carry over the facts of the case the broker gave earlier \
(ages, forms, dates, vehicles) only when the question relies on them.
3. Never add facts, assumptions or form numbers that are not in the conversation, \
and never answer the question.
4. Keep the broker's wording and language as far as possible. Return one question.
"""


class HistoryTurn(BaseModel):
    """An earlier question (as it was understood) and the answer given."""

    model_config = ConfigDict(extra="forbid", frozen=True)
    question: str = Field(min_length=1, max_length=config.WEB_MAX_QUESTION_CHARS)
    answer: str = Field(max_length=config.WEB_HISTORY_MAX_ANSWER_CHARS)


class Standalone(BaseModel):
    """The rewrite's reply: the follow-up as one self-contained question."""

    model_config = ConfigDict(extra="forbid")
    question: str = Field(min_length=3, max_length=config.WEB_MAX_QUESTION_CHARS)


def clip(text: str, limit: int) -> str:
    """At most `limit` characters, cut at a word and marked, so a long earlier answer
    gives its gist without filling the prompt."""
    if len(text) <= limit:
        return text
    return text[:limit].rsplit(" ", 1)[0] + " [...]"


def rewrite_prompt(history: list[HistoryTurn], question: str) -> str:
    """The last WEB_HISTORY_TURNS turns (answers clipped), then the follow-up."""
    turns = history[-config.WEB_HISTORY_TURNS :]
    lines = []
    for turn in turns:
        lines.append(f"Broker: {turn.question}")
        lines.append(f"Assistant: {clip(turn.answer, config.WEB_HISTORY_ANSWER_CHARS)}")
    conversation = "\n".join(lines)
    return f"Conversation:\n{conversation}\n\nLast question: {question}"


def standalone(llm: LLM, history: list[HistoryTurn], question: str) -> tuple[str, Usage]:
    """The question as it should be searched and answered, and what the rewrite cost
    (nothing without history). An invalid reply is re-asked by llm.generate; a failure
    raises LLMError, like any LLM call of the app."""
    if not history:
        return question, Usage()
    prompt = rewrite_prompt(history, question)
    reply, usage = llm.generate(prompt, Standalone, system=REWRITE_PROMPT)
    return reply.question.strip(), usage