Spaces:
Sleeping
Sleeping
File size: 8,112 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 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 | """The answer step shared by Systems A, B and C: one prompt, one schema (SPEC Step 6:
"Same answer prompt and schema as A"), so a difference between systems comes from what
they retrieve, not from how the question is asked.
answer, usage = answer_question(llm, question, day, passages)
Plain Python (no LangGraph): System C's graph calls it from its answer node.
Owner decisions (5b):
- The policy date goes into the prompt (the date questions say "the date shown"; the
date exists only as the `day` argument). Filtering versions by it is B's job.
- Each passage is labelled with its source_id, document title and in-force dates, so
every system sees the same facts about versions.
- Checks that trigger a reask: an answer that does not abstain must cite something;
every citation must name a source_id that was shown. An abstention MAY cite
(supporting context, e.g. why the documents can't answer).
"""
import hashlib
from collections.abc import Callable, Iterable
from dataclasses import dataclass
from datetime import date
from coveragecheck.agent.schemas import Answer, AnswerFailed, Response, Work
from coveragecheck.llm import LLM, LLMError, Usage
SYSTEM_PROMPT = """\
You help insurance brokers in Ontario answer underwriting questions about auto \
insurance. You answer ONLY from the passages in the user's message. They come from \
public FSRA policy forms and endorsements and from Ontario laws.
Rules:
1. Use only the passages. Do not add outside knowledge, even if you are sure of it.
2. Support every claim with a citation: a quote copied word for word from a passage \
(at least 30 characters) and that passage's source_id exactly as shown after \
"source_id:". Several passages can share a source_id.
3. Passages can come from different versions of the same document. Use the version in \
force on the policy date. If you cannot tell which version applies, answer from the one \
you judge applicable, say what is uncertain, and lower your confidence.
4. Set abstain to true only when the passages support no answer to the question: then \
say briefly what cannot be determined, and list in missing_info what a broker would \
need to find out. Never set abstain to false while saying you cannot answer, and never \
set abstain to true while giving an answer.
5. If the passages answer only part of the question, answer that part with citations \
(abstain is false), say what is missing, and list it in missing_info.
6. confidence is your estimate, from 0 to 1, that your answer is correct. When you \
abstain, it is your estimate that the best answer you could give from the passages \
would be correct, so it is low when they lack the answer. It is never your confidence \
that abstaining was right.
7. Write for a broker: the direct answer first, then the conditions and exceptions \
that matter. This is information from public documents, not coverage advice: do not \
say what a particular client is covered for beyond what the passages state.
"""
USER_TEMPLATE = """\
Policy date: {day}
Passages:
{passages}
Question: {question}"""
@dataclass(frozen=True)
class Passage:
"""One retrieved text as the model sees it. source_id is what a citation must name
(A: the doc_id; B/C: a section id); label is the rest of its header line."""
source_id: str
label: str
text: str
def version_label(title: str | None, effective_from: str | None, effective_to: str | None):
"""A document's title and in-force dates, as one header fragment. Missing dates
are said to be missing (22 of 36 documents state none), never guessed."""
start = effective_from or "no start date stated"
end = effective_to or "no end date stated"
return f"{(title or '').strip() or 'untitled'} | in force: {start} to {end}"
def format_passages(passages: Iterable[Passage]) -> str:
"""Numbered blocks: a header line (number, source_id, label), then the text."""
return "\n\n".join(
f"[{n}] source_id: {p.source_id} | {p.label}\n{p.text.strip()}"
for n, p in enumerate(passages, start=1)
)
def user_prompt(question: str, day: date, passages: list[Passage]) -> str:
"""The user message: policy date, passages, then the question (last, so the model
reads the evidence before the task)."""
return USER_TEMPLATE.format(
day=day.isoformat(), passages=format_passages(passages), question=question
)
def answer_rules(allowed_sources: Iterable[str]) -> Callable[[Answer], None]:
"""The checks llm.generate runs on a parsed Answer; a ValueError triggers the
reask, with the message as the reason, so each message says how to fix it."""
allowed = frozenset(allowed_sources)
def check(answer: Answer) -> None:
if not answer.abstain and not answer.citations:
raise ValueError(
"abstain is false but there are no citations: support the answer with "
"quotes from the passages, or set abstain to true if they don't answer it"
)
unknown = sorted({c.source_id for c in answer.citations} - allowed)
if unknown:
raise ValueError(
f"citations name source_ids that were not shown: {unknown}; use only "
f"these: {sorted(allowed)}"
)
return check
def work_from(
usage: Usage, chunk_ids: list[str], source_ids: list[str], trace: dict | None = None
) -> Work:
"""A question's Work from the passages shown (exactly those, in prompt order: the
Work contract) and the LLM usage summed over its calls. Shared so A, B and C copy
Usage into Work the same way (5b audit)."""
return Work(
retrieved_chunk_ids=list(chunk_ids),
retrieved_source_ids=list(source_ids),
tokens_in=usage.tokens_in,
tokens_out=usage.tokens_out,
llm_calls=usage.calls,
reasks=usage.reasks,
api_retries=usage.api_retries,
cache_hits=usage.cache_hits,
replayed_ms=usage.replayed_ms,
trace=dict(trace or {}) | {"llm_ms": usage.llm_ms},
)
def prompt_hash() -> str:
"""A short fingerprint of the prompt text, recorded in run settings, so a number in
the report can be traced to the prompt that produced it."""
text = SYSTEM_PROMPT + USER_TEMPLATE
return hashlib.sha256(text.encode("utf-8")).hexdigest()[:12]
RETRY_TEMPLATE = """\
{feedback}
Answer the question again. Copy every quote word for word from the passages above, \
or leave out a claim you cannot quote."""
def answer_question(
llm: LLM, question: str, day: date, passages: list[Passage], feedback: str | None = None
) -> tuple[Answer, Usage]:
"""Ask the model to answer from these passages; returns the validated Answer and
its usage. Raises llm.LLMError (with usage and kind) when it can't. feedback (System
C's verify retry, 7c): why citations of an earlier answer failed, appended after
the question so the model answers again; None = the ordinary prompt (A, B and C's
first answer: unchanged, so prompt_hash and the cache keys stay valid)."""
check = answer_rules(p.source_id for p in passages)
prompt = user_prompt(question, day, passages)
if feedback:
prompt += RETRY_TEMPLATE.format(feedback=feedback)
return llm.generate(prompt, Answer, system=SYSTEM_PROMPT, check=check)
def answer_or_fail(
llm: LLM,
question: str,
day: date,
shown: list[Passage],
make_work: Callable[[Usage], Work],
) -> Response:
"""answer_question as a system's last step: the Answer joined to its Work, or
AnswerFailed (with the Work, so an error row keeps what was shown and spent).
make_work turns the answer call's usage into the question's Work: A and B pass it
as is, C adds the usage of its earlier calls. One copy for the three systems (6b
audit: A and B each had ~8 near-identical lines)."""
try:
answer, usage = answer_question(llm, question, day, shown)
except LLMError as failure:
raise AnswerFailed(str(failure), failure.kind, make_work(failure.usage)) from failure
return Response.of(answer, make_work(usage))
|