#!/usr/bin/env python3
"""The recipes of the Nenya API page (docs/API.md), runnable: classification, extraction and tool calling asked the
way that scored best in our tests (API_deployment/bench/prompt_lab.py, tool_lab.py and tool_result_lab.py).

    pip install openai
    python cookbook.py                 # run every recipe and print what comes back
    python cookbook.py classify        # only the recipes whose name starts with "classify"
    python cookbook.py --json out.json # also save every request and reply

The three helpers at the top (classify, extract, run_tools with its Final) are the part to copy. Everything below them is sample
material: support tickets, an invoice, an email, a shop's order tools. All of it is made up.
"""
import json
import math
import sys

from openai import OpenAI

client = OpenAI(base_url="https://api.contrastivelabs.dev/v1", api_key="none")
LOG = []                                    # every request and reply, for --json


_create = client.chat.completions.create


def _logged(**request):
    """client.chat.completions.create, keeping every request and reply for --json."""
    reply = _create(**request)
    if not request.get("stream"):
        LOG.append({"request": request, "reply": reply.model_dump(exclude_none=True)})
    return reply


client.chat.completions.create = _logged


# =====================================================================================================================
# Classification: one label from a list, with the model's own confidence
# =====================================================================================================================
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


def classify_many(question, text, labels, heading="Text"):
    """Every label that applies, as a list (it may be empty)."""
    options = "\n".join(f"- {label}" for label in labels)
    prompt = (f"{question}\n\n{heading}:\n{text}\n\nOptions:\n{options}\n\n"
              'Answer with a JSON object: {"labels": [...]}. Use an empty list if none apply.')
    schema = {"type": "object", "properties": {"labels": {"type": "array", "items": {"type": "string", "enum": labels}}},
              "required": ["labels"], "additionalProperties": False}
    reply = client.chat.completions.create(
        model="nenya", messages=[{"role": "user", "content": prompt}], temperature=0, max_tokens=100,
        response_format={"type": "json_schema", "json_schema": {"name": "labels", "schema": schema}})
    return json.loads(reply.choices[0].message.content)["labels"]


# =====================================================================================================================
# Extraction: fields from a document, as JSON
# =====================================================================================================================
def extract(kind, document, fields, max_tokens=800):
    """{field: value or None}. fields: [{"name", "type", "description"}], plus "schema" for lists and objects."""
    lines = "\n".join(f"- {f['name']} ({f['type']}): {f['description']}" for f in fields)
    system = (f"You extract structured data from {kind}s. For each document the user sends, give these fields.\n\n"
              f"Fields:\n{lines}\n\n"
              "Answer with one JSON object with exactly these keys. Use null for a field the text does not give.")
    properties = {f["name"]: f.get("schema") or {"type": [f["type"], "null"]} for f in fields}
    schema = {"type": "object", "properties": properties, "required": [f["name"] for f in fields],
              "additionalProperties": False}
    reply = client.chat.completions.create(
        model="nenya",
        messages=[{"role": "system", "content": system}, {"role": "user", "content": document}],
        temperature=0,                      # one right answer: do not sample
        max_tokens=max_tokens,
        response_format={"type": "json_schema", "json_schema": {"name": "record", "schema": schema}},
    )
    choice = reply.choices[0]
    if choice.finish_reason != "stop":      # "length": the JSON was cut off and will not parse
        raise RuntimeError(f"the reply was cut off ({choice.finish_reason}): raise max_tokens")
    return json.loads(choice.message.content)


# =====================================================================================================================
# Tool calling: the loop
# =====================================================================================================================
class Final(Exception):
    """A function raises this when there is nothing more to try. Its message goes to the model as the result,
    and no tools are offered after it, so the model answers in words."""


