עבודה נכונה עם עוזר AI לקודWorking well with an AI coding assistant
מתי לסמוך, איך לבדוק, איך לבקש, ואיך לא לאבד את ההבנה.
When to trust it, how to verify, how to ask, and how not to lose understanding.
01מה עוזר AI טוב בוWhat an AI assistant is good at
עוזרי AI לקוד כמו Claude משנים את העבודה של מתכנתים: הם כותבים טיוטה במהירות, מסבירים שגיאות ומציעים גישות. אבל הם לא מכירים את הפרויקט שלכם אלא אם תספרו להם, והם יכולים לטעות בביטחון מלא. הכלל: האחריות על הקוד שלכם. מה שלא מבינים, לא מכניסים. הקוד הבא "נכתב על ידי עוזר" לבקשה "ממוצע דירוגים". יש בו שתי בעיות:
AI coding assistants like Claude change how programmers work: they draft quickly, explain errors and suggest approaches. But they don't know your project unless you tell them, and they can be confidently wrong. The rule: the code is your responsibility. What you don't understand doesn't go in. The next code was "written by an assistant" for the request "average rating". It has two problems:
def average_rating(books):
"""Average rating of the books that have one."""
total = 0
for b in books:
total += b["rating"]
return round(total / len(books), 1)
print(average_rating([{"title": "Dune", "rating": 5}, {"title": "Emma", "rating": 3}]))4.0
צפו בהרצה צעד אחר צעדWatch it run, step by step
מה קורה עכשיוWhat happens now
הקופסאות (משתנים)The boxes (variables)
מסך הפלטOutput screen
עוזר AI הוא כמו מתמחה מוכשר מאוד ביום הראשון: עובד מהר ויודע המון, אבל לא מכיר את המשרד, ואתם חותמים על מה שיוצא.
An AI assistant is like a very talented intern on day one: works fast and knows a lot, but doesn't know the office, and you sign off on what goes out.
מקבלים את הקוד בלי לבדוק מקרי קצה.
Accepting the code without checking edge cases.
def average_rating(books):
"""Average rating of the books that have one."""
total = 0
for b in books:
total += b["rating"]
return round(total / len(books), 1)
print(average_rating([{"title": "Dune", "rating": 5}, {"title": "Draft"}]))Traceback (most recent call last):
File "/Users/you/python-course/ai_draft.py", line 8, in <module>
print(average_rating([{"title": "Dune", "rating": 5}, {"title": "Draft"}]))
~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/Users/you/python-course/ai_draft.py", line 5, in average_rating
total += b["rating"]
~^^^^^^^^^^
KeyError: 'rating'KeyError: 'rating': התיעוד אמר "שיש להם דירוג" אבל הקוד לא מסנן. וגם רשימה ריקה תיתן ZeroDivisionError. כך נראית הבעיה השנייה.KeyError: 'rating': the docstring said "that have one" but the code doesn't filter. An empty list would also give ZeroDivisionError. That's the second problem.צפו איפה זה נשברWatch where it breaks
מה קורה עכשיוWhat happens now
הקופסאות (משתנים)The boxes (variables)
מסך הפלטOutput screen
02לבקש טובAsking well
בקשה טובה דומה לבקשה מעמית: מה אתם בונים, מה כבר יש, מה בדיוק צריך, ודוגמה. במקום "תכתוב ממוצע", כותבים בקשה שמגדירה מקרי קצה. אפשר אפילו לבנות את הבקשה בקוד, כמו תבנית:
A good prompt is like asking a colleague: what you're building, what exists, exactly what's needed, and an example. Instead of "write an average", write a request that spells out the edge cases. You can even build the prompt in code, like a template:
def make_prompt(task, context, examples, rules):
lines = [f"Context: {context}", f"Task: {task}", "Examples:"]
lines += [f" {inp!r} -> {out!r}" for inp, out in examples]
lines += ["Rules:"] + [f" - {r}" for r in rules]
return "\n".join(lines)
print(make_prompt(
task="Write average_rating(books) for my shelf app (Python 3.12).",
context="books is a list of dicts; some have no 'rating' key.",
examples=[([{"rating": 5}, {"rating": 3}], 4.0), ([{"title": "Draft"}], None), ([], None)],
rules=["ignore books without a rating", "return None when nothing is rated", "round to 1 decimal", "add type hints and a docstring"],
))Context: books is a list of dicts; some have no 'rating' key.
Task: Write average_rating(books) for my shelf app (Python 3.12).
Examples:
[{'rating': 5}, {'rating': 3}] -> 4.0
[{'title': 'Draft'}] -> None
[] -> None
Rules:
- ignore books without a rating
- return None when nothing is rated
- round to 1 decimal
- add type hints and a docstringצפו בהרצה צעד אחר צעדWatch it run, step by step
מה קורה עכשיוWhat happens now
הקופסאות (משתנים)The boxes (variables)
מסך הפלטOutput screen
בקשה מעורפלת לעוזר היא כמו לבקש מנהג מונית "לנסוע למרכז": הוא ייסע, אבל כנראה לא למקום שרציתם.
A vague request to an assistant is like telling a taxi driver "drive to the centre": they'll drive, just probably not where you meant.
בקשה בלי מקרי קצה מקבלת קוד בלי מקרי קצה.
A request with no edge cases gets code with no edge cases.
prompt = "write average of ratings"
checklist = ["empty", "missing", "round"]
missing = [c for c in checklist if c not in prompt]
assert not missing, f"the prompt never mentions: {missing}"Traceback (most recent call last):
File "/Users/you/python-course/prompt.py", line 4, in <module>
assert not missing, f"the prompt never mentions: {missing}"
^^^^^^^^^^^
AssertionError: the prompt never mentions: ['empty', 'missing', 'round']AssertionError: the prompt never mentions: ['empty', 'missing', 'round']: מה שלא אמרתם, העוזר מנחש. כותבים את הכללים במפורש.AssertionError: the prompt never mentions: ['empty', 'missing', 'round']: whatever you didn't say, the assistant guesses. Spell out the rules.צפו איפה זה נשברWatch where it breaks
מה קורה עכשיוWhat happens now
הקופסאות (משתנים)The boxes (variables)
מסך הפלטOutput screen
03לקרוא לפני שמקבליםRead before you accept
לפני שמכניסים קוד שנוצר, עושים סקירת קוד כמו לקוד של אדם: קוראים שורה אחרי שורה, ושואלים מה קורה ברשימה ריקה, בערך חסר, בקלט מוזר. הנה הגרסה המתוקנת של הפונקציה, והרצה על כל המקרים מהבקשה:
Before adding generated code, do a code review like you would for a person's code: read line by line, and ask what happens with an empty list, a missing value, odd input. Here's the fixed version of the function, run on every case from the request:
def average_rating(books: list[dict]) -> float | None:
"""Average rating of the books that have one, or None if none do."""
ratings = [b["rating"] for b in books if "rating" in b]
if not ratings:
return None
return round(sum(ratings) / len(ratings), 1)
cases = [([{"rating": 5}, {"rating": 3}], 4.0), ([{"title": "Draft"}], None), ([], None), ([{"rating": 4}, {"title": "x"}, {"rating": 5}], 4.5)]
for books, expected in cases:
got = average_rating(books)
print("ok " if got == expected else "BAD", books, "->", got)ok [{'rating': 5}, {'rating': 3}] -> 4.0
ok [{'title': 'Draft'}] -> None
ok [] -> None
ok [{'rating': 4}, {'title': 'x'}, {'rating': 5}] -> 4.5צפו בהרצה צעד אחר צעדWatch it run, step by step
מה קורה עכשיוWhat happens now
הקופסאות (משתנים)The boxes (variables)
מסך הפלטOutput screen
סקירת קוד היא כמו לקרוא חוזה לפני שחותמים: גם אם עורך דין מעולה ניסח אותו, השם שלכם עליו.
Code review is like reading a contract before signing: even if a great lawyer drafted it, it's your name on it.
קוד שנראה נכון ונכשל רק במקרה מסוים.
Code that looks right and fails only in one case.
def is_leap(year):
return year % 4 == 0
for y, expected in [(2024, True), (2023, False), (1900, False)]:
assert is_leap(y) == expected, f"{y}: got {is_leap(y)}, expected {expected}"Traceback (most recent call last):
File "/Users/you/python-course/review.py", line 5, in <module>
assert is_leap(y) == expected, f"{y}: got {is_leap(y)}, expected {expected}"
^^^^^^^^^^^^^^^^^^^^^^
AssertionError: 1900: got True, expected FalseAssertionError: 1900: got True, expected False: שנה שמתחלקת ב-100 אינה מעוברת, אלא אם מתחלקת ב-400. רק בדיקת מקרי קצה חושפת את זה.AssertionError: 1900: got True, expected False: a year divisible by 100 isn't a leap year unless divisible by 400. Only edge-case checks expose this.צפו איפה זה נשברWatch where it breaks
מה קורה עכשיוWhat happens now
הקופסאות (משתנים)The boxes (variables)
מסך הפלטOutput screen
גם קוד שנראה נכון צריך בדיקה. כאן הבדיקה תופסת מקרה קצה.
Even code that looks right needs checking. Here a check catches an edge case.
def average(nums):
if not nums:
return 0
return sum(nums) / len(nums)
print(average([4, 6]))
print(average([]))5.0 0
צפו בהרצה צעד אחר צעדWatch it run, step by step
מה קורה עכשיוWhat happens now
הקופסאות (משתנים)The boxes (variables)
מסך הפלטOutput screen
04בדיקות קודם, קוד אחר כךTests first, code second
השיטה הכי אמינה לעבוד עם AI היא TDD (מפגש 19): אתם כותבים את הבדיקות, שהן מפרט שאפשר להריץ, והעוזר כותב קוד שמעביר אותן. אחר כך הבדיקות, לא ההרגשה, אומרות אם הקוד נכון. הנה בדיקות לפונקציה שעדיין לא קיימת, ושתי "הצעות" שונות:
The most reliable way to work with AI is TDD (session 19): you write the tests, a spec you can run, and the assistant writes code that passes them. Then the tests, not a feeling, say whether the code is right. Here are tests for a function that doesn't exist yet, and two different "suggestions":
def tests(slugify):
cases = {"The Little Prince": "the-little-prince", " Dune ": "dune", "Hello, World!": "hello-world", "": ""}
return [text for text, want in cases.items() if slugify(text) != want]
def suggestion_a(text):
return text.lower().replace(" ", "-")
def suggestion_b(text):
words = "".join(c if c.isalnum() else " " for c in text).split()
return "-".join(words).lower()
print("A fails on:", tests(suggestion_a))
print("B fails on:", tests(suggestion_b))A fails on: [' Dune ', 'Hello, World!'] B fails on: []
צפו בהרצה צעד אחר צעדWatch it run, step by step
מה קורה עכשיוWhat happens now
הקופסאות (משתנים)The boxes (variables)
מסך הפלטOutput screen
בדיקות הן כמו שבלונה למכונית חדשה: לא משנה מי ייצר את החלק, אם הוא לא נכנס בשבלונה, הוא לא נכנס לרכב.
Tests are like a template on an assembly line: whoever made the part, if it doesn't fit the template, it doesn't go in the car.
משנים את הבדיקה כדי שתתאים לקוד שהעוזר כתב.
Changing the test to fit the code the assistant wrote.
def slugify(text):
return text.lower().replace(" ", "-")
expected = "hello-world"
assert slugify("Hello, World!") == expected, f"got {slugify('Hello, World!')!r}: fix the code, not the test"Traceback (most recent call last):
File "/Users/you/python-course/spec.py", line 5, in <module>
assert slugify("Hello, World!") == expected, f"got {slugify('Hello, World!')!r}: fix the code, not the test"
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
AssertionError: got 'hello,-world!': fix the code, not the testAssertionError: got 'hello,-world!': fix the code, not the test: הבדיקה היא ההחלטה שלכם על מה נכון. מבקשים מהעוזר לתקן את הקוד, ומדביקים לו את הכישלון.AssertionError: got 'hello,-world!': fix the code, not the test: the test is your decision about what's right. Ask the assistant to fix the code, and paste the failure to it.צפו איפה זה נשברWatch where it breaks
מה קורה עכשיוWhat happens now
הקופסאות (משתנים)The boxes (variables)
מסך הפלטOutput screen
05המצאותHallucinations
מודלים לפעמים ממציאים: מתודה שנשמעת הגיונית אבל לא קיימת, פרמטר שלא קיים, או חבילה ב-pip עם שם דומה לאמיתית (ויש תוקפים שרושמים חבילות כאלה בכוונה!). פייתון עצמה עוזרת לבדוק: hasattr, dir ו-help מראים מה באמת קיים.
Models sometimes hallucinate: a method that sounds plausible but doesn't exist, a parameter that isn't there, or a pip package with a name close to a real one (and attackers register such packages on purpose!). Python itself helps check: hasattr, dir and help show what really exists.
import inspect
claims = [("str", "title"), ("str", "capitalize_words"), ("list", "sort"), ("list", "sorted"), ("dict", "get"), ("dict", "find")]
for type_name, method in claims:
real = hasattr(eval(type_name), method)
print(f"{type_name}.{method}:", "exists" if real else "DOES NOT EXIST")
print(inspect.signature(sorted))str.title: exists str.capitalize_words: DOES NOT EXIST list.sort: exists list.sorted: DOES NOT EXIST dict.get: exists dict.find: DOES NOT EXIST (iterable, /, *, key=None, reverse=False)
צפו בהרצה צעד אחר צעדWatch it run, step by step
מה קורה עכשיוWhat happens now
הקופסאות (משתנים)The boxes (variables)
מסך הפלטOutput screen
המצאה של מודל היא כמו נווט שבטוח שיש פנייה ימינה: לפעמים הוא צודק, אבל כדאי להסתכל על השלט לפני שמסובבים את ההגה.
A model's hallucination is like a navigator certain there's a right turn: sometimes right, but look at the sign before turning the wheel.
מריצים קוד עם מתודה שהעוזר המציא.
Running code with a method the assistant invented.
shelf = ["Dune", "Emma"]
shelf.remove_all("Dune")Traceback (most recent call last):
File "/Users/you/python-course/check_claims.py", line 2, in <module>
shelf.remove_all("Dune")
^^^^^^^^^^^^^^^^
AttributeError: 'list' object has no attribute 'remove_all'AttributeError: 'list' object has no attribute 'remove_all': אין כזו. לרשימה יש remove (מופע ראשון). dir(list) מראה את כל מה שקיים.AttributeError: 'list' object has no attribute 'remove_all': there's no such thing. Lists have remove (first occurrence). dir(list) shows everything that exists.צפו איפה זה נשברWatch where it breaks
מה קורה עכשיוWhat happens now
הקופסאות (משתנים)The boxes (variables)
מסך הפלטOutput screen
06פרטיות ואבטחהPrivacy and security
שלושה כללים. אחד: לא מדביקים לצ'אט מפתחות API, סיסמאות או מידע אישי של אחרים. שניים: פקודה שעוזר מציע (rm -rf, pip install של חבילה לא מוכרת) מריצים רק אם מבינים מה היא עושה. שלושה: קוד שנוצר יכול להכיל פרצות קלאסיות, כמו SQL injection (מפגש 23). אפשר לבנות בדיקה קטנה שמחפשת סודות לפני ששולחים טקסט:
Three rules. One: don't paste API keys, passwords or other people's personal data into a chat. Two: run a command an assistant suggests (rm -rf, pip install of an unknown package) only if you understand what it does. Three: generated code can contain classic holes, like SQL injection (session 23). You can build a small check that looks for secrets before sending text:
import re
PATTERNS = {
"API key": r"\b(sk|pk)[-_][A-Za-z0-9_-]{12,}",
"password": r"(?i)password\s*[:=]\s*\S+",
"email": r"[\w.+-]+@[\w-]+\.[\w.]+",
}
def secrets_in(text):
return [name for name, pat in PATTERNS.items() if re.search(pat, text)]
snippet = 'API_KEY = "sk-live_abc123def456ghi789"\nDB_PASSWORD = hunter2\nprint("hello")'
print(secrets_in(snippet))
print(secrets_in("def add(a, b):\n return a + b"))['API key', 'password'] []
צפו בהרצה צעד אחר צעדWatch it run, step by step
מה קורה עכשיוWhat happens now
הקופסאות (משתנים)The boxes (variables)
מסך הפלטOutput screen
להדביק מפתח API לצ'אט זה כמו לצעוק את הקוד של הכספת באמצע רחוב: גם אם אף אחד לא שמע, עדיף להחליף אותו.
Pasting an API key into a chat is like shouting the safe's code in the street: even if nobody heard, better change it.
עוזר מציע קוד עם f-string בתוך SQL.
An assistant suggests code with an f-string inside SQL.
import sqlite3
con = sqlite3.connect(":memory:")
con.execute("CREATE TABLE users (name TEXT, admin INTEGER)")
con.execute("INSERT INTO users VALUES ('noa', 0), ('boss', 1)")
name = "x' OR admin=1 --"
rows = con.execute(f"SELECT name FROM users WHERE name = '{name}'").fetchall()
assert rows == [], f"injection found {rows}: use ? placeholders"Traceback (most recent call last):
File "/Users/you/python-course/secrets_check.py", line 7, in <module>
assert rows == [], f"injection found {rows}: use ? placeholders"
^^^^^^^^^^
AssertionError: injection found [('boss',)]: use ? placeholdersAssertionError: injection found [('boss',)]: use ? placeholders: קוד שנוצר לא תמיד בטוח. מזהים את הדפוס ומבקשים גרסה עם ?.AssertionError: injection found [('boss',)]: use ? placeholders: generated code isn't always safe. Spot the pattern and ask for a version with ?.סיימתם את ההרצאה!Lecture complete!
עכשיו המצגת לחזרה מהירה, או ישר לתרגול.
Next: the slides for a quick review, or straight to practice.