נבנה על ידי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.

01מה קורה כשקוראים למודלWhat happens when you call a model

מודל שפה כמו 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).

llm.py
import os
import requests

API_URL = "https://api.anthropic.com/v1/messages"


def ask(prompt, system="", max_tokens=300):
    r = requests.post(
        API_URL,
        headers={
            "x-api-key": os.environ.get("ANTHROPIC_API_KEY", "demo-key"),
            "anthropic-version": "2023-06-01",
            "content-type": "application/json",
        },
        json={
            "model": "claude-sonnet-5-5",
            "max_tokens": max_tokens,
            "system": system,
            "messages": [{"role": "user", "content": prompt}],
        },
        timeout=30,
    )
    r.raise_for_status()
    return r.json()
first_call.py
import os
import requests

API_URL = "https://api.anthropic.com/v1/messages"


def ask(prompt, system="", max_tokens=300):
    r = requests.post(
        API_URL,
        headers={
            "x-api-key": os.environ.get("ANTHROPIC_API_KEY", "demo-key"),
            "anthropic-version": "2023-06-01",
            "content-type": "application/json",
        },
        json={
            "model": "claude-sonnet-5-5",
            "max_tokens": max_tokens,
            "system": system,
            "messages": [{"role": "user", "content": prompt}],
        },
        timeout=30,
    )
    r.raise_for_status()
    return r.json()

reply = ask("Say hello to a new reader in one sentence.")
print(reply["content"][0]["text"])
print(reply["usage"], reply["stop_reason"])
פלט (תשובת השרת הוקלטה מראש)Output (server reply recorded in advance)
Hello! How can I help with your reading list today?
{'input_tokens': 31, 'output_tokens': 12} end_turn
אנלוגיה מהחייםReal-life 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.

טעות נפוצהCommon mistake

שולחים בקשה בלי מפתח.

Sending a request without a key.

first_call.py
import os
import requests

API_URL = "https://api.anthropic.com/v1/messages"


def ask(prompt, system="", max_tokens=300):
    r = requests.post(
        API_URL,
        headers={
            "x-api-key": "missing",
            "anthropic-version": "2023-06-01",
            "content-type": "application/json",
        },
        json={
            "model": "claude-sonnet-5-5",
            "max_tokens": max_tokens,
            "system": system,
            "messages": [{"role": "user", "content": prompt}],
        },
        timeout=30,
    )
    r.raise_for_status()
    return r.json()

ask("hi")
מה Python עונהWhat Python says
Traceback (most recent call last):
  File "/Users/you/python-course/first_call.py", line 26, in <module>
    ask("hi")
    ~~~^^^^^^
  File "/Users/you/python-course/first_call.py", line 23, in ask
    r.raise_for_status()
    ~~~~~~~~~~~~~~~~~~^^
  File "/usr/local/lib/python3.13/site-packages/requests/models.py", line 1167, in raise_for_status
    raise HTTPError(http_error_msg, response=self)
requests.exceptions.HTTPError: 401 Client Error: Unauthorized for url: https://api.anthropic.com/v1/messages
בעברית פשוטה: In plain words: requests.exceptions.HTTPError: 401 Client Error: Unauthorized for url: https://api.anthropic.com/v1/messages: המפתח חסר או שגוי. בודקים את משתנה הסביבה.requests.exceptions.HTTPError: 401 Client Error: Unauthorized for url: https://api.anthropic.com/v1/messages: the key is missing or wrong. Check the environment variable.

02מפתח API ומשתני סביבהAPI keys and environment variables

מפתח 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:

Terminal
export ANTHROPIC_API_KEY="sk-ant-..."      # Mac / Linux
setx ANTHROPIC_API_KEY "sk-ant-..."         # Windows (open a new terminal after)
keys.py
import os

def get_key(name="ANTHROPIC_API_KEY"):
    key = os.environ.get(name, "").strip()
    if not key:
        raise SystemExit(f"{name} is not set. Create a key in the console, then: export {name}=...")
    return key

os.environ["ANTHROPIC_API_KEY"] = "sk-ant-demo-1234"
key = get_key()
print("key found:", key[:7] + "..." + key[-4:])
פלטOutput
key found: sk-ant-...1234
אנלוגיה מהחייםReal-life 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.

