Classify · Forum questions
Send a question to the community that can answer it
A help centre, a forum or an internal Q&A board gets questions about everything, and each belongs with the people who can answer it. Nenya reads the title and the body and names the community. This is the task it does best of our four, so this cookbook is about volume: many requests at once, and a threshold that makes what you act on almost always right.
- The move
- Route a question to one of your communities, queues or teams.
- The model’s role
- It takes the place of the triage a moderator does by hand.
- Why it fits
- The questions are long and written in everyday words, and the communities are easy to tell apart for a reader. Volume is the problem, not difficulty.
- How it goes
- Title and body in → the question, the two blocks of text and your communities → one community and a confidence → route it, or leave it for a moderator.
- Payoff
- Measured: 90.0% right on 250 real questions and ten communities. Keep the answers it is at least 90% sure of, which is 72% of the questions, and 97.2% are right. Sixty questions take a little over a second with 16 requests in flight.
On this page
The data#
250 questions asked in 2026 on ten Stack Exchange sites about everyday subjects, each with the site it was asked on. Stack Exchange content is licensed CC BY-SA 4.0: every question below is shown with its author and its link, and the data file keeps both for all of them. They are a test set: the model has no training data for this task.
Which of these Q&A communities was this question asked in?
- Bicycles
- Cooking
- English language and usage
- Gardening and landscaping
- Home improvement
- Law
- Motor vehicle maintenance and repair
- Personal finance and money
- Photography
- TravelSet up#
pip install openai. The API is free and needs no key.
import json
import math
import textwrap
import time
from concurrent.futures import ThreadPoolExecutor
from pathlib import Path
from openai import OpenAI
client = OpenAI(base_url="https://api.contrastivelabs.dev/v1", api_key="none")The recipe#
The classify function of the API page, unchanged.
def classify(question, text, labels, heading="Text", descriptions=None, allow_none=False):
"""(label, confidence)"""
options = "\n".join(f"- {label}: {descriptions[label]}" if descriptions else f"- {label}" for label in labels)
prompt = f"{question}\n\n{heading}:\n{text}\n\nOptions:\n{options}\n\nAnswer with the label only."
if allow_none:
prompt += ' If none of the options fits, answer "none".'
reply = client.chat.completions.create(
model="nenya",
messages=[{"role": "user", "content": prompt}],
temperature=0, # one right answer: do not sample
max_tokens=24,
logprobs=True, # for the confidence
extra_body={"structured_outputs": {"choice": labels + (["none"] if allow_none else [])}},
)
choice = reply.choices[0]
tokens = [t for t in choice.logprobs.content if not t.token.startswith("<|")]
confidence = math.exp(sum(t.logprob for t in tokens))
return choice.message.content, confidenceA question is a title and a body. text_of sends the title first and the body under a heading of its own:
DATA = json.loads((Path(__file__).parent / "data" / "classify-forum-questions.json").read_text())
QUESTION = DATA["question"]
COMMUNITIES = DATA["labels"] # ten communities
def text_of(post):
"""The title, then the body of the question under a heading of its own."""
return f"{post['title']}\n\nQuestion:\n{post['text']}"
print(QUESTION)
for name in COMMUNITIES:
print(f"- {name}")The request#
post = DATA["examples"][0]
print(post["title"])
print(textwrap.fill(post["text"], 100))
print(f"(asked by {post['author']}: {post['url']})")
label, confidence = classify(QUESTION, text_of(post), COMMUNITIES, heading="Title")
print()
print(f"model: {label} ({confidence:.0%} sure)")
print(f"asked on: {post['label']}")The response#
How can I disable one of two doorbells if the transformer is with it?
I have a second doorbell in the basement and the transformer is in the same location. I'd like to
remove this doorbell but also not sure if this will affect the upstairs doorbell. (Is the
transformer in question for both the upstairs and basement doorbells?) This basement doorbell is
not needed. In the interest of future homeowners, I am OK with leaving everything in place, I just
want it disconnected. [image]
(asked by Christian: https://diy.stackexchange.com/questions/330183/how-can-i-disable-one-of-two-doorbells-if-the-transformer-is-with-it)
model: Home improvement (99% sure)
asked on: Home improvement{
"model": "nenya-1",
"choices": [
{
"message": {
"content": "Home improvement",
"role": "assistant"
},
"finish_reason": "stop",
"logprobs": {
"content": [
{
"token": "Home",
"logprob": -0.0148
},
{
"token": " improvement",
"logprob": -0.0
}
]
}
}
],
"usage": {
"completion_tokens": 3,
"prompt_tokens": 222,
"total_tokens": 225
}
}Six questions#
for post in DATA["examples"]:
label, confidence = classify(QUESTION, text_of(post), COMMUNITIES, heading="Title")
print(f"{label:<38} {confidence:4.0%} {post['title'][:54]} ({post['author']})")Home improvement 99% How can I disable one of two doorbells if the transfor (Christian)
English language and usage 99% How should -dom words be capitalized? (DumbNerd)
Personal finance and money 91% How can a European invest in Swiss stocks using Swiss (user1868607)
Law 98% Bankruptcy & Show Dogs II: no-breeding clause (In Hoc Signo)
Cooking 97% Fried Tofu with Silk Tofu? (Trish)
Motor vehicle maintenance and repair 94% 2004 Honda Accord without preset bottons: How do I put (Donald Williams)All six are the site the question was asked on.
Many at once#
There are no rate limits. A thread pool is all it takes:
sample = DATA["sample"] # 60 questions, taken without looking at the answers
start = time.perf_counter()
with ThreadPoolExecutor(16) as pool: # 16 requests in flight at a time
answers = list(pool.map(lambda post: classify(QUESTION, text_of(post), COMMUNITIES, heading="Title"), sample))
seconds = time.perf_counter() - start
print(f"{len(sample)} questions in {seconds:.1f} s: {len(sample) / seconds:.0f} a second")60 questions in 1.3 s: 46 a secondThat was measured from a machine in the same region as the server.
Measure it#
The same sixty answers, kept or dropped by confidence:
for threshold in (0.0, 0.8, 0.9, 0.95):
kept = [(label, post) for (label, confidence), post in zip(answers, sample) if confidence >= threshold]
right = sum(label == post["label"] for label, post in kept)
print(f"confidence at least {threshold:.2f}: {len(kept):2d} of {len(sample)} kept, {right:2d} right ({right / len(kept):.0%})")confidence at least 0.00: 60 of 60 kept, 55 right (92%)
confidence at least 0.80: 53 of 60 kept, 52 right (98%)
confidence at least 0.90: 48 of 60 kept, 48 right (100%)
confidence at least 0.95: 35 of 60 kept, 35 right (100%)On the whole test set#
All 250 questions, asked exactly as above, one request at a time: 90.0% right (225 of 250). Sent a second time, one at a time, all 250 answers were the same.
| Act only when the confidence is at least | Questions you keep | Right among them |
|---|---|---|
| 0.80 | 83.2% | 94.7% |
| 0.90 | 71.6% | 97.2% |
| 0.95 | 57.2% | 99.3% |
Nine communities are between 17 of 20 and 55 of 56. One is not: “Bicycles” was right in 9 of 20. Seven of its questions came back as “Motor vehicle maintenance and repair” and four as “Home improvement”: a hydraulic brake lever, a wheel bearing and a frayed gear cable read like a garage or a workshop. Most of those answers came with a low confidence, so the threshold catches them.
Make it yours#
- Send in parallel. Sixteen requests in flight gave more than 40 answers a second here.
- The same request gives the same answer when it is computed alone. Among other requests an answer near a tie can change, so keep the label you stored and do not ask twice.
- Two labels that share a vocabulary (bicycles and cars) are where the misses are. A line of description after each, or a threshold, deals with them.
- Keep the list short. Ten labels is comfortable. Past 20, accuracy falls by about 8 points each time the list doubles.
Run it#
pip install openai
curl -O https://contrastivelabs.com/cookbook/classify-forum-questions.py
curl --create-dirs -o data/classify-forum-questions.json \
https://contrastivelabs.com/cookbook/data/classify-forum-questions.json
python classify-forum-questions.pyThe file is this page’s code in one piece: classify-forum-questions.py. The questions are in data/classify-forum-questions.json, each with its author and its link (CC BY-SA 4.0).