-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathClipLLM.java
More file actions
157 lines (132 loc) · 6.3 KB
/
Copy pathClipLLM.java
File metadata and controls
157 lines (132 loc) · 6.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
// ClipLLM.java — Build this yourself, step by step!
import java.awt.Toolkit;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.StringSelection;
import java.lang.Thread;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
public class ClipLLM {
// Config
static final String OLLAMA_URL = "http://localhost:11434/api/generate";
static final String PRIMARY_MODEL = "gemma4:e4b";
static final String FALLBACK_MODEL = "nemotron-3-nano:4b";
static final String TRIGGER = "//ollama ";
static final int POLL_INTERVAL_MS = 500;
// ──── Step 1: Read Clipboard ────────────────────────────
static String getClipboard() {
try {
Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
Object data = clipboard.getData(DataFlavor.stringFlavor);
return data.toString();
} catch (Exception e) {
return "";
}
}
static void setClipboard(String text) {
try {
StringSelection selection = new StringSelection(text);
Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
clipboard.setContents(selection, null);
} catch (Exception e) {
System.out.println(" ⚠️ Error writing to clipboard: " + e.getMessage());
}
}
// Helper to make the prompt safe for JSON (handles quotes and newlines)
static String escapeJson(String text) {
return text.replace("\\", "\\\\")
.replace("\"", "\\\"")
.replace("\n", "\\n")
.replace("\r", "\\r")
.replace("\t", "\\t");
}
static String queryOllama(String prompt, String model) {
try {
HttpClient client = HttpClient.newHttpClient();
String safePrompt = escapeJson(prompt);
String jsonBody = "{\"model\":\"" + model + "\", \"prompt\":\"" + safePrompt + "\", \"stream\":false}";
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create(OLLAMA_URL))
.header("Content-Type", "application/json")
.POST(HttpRequest.BodyPublishers.ofString(jsonBody))
.build();
HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
if (response.statusCode() == 200) {
String body = response.body();
int start = body.indexOf("\"response\":\"") + 12;
int end = body.lastIndexOf("\",\"done\":");
if (start > 11 && end > start) {
String result = body.substring(start, end);
return result.replace("\\n", "\n")
.replace("\\\"", "\"")
.replace("\\\\", "\\")
.trim();
}
return "Error: Could not parse response";
} else {
return "Error: Ollama returned " + response.statusCode();
}
} catch (java.net.http.HttpConnectTimeoutException e) {
return "Error: Connection timed out";
} catch (Exception e) {
return "Error: " + e.getMessage();
}
}
static String queryWithFallback(String prompt) {
System.out.println(" ⏳ Querying " + PRIMARY_MODEL + "...");
String response = queryOllama(prompt, PRIMARY_MODEL);
if (response.startsWith("Error:") || response.isEmpty()) {
System.out.println(" ⚠️ " + PRIMARY_MODEL + " failed: " + response);
System.out.println(" 🔄 Falling back to " + FALLBACK_MODEL + "...");
return queryOllama(prompt, FALLBACK_MODEL);
}
return response;
}
public static void main(String[] args) {
System.out.println("\n ╔══════════════════════════════════════════════════╗");
printConfigLine("ClipLLM Java IS RUNNING", "");
System.out.println(" ╠══════════════════════════════════════════════════╣");
printConfigLine("Primary:", PRIMARY_MODEL);
printConfigLine("Fallback:", FALLBACK_MODEL);
printConfigLine("Trigger:", TRIGGER);
System.out.println(" ╚══════════════════════════════════════════════════╝\n");
String lastClipboard = getClipboard();
while (true) {
try {
Thread.sleep(POLL_INTERVAL_MS);
String currentClipboard = getClipboard();
if (currentClipboard.equals(lastClipboard)) {
continue;
}
lastClipboard = currentClipboard;
if (currentClipboard.startsWith(TRIGGER)) {
String prompt = currentClipboard.substring(TRIGGER.length()).trim();
if (prompt.isEmpty()) {
System.out.println(" Empty prompt detected.");
continue;
}
System.out.println(
"prompt: \"" + (prompt.length() > 60 ? prompt.substring(0, 57) + "..." : prompt) + "\"");
String result = queryWithFallback(prompt);
if (result.startsWith("Error:")) {
System.out.println("SOS: " + result);
} else {
setClipboard(result);
lastClipboard = result;
System.out.println("Done! Response copied to clipboard.");
}
System.out.println();
}
} catch (Exception e) {
System.out.println("\n Stopping ClipLLM...");
break;
}
}
}
private static void printConfigLine(String label, String value) {
String line = String.format(" ║ %-10s %-35s ║", label, value);
System.out.println(line);
}
}