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

או Ctrl+Por Ctrl+P

הנקודות החשובותKey points

  • בקשת POST עם JSON, כמו במפגש 22A POST request with JSON, like session 22
  • שולחים הודעות, מקבלים הודעהSend messages, get a message back
  • מפתח = כסף. לא בקוד, לא ב-GitA key = money. Not in code, not in Git
  • משתנה סביבה: export / setxEnvironment variable: export / setx
  • `system`: תפקיד וסגנון`system`: role and style
  • messages: כל ההיסטוריה, בכל בקשהmessages: the full history, every request
  • מבקשים בפירוש: "רק JSON עם השדות..."Ask explicitly: "only JSON with the fields..."
  • json.loads בתוך tryjson.loads inside try
  • usage: טוקנים נכנסים ויוצאיםusage: input and output tokens

מונחיםTerms

  • מודל שפה (LLM)language model (LLM): תוכנה שמקבלת טקסט ומחזירה המשך או תשובה, כמו Claude. ניגשים אליה דרך API.Software that takes text and returns a continuation or answer, like Claude. You reach it through an API.
  • מפתח APIAPI key: מחרוזת סודית שמזהה אתכם מול שירות, ומחויבים לפיה. שומרים במשתנה סביבה, לעולם לא בקוד.A secret string that identifies you to a service, and that usage is billed to. Keep it in an environment variable, never in code.
  • משתנה סביבהenvironment variable: ערך שמוגדר במערכת ההפעלה מחוץ לקוד. os.environ["NAME"] קורא אותו.A value set in the operating system outside your code. os.environ["NAME"] reads it.
  • הנחיית מערכתsystem prompt: הוראות כלליות למודל שחלות על כל השיחה: תפקיד, סגנון, שפה, פורמט.General instructions for the model that apply to the whole conversation: role, style, language, format.
  • טוקןtoken: יחידת טקסט שהמודל סופר (בערך 3–4 תווים באנגלית). המחיר והמגבלות נמדדים בטוקנים.A unit of text the model counts (about 3–4 characters in English). Prices and limits are measured in tokens.
  • SDKSDK: ספרייה רשמית שעוטפת API, כמו anthropic לפייתון. חוסכת לבנות בקשות HTTP ביד.An official library wrapping an API, like anthropic for Python. Saves building HTTP requests by hand.

Cheatsheet

איךHow
import os
import requests

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


def ask(prompt, system="", max_tokens=300):
מפתחKey
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
שיחהConversation
import os
import requests

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


def ask(prompt, system="", max_tokens=300):
JSONJSON
import os
import requests

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


def ask(prompt, system="", max_tokens=300):
עלותCost
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))
SDKSDK
import anthropic

client = anthropic.Anthropic()
message = client.messages.create(
    model="claude-sonnet-5-5",
    max_tokens=300,
    system="You are a friendly librarian.",

שגיאות שפגשנוErrors we met

שגיאהErrorמה זה אומרWhat it meansמה עושיםWhat to do
requests.exceptions.HTTPErrorשולחים בקשה בלי מפתח.Sending a request without a key.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.
KeyErrorקוראים מפתח שלא הוגדר עם סוגריים מרובעים.Reading an unset key with square brackets.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.
AssertionErrorשתי הודעות user ברצף.Two user messages in a row.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.
json.decoder.JSONDecodeErrorמפרקים תשובה שיש בה טקסט לפני ה-JSON.Parsing an answer with text before the JSON.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 {).
AssertionErrorשולחים את כל הספרייה בכל בקשה, ומשלמים על זה כל פעם.Sending the whole library in every request, and paying for it each time.AssertionError: שולחים רק את מה שרלוונטי לשאלה (למשל 10 הספרים האחרונים וכותרות בלבד).AssertionError: send only what's relevant to the question (e.g. the last 10 books, titles only).
AssertionErrorשם מודל שגוי.A wrong model name.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.

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