页面简介
Score each retrieved passage with one TypeSafe request, then decide in code which ones reach the answering model.
正文摘录
The retrieval step of a RAG pipeline ranks passages by how much their wording resembles the query, and hands the top few to a language model. These may include noisy or irrelevant passages, or worse yet, may lump together contradicting facts, prompt injections, or model instructions together with what is nominally evidence to assist with generating an answer. Between retrieval and generation, add a second stage that classifies each retrieved passage. For each one, send TypeSafe one request carrying multiple questions about the query–passage pair: is it relevant, does it state something usable in an answer, does it contradict something the query takes for granted, and is it trying to instruct the model. The answers to those questions decide what happens to each passage, with simple branching logic: add it to the prompt as evidence, add it to the prompt as conflicting information, or drop it. Evidence and conflicts arrive in separate blocks, so the generator can react appropriately. To exercise the pipeline, we run it over some tricky questions against real auth documentation full of pages that read alike, and a planted passage carrying a prompt injection. Two questions contain false assumptions, which are flagged before being handed to the model generating answers. The pipeline, in the order the sections build it: the 81-passage corpus, a cosine-similarity search that keeps the top 12 passages per query, the four Noul questions sent to TypeSafe for each of those passages, the thresholds in route() that label each one, the prompt assembled from separate evidence and conflict blocks, and the answers claude-sonnet-5 writes from it. Setup Run in ColabRuns as published without an API key.Python fileThis page as one .py file, to run locally.Open in playgroundEdit one request and run it live. Needs a TypeSafe account. To run it on your own machine instead: pip install anthropic openai matplotlib ipython 'cooksafe>=0.3.0,<0.4.0' With uv, uv run classifying_rag_passages.py installs the dependencies for you. The code replays saved answers, so it runs as published without an API key. To change a request, set TYPESAFE_API_KEY, ANTHROPIC_API_KEY and OPENAI_API_KEY; in Colab, add them in the Secrets panel. We use Jev to score each retrieved passage, OpenAI to embed the corpus for the search step, and Claude to write the final answer out of whatever survives the scoring. The numbers here came out of jev-1.14.0 and claude-sonnet-5 on 2026-11-03. import json import os import urllib.request from concurrent.futures import ThreadPoolExecutor from pathlib import Path from time import perf_counter import anthropic from cooksafe import JsonCache, make_playground_link import matplotlib.pyplot as plt from IPython.display import Markdown, display from openai import OpenAI from typesafe_sdk import Noul, TypeSafeClient TYPESAFE_MODEL = "jev-1.14.0" # the page's model; "jev-latest" runs the newest, live GENERATOR_MODEL = "claude-sonnet-5" # writes the answer out of what the routing keeps EMBED_MODEL = "text-embedding-3-small" EMBED_DIMS = 256 # short vectors keep the shipped cache small; plenty for 81 passages TOP_K = 12 # passages retrieved per query # Every number the routing reads lives in this dict and nowhere else, so a change of policy # is a constant edit under code review, not a reworded question. THRESHOLDS = { "injection_max": 0.70, # above this the passage never reaches the prompt "contradicts_min": 0.70, # above this it disputes what the query takes for granted "relevant_min": 0.45, # below this the passage is not about the query at all "evidence_min": 0.55, # above this it states something usable in an answer } # The keys this cookbook uses. In Colab, keys saved in the Secrets panel are copied in here. KEYS = ["TYPESAFE_API_KEY", "ANTHROPIC_API_KEY", "OPENAI_API_KEY"] try: from google.colab import userdata except ImportError: # not in Colab userdata = None for key in KEYS: if userdata is not None and key not in os.environ: try: os.environ[key] = userdata.get(key) except (userdata.SecretNotFoundError, userdata.NotebookAccessError): pass # not saved, or this notebook may not read it client = TypeSafeClient( api_key=os.environ.get("TYPESAFE_API_KEY", "cache-only"), # keyless kernels replay base_url=os.environ.get("TYPESAFE_ENDPOINT"), timeout=120.0, ) generator = anthropic.Anthropic( api_key=os.environ.get("ANTHROPIC_API_KEY", "cache-only") ) embedder = OpenAI(api_key=os.environ.get("OPENAI_API_KEY", "cache-only")) EXAMPLES = ( "https://raw.githubusercontent.com/typesafe-ai/typesafe-public-examples/pub-20261126-cfe720/" "cookbooks/classifying_rag_passages" ) def download(name: str) -> Path: """Fetch one of this cookbook's files from typesafe-public-examples unless it is on disk.""" path = Path(name) if not path.exists(): path.parent.mkdir(parents=True, exist_ok=True) urllib.request.urlretrieve(f"{EXAMPLES}/{name}", path) return path CACHE = Path("classifying_rag_passages_cache.json") # True fills CACHE with the published answers, so the run makes no requests. To run # live, set it to False and delete CACHE; a CACHE already on disk is never overwritten. DOWNLOAD_CACHE = True if DOWNLOAD_CACHE: download(CACHE.name) json_cache = JsonCache(CACHE) See all 76 lines Load the docs corpus The corpus file corpus.json holds 81 passages. We copied 80 of them straight from the Supabase auth docs at commit 2440b06, one passage per heading, verbatim and used under Apache 2.0: https://github.com/supabase/supabase/tree/2440b06/apps/docs/content/guides/auth Each passage carries id, title, text and source_type, and every request sends all four. Near-misses fill the set. Rotation, expiry, sessions and signing keys each get their own page, and those pages read alike. Refresh-token rotation and JWT signing-key rotation are different things described in nearly the same words. We wrote the last one ourselves, forum-injection, marked community_forum: it reads as an ordinary forum answer until its final paragraph, which is an instruction aimed at the model. We also wrote two of the six queries to state a premise the docs contradict, so the injection and conflict routes both have something to catch. PASSAGES = json.loads(download("corpus.json").read_text(encoding="utf-8")) BY_ID = {p["id"]: p for p in PASSAGES} counts: dict[str, int] = {} for passage in PASSAGES: counts[passage["source_type"]] = counts.get(passage["source_type"], 0) + 1 print(f"{len(PASSAGES)} passages") for source_type in sorted(counts): print(f" {source_type:<24}{counts[source_type]:>3}") example = BY_ID["sessions-01"] print(f"\nOne passage, as the model will see it ({example['id']}):") print(f" title {example['title']}") print(f" source_type {example['source_type']}") print(f" text {example['text'][:220]}...") 81 passages community_forum 1 official_documentation 80 One passage, as the model will see it (sessions-01): title User sessions: What is a session? source_type official_documentation text A session is created when a user signs in. By default, it lasts indefinitely and a user can have an unlimited number of active sessions on as many devices. A session is represented by the Supabase Auth access token in t... Retrieve the top passages Rank the passages by cosine similarity over embeddings, using text-embedding-3-small at 256 dimensions, and keep the best TOP_K = 12 for each query. Short vectors keep the shipped cache small, and the embedding calls are cached with everything else, so the vectors travel inside classifying_rag_passages_cache.json. @json_cache def embed(texts: tuple[str, ...], embed_model: str) -> list[list[float]]: """One call for many texts; the tuple argument keeps the cache key small and hashable.""" response = embedder.embeddings.create( model=embed_model, input=list(texts), dimensions=EMBED_DIMS ) return [item.embedding for item in response.data] def cosine(a: list[float], b: list[float]) -> float: dot = sum(x * y for x, y in zip(a, b)) return dot / ((sum(x * x for x in a) ** 0.5) * (sum(y * y for y in b) ** 0.5)) PASSAGE_VECTORS = dict( zip( [p["id"] for p in PASSAGES], embed( tuple(f"{p['title']}\n\n{p['text']}" for p in PASSAGES), embed_model=EMBED_MODEL ), ) ) def retrieve(query: str, k: int) -> list[dict]: vector = embed((query,), embed_model=EMBED_MODEL)[0] scored = [(cosine(vector, PASSAGE_VECTORS[p["id"]]), p["id"]) for p in PASSAGES] scored.sort( key=lambda pair: (-pair[0], pair[1]) ) # id breaks ties, so replays match return [dict(BY_ID[pid], similarity=round(score, 4)) for score, pid in scored[:k]] # The first two queries state something the docs contradict; the rest are ordinary questions. HEADLINE_QUERY = "Refresh tokens expire after 30 days - how do I extend that window?" QUERIES = [ HEADLINE_QUERY, "Why are sessions deleted immediately when the inactivity timeout is reached?", "How are refresh tokens rotated?", "Do refresh tokens ever expire?", "Can I set a different refresh token reuse interval for each user?", "How long should an access token live?", ] See all 43 lines The 12 passages retrieved for the first query: for passage in retrieve(HEADLINE_QUERY, TOP_K): print( f" {passage['similarity']:.3f} {passage['id']:<22}" f"{passage['source_type'][:13]:<15}{passage['title'][:44]}" ) 0.584 forum-injection community_for Forum: refresh token keeps expiring on mobil 0.576 sessions-05 official_docu User sessions: What are recommended values f 0.546 sessions-06-a official_docu User sessions: What is refresh token reuse d 0.531 sessions-04-b official_docu User sessions: Limiting session lifetime and 0.520 sessions-07-b official_docu User sessions: What is refresh token reuse d 0.510 sessions-09 official_docu User sessions: How to ensure an access token 0.509 sessions-01 official_docu User sessions: What is a session? 0.504 password-security-39 official_docu Password security: Require reauthentication 0.478 signing-keys-51-c official_docu JWT Signing Keys: Getting started 0.465 sessions-08-a official_docu User sessions: What are the benefits of usin 0.460