def run_tools(messages, tools, functions, tool_choice="auto", max_turns=6):
    """Run the conversation until the model answers in words. functions: {tool name: Python function}."""
    messages = list(messages)
    for _ in range(max_turns):
        offer = {"tools": tools, "tool_choice": tool_choice} if tools else {"temperature": 0}
        reply = client.chat.completions.create(model="nenya", messages=messages, **offer)
        message = reply.choices[0].message
        if not message.tool_calls:
            return message.content
        messages.append(message.model_dump(exclude_none=True))     # the model's message, as it came
        for call in message.tool_calls:
            arguments = json.loads(call.function.arguments)        # a JSON string: parse it, then check it
            print(f"-> {call.function.name}({arguments})")
            try:
                result = json.dumps(functions[call.function.name](**arguments))
            except Final as final:          # nothing more to try: a sentence for the model, and no more tools
                result, tools = str(final), None
            messages.append({"role": "tool", "tool_call_id": call.id, "content": result})
        tool_choice = "auto"                # a forced first step must not force every later one
    raise RuntimeError("the model kept calling tools: stop and look")


def tool(name, description, properties, required):
    return {"type": "function", "function": {"name": name, "description": description, "parameters": {
        "type": "object", "properties": properties, "required": required}}}


# =====================================================================================================================
# Sample material and the recipes
# =====================================================================================================================
TEAMS = ["Billing", "Technical", "Shipping", "Account"]


def classify_ticket():
    """Route a support ticket; send the unsure ones to a person."""
    for ticket in ("I was charged twice for my November invoice.",
                   "Tracking has not updated in five days. Where is my parcel?",
                   "I cannot log in, and my card was still charged."):
        label, confidence = classify("Which team should handle this support ticket?", ticket, TEAMS, heading="Ticket")
        print(f"    {label:<10} {confidence:4.0%}  {'-> a person looks' if confidence < 0.9 else ''}  {ticket}")


def classify_with_descriptions():
    """Say what each label covers when the names alone are not clear."""
    label, confidence = classify(
        "Which queue does this message to an online bank belong in?",
        "My card was declined abroad even though I told you I was travelling.",
        ["Cards", "Fraud", "Payments", "General"], heading="Message",
        descriptions={"Cards": "lost, blocked, declined or expiring cards",
                      "Fraud": "transactions the customer does not recognise",
                      "Payments": "transfers, standing orders and direct debits",
                      "General": "opening hours, branches and everything else"})
    print(f"    {label} ({confidence:.0%})")


def classify_yes_no():
    """A yes/no check is a two-label classification."""
    for message in ("Please cancel my order and send my money back.", "When will the blue one be back in stock?"):
        label, confidence = classify("Does this message ask for a refund?", message, ["yes", "no"], heading="Message")
        print(f"    {label:<4} {confidence:4.0%}  {message}")


def classify_none():
    """Let it say that nothing fits."""
    for request in ("Turn the living room lights down a bit.", "What is the meaning of life?"):
        label, confidence = classify("Which intent does this request express?", request,
                                     ["lights", "heating", "music", "alarm"], heading="Request", allow_none=True)
        print(f"    {label:<8} {confidence:4.0%}  {request}")


def classify_several_labels():
    """Every label that applies."""
    review = "The room was spotless and the staff were lovely, but the wifi kept dropping and breakfast was cold."
    labels = classify_many("Which topics does this hotel review mention?", review,
                           ["cleanliness", "staff", "food", "wifi", "location", "price"], heading="Review")
    print(f"    {labels}")


INVOICE = """INVOICE

Northwind Supply Co.
Invoice no.: INV-2041
Date: 3 November 2026
Due: 3 December 2026
Bill to: Halden Robotics Ltd

Description                  Qty    Unit    Amount
M6 hex bolts, box of 500      12   18.40    220.80
Aluminium bracket, 40 mm     250    2.15    537.50
Freight                        1   64.00     64.00

Subtotal      822.30
VAT 20%       164.46
Total due     GBP 986.76"""

LINE_ITEM = {"type": "object",
             "properties": {"description": {"type": "string"}, "quantity": {"type": "number"},
                            "unit_price": {"type": "number"}, "amount": {"type": "number"}},
             "required": ["description", "quantity", "unit_price", "amount"], "additionalProperties": False}


