"""Route a spoken command to the skill that handles it.

The commands are real: utterances people spoke to a voice assistant, from the public MASSIVE data set (en-US test
split), each with the intent its annotators gave it. Run it with `pip install openai`, then
`python classify-voice-commands.py`. The API is free and needs no key.
"""
# === setup ===
import json
import math
import time
from pathlib import Path

from openai import OpenAI

client = OpenAI(base_url="https://api.contrastivelabs.dev/v1", api_key="none")

# === the recipe ===
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, confidence

# === the data ===
DATA = json.loads((Path(__file__).parent / "data" / "classify-voice-commands.json").read_text())
QUESTION = DATA["question"]
INTENTS = DATA["labels"]                    # the twelve things people ask this assistant for

print(QUESTION)
for name in INTENTS:
    print(f"- {name}")

# === the request ===
command = DATA["examples"][0]
label, confidence = classify(QUESTION, command["text"], INTENTS, heading="Command")
print(f"command:   {command['text']}")
print(f"model:     {label} ({confidence:.0%} sure)")
print(f"annotator: {command['label']}")

# === six commands ===
for command in DATA["examples"]:
    label, confidence = classify(QUESTION, command["text"], INTENTS, heading="Command")
    print(f"{label:<18} {confidence:4.0%}   {command['text']}")

# === a command the assistant cannot do ===
SKILLS = DATA["skills"]                     # say the assistant can do eight of the twelve things
for command in DATA["unknown"]:
    label, confidence = classify(QUESTION, command["text"], SKILLS, heading="Command", allow_none=True)
    if label == "none" or confidence < 0.8:
        action = "say: sorry, I cannot do that yet"
    else:
        action = f"run the skill: {label}"
    print(f"{command['text']:<54} {label:<17} {confidence:4.0%}   {action}")

# === measure it ===
sample = DATA["sample"]                     # 60 commands, taken without looking at the answers
start = time.perf_counter()
answers = [classify(QUESTION, command["text"], INTENTS, heading="Command") for command in sample]
seconds = time.perf_counter() - start

right = sum(label == command["label"] for (label, _), command in zip(answers, sample))
sure = [(label, command) for (label, confidence), command in zip(answers, sample) if confidence >= 0.9]
sure_right = sum(label == command["label"] for label, command in sure)
print(f"{right} of {len(sample)} right ({right / len(sample):.0%})")
print(f"at least 90% sure of {len(sure)}; {sure_right} of those right ({sure_right / len(sure):.0%})")
print(f"{seconds / len(sample):.2f} s a command, one at a time")
