קריאה למודל שפה מ-PythonCalling a language model from Python
API של מודל שפה, מפתחות, פרומפטים, עלויות ובטיחות.
A language-model API, keys, prompts, cost and safety.
כותבים בעורך שבכל תרגיל, לוחצים הרצה כדי לראות פלט, ובדיקה כדי שהבודק האוטומטי יבדוק. אפשר גם לעבוד ב-VS Code. ההתקדמות נשמרת.Write in each exercise's editor, press Run to see output and Check for the automatic checker. You can also work in VS Code. Progress is saved.
חימום: 3 שאלותWarm-up: 3 questions
תרגיליםExercises
תרגילExercise 1
לבנות בקשהBuilding a request
כתבו 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.
איך הפלט אמור להיראות?What should the output look like?
כתבו 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.
איך הפלט אמור להיראות?What should the output look like?
Try Emma. 0.006
main.py
רמזHint 1:"".join(c["text"] for c in reply["content"] if c.get("type") == "text")"".join(c["text"] for c in reply["content"] if c.get("type") == "text")
כתבו מחלקה 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.
איך הפלט אמור להיראות?What should the output look like?
['user', 'assistant'] Hi
I liked Dune
main.py
רמזHint 1:בודקים את ההודעה האחרונה: if self.messages and self.messages[-1]["role"] == "user".Check the last message: if self.messages and self.messages[-1]["role"] == "user".
רמזHint 2:ב-body מעבירים עותק: list(self.messages).In body pass a copy: list(self.messages).
כתבו 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.
איך הפלט אמור להיראות?What should the output look like?
מדף, צעד 33: המלצה לספר הבאShelf, step 33: recommending the next book
פרויקט מלווהCompanion project
כתבו 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.
איך הפלט אמור להיראות?What should the output look like?
{'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
רמזHint 2:בדיקה: data["title"].lower() in {b["title"].lower() for b in shelf} → שגיאה.Check: data["title"].lower() in {b["title"].lower() for b in shelf} → error.
שיחות ארוכות יקרות. כתבו 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.
איך הפלט אמור להיראות?What should the output look like?
['zzz', 'ok', 'and']
main.py
רמזHint 1:עוברים מהסוף להתחלה וסוכמים.Walk from the end to the start, summing.
רמזHint 2:אחרי החיתוך: while kept and kept[0]["role"] != "user": kept.pop(0).After cutting: while kept and kept[0]["role"] != "user": kept.pop(0).
כתבו מחלקה 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).
איך הפלט אמור להיראות?What should the output look like?
Hi there!
{"title": "Emma",
I don't know 3 weather?
main.py
רמזHint 1:__call__ הופך אובייקט לפונקציה: model("hi").__call__ makes an object callable: model("hi").
רמזHint 2:next((a for k, a in self.rules if k.lower() in p), default)next((a for k, a in self.rules if k.lower() in p), default)