def extract_invoice():
    """An invoice, with its lines as a list of objects."""
    record = extract("invoice", INVOICE, [
        {"name": "vendor", "type": "string", "description": "Name of the company that issued the invoice"},
        {"name": "invoice_number", "type": "string", "description": "The invoice number"},
        {"name": "invoice_date", "type": "string", "description": "The date the invoice was issued, as YYYY-MM-DD"},
        {"name": "due_date", "type": "string", "description": "The date payment is due, as YYYY-MM-DD"},
        {"name": "customer", "type": "string", "description": "Name of the customer the invoice is billed to"},
        {"name": "po_number", "type": "string", "description": "The purchase order number"},
        {"name": "currency", "type": "string", "description": "Three-letter currency code, such as GBP"},
        {"name": "total", "type": "number", "description": "The total amount due"},
        {"name": "line_items", "type": "list of {description, quantity, unit_price, amount}",
         "description": "One entry for each line of the invoice",
         "schema": {"type": "array", "items": LINE_ITEM}},
    ])
    print("    " + json.dumps(record, indent=2).replace("\n", "\n    "))


EMAIL = """From: Priya Nair <priya@halden-robotics.example>
To: Sam Okafor
Subject: Supplier review

Hi Sam,

Can we move the supplier review to next Thursday at 2:30pm? An hour should do. I have booked the Faraday room, and
Dana from procurement will join us. Please bring the Q3 defect figures.

Thanks,
Priya"""


def extract_email():
    """A meeting from an email. The model does not work dates out: take "next Thursday" as it is written and
    resolve it in your own code. Ask for YYYY-MM-DD only where the text gives a calendar date."""
    record = extract("email", EMAIL, [
        {"name": "organiser", "type": "string", "description": "Name of the person asking for the meeting"},
        {"name": "topic", "type": "string", "description": "What the meeting is about, in a few words"},
        {"name": "when_as_written", "type": "string",
         "description": "The day and time of the meeting, in the email's own words"},
        {"name": "duration_minutes", "type": "integer", "description": "Length of the meeting in minutes"},
        {"name": "room", "type": "string", "description": "The room that was booked"},
        {"name": "video_link", "type": "string", "description": "Link for joining by video"},
        {"name": "to_bring", "type": "string", "description": "What the reader is asked to bring"},
    ])
    print("    " + json.dumps(record, indent=2).replace("\n", "\n    "))


def extract_ticket():
    """Free text into a record with fixed choices: an enum in the schema holds a field to your values."""
    record = extract("support ticket", "Hi, I ordered the standing desk (order 48213) two weeks ago and it arrived "
                     "with a cracked top. I need it replaced before the 12th, we have an office move. Jo Brandt", [
        {"name": "customer_name", "type": "string", "description": "Name of the customer"},
        {"name": "order_id", "type": "string", "description": "The order number, digits only"},
        {"name": "product", "type": "string", "description": "The product the ticket is about"},
        {"name": "problem", "type": "string", "description": "One of: damaged, late, wrong_item, missing_part, other",
         "schema": {"anyOf": [{"type": "string", "enum": ["damaged", "late", "wrong_item", "missing_part", "other"]},
                              {"type": "null"}]}},
        {"name": "wants", "type": "string", "description": "One of: refund, replacement, repair, information",
         "schema": {"anyOf": [{"type": "string", "enum": ["refund", "replacement", "repair", "information"]},
                              {"type": "null"}]}},
        {"name": "phone", "type": "string", "description": "The customer's phone number"},
    ])
    print("    " + json.dumps(record))


ORDERS = {"48213": {"order_id": "48213", "item": "Standing desk", "status": "delivered", "total_gbp": 329.00}}
# Every rule says what to do. The one about refunds says it for the usual case, a customer who names no amount:
# with "Refund only what the customer asks for" in its place, 1 conversation in 5 ended without the refund.
SHOP_SYSTEM = ("You are the support assistant of Fernhill, an online furniture shop. You help customers with their "
               "orders.\n\n"
               "Rules:\n"
               "- Always look an order up first.\n"
               "- Use a tool whenever one fits the request, and pass exactly the values the customer gave.\n"
               "- A customer who asks for their money back gets the order's total refunded.\n"
               "- If no tool fits, answer in one or two sentences.\n"
               "- Keep answers short and plain.")
