Вы знаете что с этим делать, друзья.
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 | const https = require('https');
const http = require('http');
const options = {
hostname: 'play.vercel.ai',
port: 443,
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
};
const readBody = (res, json, onData) => new Promise((resolve, reject) => {
let buffer = '';
res.on('data', chunk => {
onData?.(chunk.toString());
buffer += chunk;
});
res.on('end', () => {
try {
if (json) buffer = JSON.parse(buffer);
resolve(buffer);
} catch (e) {
console.error(buffer);
reject(e);
}
});
})
const request = (path, data, onData) =>
new Promise((resolve, reject) => {
options.headers['User-Agent'] = `Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:109.0) Gecko/${Math.floor(Math.random() * 10000000)} Firefox/${(Math.random() * 200).toFixed(2)}`;
const req = https.request({ ...options, path }, async (res) => {
try {
const body = await readBody(res, false, onData);
resolve(body);
} catch (e) {
reject(e);
}
});
req.write(JSON.stringify(data));
req.end();
});
async function generate(text, { model, temperature, maxTokens, frequencyPenalty, presencePenalty, onData }) {
console.log(`Model: ${model}\nPrompt length: ${text.length}`);
let currentLine = '';
let wasTimeout = false;
let timeout;
const timeoutPromise = new Promise(resolve => {
timeout = setTimeout(() => {
wasTimeout = true;
currentLine = "";
resolve();
}, 15000);
})
await Promise.race([
request('/api/generate', {
prompt: text,
model,
temperature,
maxTokens: Math.min(maxTokens, 511),
topP: 1,
frequencyPenalty,
presencePenalty,
stopSequences: model.startsWith('anthropic:claude') ? ['\nHuman:'] : [],
}, (line) => {
if (wasTimeout) return;
if (timeout) {
process.stdout.write('Generating response ');
clearTimeout(timeout);
timeout = 0;
} else {
process.stdout.write('.');
}
line = ((l) => {
try {
return JSON.parse(l);
} catch (e) {
return l;
}
})(line);
if (model.startsWith('anthropic:claude') && line.trim()) {
onData?.(line.slice(currentLine.length));
currentLine = line;
} else {
onData?.(line);
currentLine += line;
}
}),
timeoutPromise,
]);
console.log(wasTimeout ? 'Timeout' : ' Done');
return currentLine;
}
function preparePrompt(messages) {
return messages.filter(m => m.content?.trim()).map(m => {
let author = '';
switch (m.role) {
case 'user': author = 'Human'; break;
case 'assistant': author = 'Assistant'; break;
case 'system': author = 'System Note'; break;
default: author = m.role; break;
}
return `${author}: ${m.content.trim()}`;
}).join('\n') + `\nAssistant: `;
}
async function main() {
const server = http.createServer(async (req, res) => {
if (req.method.toUpperCase() === 'POST') {
const body = await readBody(req, true);
const [, owner, modelName] = req.url.split('/');
const model = `${owner}:${modelName}`;
const {
messages,
temperature,
max_tokens,
presence_penalty,
frequency_penalty,
stream,
} = body;
if (stream) {
res.setHeader('Content-Type', 'text/event-stream');
} else {
res.setHeader('Content-Type', 'application/json');
}
const id = `chatcmpl-${(Math.random().toString(36).slice(2))}`;
const created = Math.floor(Date.now() / 1000);
if (stream) {
const data = JSON.stringify({
id, created,
object: 'chat.completion.chunk',
model: modelName,
choices: [{
delta: { role: 'assistant' },
finish_reason: null,
index: 0,
}],
});
res.write(`data: ${data}\n\n`);
}
const prompt = preparePrompt(messages);
const result = await generate(prompt, {
model,
temperature,
maxTokens: max_tokens,
frequencyPenalty: frequency_penalty,
presencePenalty: presence_penalty,
onData: (line) => {
if (stream) {
const data = JSON.stringify({
id, created,
object: 'chat.completion.chunk',
model: modelName,
choices: [{
delta: { content: line },
finish_reason: null,
index: 0,
}]
});
res.write(`data: ${data}\n\n`);
}
},
});
if (stream) {
const data = JSON.stringify({
id, created,
object: 'chat.completion.chunk',
model: modelName,
choices: [{
delta: {},
finish_reason: 'stop',
index: 0,
}],
});
res.write(`data: ${data}\n\ndata: [DONE]\n\n`);
} else {
res.write(JSON.stringify({
id, created,
object: 'chat.completion',
model: modelName,
choices: [{
message: {
role: 'assistant',
content: result,
},
finish_reason: 'stop',
index: 0,
}]
}));
}
res.end();
} else {
res.setHeader('Content-Type', 'application/json');
res.write(JSON.stringify({
object: 'list',
data: [
{ id: 'claude-v1', object: 'model', created: Date.now(), owned_by: 'anthropic', permission: [], root: 'claude-v1', parent: null },
{ id: 'gpt-3.5-turbo', object: 'model', created: Date.now(), owned_by: 'openai', permission: [], root: 'gpt-3.5-turbo', parent: null },
]
}));
}
res.end();
});
server.listen(5004, '0.0.0.0', () => {
console.log(`proxy for claude-v1: 'http://127.0.0.1:5004/anthropic/claude-v1'`);
});
}
main().catch(console.error);
|