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.
לבנות promptBuilding a prompt
תזכורת: מה ביקשוReminder: the task
prompt(shelf, mood) בונה טקסט: תפקיד, רשימת הספרים (כל אחד בשורה עם - ), מצב רוח, והוראה לענות בכותר אחד מהמדף. הדפיסו את ה-prompt עבור Dune ו-Emma ו-adventure.
prompt(shelf, mood) builds text: a role, the list of books (each on a line with - ), a mood, and an instruction to answer with one title from the shelf. Print the prompt for Dune and Emma and adventure.
סימולציה: הפתרון רץ שורה אחרי שורהSimulation: the solution runs line by line
לוחצים הבא או נגן: רואים איזו שורה Java מבצעת, מה יש בכל קופסה (משתנה) ומה מופיע על המסך. זו הרצה אמיתית של הפתרון.
Press Next or Play: see which line Java runs, what is in each box (variable) and what appears on the screen. This is a real run of the solution.
צפו בהרצה צעד אחר צעדWatch it run, step by step
מה קורה עכשיוWhat happens now
הקופסאות (משתנים)The boxes (variables)
מסך הפלטOutput screen
הפתרון המלא והפלט שלוFull solution and its output
import java.util.List;
public class Main {
static String prompt(List<String> shelf, String mood) {
StringBuilder sb = new StringBuilder();
sb.append("You recommend books from a personal shelf.\n");
sb.append("Shelf:\n");
for (String t : shelf) {
sb.append("- ").append(t).append("\n");
}
sb.append("Mood: ").append(mood).append("\n");
sb.append("Answer with exactly one title from the shelf.");
return sb.toString();
}
public static void main(String[] args) {
System.out.println(prompt(List.of("Dune", "Emma"), "adventure"));
}
}You recommend books from a personal shelf. Shelf: - Dune - Emma Mood: adventure Answer with exactly one title from the shelf.
יש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.
תשובה מוקלטתA recorded reply
תזכורת: מה ביקשוReminder: the task
עם RecordedModel בקשו סיכום של Dune, הדפיסו אותו, בדקו שהוא עד 80 תווים (short enough), והדפיסו calls: 1.
With RecordedModel ask for a summary of Dune, print it, check it's at most 80 characters (short enough), and print calls: 1.
סימולציה: הפתרון רץ שורה אחרי שורהSimulation: the solution runs line by line
לוחצים הבא או נגן: רואים איזו שורה Java מבצעת, מה יש בכל קופסה (משתנה) ומה מופיע על המסך. זו הרצה אמיתית של הפתרון.
Press Next or Play: see which line Java runs, what is in each box (variable) and what appears on the screen. This is a real run of the solution.
צפו בהרצה צעד אחר צעדWatch it run, step by step
מה קורה עכשיוWhat happens now
הקופסאות (משתנים)The boxes (variables)
מסך הפלטOutput screen
הפתרון המלא והפלט שלוFull solution and its output
import java.util.Map;
public class Main {
public static void main(String[] args) {
RecordedModel model = new RecordedModel(Map.of("summary", "A desert planet, a young duke, and a fight over spice."));
String s = model.complete("Write a one-line summary of Dune.");
System.out.println(s);
System.out.println(s.length() <= 80 ? "short enough" : "too long");
System.out.println("calls: " + model.calls);
}
}
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.";
}
}A desert planet, a young duke, and a fight over spice. short enough calls: 1
יש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.
לפרק תשובהParsing a reply
תזכורת: מה ביקשוReminder: the task
המודל ענה בטקסט שבתוכו JSON. parse(reply) מוציאה רשימת Suggestion(title, score) בעזרת regex, ומחזירה רשימה ריקה כשאין JSON. הדפיסו [Suggestion[title=Dune, score=9], Suggestion[title=Emma, score=7]] ואז [].
The model answered with text containing JSON. parse(reply) pulls out a list of Suggestion(title, score) with a regex, and returns an empty list when there's no JSON. Print [Suggestion[title=Dune, score=9], Suggestion[title=Emma, score=7]] then [].
סימולציה: הפתרון רץ שורה אחרי שורהSimulation: the solution runs line by line
לוחצים הבא או נגן: רואים איזו שורה Java מבצעת, מה יש בכל קופסה (משתנה) ומה מופיע על המסך. זו הרצה אמיתית של הפתרון.
Press Next or Play: see which line Java runs, what is in each box (variable) and what appears on the screen. This is a real run of the solution.
צפו בהרצה צעד אחר צעדWatch it run, step by step
מה קורה עכשיוWhat happens now
הקופסאות (משתנים)The boxes (variables)
מסך הפלטOutput screen
הפתרון המלא והפלט שלוFull solution and its output
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Main {
record Suggestion(String title, int score) {
}
static List<Suggestion> parse(String reply) {
List<Suggestion> out = new ArrayList<>();
Matcher m = Pattern.compile("\\{\"title\": \"([^\"]+)\", \"score\": (\\d+)\\}").matcher(reply);
while (m.find()) {
out.add(new Suggestion(m.group(1), Integer.parseInt(m.group(2))));
}
return out;
}
public static void main(String[] args) {
String reply = "Here you go: [{\"title\": \"Dune\", \"score\": 9}, {\"title\": \"Emma\", \"score\": 7}]";
System.out.println(parse(reply));
System.out.println(parse("Sorry, I can't help with that."));
}
}[Suggestion[title=Dune, score=9], Suggestion[title=Emma, score=7]] []
יש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.
לא לסמוך בעיניים עצומותDon't trust blindly
תזכורת: מה ביקשוReminder: the task
safeRecommend(model, shelf) מחזירה את התשובה רק אם היא באמת במדף. אחרת: fallback: Dune (model said 'Moby Dick'). הדפיסו עבור שני מודלים מוקלטים: Emma ואז ה-fallback.
safeRecommend(model, shelf) returns the reply only if it really is on the shelf. Otherwise: fallback: Dune (model said 'Moby Dick'). Print for two recorded models: Emma then the fallback.
סימולציה: הפתרון רץ שורה אחרי שורהSimulation: the solution runs line by line
לוחצים הבא או נגן: רואים איזו שורה Java מבצעת, מה יש בכל קופסה (משתנה) ומה מופיע על המסך. זו הרצה אמיתית של הפתרון.
Press Next or Play: see which line Java runs, what is in each box (variable) and what appears on the screen. This is a real run of the solution.
צפו בהרצה צעד אחר צעדWatch it run, step by step
מה קורה עכשיוWhat happens now
הקופסאות (משתנים)The boxes (variables)
מסך הפלטOutput screen
הפתרון המלא והפלט שלוFull solution and its output
import java.util.List;
import java.util.Map;
public class Main {
static String safeRecommend(Model model, List<String> shelf) {
String reply = model.complete("Pick one title from: " + shelf).trim();
if (shelf.contains(reply)) {
return reply;
}
return "fallback: " + shelf.get(0) + " (model said '" + reply + "')";
}
public static void main(String[] args) {
List<String> shelf = List.of("Dune", "Emma");
System.out.println(safeRecommend(new RecordedModel(Map.of("Pick one", "Emma")), shelf));
System.out.println(safeRecommend(new RecordedModel(Map.of("Pick one", "Moby Dick")), shelf));
}
}
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.";
}
}Emma fallback: Dune (model said 'Moby Dick')
יש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.
מדף, צעד 41: המלצה לפי מצב רוחShelf, step 41: a recommendation by mood
תזכורת: מה ביקשוReminder: the task
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.
סימולציה: הפתרון רץ שורה אחרי שורהSimulation: the solution runs line by line
לוחצים הבא או נגן: רואים איזו שורה Java מבצעת, מה יש בכל קופסה (משתנה) ומה מופיע על המסך. זו הרצה אמיתית של הפתרון.
Press Next or Play: see which line Java runs, what is in each box (variable) and what appears on the screen. This is a real run of the solution.
צפו בהרצה צעד אחר צעדWatch it run, step by step
מה קורה עכשיוWhat happens now
הקופסאות (משתנים)The boxes (variables)
מסך הפלטOutput screen
הפתרון המלא והפלט שלוFull solution and its output
import java.util.List;
import java.util.Map;
public class Main {
public static void main(String[] args) {
List<String> shelf = List.of("Dune", "Emma", "Ulysses");
Model model = new RecordedModel(Map.of(
"adventure", "Dune",
"romance", "Emma",
"something light", "The Hobbit"));
Recommender r = new Recommender(model, shelf);
for (String mood : List.of("adventure", "romance", "something light")) {
System.out.println(mood + " -> " + r.recommend(mood));
}
}
}
class Recommender {
private final Model model;
private final List<String> shelf;
Recommender(Model model, List<String> shelf) {
this.model = model;
this.shelf = shelf;
}
String recommend(String mood) {
String prompt = "Shelf: " + String.join(", ", shelf) + ". Mood: " + mood + ". One title from the shelf only.";
String reply = model.complete(prompt).trim();
return shelf.contains(reply) ? reply : "no match on your shelf";
}
}
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.";
}
}adventure -> Dune romance -> Emma something light -> no match on your shelf
יש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.
מטמון לתשובותCaching replies
תזכורת: מה ביקשוReminder: the task
CachedModel עוטף Model ושומר תשובות לפי prompt (computeIfAbsent). ארבע שאלות זהות עולות קריאה אמיתית אחת: Frank Herbert | real calls: 1.
CachedModel wraps a Model and stores replies by prompt (computeIfAbsent). Four identical questions cost one real call: Frank Herbert | real calls: 1.
סימולציה: הפתרון רץ שורה אחרי שורהSimulation: the solution runs line by line
לוחצים הבא או נגן: רואים איזו שורה Java מבצעת, מה יש בכל קופסה (משתנה) ומה מופיע על המסך. זו הרצה אמיתית של הפתרון.
Press Next or Play: see which line Java runs, what is in each box (variable) and what appears on the screen. This is a real run of the solution.
צפו בהרצה צעד אחר צעדWatch it run, step by step
מה קורה עכשיוWhat happens now
הקופסאות (משתנים)The boxes (variables)
מסך הפלטOutput screen
הפתרון המלא והפלט שלוFull solution and its output
import java.util.Map;
public class Main {
public static void main(String[] args) {
RecordedModel model = new RecordedModel(Map.of("Dune", "Frank Herbert"));
CachedModel cached = new CachedModel(model);
for (int i = 0; i < 3; i++) {
cached.complete("Author of Dune?");
}
System.out.println(cached.complete("Author of Dune?") + " | real calls: " + model.calls);
}
}
class CachedModel implements Model {
private final Model inner;
private final Map<String, String> cache = new java.util.HashMap<>();
CachedModel(Model inner) {
this.inner = inner;
}
public String complete(String prompt) {
return cache.computeIfAbsent(prompt, inner::complete);
}
}
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.";
}
}Frank Herbert | real calls: 1
יש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.
ניסיון חוזרRetrying
תזכורת: מה ביקשוReminder: the task
שירותים עונים לפעמים 429 (יותר מדי בקשות). withRetry(model, prompt, tries) מנסה שוב אחרי כישלון, עד מספר ניסיונות. עם מודל שנכשל פעמיים: try 1 failed: ..., try 2 failed: ..., Emma (after 3 tries).
Services sometimes answer 429 (too many requests). withRetry(model, prompt, tries) tries again after a failure, up to a number of tries. With a model that fails twice: try 1 failed: ..., try 2 failed: ..., Emma (after 3 tries).
סימולציה: הפתרון רץ שורה אחרי שורהSimulation: the solution runs line by line
לוחצים הבא או נגן: רואים איזו שורה Java מבצעת, מה יש בכל קופסה (משתנה) ומה מופיע על המסך. זו הרצה אמיתית של הפתרון.
Press Next or Play: see which line Java runs, what is in each box (variable) and what appears on the screen. This is a real run of the solution.
צפו בהרצה צעד אחר צעדWatch it run, step by step
מה קורה עכשיוWhat happens now
הקופסאות (משתנים)The boxes (variables)
מסך הפלטOutput screen
הפתרון המלא והפלט שלוFull solution and its output
import java.util.Map;
public class Main {
public static void main(String[] args) {
Model flaky = new Model() {
int n = 0;
public String complete(String prompt) {
n++;
if (n < 3) {
throw new IllegalStateException("429 too many requests");
}
return "Emma";
}
};
System.out.println(withRetry(flaky, "Pick a novel", 5));
}
static String withRetry(Model m, String prompt, int tries) {
for (int i = 1; i <= tries; i++) {
try {
String r = m.complete(prompt);
return r + " (after " + i + " tries)";
} catch (IllegalStateException e) {
System.out.println("try " + i + " failed: " + e.getMessage());
}
}
return "gave up";
}
}
interface Model {
String complete(String prompt);
}try 1 failed: 429 too many requests try 2 failed: 429 too many requests Emma (after 3 tries)
יש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.