קריאה למודל שפה מ-PythonCalling a language model from Python
API של מודל שפה, מפתחות, פרומפטים, עלויות ובטיחות.
A language-model API, keys, prompts, cost and safety.
לבנות בקשהBuilding a request
תזכורת: מה ביקשוReminder: the task
כתבו build_request(prompt, system="", max_tokens=300) שמחזירה את גוף הבקשה כמילון: model (claude-sonnet-5-5), max_tokens, messages עם הודעת user אחת, ו-system רק אם הוא לא ריק.
Write build_request(prompt, system="", max_tokens=300) returning the request body as a dict: model (claude-sonnet-5-5), max_tokens, messages with one user message, and system only if it isn't empty.
הפתרון המלא והפלט שלוFull solution and its output
def build_request(prompt, system="", max_tokens=300):
body = {"model": "claude-sonnet-5-5", "max_tokens": max_tokens, "messages": [{"role": "user", "content": prompt}]}
if system:
body["system"] = system
return body
print(build_request("Hi", system="Be brief", max_tokens=50)){'model': 'claude-sonnet-5-5', 'max_tokens': 50, 'messages': [{'role': 'user', 'content': 'Hi'}], 'system': 'Be brief'}יש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.
לחלץ טקסט מתשובהExtracting text from a reply
תזכורת: מה ביקשוReminder: the task
כתבו reply_text(reply) שמקבלת תשובת API (מילון) ומחזירה את כל קטעי הטקסט מ-content מחוברים (רק פריטים עם type == "text"), ו-token_cost(reply, price_in, price_out) שמחזירה עלות לפי usage (מחיר למיליון טוקנים), מעוגלת ל-6.
Write reply_text(reply) taking an API reply (a dict) and returning all text pieces from content joined (only items with type == "text"), and token_cost(reply, price_in, price_out) returning the cost from usage (price per million tokens), rounded to 6.
הפתרון המלא והפלט שלוFull solution and its output
def reply_text(reply):
return "".join(c["text"] for c in reply.get("content", []) if c.get("type") == "text")
def token_cost(reply, price_in, price_out):
u = reply["usage"]
return round(u["input_tokens"] / 1e6 * price_in + u["output_tokens"] / 1e6 * price_out, 6)
reply = {"content": [{"type": "text", "text": "Try "}, {"type": "text", "text": "Emma."}], "usage": {"input_tokens": 1000, "output_tokens": 200}}
print(reply_text(reply), token_cost(reply, 3, 15))Try Emma. 0.006
יש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.
שיחהA conversation
תזכורת: מה ביקשוReminder: the task
כתבו מחלקה Conversation(system) עם add_user(text), add_assistant(text) ו-body() שמחזירה גוף בקשה עם כל ההודעות. add_user פעמיים ברצף מאחד את הטקסטים להודעה אחת (מופרדים בירידת שורה), כדי שהתפקידים יתחלפו תמיד.
Write a Conversation(system) class with add_user(text), add_assistant(text) and body() returning a request body with all messages. Calling add_user twice in a row merges the texts into one message (joined by a newline), so roles always alternate.
הפתרון המלא והפלט שלוFull solution and its output
class Conversation:
def __init__(self, system):
self.system = system
self.messages = []
def _add(self, role, text):
if self.messages and self.messages[-1]["role"] == role:
self.messages[-1]["content"] += "\n" + text
else:
self.messages.append({"role": role, "content": text})
def add_user(self, text):
self._add("user", text)
def add_assistant(self, text):
self._add("assistant", text)
def body(self):
return {"model": "claude-sonnet-5-5", "max_tokens": 300, "system": self.system, "messages": list(self.messages)}
c = Conversation("You are a librarian.")
c.add_user("Hi")
c.add_user("I liked Dune")
c.add_assistant("Try Emma.")
print([m["role"] for m in c.body()["messages"]], c.body()["messages"][0]["content"])['user', 'assistant'] Hi I liked Dune
יש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.
JSON בטוחSafe JSON
תזכורת: מה ביקשוReminder: the task
כתבו parse_book(text) שמקבלת את הטקסט שהמודל החזיר ומחזירה מילון {title, author, why} או None. היא מתמודדת עם טקסט לפני ואחרי ה-JSON (חותכים מה-{ הראשון עד ה-} האחרון), עם JSON שבור, ועם שדה חסר או ריק.
Write parse_book(text) taking the text the model returned and returning a dict {title, author, why} or None. It handles text before and after the JSON (cut from the first { to the last }), broken JSON, and a missing or empty field.
הפתרון המלא והפלט שלוFull solution and its output
import json
KEYS = ("title", "author", "why")
def parse_book(text):
start, end = text.find("{"), text.rfind("}")
if start < 0 or end < start:
return None
try:
d = json.loads(text[start:end + 1])
except json.JSONDecodeError:
return None
if not isinstance(d, dict) or not all(isinstance(d.get(k), str) and d[k].strip() for k in KEYS):
return None
return {k: d[k].strip() for k in KEYS}
print(parse_book('Sure! {"title": "Emma", "author": "Jane Austen", "why": "Sharp and funny."} Enjoy!'))
print(parse_book('{"title": "Emma"}'), parse_book("no json here")){'title': 'Emma', 'author': 'Jane Austen', 'why': 'Sharp and funny.'}
None Noneיש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.
מדף, צעד 33: המלצה לספר הבאShelf, step 33: recommending the next book
תזכורת: מה ביקשוReminder: the task
כתבו recommend(shelf, ask) ש-ask(prompt) שלה מחזירה את טקסט התשובה של המודל. היא בונה בקשה עם עד 5 הספרים בעלי הדירוג הגבוה ביותר (כותרת וסופר בלבד, כדי לחסוך טוקנים), מבקשת JSON, ומחזירה מילון ממוין עם המלצה, או {"error": "bad reply"}. ההמלצה לא יכולה להיות ספר שכבר במדף.
Write recommend(shelf, ask) whose ask(prompt) returns the model's reply text. It builds a prompt with up to the 5 top-rated books (title and author only, to save tokens), asks for JSON, and returns a dict with the recommendation, or {"error": "bad reply"}. The recommendation can't be a book already on the shelf.
הפתרון המלא והפלט שלוFull solution and its output
import json
def build_prompt(shelf):
top = sorted(shelf, key=lambda b: -b.get("rating", 0))[:5]
liked = "; ".join(f'{b["title"]} by {b["author"]}' for b in top)
return f"I liked: {liked}. Recommend one book I have not read. Reply with only JSON with keys title, author, why."
def recommend(shelf, ask):
text = ask(build_prompt(shelf))
try:
data = json.loads(text[text.find("{"):text.rfind("}") + 1])
except json.JSONDecodeError:
return {"error": "bad reply"}
if not all(isinstance(data.get(k), str) and data[k] for k in ("title", "author", "why")):
return {"error": "bad reply"}
if data["title"].lower() in {b["title"].lower() for b in shelf}:
return {"error": "bad reply"}
return {k: data[k] for k in ("title", "author", "why")}
shelf = [{"title": "Dune", "author": "Frank Herbert", "rating": 5}, {"title": "The Hobbit", "author": "J. R. R. Tolkien", "rating": 5}, {"title": "Emma", "author": "Jane Austen", "rating": 3}]
recorded = '{"title": "The Left Hand of Darkness", "author": "Ursula K. Le Guin", "why": "Thoughtful science fiction about politics and identity, like Dune."}'
print(recommend(shelf, lambda prompt: recorded))
print(recommend(shelf, lambda prompt: '{"title": "dune", "author": "x", "why": "y"}'))
print(build_prompt(shelf)[:60]){'title': 'The Left Hand of Darkness', 'author': 'Ursula K. Le Guin', 'why': 'Thoughtful science fiction about politics and identity, like Dune.'}
{'error': 'bad reply'}
I liked: Dune by Frank Herbert; The Hobbit by J. R. R. Tolkiיש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.
חותך היסטוריהA history trimmer
תזכורת: מה ביקשוReminder: the task
שיחות ארוכות יקרות. כתבו trim(messages, budget) שמחזירה את הסיומת הארוכה ביותר של ההיסטוריה שסך הטוקנים המשוער שלה (len(content) // 4 + 1 להודעה) לא עובר את budget, ושתמיד מתחילה בהודעת user (אם צריך, משמיטים עוד הודעה מההתחלה). אם גם ההודעה האחרונה לבד עוברת, מחזירים רק אותה.
Long conversations are expensive. Write trim(messages, budget) returning the longest suffix of the history whose estimated tokens (len(content) // 4 + 1 per message) stay within budget, and which always starts with a user message (drop one more from the start if needed). If even the last message alone exceeds it, return just that one.
הפתרון המלא והפלט שלוFull solution and its output
def cost(m):
return len(m["content"]) // 4 + 1
def trim(messages, budget):
if not messages:
return []
kept, total = [], 0
for m in reversed(messages):
if total + cost(m) > budget:
break
kept.insert(0, m)
total += cost(m)
while kept and kept[0]["role"] != "user":
kept.pop(0)
return kept or [messages[-1]]
history = [{"role": "user", "content": "x" * 40}, {"role": "assistant", "content": "y" * 40}, {"role": "user", "content": "z" * 20}, {"role": "assistant", "content": "ok"}, {"role": "user", "content": "and now?"}]
print([m["content"][:3] for m in trim(history, 20)])['zzz', 'ok', 'and']
יש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.
מודל מזויף לבדיקותA fake model for tests
תזכורת: מה ביקשוReminder: the task
כתבו מחלקה FakeModel(rules) שמשמשת בבדיקות במקום API אמיתי: rules היא רשימת זוגות (מילת מפתח, תשובה). __call__(prompt) מחזירה את התשובה של הכלל הראשון שמילת המפתח שלו מופיעה ב-prompt (בלי רגישות לאותיות), או "I don't know". היא גם סופרת קריאות (calls) וזוכרת את הבקשה האחרונה (last).
Write a FakeModel(rules) class used in tests instead of a real API: rules is a list of pairs (keyword, answer). __call__(prompt) returns the answer of the first rule whose keyword appears in the prompt (case-insensitive), or "I don't know". It also counts calls (calls) and remembers the last prompt (last).
הפתרון המלא והפלט שלוFull solution and its output
class FakeModel:
def __init__(self, rules):
self.rules = rules
self.calls = 0
self.last = None
def __call__(self, prompt):
self.calls += 1
self.last = prompt
p = prompt.lower()
return next((answer for key, answer in self.rules if key.lower() in p), "I don't know")
model = FakeModel([("recommend", '{"title": "Emma", "author": "Jane Austen", "why": "Witty."}'), ("hello", "Hi there!")])
print(model("HELLO model"))
print(model("Please RECOMMEND a book")[:17])
print(model("weather?"), model.calls, model.last)Hi there!
{"title": "Emma",
I don't know 3 weather?יש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.