SHOP_TOOLS = [
    tool("get_order", "Look up an order by its number.",
         {"order_id": {"type": "string", "description": "The order number, digits only"}}, ["order_id"]),
    tool("issue_refund", "Refund an order, in full or in part.",
         {"order_id": {"type": "string", "description": "The order number, digits only"},
          "amount": {"type": "number", "description": "Amount to refund, in pounds"},
          "reason": {"type": "string", "enum": ["damaged", "late", "wrong_item", "other"],
                     "description": "Why the customer is refunded"}}, ["order_id", "amount", "reason"]),
    tool("escalate_to_human", "Hand the conversation to a person.",
         {"summary": {"type": "string", "description": "What the customer wants, in one sentence"}}, ["summary"]),
]


def get_order(order_id):
    if order_id not in ORDERS:              # found nothing: say so in a sentence, and end the tool calls
        raise Final(f"There is no order {order_id}. Tell the customer, and ask them to check the number.")
    return ORDERS[order_id]


def issue_refund(order_id, amount, reason):
    total = get_order(order_id)["total_gbp"]
    if not 0 < amount <= total:             # a limit belongs here: the model passes on what it is asked for
        return {"error": f"The amount must be more than 0 and at most the order's total of {total:.2f} GBP. "
                         f"Nothing was refunded."}
    return {"refunded_gbp": amount, "order_id": order_id}


SHOP_FUNCTIONS = {                          # your own code: here, stand-ins
    "get_order": get_order,
    "issue_refund": issue_refund,
    "escalate_to_human": lambda summary: {"ticket": "H-1042"},
}


def tools_agent():
    """A support agent: a system message that says what it is for, three tools, the loop."""
    answer = run_tools([{"role": "system", "content": SHOP_SYSTEM},
                        {"role": "user", "content": "My standing desk from order 48213 arrived with a cracked top. "
                                                    "I would like my money back."}],
                       SHOP_TOOLS, SHOP_FUNCTIONS)
    print(f"    {answer}")


def tools_limit():
    """A limit is kept by your code: the function refuses an amount above the order's total.
    The model passes on the 500 it was asked for. After the refusal it refunds the total or tells the customer."""
    answer = run_tools([{"role": "system", "content": SHOP_SYSTEM},
                        {"role": "user", "content": "My standing desk from order 48213 arrived broken. "
                                                    "Refund me 500 pounds."}],
                       SHOP_TOOLS, SHOP_FUNCTIONS)
    print(f"    {answer}")


def tools_not_found():
    """A look-up that finds nothing: the function raises Final and the model tells the customer.
    With {"error": "no such order"} as the result it would look the order up again and again."""
    answer = run_tools([{"role": "system", "content": SHOP_SYSTEM},
                        {"role": "user", "content": "My standing desk from order 77120 arrived with a cracked top. "
                                                    "I would like my money back."}],
                       SHOP_TOOLS, SHOP_FUNCTIONS)
    print(f"    {answer}")


def tools_how_sure():
    """How sure the model is of its next step: the first token of the reply, with its alternatives."""
    messages = [
        {"role": "system", "content": SHOP_SYSTEM},
        {"role": "user", "content": "My standing desk from order 48213 arrived with a cracked top. "
                                    "I would like my money back."},
        {"role": "assistant", "content": None, "tool_calls": [{"id": "call_1", "type": "function", "function": {
            "name": "get_order", "arguments": "{\"order_id\": \"48213\"}"}}]},
        {"role": "tool", "tool_call_id": "call_1", "content": json.dumps(ORDERS["48213"])},
    ]
    reply = client.chat.completions.create(model="nenya", messages=messages, tools=SHOP_TOOLS, logprobs=True,
                                           top_logprobs=3)
    for alternative in reply.choices[0].logprobs.content[0].top_logprobs:      # the first token of the reply
        print(f"    {alternative.token!r:20} {math.exp(alternative.logprob):.0%}")


