A stand-in model: a function that answers like one
A real model needs an API key and charges for every call. For learning, a function that answers the same way is better: free, instant, and easy to read.
A model asked to sort a ticket as JSON sends back a string. Usually it is the JSON you asked for. Sometimes it is a polite sentence instead. The stand-in does both:
def ask_model(ticket_text):
text = ticket_text.lower()
if "charged" in text or "refund" in text:
return '{"category": "billing", "priority": 4}'
if "parcel" in text or "arrived" in text:
return '{"category": "shipping", "priority": 3}'
return "I am not sure how to sort this one."
print(ask_model("I was charged twice for one order"))
print(ask_model("How do I change my password?"))It returns strings, not dictionaries, because that is what arrives from a real model: text, which your program then has to read. It decides from the words in the ticket, so a different ticket really does get a different answer.
Asking about every ticket
import json
with open("tickets.json") as f:
tickets = json.load(f)
for ticket in tickets:
answer = ask_model(ticket["text"])
print(ticket["id"], answer)Four answers are JSON and ticket 4's is not. That is not a flaw in the stand-in. Real models do this too, which is why a program that trusts every answer eventually breaks.
Where it breaks
for ticket in tickets:
data = json.loads(ask_model(ticket["text"]))
print(ticket["id"], data["category"])Tickets 1 to 3 print, then ticket 4's sentence reaches json.loads and the whole program stops. Ticket 5 is never sorted. The next lesson keeps the program running.
- Add a branch for
"password"that returns{"category": "other", "priority": 2}as JSON text, and run the loop that broke. - Make it return
'{"category": "billing", "priority": "high"}'for refunds. It parses; is it still right? Lesson 24 comes back to this. - Print
type(ask_model("refund")).
You understood something today that you didn't yesterday.