טעות נפוצהCommon mistake

קוראים מפתח שלא הוגדר עם סוגריים מרובעים.

Reading an unset key with square brackets.

keys.py
import os
os.environ.pop("ANTHROPIC_API_KEY", None)
key = os.environ["ANTHROPIC_API_KEY"]
מה Python עונהWhat Python says
Traceback (most recent call last):
  File "/Users/you/python-course/keys.py", line 3, in <module>
    key = os.environ["ANTHROPIC_API_KEY"]
          ~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^
  File "<frozen os>", line 717, in __getitem__
KeyError: 'ANTHROPIC_API_KEY'
בעברית פשוטה: In plain words: 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.

03הנחיות ושיחהInstructions and conversation

ההנחיה הכללית (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:

chat.py
import os
import requests

API_URL = "https://api.anthropic.com/v1/messages"


def ask(prompt, system="", max_tokens=300):
    r = requests.post(
        API_URL,
        headers={
            "x-api-key": os.environ.get("ANTHROPIC_API_KEY", "demo-key"),
            "anthropic-version": "2023-06-01",
            "content-type": "application/json",
        },
        json={
            "model": "claude-sonnet-5-5",
            "max_tokens": max_tokens,
            "system": system,
            "messages": [{"role": "user", "content": prompt}],
        },
        timeout=30,
    )
    r.raise_for_status()
    return r.json()


class Chat:
    def __init__(self, system):
        self.system = system
        self.messages = []

    def say(self, text):
        self.messages.append({"role": "user", "content": text})
        r = requests.post(API_URL, headers={"x-api-key": "demo-key", "anthropic-version": "2023-06-01"},
                          json={"model": "claude-sonnet-5-5", "max_tokens": 300, "system": self.system, "messages": self.messages}, timeout=30)
        answer = r.json()["content"][0]["text"]
        self.messages.append({"role": "assistant", "content": answer})
        return answer

chat = Chat(system="You are a friendly librarian. Answer in one or two sentences.")
print(chat.say("I loved Dune and The Hobbit. Can you recommend my next book?"))
print(len(chat.messages), [m["role"] for m in chat.messages])
פלט (תשובת השרת הוקלטה מראש)Output (server reply recorded in advance)
Since you enjoyed Dune and The Hobbit, try The Left Hand of Darkness by Ursula K. Le Guin: a thoughtful science-fiction world with politics and a long journey across ice.
2 ['user', 'assistant']
אנלוגיה מהחייםReal-life analogy

המודל הוא כמו מישהו בלי זיכרון לטווח קצר: בכל שיחת טלפון מקריאים לו את כל מה שנאמר עד עכשיו, ואז הוא עונה.

The model is like someone with no short-term memory: on every call you read out everything said so far, then they answer.

טעות נפוצהCommon mistake

שתי הודעות user ברצף.

Two user messages in a row.

chat.py
messages = [{"role": "user", "content": "hi"}, {"role": "user", "content": "recommend a book"}]
roles = [m["role"] for m in messages]
assert all(a != b for a, b in zip(roles, roles[1:])), f"roles {roles}: user and assistant must alternate"
מה Python עונהWhat Python says
Traceback (most recent call last):
  File "/Users/you/python-course/chat.py", line 3, in <module>
    assert all(a != b for a, b in zip(roles, roles[1:])), f"roles {roles}: user and assistant must alternate"
           ~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
AssertionError: roles ['user', 'user']: user and assistant must alternate
בעברית פשוטה: In plain words: AssertionError: roles ['user', 'user']: user and assistant must alternate: מאחדים את שתי ההודעות לאחת, או מוסיפים את תשובת המודל ביניהן.AssertionError: roles ['user', 'user']: user and assistant must alternate: merge the two messages into one, or add the model's reply between them.
צפו איפה זה נשברWatch where it breaks
איפה זה נשברWhere it breaksשורה אחרי שורה, כמו ש-Python קוראתLine by line, the way Python reads it

מה קורה עכשיוWhat happens now

הקופסאות (משתנים)The boxes (variables)

מסך הפלטOutput screen

04לבקש JSON ולבדוקAsk for JSON and validate

כדי שתוכנה תשתמש בתשובה, מבקשים פורמט מובנה: "ענה רק ב-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).

recommend.py
import os
import requests

API_URL = "https://api.anthropic.com/v1/messages"


def ask(prompt, system="", max_tokens=300):
    r = requests.post(
        API_URL,
        headers={
            "x-api-key": os.environ.get("ANTHROPIC_API_KEY", "demo-key"),
            "anthropic-version": "2023-06-01",
            "content-type": "application/json",
        },
        json={
            "model": "claude-sonnet-5-5",
            "max_tokens": max_tokens,
            "system": system,
            "messages": [{"role": "user", "content": prompt}],
        },
        timeout=30,
    )
    r.raise_for_status()
    return r.json()

import json

def recommend(liked):
    prompt = f"I liked: {', '.join(liked)}. Reply with only JSON: {{\"title\": ..., \"author\": ..., \"why\": ...}}"
    text = ask(prompt)["content"][0]["text"]
    try:
        data = json.loads(text)
    except json.JSONDecodeError:
        return None
    if not all(isinstance(data.get(k), str) and data[k] for k in ("title", "author", "why")):
        return None
    return data

book = recommend(["Dune", "The Hobbit"])
print(f'{book["title"]} by {book["author"]}')
print("why:", book["why"])
פלט (תשובת השרת הוקלטה מראש)Output (server reply recorded in advance)
The Left Hand of Darkness by Ursula K. Le Guin
why: Thoughtful science fiction about politics and identity, like Dune.
אנלוגיה מהחייםReal-life analogy

לבדוק JSON ממודל זה כמו לבדוק משלוח לפני שחותמים: לרוב הכול בסדר, אבל פותחים את הקופסה בכל זאת.

Validating a model's JSON is like checking a delivery before signing: usually it's fine, but you open the box anyway.

טעות נפוצהCommon mistake

מפרקים תשובה שיש בה טקסט לפני ה-JSON.

Parsing an answer with text before the JSON.

recommend.py
import json
text = 'Sure! Here you go: {"title": "Emma"}'
print(json.loads(text))
מה Python עונהWhat Python says
Traceback (most recent call last):
  File "/Users/you/python-course/recommend.py", line 3, in <module>
    print(json.loads(text))
          ~~~~~~~~~~^^^^^^
  File "/usr/local/lib/python3.13/json/__init__.py", line 352, in loads
    return _default_decoder.decode(s)
           ~~~~~~~~~~~~~~~~~~~~~~~^^^
  File "/usr/local/lib/python3.13/json/decoder.py", line 345, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
               ~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/local/lib/python3.13/json/decoder.py", line 363, in raw_decode
    raise JSONDecodeError("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)
בעברית פשוטה: In plain words: json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0): המודל הוסיף משפט פתיחה. מבקשים "רק JSON", ובכל מקרה תופסים את השגיאה (או חותכים מה-{ הראשון).json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0): the model added an opening sentence. Ask for "only JSON", and catch the error anyway (or cut from the first {).
צפו איפה זה נשברWatch where it breaks
איפה זה נשברWhere it breaksשורה אחרי שורה, כמו ש-Python קוראתLine by line, the way Python reads it

מה קורה עכשיוWhat happens now

הקופסאות (משתנים)The boxes (variables)

מסך הפלטOutput screen

מודל שפה יכול להחזיר JSON. קוראים אותו ובודקים שהשדות קיימים.

A language model can return JSON. Read it and check the fields exist.

עוד דוגמה: קוראים תשובה מובניתOne more: reading a structured answer
example.py
import json
reply = '{"mood": "happy", "score": 8}'
data = json.loads(reply)
print(data["mood"], data.get("score", 0))
print("ok" if {"mood", "score"} <= data.keys() else "missing")
פלטOutput
happy 8
ok
צפו בהרצה צעד אחר צעדWatch it run, step by step
צפו בהרצהWatch it runשורה אחרי שורה, כמו ש-Python קוראתLine by line, the way Python reads it

מה קורה עכשיוWhat happens now

הקופסאות (משתנים)The boxes (variables)

מסך הפלטOutput screen

05עלות, מגבלות ושגיאותCost, limits and errors

כל בקשה נמדדת בטוקנים, וכל טוקן עולה כסף. השדה 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.

cost.py
PRICE_PER_MILLION = {"input": 3.00, "output": 15.00}

def cost(usage):
    return round(usage["input_tokens"] / 1e6 * PRICE_PER_MILLION["input"] + usage["output_tokens"] / 1e6 * PRICE_PER_MILLION["output"], 6)

usage = {"input_tokens": 1200, "output_tokens": 350}
print("one request: $", cost(usage))
print("1000 requests a day for 30 days: $", round(cost(usage) * 1000 * 30, 2))
פלטOutput
one request: $ 0.00885
1000 requests a day for 30 days: $ 265.5
שימו לבNote

המחירים בדוגמה הם להמחשה בלבד. את המחיר העדכני של כל מודל בודקים בדף התמחור הרשמי.

The prices in the example are for illustration only. Check each model's current price on the official pricing page.

אנלוגיה מהחייםReal-life analogy

טוקנים הם כמו דקות שיחה בחבילה של פעם: כל מילה עולה משהו, ולכן כדאי לשאול בקיצור ולא לחזור על אותה שאלה.

Tokens are like minutes on an old phone plan: every word costs something, so ask concisely and don't repeat the same question.

טעות נפוצהCommon mistake

שולחים את כל הספרייה בכל בקשה, ומשלמים על זה כל פעם.

Sending the whole library in every request, and paying for it each time.

cost.py
library = [{"title": f"Book {i}", "notes": "x" * 400} for i in range(300)]
prompt = str(library) + "\nRecommend one book."
approx_tokens = len(prompt) // 4
assert approx_tokens < 5000, f"~{approx_tokens} tokens per request: send only what the question needs"
מה Python עונהWhat Python says
Traceback (most recent call last):
  File "/Users/you/python-course/cost.py", line 4, in <module>
    assert approx_tokens < 5000, f"~{approx_tokens} tokens per request: send only what the question needs"
           ^^^^^^^^^^^^^^^^^^^^
AssertionError: ~32677 tokens per request: send only what the question needs
בעברית פשוטה: In plain words: AssertionError: שולחים רק את מה שרלוונטי לשאלה (למשל 10 הספרים האחרונים וכותרות בלבד).AssertionError: send only what's relevant to the question (e.g. the last 10 books, titles only).

06ה-SDK הרשמיThe official SDK

בפרויקטים אמיתיים משתמשים ב-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:

sdk.py
import anthropic

client = anthropic.Anthropic()
message = client.messages.create(
    model="claude-sonnet-5-5",
    max_tokens=300,
    system="You are a friendly librarian.",
    messages=[{"role": "user", "content": "Recommend one book after Dune."}],
)
print(message.content[0].text)
print(message.usage.input_tokens, message.usage.output_tokens)
אנלוגיה מהחייםReal-life 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.

טעות נפוצהCommon mistake

שם מודל שגוי.

A wrong model name.

sdk.py
MODELS = {"claude-sonnet-5-5", "claude-opus-5-5", "claude-haiku-5-5"}
wanted = "claude-sonet-5-5"
assert wanted in MODELS, f"{wanted!r} is not a model name: the API would answer 404 not_found_error"
מה Python עונהWhat Python says
Traceback (most recent call last):
  File "/Users/you/python-course/sdk.py", line 3, in <module>
    assert wanted in MODELS, f"{wanted!r} is not a model name: the API would answer 404 not_found_error"
           ^^^^^^^^^^^^^^^^
AssertionError: 'claude-sonet-5-5' is not a model name: the API would answer 404 not_found_error
בעברית פשוטה: In plain words: AssertionError: 'claude-sonet-5-5' is not a model name: ...: טעות כתיב בשם המודל מחזירה שגיאת not_found. מעתיקים את השם המדויק מהתיעוד.AssertionError: 'claude-sonet-5-5' is not a model name: ...: a typo in the model name returns a not_found error. Copy the exact name from the docs.
צפו איפה זה נשברWatch where it breaks
איפה זה נשברWhere it breaksשורה אחרי שורה, כמו ש-Python קוראתLine by line, the way Python reads it

מה קורה עכשיוWhat happens now

הקופסאות (משתנים)The boxes (variables)

מסך הפלטOutput screen

סיימתם את ההרצאה!Lecture complete!

עכשיו המצגת לחזרה מהירה, או ישר לתרגול.

Next: the slides for a quick review, or straight to practice.

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