-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathclaude
executable file
·410 lines (367 loc) · 15.6 KB
/
claude
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
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
#!/usr/bin/env node
const fs = require('fs');
const path = require('path');
const execSync = require('child_process').execSync;
const spawnSync = require('child_process').spawnSync;
const https = require('https');
let model = 'claude-3-haiku-20240307'; // see https://docs.anthropic.com/en/docs/about-claude/models#model-names
let maxTokens=4096;
const programname = path.basename(process.argv[1]);
const helpMessage = `
${programname} - Submit a prompt to Claude conversation and print the response to stdout. The prompt can be given on the command line or read from stdin.
Usage: ${programname} [options] [prompt]
Options:
- Reads prompt from stdin; if a prompt is given on the command line it is appended
-f filename Includes the content of the given file as additional message in https://www.stoerr.net/blog/aimouth pattern.
Can be given multiple times. if - is given as filename, the content is read from stdin.
-fp filename Includes the content of the given file as codeblock into the prompt, together with the filename. Can be given multiple times.
-i imagefile Includes the given image file as image, together with the filename. Can be given multiple times.
-iu imageurl Includes the given image url as image, together with the url. Can be given multiple times.
-p prefix Prefix the prompt with a string. Use this or -pf, not both.
-pf prefixfile Prefix the prompt with the contents of a file
-pl key Add a prompt from the ChatGPT prompt library using the given key (see script chatgptpromptlib)
-pa Record audio from the microphone until a key is pressed (using chatgptdictate) and use the result as prompt prefis
-u suffix Suffix the prompt with a string. Use this or -sf, not both.
-uf suffixfile Suffix the prompt with the contents of a file
-ua Record audio from the microphone until a key is pressed (using chatgptdictate) and use the result as prompt suffix
-m modelname Use a specific model (default: ${model})
-mh Use the model with - the time of updating this script - highest intelligence (claude-3-5-sonnet-20240620).
-t number Set max tokens for response (default: ${maxTokens})
-v verbose output : prints the sent and received json message to stderr and gives info about connection retries
-w column Word wrap the response to a specified column width using fmt.
-s systemmsg Use the given string as system message
-sf systemfile Use the contents of the given file as system message
-sl key Add a system message from the ChatGPT prompt library using the given key with chatgptpromptlib
-h, --help Show this help message
-ha, --helpai Answer a question about the tool from this helptext and exit. The rest of the command line (prompt) is the question.
If the prompt or system message contain a construct like promptlib:key , the chatgptpromptlib command will be called with that key
and this will be replaced with the prompt library entry, as an alternative to -pl key .
`;
// probably never supported: -id detaillevel Sets the detail level for the image. Can be 'low', 'high', or 'auto'. Default is 'auto'.
// -a (abbreviate) doesn't make sense with the large context windows and cheap prices nowadays - ask if you need it.
if (process.argv.length < 3) {
console.log(helpMessage);
process.exit(0);
}
const apiKeyFile = `${process.env.HOME}/.anthropic-api-key.txt`;
const apiURL = 'https://api.anthropic.com/v1/messages';
const headers = {
'Content-Type': 'application/json',
'X-API-Key': fs.readFileSync(apiKeyFile, 'utf8').trim(),
'anthropic-version': '2023-06-01'
};
let prompt = '';
let inOptions = true;
let readStdin = false;
let verbose = false;
let prefix = '';
let suffix = '';
let files = [];
let fmfiles = [];
let fmfilemessages = [];
let wordWrapColumn;
let systemMsg = '';
let imageFiles = [];
let imageUrls = [];
let helpaimode = false;
let audioPrefix = false;
let audioSuffix = false;
for (let i = 2; i < process.argv.length; i++) {
const arg = process.argv[i];
if (inOptions) {
if (arg === '--help' || arg === '-h' || arg === ' -?') {
console.log(helpMessage);
process.exit(0);
} else if (arg === '-m' && process.argv[i + 1]) {
model = process.argv[i + 1];
i++;
} else if (arg === '-4') {
model = 'claude-3-5-sonnet-20240620'; // see https://docs.anthropic.com/en/docs/about-claude/models#model-names
} else if (arg === '-t' && process.argv[i + 1]) {
maxTokens = parseInt(process.argv[i + 1], 10);
i++;
} else if (arg === '-') {
readStdin = true;
} else if (arg === '-v') {
verbose = true;
} else if (arg === '-p' && process.argv[i + 1]) {
prefix = process.argv[i + 1];
i++;
} else if (arg === '-pf' && process.argv[i + 1]) {
prefix = fs.readFileSync(process.argv[i + 1], 'utf8');
i++;
} else if (arg === '-pl' && process.argv[i + 1]) {
const promptlibkey = process.argv[i + 1];
try {
const promptlibOutput = execSync(`chatgptpromptlib ${promptlibkey}`, {encoding: 'utf8'});
prompt += '\n' + promptlibOutput + '\n';
} catch (e) {
console.error('Error: Prompt library key not found (1): ' + promptlibkey);
process.exit(1);
}
i++;
} else if (arg === '-u' && process.argv[i + 1]) {
suffix = process.argv[i + 1];
i++;
} else if (arg === '-uf' && process.argv[i + 1]) {
suffix = fs.readFileSync(process.argv[i + 1], 'utf8');
i++;
} else if (arg === '-s' && process.argv[i + 1]) {
systemMsg = process.argv[i + 1];
i++;
} else if (arg === '-sf' && process.argv[i + 1]) {
systemMsg = fs.readFileSync(process.argv[i + 1], 'utf8');
i++;
} else if (arg === '-sl' && process.argv[i + 1]) {
const promptlibkey = process.argv[i + 1];
try {
systemMsg = execSync(`chatgptpromptlib ${promptlibkey}`, {encoding: 'utf8'});
} catch (e) {
console.error('Error: Prompt library key not found (2): ' + promptlibkey);
process.exit(1);
}
i++;
} else if (arg === '-fp' && process.argv[i + 1]) {
files.push(process.argv[i + 1]);
i++;
} else if ((arg === '-fm' || arg === '-f') && process.argv[i + 1]) { // -fm is for backwards compatibility
fmfiles.push(process.argv[i + 1]);
i++;
} else if (arg === '-w' && process.argv[i + 1]) {
wordWrapColumn = parseInt(process.argv[i + 1], 10);
i++;
} else if (arg === '-y' && process.argv[i + 1]) {
systemMsg = process.argv[i + 1];
i++;
} else if (arg === '-i' && process.argv[i + 1]) {
imageFiles.push(process.argv[i + 1]);
i++;
} else if (arg === '-iu' && process.argv[i + 1]) {
imageUrls.push(process.argv[i + 1]);
i++;
} else if (arg === '-pa') {
audioPrefix = true;
} else if (arg === '-ua') {
audioSuffix = true;
} else if (arg === '-ha' || arg === '--helpai') {
helpaimode = true;
} else if (!arg.startsWith('-')) {
inOptions = false;
prompt += arg;
} else {
console.error('Error: Unknown option: ' + arg);
console.error(helpMessage);
process.exit(1);
}
} else {
prompt += ' ' + arg;
}
}
if (readStdin) {
const stdinPrompt = fs.readFileSync(0, 'utf-8');
prompt = stdinPrompt.trim() + '\n\n' + prompt;
}
prompt = replacePromptlibKey(prompt);
if (prefix) {
prompt = prefix.trim() + '\n\n' + prompt;
}
if (suffix) {
prompt = prompt + '\n\n' + suffix.trim();
}
let filecontents = "";
function resolveFile(file) {
let filename = file;
const homeDir = process.env.HOME;
return filename.replace(homeDir, '~');
}
for (let i = 0; i < fmfiles.length; i++) {
const file = fmfiles[i];
if (file === '-') {
const filecontent = fs.readFileSync(0, 'utf-8');
fmfilemessages.push({role: 'user', content: "Print the raw input text the instructions will apply to."});
fmfilemessages.push({role: 'assistant', content: filecontent});
} else {
const filecontent = fs.readFileSync(resolveFile(file), 'utf-8');
fmfilemessages.push({role: 'user', content: "Print the current raw content of the file " + file});
fmfilemessages.push({role: 'assistant', content: filecontent});
}
}
for (let i = 0; i < files.length; i++) {
const file = files[i];
let filename = resolveFile(file);
const filePrompt = fs.readFileSync(file, 'utf-8');
if (files.length > 1) {
filecontents = filecontents + "=== FILE " + (i + 1) + ": " + filename + " ===\n```\n" + filePrompt.trim() + "\n```\n";
} else {
filecontents = filecontents + "```\n" + filePrompt.trim() + "\n```\n";
}
}
if (filecontents) {
prompt = prompt + "\n\n" + filecontents;
}
if (helpaimode) {
fmfilemessages.push({role: 'user', content: "Print the help text for the 'chatgpt' tool. You will use that as background knowledge to answer my question."});
fmfilemessages.push({role: 'assistant', content: helpMessage});
}
if (audioPrefix) {
const audioPrefix = execSync('chatgptdictate', {encoding: 'utf8', stdio: ['inherit', 'pipe', 'pipe']});
if (audioPrefix) {
console.log('Dicated prompt: ' + audioPrefix.trim());
prompt = audioPrefix.trim() + '\n\n' + prompt;
}
}
if (audioSuffix) {
const audioSuffix = execSync('chatgptdictate', {encoding: 'utf8', stdio: ['inherit', 'pipe', 'pipe']});
if (audioSuffix) {
console.log('Dictated prompt suffix: ' + audioSuffix.trim());
prompt = prompt + '\n\n' + audioSuffix.trim();
}
}
if (!prompt || !prompt.trim()) {
console.error('Error: No prompt provided');
console.error(helpMessage);
process.exit(1);
}
if (verbose) {
console.error('Arguments: ', process.argv);
console.error('Prompt: ', prompt, '\n');
console.error('Prompt word count: ', prompt.split(/\s+/).length, '\n');
console.error("---------------------------------------------\n\n");
}
let content = prompt;
function addImageFile(imageFile) {
const imageFileContent = execSync(`base64 -i '${imageFile}'`, {
encoding: 'utf8',
maxBuffer: 1024 * 1024 * 25
}).trim();
const imageFileType = execSync(`file -b --mime-type '${imageFile}'`, {encoding: 'utf8'}).trim();
content.push({
"type": "image",
"source": {
"type": "base64",
"media_type": imageFileType,
"data": imageFileContent
}
});
}
if (imageFiles.length > 0 || imageUrls.length > 0) {
content = [
{
"type": "text",
"text": prompt
}
];
for (let i = 0; i < imageFiles.length; i++) {
const imageFile = imageFiles[i];
addImageFile(imageFile);
}
for (let i = 0; i < imageUrls.length; i++) {
// emulate image file download as this as of 8/24 only supported by OpenAI but not Claude
const imageUrl = imageUrls[i];
const imageFileName = imageUrl.split('/').pop();
// create temp file name with mktemp -u
const tmpfile = execSync('mktemp -u', {encoding: 'utf8'}).trim() + "-" + imageFileName;
// register that for deletion on exit
process.on('exit', () => {
try {
fs.unlinkSync(tmpfile);
} catch (e) {
console.error('Error: Could not delete temporary file ' + tmpfile + ' because of ' + e);
}
});
// download the image, exit if it fails
const curlResult = spawnSync('curl', ['-s', '-o', tmpfile, imageUrl]);
if (curlResult.status !== 0) {
console.error('Error: Could not download image from ' + imageUrl + ' because of ' + curlResult.error);
process.exit(1);
}
addImageFile(tmpfile);
}
}
const requestData = {
model: model,
messages: [{role: 'user', content: content}],
};
if (fmfilemessages.length > 0) {
requestData.messages = fmfilemessages.concat(requestData.messages);
}
if (systemMsg) {
requestData.system = replacePromptlibKey(systemMsg);
}
if (maxTokens) {
requestData.max_tokens = maxTokens;
}
function replacePromptlibKey(inputString) {
if (!inputString) return inputString;
const promptlibRegex = /promptlib:([a-zA-Z0-9_.-]+)/g;
return inputString.replace(promptlibRegex, function (match, key) {
try {
return execSync(`chatgptpromptlib ${key}`, {encoding: 'utf8'});
} catch (e) {
console.error('Error: Prompt library key not found (3): ' + key);
process.exit(1);
}
});
}
function requestClaude(attempt = 1) {
if (verbose) console.error("Request: ", JSON.stringify(requestData, null, 2));
const req = https.request(apiURL, {
method: 'POST',
headers: headers,
}, (res) => {
let data = '';
res.on('data', (chunk) => {
data += chunk;
});
res.on('end', () => {
if (verbose) console.error("Response status: ", res.statusCode);
if (res.statusCode === 429) {
if (verbose) console.error("Retry message: ", data);
let waitTime = 10; // Default wait time if we can't parse it from the response
try {
const retryAfter = res.headers['retry-after'];
if (retryAfter) {
waitTime = parseInt(retryAfter, 10);
}
} catch (e) {
console.error('Error parsing retry-after header:', e);
}
if (attempt < 5) {
if (verbose) {
console.error(`Error: Rate limit exceeded, retrying in ${waitTime} seconds`);
}
setTimeout(() => requestClaude(attempt + 1), waitTime * 1000);
} else {
console.error('Error: Too many retries');
process.exit(4);
}
} else if (res.statusCode === 400) {
console.error('Error: Request failed with status', res.statusCode, 'and message', res.statusMessage, 'and body', data);
process.exit(5);
} else if (res.statusCode !== 200) {
console.error('Error: Request failed with status', res.statusCode, 'and message', res.statusMessage, 'and body', data);
process.exit(5);
} else {
const responseData = JSON.parse(data);
if (verbose) console.error("Response: ", JSON.stringify(responseData, null, 2));
let output = responseData.content[0].text;
if (wordWrapColumn) {
const fmt = spawnSync('fmt', ['-w', wordWrapColumn, '-p'], {input: output, encoding: 'utf8'});
if (fmt.error) {
console.error(`Error: fmt command failed with error ${fmt.error.message}`);
process.exit(7);
}
output = fmt.stdout;
}
console.log(output);
}
});
});
req.on('error', (error) => {
console.error('Error:', error.message);
process.exit(6);
});
req.write(JSON.stringify(requestData));
req.end();
}
requestClaude();