קריאה למודל שפה מ-PythonCalling a language model from Python
מפגש 33: API של מודל שפה, מפתחות, פרומפטים, עלויות ובטיחות.Session 33: A language-model API, keys, prompts, cost and safety.
API של מודל שפה, מפתחות, פרומפטים, עלויות ובטיחות. בסוף המפגש מוסיפים צעד לפרויקט המלווה.A language-model API, keys, prompts, cost and safety. At the end we add a step to the companion project.
מה נעשה היוםToday's plan
איךHow
מפתחKey
שיחהConversation
JSONJSON
עלותCost
SDKSDK
עוברים על סדר היום ומזכירים את הפרויקט המלווה.Walk through the plan and mention the companion project.
נושאTopic 1
איךHow
מה קורה כשקוראים למודלWhat happens when you call a model
בקשת POST עם JSON, כמו במפגש 22A POST request with JSON, like session 22
שולחים הודעות, מקבלים הודעהSend messages, get a message back
מודל שפה כמו Claude הוא API כמו כל API אחר: שולחים בקשת POST עם JSON שמכיל את ההודעות, ומקבלים JSON עם התשובה. אין קסם: אותו requests ממפגש 22. התשובה מגיעה ברשימה content, יחד עם מספר הטוקנים שנספרו. כמו קודם: באתר אין אינטרנט בזמן הבנייה, ולכן התשובות כאן הוקלטו מראש. אצלכם, עם מפתח אמיתי, תקבלו תשובה חיה (וכנראה מנוסחת אחרת).A language model like Claude is an API like any other: send a POST request with JSON holding the messages, get JSON with the answer. No magic: the same requests as session 22. The answer arrives in a content list, with the number of tokens counted. As before: the site has no internet at build time, so replies here were recorded in advance. On your machine, with a real key, you'll get a live answer (probably worded differently).
אנלוגיהAnalogy
לקרוא למודל זה כמו לשלוח מכתב לחבר חכם מאוד: מה שתכתבו במכתב הוא כל מה שהוא יודע על המצב, והתשובה חוזרת במעטפה.Calling a model is like posting a letter to a very clever friend: what you write is all they know about the situation, and the answer comes back in an envelope.
שואלים אם מישהו מכיר דוגמה נוספת מהחיים.Ask for another real-life example.
נושאTopic 2
מפתחKey
מפתח API ומשתני סביבהAPI keys and environment variables
מפתח = כסף. לא בקוד, לא ב-GitA key = money. Not in code, not in Git
קובץ .env שמופיע ב-.gitignoreA .env file listed in .gitignore
מפתח API מאפשר למי שמחזיק בו לבצע בקשות על חשבונכם. לכן הוא לא נכתב בקוד ולא נכנס ל-Git (מפגש 20). שומרים אותו במשתנה סביבה, וקוראים עם os.environ. כשהמפתח חסר, עוצרים מוקדם עם הודעה ברורה:An API key lets whoever holds it make requests on your account. So it isn't written in code and never enters Git (session 20). Keep it in an environment variable and read it with os.environ. When it's missing, stop early with a clear message:
אנלוגיהAnalogy
מפתח API הוא כמו כרטיס אשראי: לא מצלמים אותו ולא שולחים בקבוצה. אם דלף, מבטלים ומוציאים חדש.An API key is like a credit card: you don't photograph it or post it in a group chat. If it leaks, cancel it and get a new one.
שואלים אם מישהו מכיר דוגמה נוספת מהחיים.Ask for another real-life example.
טעות נפוצהCommon mistake
keys.py
import os
os.environ.pop("ANTHROPIC_API_KEY", None)
key = os.environ["ANTHROPIC_API_KEY"]
מה Python עונהWhat Python says
KeyError: 'ANTHROPIC_API_KEY'
KeyError: 'ANTHROPIC_API_KEY': המשתנה לא מוגדר בטרמינל הזה. מגדירים אותו (ובוינדוס פותחים טרמינל חדש אחרי setx), או משתמשים ב-.get עם הודעה ברורה.KeyError: 'ANTHROPIC_API_KEY': the variable isn't set in this terminal. Set it (and on Windows open a new terminal after setx), or use .get with a clear message.
קוראים מפתח שלא הוגדר עם סוגריים מרובעים.Reading an unset key with square brackets.
messages: כל ההיסטוריה, בכל בקשהmessages: the full history, every request
המודל לא זוכר בין בקשותThe model doesn't remember between requests
ההנחיה הכללית (system) קובעת תפקיד וסגנון לכל השיחה. ודבר חשוב: המודל לא זוכר בקשות קודמות. כדי לנהל שיחה, שולחים בכל פעם את כל ההיסטוריה ברשימת messages, עם תפקידים user ו-assistant לסירוגין. מחלקה קטנה עושה את זה בשבילנו:The general instruction (system) sets a role and style for the whole conversation. And an important point: the model doesn't remember earlier requests. To hold a conversation, send the full history every time in the messages list, with user and assistant roles alternating. A small class does it for us:
אנלוגיהAnalogy
המודל הוא כמו מישהו בלי זיכרון לטווח קצר: בכל שיחת טלפון מקריאים לו את כל מה שנאמר עד עכשיו, ואז הוא עונה.The model is like someone with no short-term memory: on every call you read out everything said so far, then they answer.
שואלים אם מישהו מכיר דוגמה נוספת מהחיים.Ask for another real-life example.
נושאTopic 4
JSONJSON
לבקש JSON ולבדוקAsk for JSON and validate
מבקשים בפירוש: "רק JSON עם השדות..."Ask explicitly: "only JSON with the fields..."
json.loads בתוך tryjson.loads inside try
בודקים שדות לפני שמשתמשיםCheck fields before use
כדי שתוכנה תשתמש בתשובה, מבקשים פורמט מובנה: "ענה רק ב-JSON עם title, author, why". אבל מודל עלול להחזיר טקסט נוסף, שדה חסר או פורמט שבור, ולכן מתייחסים לתשובה כמו לקלט של משתמש: מפרקים בתוך try ובודקים כל שדה (pydantic ממפגש 29 מצוין לזה).For software to use the answer, ask for a structured format: "answer only in JSON with title, author, why". But a model may return extra text, a missing field or broken formatting, so treat the answer like user input: parse inside try and check every field (pydantic from session 29 is great for this).
אנלוגיהAnalogy
לבדוק JSON ממודל זה כמו לבדוק משלוח לפני שחותמים: לרוב הכול בסדר, אבל פותחים את הקופסה בכל זאת.Validating a model's JSON is like checking a delivery before signing: usually it's fine, but you open the box anyway.
שואלים אם מישהו מכיר דוגמה נוספת מהחיים.Ask for another real-life example.
נושאTopic 5
עלותCost
עלות, מגבלות ושגיאותCost, limits and errors
usage: טוקנים נכנסים ויוצאיםusage: input and output tokens
max_tokens מגביל את אורך התשובהmax_tokens caps the answer length
429 / 529: מנסים שוב אחרי המתנה429 / 529: retry after a wait
כל בקשה נמדדת בטוקנים, וכל טוקן עולה כסף. השדה usage בתשובה אומר כמה נספרו, ו-max_tokens מגביל את אורך התשובה. שירותים עמוסים עונים לפעמים 429 (יותר מדי בקשות) או 529 (עומס), ואז מחכים ומנסים שוב, כמו ב-retry ממפגש 22. כדאי גם לשמור מטמון: אותה שאלה בדיוק לא צריכה להישלח פעמיים.Every request is measured in tokens, and every token costs money. The reply's usage field says how many were counted, and max_tokens caps the answer's length. Busy services sometimes answer 429 (too many requests) or 529 (overloaded); then wait and retry, like the retry from session 22. It's also worth caching: the exact same question needn't be sent twice.
אנלוגיהAnalogy
טוקנים הם כמו דקות שיחה בחבילה של פעם: כל מילה עולה משהו, ולכן כדאי לשאול בקיצור ולא לחזור על אותה שאלה.Tokens are like minutes on an old phone plan: every word costs something, so ask concisely and don't repeat the same question.
שואלים אם מישהו מכיר דוגמה נוספת מהחיים.Ask for another real-life example.
ניסיונות חוזרים ושגיאות מסודרות מובניםRetries and tidy errors built in
בפרויקטים אמיתיים משתמשים ב-SDK הרשמי, ספרייה שעוטפת את ה-API. הוא קורא את המפתח ממשתנה הסביבה לבד, מנסה שוב כשהשרת עמוס, וזורק שגיאות עם שמות ברורים. מה שבנינו ביד עם requests הוא בדיוק מה שהוא עושה מאחורי הקלעים, אז עכשיו אתם יודעים מה קורה שם. הקוד הזה רץ על המחשב שלכם עם מפתח אמיתי:Real projects use the official SDK, a library wrapping the API. It reads the key from the environment variable by itself, retries when the server is busy, and raises errors with clear names. What we built by hand with requests is exactly what it does behind the scenes, so now you know what's going on there. This code runs on your computer with a real key:
אנלוגיהAnalogy
SDK הוא כמו שלט אוניברסלי מקורי: אותם ערוצים שהיה אפשר להחליף ביד בטלוויזיה, רק נוח ובטוח יותר.An SDK is like the original remote control: the same channels you could change by hand on the TV, just more convenient and safer.
שואלים אם מישהו מכיר דוגמה נוספת מהחיים.Ask for another real-life example.
בקשת POST עם JSON, כמו במפגש 22A POST request with JSON, like session 22
מה קורה כשקוראים למודלWhat happens when you call a model
שולחים הודעות, מקבלים הודעהSend messages, get a message back
מה קורה כשקוראים למודלWhat happens when you call a model