翻篇收录说明
翻篇网页快照

SDE cascade - TypeSafe

https://docs.typesafe.ai/cookbooks/sde_cascade

最近抓取:2026-12-03 20:24:26(北京时间)

最近内容变化:2026-12-03 20:24:26(北京时间)

这是最近一次有效抓取的文本快照,不含网页脚本、图片和动态交互内容。实际网页可能已更新。

访问原网页

页面简介

Extracts structured data with a cheap model, checks each field with Jev, and escalates to a reasoning model only when a check fires.

正文摘录

Overview big reasoning models turn text into correct structured data, but are slow and expensive small models are cheap, but make mistakes a cascade runs the small model first and pays for the big one only when a check flags the small model’s answer the models we use: rung 0 (cheap): gpt-6-luna rung 1 (reasoning): gpt-6.1-sol with reasoning_effort="high" verifier: jev-1.14.0 Algorithm Answer with the cheap model, as a JSON object that matches a schema. Verify with Jev: ask yes/no questions (“Noul questions”) about the answer, one per rule it must follow, such as “does this time overlap someone’s meeting?”; each returns P(the rule is broken). Escalate to the reasoning model if the answer fails the schema or a rule check fires; otherwise keep the cheap answer. 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 openai jsonschema ipython matplotlib pandas 'cooksafe>=0.3.0,<0.4.0' With uv, uv run cascade_cookbook.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 and OPENAI_API_KEY; in Colab, add them in the Secrets panel. import json import os import re import urllib.request from pathlib import Path import jsonschema import matplotlib.pyplot as plt import numpy as np import pandas as pd from cooksafe import JsonCache, make_playground_link from IPython.display import Markdown, display from openai import OpenAI from typesafe_sdk import Noul, NoulCriteria, TypeSafeClient CHEAP = "gpt-6-luna" # rung 0: cheap + fast STRONG = "gpt-6.1-sol-high" # rung 1: gpt-6.1-sol with reasoning_effort="high" CONFIGS = { CHEAP: {"model": "gpt-6-luna"}, STRONG: {"model": "gpt-6.1-sol", "reasoning_effort": "high"}, } TYPESAFE_MODEL = "jev-1.14.0" # the page's model; "jev-latest" runs the newest, live FIRE_T = 0.7 # escalate if any rule's P(broken) exceeds this; also the "<== FIRES" display marker # The keys this cookbook uses. In Colab, keys saved in the Secrets panel are copied in here. KEYS = ["TYPESAFE_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 oai = OpenAI(api_key=os.environ.get("OPENAI_API_KEY", "cache-only")) ts = TypeSafeClient( api_key=os.environ.get("TYPESAFE_API_KEY", "cache-only"), timeout=30.0 ) See all 42 lines Step 1: the data example.json holds one task from the calendar set of NATURAL PLAN: the busy times of three people on one work day, and a one-hour meeting to fit around them the code below downloads it from typesafe-public-examples unless it is already on disk EXAMPLE = Path("example.json") EXAMPLE_URL = ( "https://raw.githubusercontent.com/typesafe-ai/typesafe-public-examples/pub-20261126-cfe720/" "cookbooks/sde_cascade/example.json" ) if not EXAMPLE.exists(): urllib.request.urlretrieve(EXAMPLE_URL, EXAMPLE) task = json.loads(EXAMPLE.read_text())["prompt_0shot"] print(task.split("TASK:")[-1].replace("SOLUTION:", "").strip()) You need to schedule a meeting for Joan, Theresa and Shirley for one hour between the work hours of 9:00 to 17:00 on Monday. Here are the existing schedules for everyone during the day: Joan has meetings on Monday during 11:00 to 11:30, 12:30 to 13:00; Theresa has meetings on Monday during 12:00 to 12:30, 15:00 to 15:30; Shirley has meetings on Monday during 9:30 to 10:30, 11:00 to 12:00, 13:00 to 14:00, 15:30 to 16:30; Find a time that works for everyone's schedule and constraints. Every fact the answer depends on is in the text, but the answer itself isn’t: the model has to work out a free hour from the busy times Shirley has four meetings, so only one full hour of the day is free for all three Step 2: answer with the cheap model the prompt ends with a JSON Schema for the answer: a day, a start time and an end time the model reads the schema in the prompt and replies with plain text that we parse. We don’t use structured outputs, which would force valid JSON and hide the rare answer that breaks the schema TIME = {"type": "string", "pattern": "^([01][0-9]|2[0-3]):[0-5][0-9]$"} SCHEMA = { "type": "object", "properties": { "day": {"type": "string", "enum": ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday"], "description": "the day of the meeting"}, "start_time": TIME | {"description": "when the meeting starts, 24-hour HH:MM"}, "end_time": TIME | {"description": "when the meeting ends, 24-hour HH:MM"}, }, "required": ["day", "start_time", "end_time"], "additionalProperties": False, } FORMAT_LINE = "Return ONLY a JSON object matching this JSON Schema:\n" + json.dumps(SCHEMA, indent=2) def prompt_for(task: str) -> str: """The task's prompt with the schema placed just before its closing SOLUTION:.""" return re.sub(r"SOLUTION:\s*$", FORMAT_LINE + "\nSOLUTION: ", task.rstrip()) # LLM and TypeSafe calls are cached in CACHE, so a re-run reuses earlier answers instead of # calling the APIs again. EXAMPLES_URL = ( "https://raw.githubusercontent.com/typesafe-ai/typesafe-public-examples/pub-20261126-cfe720/" "cookbooks/sde_cascade" ) 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(): urllib.request.urlretrieve(f"{EXAMPLES_URL}/{name}", path) return path CACHE = Path("sde_cascade_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) @json_cache def ask(prompt: str, **config) -> dict: """One reply from a rung, keyed on the prompt and the whole config: model and effort.""" r = oai.chat.completions.create(messages=[{"role": "user", "content": prompt}], **config) return {"text": r.choices[0].message.content, "in": r.usage.prompt_tokens, "out": r.usage.completion_tokens} def parse(text: str) -> dict | None: """The answer as a record, or None if it isn't a JSON object matching ``SCHEMA``. The prompt asks for ONLY a JSON object, so parse the reply as-is -- no regex fishing a substring out of a malformed reply. A reply that fails either check escalates: the safe direction.""" try: record = json.loads(text) except ValueError: return None return record if jsonschema.Draft202012Validator(SCHEMA).is_valid(record) else None cheap_text = ask(prompt_for(task), **CONFIGS[CHEAP])["text"] cheap_record = parse(cheap_text) print("cheap answer:", cheap_text) print("\nschema-valid:", cheap_record is not None) See all 67 lines cheap answer: {"day":"Monday","start_time":"10:30","end_time":"11:30"} schema-valid: True The answer is schema-valid (the line above prints True), yet it’s wrong: Monday 10:30-11:30 overlaps Joan’s meeting at 11:00 and Shirley’s at 11:00 a JSON-Schema check can’t see this. A cheap model produces confident, schema-satisfying mistakes of this kind, and catching them is the job of a semantic verifier Step 3: verify with Jev the verifier is Jev; we ask it one Noul question per rule the answer must follow, each framed so that true = the rule is broken (escalate) Jev returns a calibrated noul = P(true) per question, in one system_one call the state holds the task and the cheap model’s record; Jev never sees a correct answer The TypeSafe Way: Decomposition we split the check in code into narrow questions, one per rule, never one question about the whole answer a flag then names the rule that broke, and each question can be reworded or re-thresholded on its own a single “is this answer right?” returns one score that cannot say what went wrong see Decompose the questions RULES = { "busy_conflict": "Does the meeting time in the `answer` overlap a time when any participant in the `task` is busy?", "outside_hours": "Is the meeting time in the `answer` outside the work hours or the days the `task` allows?", "breaks_preference": "Does the meeting time in the `answer` break a preference stated in the `task`, such as a participant who would rather not meet on a certain day or before or after a certain time?", "not_earliest": "Does the `task` ask for the earliest availability, and is there an earlier time that works for every participant?", "wrong_length": "Is the meeting in the `answer` a different length from the one the `task` asks for?", "no_single_time": "Does the `answer` fail to propose exactly one day and one start and end time?", } CHECKS = { rule: Noul( instructions=question, criteria=NoulCriteria(true="the answer breaks this rule", false="the answer follows this rule"), ) for rule, question in RULES.items() } @json_cache def verify(state_json: str, model: str) -> dict[str, float]: """Ask every rule question about one answer in one TypeSafe call; return ``{rule: P(broken)}``.""" questions = {k: q.model_dump(mode="json", exclude_none=True) for k, q in CHECKS.items()} answers = ts.system_one(state=json.loads(state_json), questions=questions, model=model).answers return {rule: ans.noul for rule, ans in answers.items()} state = {"task": task, "answer": cheap_record} checks = verify(json.dumps(state), model=TYPESAFE_MODEL) playground_link = make_playground_link(state, {k: q.model_dump(mode="json", exclude_none=True) for k, q in CHECKS.items()}) display(Markdown(f"🔗 [Open in the TypeSafe playground]({playground_link})")) print(f"{'rule':<20}{'P(broken)':>10}") print("-" * 30) for rule, p in sorted(checks.items(), key=lambda c: -c[1]): flag = " <== FIRES" if p > FIRE_T else "" print(f"{rule:<20}{p:>10.2f}{flag}") rule P(broken) ------------------------------ busy_conflict 0.97 <== FIRES not_earliest 0