WEATHER = tool("get_weather", "Get the current weather for a city.",
               {"city": {"type": "string", "description": "Name of the city"}}, ["city"])


def tools_parallel():
    """Two calls in one reply: run both, send both results, then ask again."""
    answer = run_tools([{"role": "user", "content": "What is the weather in Paris and in Tokyo?"}], [WEATHER],
                       {"get_weather": lambda city: {"city": city, "temperature_c": {"Paris": 9, "Tokyo": 14}.get(city, 11),
                                                     "sky": "clear"}})
    print(f"    {answer}")


HOME_TOOLS = [
    tool("set_lights", "Switch the lights of a room on or off, or dim them.",
         {"room": {"type": "string", "description": "The room"},
          "brightness": {"type": "integer", "description": "0 (off) to 100 (full)"}}, ["room", "brightness"]),
    tool("set_temperature", "Set the heating of a room to a temperature.",
         {"room": {"type": "string", "description": "The room"},
          "celsius": {"type": "number", "description": "Target temperature in degrees Celsius"}}, ["room", "celsius"]),
    tool("play_music", "Play music in a room.",
         {"room": {"type": "string", "description": "The room"},
          "query": {"type": "string", "description": "What to play: an artist, an album, a genre"}}, ["room", "query"]),
    tool("no_matching_tool", "Call this when none of the other tools can do what the user asks.",
         {"reason": {"type": "string", "description": "One sentence on why no tool fits"}}, ["reason"]),
]


def tools_router():
    """A command interface: every request becomes exactly one call. `tool_choice="required"` makes the model call,
    and `no_matching_tool` gives it a way to say that nothing fits."""
    for command in ("Make it a bit warmer in the bedroom, 21 degrees.", "Dim the kitchen lights to 30%.",
                    "Order me a pizza."):
        reply = client.chat.completions.create(model="nenya", messages=[{"role": "user", "content": command}],
                                               tools=HOME_TOOLS, tool_choice="required")
        call = reply.choices[0].message.tool_calls[0]
        print(f"    {command:<50} -> {call.function.name}({call.function.arguments})")


def stream_answer():
    """Stream the sentence the model writes from a tool's result."""
    messages = [
        {"role": "system", "content": SHOP_SYSTEM},
        {"role": "user", "content": "Where is my order 48213?"},
        {"role": "assistant", "content": None, "tool_calls": [{"id": "call_1", "type": "function", "function": {
            "name": "get_order", "arguments": "{\"order_id\": \"48213\"}"}}]},
        {"role": "tool", "tool_call_id": "call_1", "content": json.dumps(
            {"order_id": "48213", "status": "in transit", "carrier": "DHL", "expected_delivery": "2026-12-04"})},
    ]
    stream = client.chat.completions.create(model="nenya", messages=messages, tools=SHOP_TOOLS, stream=True)
    print("    ", end="")
    for chunk in stream:
        if chunk.choices:
            print(chunk.choices[0].delta.content or "", end="", flush=True)
    print()


RECIPES = [classify_ticket, classify_with_descriptions, classify_yes_no, classify_none, classify_several_labels,
           extract_invoice, extract_email, extract_ticket, tools_agent, tools_limit, tools_not_found, tools_how_sure,
           tools_parallel, tools_router, stream_answer]


def main():
    args = sys.argv[1:]
    out = None
    if "--json" in args:
        i = args.index("--json")
        out = args[i + 1]
        del args[i:i + 2]
    for recipe in RECIPES:
        if args and not any(recipe.__name__.startswith(a) for a in args):
            continue
        print(f"\n{recipe.__name__}: {recipe.__doc__.splitlines()[0]}")
        recipe()
    if out:
        with open(out, "w") as f:
            json.dump(LOG, f, indent=1)


if __name__ == "__main__":
    main()
