Project: Chat With It
A small support app.
A model on its own isn't a product. Let's wrap it in a small app, that reads customer messages, and routes each one to the right team.
- A model isn't a product
- Wrap it in an app
- Route each message
A support app
Here's the app. It loads our merged model. Then it keeps reading messages, until you type quit. For each one, it asks the model, and parses the JSON. If the intent is one of our five, it routes the message to that team. If not, it sends it to a person. Run it. Orders and complaints go to the right teams. The reserve message gets an invented intent, so it goes to a person. And so does a question about opening times.
import json
from transformers import AutoTokenizer, AutoModelForCausalLM
from ask import ask
from chat import INTENTS
tok = AutoTokenizer.from_pretrained("riverside-tickets")
model = AutoModelForCausalLM.from_pretrained("riverside-tickets")
print("Riverside Books support. Type quit to stop.")
while (message := input("> ")) != "quit":
try:
answer = json.loads(ask(model, tok, message))
except json.JSONDecodeError:
answer = {}
if answer.get("intent") in INTENTS:
print(f" route to {answer['intent']} team, book: {answer.get('book')}")
else:
print(" not sure, send to a person:", answer)Riverside Books support. Type quit to stop.
> Where is my copy of Rebecca?
route to order_status team, book: Rebecca
> Hi, Can I reserve a copy of Dune?
not sure, send to a person: {'intent': 'reserve_copy', 'book': 'Dune'}
> The Hobbit arrived with torn pages!
route to complaint team, book: The Hobbit
> What time do you open on Sunday?
not sure, send to a person: {'intent': 'time', 'book': 'Sunday'}
> quitAlso uses _setup.py
import shutil
shutil.copytree('/Users/hussain/Docker Complete Course/shared-data/ft_cache/riverside-tickets', 'riverside-tickets')Also uses chat.py
import json
from datasets import load_dataset
INTENTS = ["order_status", "return", "price", "stock", "complaint"]
SYSTEM = ("Read the customer's message. Reply with JSON: the intent and the book. "
"The intent must be one of: " + ", ".join(INTENTS) + ".")
def to_example(row):
answer = json.dumps({"intent": row["intent"], "book": row["book"]})
return {"prompt": [{"role": "system", "content": SYSTEM},
{"role": "user", "content": row["message"]}],
"completion": [{"role": "assistant", "content": answer}]}
data = load_dataset("json", data_files={"train": "tickets_train.jsonl",
"test": "tickets_test.jsonl"})
data = data.map(to_example, remove_columns=["message", "intent", "book"])Also uses ask.py
from chat import SYSTEM
def ask(model, tok, message):
model.eval() # switch off training-only behaviour
messages = [{"role": "system", "content": SYSTEM}, {"role": "user", "content": message}]
ids = tok.apply_chat_template(messages, add_generation_prompt=True,
return_dict=True, return_tensors="pt")
out = model.generate(**ids, max_new_tokens=30, do_sample=False)
return tok.decode(out[0][ids["input_ids"].shape[1]:], skip_special_tokens=True)Also uses score.py
import json
from ask import ask
def score(model, tok, rows):
valid = correct = 0
for row in rows:
reply = ask(model, tok, row["message"])
try:
answer = json.loads(reply)
except json.JSONDecodeError:
continue # not JSON: neither valid nor correct
if not isinstance(answer, dict):
continue # JSON, but not an object
valid += 1
if answer.get("intent") == row["intent"] and answer.get("book") == row["book"]:
correct += 1
n = len(rows)
return {"valid_json": f"{valid / n:.0%}", "correct": f"{correct / n:.0%}"}Why the safety check matters
That last check is the most important line in the app. Models make mistakes, and sometimes invent things. Code that checks the output, and has a safe fallback, turns a ninety seven percent model into a system you can trust.
| key | value |
|---|---|
| Models | sometimes invent |
| Check | validate every answer |
| Fallback | a person |
| Result | a system you can trust |
Summary
Let's recap. Wrap the model in a small app. Parse, and validate, every answer. And send anything uncertain to a person. Next, we wrap up the project.
Key takeaways- Load the merged model
- Validate every answer
- Fallback to a person