页面简介
Let an LLM propose questions about labelled text, have Jev answer them for every row, and train CatBoost on the answers, feeding its misses back to the next step. The worked example predicts how polite Wikipedia editors' requests read.
正文摘录
How polite will people find a message? In this cookbook we use 2,000 requests that Wikipedia editors left on each other’s talk pages, each rated for politeness by five people. As a control, we train a CatBoost regressor (gradient-boosted trees) on the raw text, using its default text features, which represent each message by the words it contains. Its error is only 11% lower than always predicting the mean rating, so which words a message contains says little about how polite it reads. In this cookbook an LLM, the proposer, writes questions about the messages. Jev answers every question for every message, and CatBoost trains on the answers. CatBoost then reports which questions it used and which messages it still gets wrong. The proposer reads that report and suggests changes to the questions. A change stays only if it makes CatBoost’s predictions better, and each kept change is one step of the loop. The table scores each approach by RMSE: how far its predictions miss on the rating scale, with big misses counting for more. Lower is better. Every number comes from 800 requests the loop never saw. how the message becomes a ratingRMSEpredict the average rating of the training rows0.788the control: the same CatBoost, reading the raw text0.703ask Jev for the rating itself, with a line fitted to the training rows0.49216 questions from the proposer’s first call, no loop0.47120 questions after five steps of the loop0.456 The proposer’s first call does most of the work. It was told nothing about politeness research, and it wrote questions about thanks and praise, apologies and hedging (softened wording), greetings, asking indirectly (“would you be willing to…”), and framing a request as a shared “we” effort. A 2013 study of this corpus built a feature for each of those by hand. Four more steps lowered the error by another 0.015, about 3%. One of them added a question about “please” and similar courtesy words, another of the study’s features, which the first call had missed. The loop keeps a change only when it lowers the error on rows the proposer never reads, so it turned down most of what the proposer suggested after step 1 and ended with 20 questions. By the end you have a loop you can run on your own labelled text, a curve of held-out error per step, and a table of which questions the final model used most. To take this notebook further or apply it to another problem, see Next steps. from __future__ import annotations import json import os import random import textwrap import urllib.request from concurrent.futures import ThreadPoolExecutor from pathlib import Path from time import perf_counter from typing import NamedTuple import matplotlib import matplotlib.pyplot as plt import numpy as np from catboost import CatBoostRegressor from cooksafe import JsonCache, make_playground_link from IPython.display import Markdown, display from typesafe_sdk import Noul, NoulCriteria, Score, TypeSafeClient TYPESAFE_MODEL = "jev-1.14.0" # the page's model; "jev-latest" runs the newest, live FOLDS, REPEATS = 5, 3 # repeats steady the error at this sample size CATBOOST = dict( iterations=400, depth=4, learning_rate=0.05, loss_function="RMSE", verbose=0, random_seed=0, thread_count=1, allow_writing_files=False, ) # 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( # keyless kernels replay the cache api_key=os.environ.get("TYPESAFE_API_KEY", "cache-only"), base_url=os.environ.get("TYPESAFE_ENDPOINT"), timeout=120.0, ) EXAMPLES_URL = ( "https://raw.githubusercontent.com/typesafe-ai/typesafe-public-examples/pub-20261126-cfe720/" "cookbooks/autoresearch_feature_discovery" ) 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("autoresearch_feature_discovery_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) # ----------------------------------------------------------------- the specification INTENSITY_LEVELS = [ "Not present in this message at all", "Barely present - a single small trace", "Present at a moderate level", "Present strongly - it marks the whole message", "Dominant - the message is defined by it", ] PRESENCE_CRITERIA = NoulCriteria( true="The message shows this or clearly implies it", false="The message gives no indication of this", ) # Asking for the rating outright: ten bands from hostile to gracious. SCORE_LEVELS = [ "Insults the reader or is openly hostile", "Curt and accusing, with no courtesy at all", "Blunt and demanding", "Abrupt, a bare question or order with no softening", "Neutral and businesslike", "Plain but carries a small courtesy", "Friendly, with some softening or thanks", "Warm and considerate of the reader", "Very courteous, thanking or apologising and asking gently", "Exceptionally gracious and deferential", ] # Structured output requires every property in `required`, so unused fields come back empty. PROPOSAL_SCHEMA = { "type": "object", "properties": { "actions": { "type": "array", "items": { "type": "object", "properties": { "op": {"type": "string", "enum": ["add", "revise", "drop"]}, "target": {"type": "string"}, "name": {"type": "string"}, "kind": {"type": "string", "enum": ["intensity", "presence"]}, "question": {"type": "string"}, }, "required": ["op", "target", "name", "kind", "question"], "additionalProperties": False, }, } }, "required": ["actions"], "additionalProperties": False, } PROPOSALS = 18 # actions the proposer may return per call # The one string that knows this is about politeness. Point it at your own label and text. PROPOSER_TASK = f"""You are designing numeric features for a gradient-boosting model that predicts how polite a request reads: the average of five people's ratings, normalised so that 0 is typical, negative is less polite and positive is more polite (most fall between -2 and 2). Each message is a request one Wikipedia editor left on another editor's talk page. The model sees nothing but the features you design. Return up to {PROPOSALS} actions. Each action is one of: - {{"op": "add", "target": "", "name": ..., "kind": ..., "question": ...}} A new feature. - {{"op": "revise", "target": <name of an existing feature>, "name": ..., "kind": ..., "question": ...}} Replace that feature's question with better wording. Use this when a feature measures the right thing badly: too narrow, too vague, or worded so nearly every message answers the same. - {{"op": "drop", "target": <name of an existing feature>, "name": "", "kind": "intensity", "question": ""}} Remove a feature that is not earning its place. `kind` is "intensity" for something with a degree, or "presence" for a yes/no fact. `question` is what gets asked about one message. An "intensity" question is graded against this fixed five-level rubric, so word it so that the levels make sense: {chr(10).join(f" {i}. {level}" for i, level in enumerate(INTENSITY_LEVELS))} A "presence" question is answered as the probability that it is true of the message. Good features can be judged from the message's own words, vary from message to message, and carry information about politeness that the other features do not. Raters react to word choice, how the writer frames the request, how they address the reader, and what they say about the reader. Write every question in your own words. Do not quote or closely paraphrase any one example message in a question, not even as an "e.g.": describe the pattern it shows instead. Common words and stock phrases that many messages use may still be named.""" class Split(NamedTuple): """The rows, their labels, and which rows each part of the loop may use.""" messages: list[str] scores: np.ndarray dev: np.ndarray # the rows the models train on read: np.ndarray # dev rows the proposer may see check: np.ndarray # dev rows that judge each change; the proposer never sees them test: np.ndarray # held out, scored once at the end # ----------------------------------------------------------------- the data DATA = Path("wikipedia_politeness.json") DATA_URL = ( "https://raw.githubusercontent.com/typesafe-ai/typesafe-public-examples/pub-20261126-cfe720/" "cookbooks/autoresearch_feature_discovery/wikipedia_politeness.json" ) @json_cache def load_slice(n_dev: int, n_test: int, seed: int) -> dict: """Read the corpus and take a seeded sample of message + rating, one row per message.""" if not DATA.exists(): urllib.request.urlretrieve(DATA_URL, DATA) rows, seen = [], set() for row in json.loads(DATA.read_text(encoding="utf-8")): # a few requests repeat verbatim if not row["text"] or row["text"] in seen: continue seen.add(row["text"]) rows.append((row["text"], float(row["score"]))) random.Random(seed).shuffle(rows) picked = rows[: n_dev + n_test] return {"messages": [r[0] for r in picked], "scores": [r[1] for r in picked]} def example_rows(split: Split, out_of_fold: np.ndarray | None, n: int) -> list[int]: """Select the rows a proposal call reads, from the rows the proposer may see.""" read = split.read if out_of_fold is None: ranked = read[np.argsort(split.scores[read], kind="stable")] return [int(ranked[round(q * (len(ranked) - 1))]) for q in np.linspace(0, 1, n)] error = np.abs(split.scores[read] - out_of_fold[read]) order = np.argsort(-error, kind="stable") wor