-
Notifications
You must be signed in to change notification settings - Fork 15
/
test-anthropic-apikey
85 lines (65 loc) · 2.23 KB
/
test-anthropic-apikey
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
// Test Anthropic API v1 (c) MikeRhodes.com.au
// Enter your Anthropic API Key here between the quotes, eg const API_KEY = 'sk-ant-api03-y......AA'
const API_KEY = '';
// You can change this prompt if you want - the goal is to ask a simple question to test that the API is working
const PROMPT = 'Describe the view from the top of the tallest mountain in the world?';
const MODEL = 'claude-3-5-sonnet-20240620';
function main() {
try {
let ouput = generateTextAnthropicAPI(PROMPT, API_KEY, MODEL); // output
Logger.log('Output: ' + ouput);
} catch (error) {
Logger.log('An error occurred: ' + error);
}
}
function generateTextAnthropicAPI(prompt, api_key, model) {
Logger.log('Generating report with Anthropic API');
let url = 'https://api.anthropic.com/v1/messages';
let message = [
{ 'role': 'user', 'content': prompt }
];
let payload = {
'messages': message,
'model': model,
'max_tokens': 500
};
let httpOptions = {
'method': 'POST',
'muteHttpExceptions': true,
'contentType': 'application/json',
'headers': {
'x-api-key': api_key,
'anthropic-version': '2023-06-01'
},
'payload': JSON.stringify(payload)
};
let response = UrlFetchApp.fetch(url, httpOptions);
let rCode = response.getResponseCode();
let rText = response.getContentText();
let start = Date.now();
while (rCode !== 200 && Date.now() - start < 10000) {
Utilities.sleep(1000);
response = UrlFetchApp.fetch(url, httpOptions);
}
if (rCode !== 200) {
Logger.log(`Error: Anthropic API request failed with status ${rCode}.`);
try {
let errorResponse = JSON.parse(rText);
return `Error: ${errorResponse.error.message}`;
} catch (e) {
return 'Error: Failed to parse the Anthropic API error response.';
}
}
let rJson = JSON.parse(rText);
let answerText;
if (rJson && rJson.content && rJson.content.length > 0) {
answerText = rJson.content[0].text;
} else {
answerText = 'No answer found in the response.';
}
return answerText; // Return the extracted text.
}
// Thanks for trying out the script.
// To get updates about my scripts & training, drop me your email here:
// https://pmaxscript.ck.page/update
// PS you're awesome!