Spaces:
Sleeping
Sleeping
Download src/coveragecheck/agent/answer.py from TBM99/CoverageCheck: direct link, hf CLI and curl.
- Browser
- Download file 8.11 kB
-
https://huggingface.co/spaces/TBM99/CoverageCheck/resolve/main/src/coveragecheck/agent/answer.py
- Command line
-
hf download hf://spaces/TBM99/CoverageCheck/src/coveragecheck/agent/answer.py
-
curl -L -o answer.py https://huggingface.co/spaces/TBM99/CoverageCheck/resolve/main/src/coveragecheck/agent/answer.py
8.11 kB
| """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}""" | |
| 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)) | |