נבנה על ידיBuilt by Ariel Yohimovich

PythonPython
33
חלקPart 6: Python בעידן ה-AI וקריירהPython in the AI era & career כ-3 שעות (כולל הפסקה)About 3 hours (with a break)

קריאה למודל שפה מ-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

1. איפה שומרים מפתח API?Where do you keep an API key?

2. למה שולחים את כל ההיסטוריה בכל בקשה?Why send the full history with every request?

3. מה עושים עם JSON שמודל החזיר?What do you do with JSON a model returned?

תרגילים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?
{'model': 'claude-sonnet-5-5', 'max_tokens': 50, 'messages': [{'role': 'user', 'content': 'Hi'}], 'system': 'Be brief'}
main.py
רמזHint 1: בונים מילון ואז if system: body["system"] = system.Build the dict then if system: body["system"] = system.
רמזHint 2: [{"role": "user", "content": prompt}][{"role": "user", "content": prompt}]
לפתרוןSolution
תרגילExercise 2

לחלץ טקסט מתשובהExtracting text from a reply

כתבו 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")
רמזHint 2: u = reply["usage"]u = reply["usage"]
לפתרוןSolution
תרגילExercise 3

שיחהA conversation

כתבו מחלקה 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).
לפתרוןSolution
תרגילExercise 4

JSON בטוחSafe JSON

כתבו 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?
{'title': 'Emma', 'author': 'Jane Austen', 'why': 'Sharp and funny.'}
None None
main.py
רמזHint 1: start, end = text.find("{"), text.rfind("}")start, end = text.find("{"), text.rfind("}")
רמזHint 2: all(isinstance(d.get(k), str) and d[k].strip() for k in KEYS)all(isinstance(d.get(k), str) and d[k].strip() for k in KEYS)
לפתרוןSolution
תרגילExercise 5

מדף, צעד 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
recommend.py
רמזHint 1: top = sorted(shelf, key=lambda b: -b.get("rating", 0))[:5]top = sorted(shelf, key=lambda b: -b.get("rating", 0))[:5]
רמז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.
לפתרוןSolution

אתגרים לחזקיםChallenges for the brave

אתגרChallenge 1

חותך היסטוריהA history trimmer

שיחות ארוכות יקרות. כתבו 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).
לפתרוןSolution
אתגרChallenge 2

מודל מזויף לבדיקותA fake model for tests

כתבו מחלקה 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)
לפתרוןSolution

נבנה על ידיBuilt by Ariel Yohimovich