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

JavaJava
41
חלקPart 7: Java בעולם האמיתיJava in the real world כ-3 שעות (כולל הפסקה)About 3 hours (with a break)

Java בעידן ה-AIJava in the AI era

עבודה נכונה עם עוזר AI, קריאה ל-API של מודל שפה מ-Java (עם תשובות מוקלטות מראש), ובדיקת מה שהמודל כתב.

Working well with an AI assistant, calling a language model API from Java (with recorded replies), and checking what the model wrote.

01המונחים של המפגשThis session's terms

לפני הקוד, המילים. כל מונח כאן מקושר גם במילון של הקורס.

Before the code, the words. Every term here is also linked in the course glossary.

  • מודל שפה: תוכנה שמקבלת טקסט (prompt) ומחזירה טקסט. היא יכולה לטעות או להמציא, ולכן הקוד שסביבה בודק את מה שחזר.language model: Software that takes text (a prompt) and returns text. It can be wrong or make things up, so the code around it checks what came back.
  • prompt: הטקסט ששולחים למודל: מה התפקיד, אילו נתונים יש, ובאיזו צורה לענות. prompt מדויק נותן תשובה שקל לבדוק.prompt: The text sent to the model: the role, the data available, and the shape of the answer. A precise prompt gives an answer that's easy to check.
  • מפתח API: סיסמה שמזהה אתכם מול השירות. שומרים אותה במשתנה סביבה (System.getenv), אף פעם לא בקוד או ב-Git.API key: A password identifying you to the service. Keep it in an environment variable (System.getenv), never in code or in Git.
  • תשובה מוקלטת: מימוש של ה-interface שמחזיר תשובות קבועות מראש. כך בודקים את הקוד בלי רשת, בלי עלות ובלי תוצאות משתנות.recorded reply: An implementation of the interface returning answers fixed in advance. That way you test the code with no network, no cost and no changing results.
  • בדיקת הפלט: לפני שמשתמשים בתשובה: בודקים שהיא בפורמט הנכון ושהיא הגיונית (למשל שהספר באמת במדף). אם לא, ברירת מחדל.validating output: Before using a reply: check it's in the right format and makes sense (say, the book really is on the shelf). If not, a fallback.

02הקריאה האמיתיתThe real call

בקשת POST עם מפתח מתוך משתנה סביבה, גוף JSON עם המודל וההודעות, ותשובה ב-JSON. ה-text block (""") שומר על ה-JSON קריא.

A POST request with an API key from an environment variable, a JSON body with the model and the messages, and a JSON reply. The text block (""") keeps the JSON readable.

Main.java
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;

public class Main {
    public static void main(String[] args) throws Exception {
        String key = System.getenv("ANTHROPIC_API_KEY");
        String body = """
                {"model": "claude-sonnet-5-5", "max_tokens": 200,
                 "messages": [{"role": "user", "content": "Suggest one classic novel. Reply with the title only."}]}
                """;
        HttpRequest req = HttpRequest.newBuilder(URI.create("https://api.anthropic.com/v1/messages"))
                .header("x-api-key", key)
                .header("anthropic-version", "2023-06-01")
                .header("content-type", "application/json")
                .POST(HttpRequest.BodyPublishers.ofString(body))
                .build();
        HttpResponse<String> res = HttpClient.newHttpClient().send(req, HttpResponse.BodyHandlers.ofString());
        System.out.println(res.statusCode());
        System.out.println(res.body());
    }
}
להרצה במחשב שלכםRun it on your computer

להרצה במחשב שלכם, עם מפתח API משלכם במשתנה ANTHROPIC_API_KEY. לבניית האתר אין רשת, ולכן הקוד מוצג בלי הרצה. התשובה מגיעה כ-JSON, והטקסט נמצא בתוך content.

Run it on your computer, with your own API key in ANTHROPIC_API_KEY. The site build has no network, so the code is shown without running. The reply arrives as JSON, with the text inside content.

03המודל מאחורי interfaceThe model behind an interface

Model הוא interface עם מתודה אחת. RecordedModel עונה מתשובות מוקלטות, ולכן כל הקוד שסביבו רץ ונבדק כאן, באותה צורה שבה ירוץ מול מודל אמיתי.

Model is an interface with one method. RecordedModel answers from recorded replies, so all the code around it runs and is checked here, just as it will run against a real model.

Main.java
import java.util.Map;

public class Main {
    public static void main(String[] args) {
        Model model = new RecordedModel(Map.of(
                "classic novel", "Emma",
                "author of Dune", "Frank Herbert"));
        System.out.println(model.complete("Suggest one classic novel. Title only."));
        System.out.println(model.complete("Who is the author of Dune? Name only."));
        System.out.println(model.complete("What is the weather?"));
    }
}

interface Model {
    String complete(String prompt);
}

class RecordedModel implements Model {
    private final Map<String, String> replies;
    int calls = 0;

    RecordedModel(Map<String, String> replies) {
        this.replies = replies;
    }

    public String complete(String prompt) {
        calls++;
        for (Map.Entry<String, String> e : replies.entrySet()) {
            if (prompt.contains(e.getKey())) {
                return e.getValue();
            }
        }
        return "I'm not sure.";
    }
}
פלטOutput
Emma
Frank Herbert
I'm not sure.
צפו בהרצה צעד אחר צעדWatch it run, step by step
צפו בהרצהWatch it runשורה אחרי שורה, כמו ש-Java מבצעתLine by line, the way Java runs it

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

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

מסך הפלטOutput screen

04הצעד של היום בפרויקט מדףToday's step in the Shelf project

Recommender מקבל Model ומדף, בונה prompt עם המדף ומצב הרוח, ומחזיר רק כותר שבמדף (אחרת no match on your shelf). הדפיסו adventure -> Dune, romance -> Emma, something light -> no match on your shelf.

Recommender takes a Model and a shelf, builds a prompt with the shelf and the mood, and returns only a title on the shelf (otherwise no match on your shelf). Print adventure -> Dune, romance -> Emma, something light -> no match on your shelf.

טיפTip

את הצעד הזה כותבים בעמוד התרגול (התרגיל המסומן כצעד בפרויקט). בעמוד הפתרונות יש פתרון מלא עם סימולציה שמריצה אותו.

You write this step on the practice page (the exercise marked as a project step). The solutions page has a full solution with a simulation that runs it.

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

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

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

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