Val Town is a social website to write and deploy JavaScript.
Build APIs and schedule functions from your browser.
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
import { TokenBucket } from "https://esm.town/v/iamseeley/tokenBucket";
const tokenBucket = new TokenBucket(5, 1/12);
export async function getRecommendations(jobDescription, resume, apiKey) {
if (!tokenBucket.consume()) {
throw new Error("Rate limit reached. Please try again later.");
}
const endpoint = 'https://api.openai.com/v1/chat/completions';
const model = 'gpt-4';
const messages = [
{
role: "system",
content: `You are an assistant that helps tailor resumes to job descriptions. Use the job description to provide recommendations on how the resume can be improved to better fit the job. Include advice on keywords for applicant tracking systems.
},
{
role: "user",
content: `Job Description: ${jobDescription}`,
},
{
role: "user",
content: `Resume: ${JSON.stringify(resume)}`,
},
];
const response = await fetch(endpoint, {
method: 'POST',
headers: {
'Authorization': `Bearer ${apiKey}`,
'Content-Type': 'application/json'
},
body: JSON.stringify({
model: model,
messages: messages,
max_tokens: 500,
stream: true,
}),
});
if (!response.ok) {
throw new Error(`Error: ${response.statusText}`);
}
const reader = response.body.getReader();
const decoder = new TextDecoder("utf-8");
let result = '';
while (true) {
const { value, done } = await reader.read();
if (done) break;
const lines = decoder.decode(value, { stream: true }).split('\n').filter(line => line.trim() !== '');
for (const line of lines) {
const message = line.replace(/^data: /, '');
if (message === '[DONE]') return result;
try {
const parsed = JSON.parse(message);
const token = parsed.choices[0].delta.content || '';
result += token;
const escapedToken = token
.replace(/&/g, '&')
.replace(/</g, '&lt;')
.replace(/>/g, '&gt;')
.replace(/"/g, '&quot;')
.replace(/'/g, '&#039;')
.replace(/\n/g, '<br>');
document.getElementById('recommendations').innerHTML += escapedToken;
} catch (error) {
console.error('Could not parse stream message', message, error);
}
}
}
return result;
}
May 27, 2024