-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathserver.ts
209 lines (190 loc) · 5.49 KB
/
server.ts
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
/**
* @module server.ts
* @description A simple chatbot server that uses the Hugging Face transformers pipeline.
*/
// deno-lint-ignore-file no-explicit-any
import { pipeline } from "npm:@huggingface/[email protected]";
import { parse } from "jsr:@std/[email protected]";
import { exists } from "jsr:@std/[email protected]";
import { type Handler, router } from "jsr:@denosaurs/[email protected]";
import { parseArgs } from "jsr:@std/[email protected]/parse-args";
import { cyan, gray } from "jsr:@std/[email protected]/colors";
import { help, modelCallback } from "./utils.ts";
let systemStuff: string[] | undefined;
let model: string | undefined;
let config: any;
/**
* Parse the command line arguments
*/
const args = parseArgs(Deno.args, {
boolean: ["help", "openai"],
string: ["model", "device"],
alias: { help: ["h"], model: ["m"], device: ["d"] },
});
if (args.help) {
help();
}
if (await exists("./chat-config.toml")) {
console.log("Loading configuration from chat-config.toml...\n");
config = parse(await Deno.readTextFile("chat-config.toml")) as any;
if (config.config?.model) {
model = config.config.model;
}
if (config.config?.system) {
systemStuff = config.config.system;
}
}
if (args.model) {
model = args.model;
}
const generator = await pipeline(
"text-generation",
model || "onnx-community/Llama-3.2-1B-Instruct",
{
device: args.device as any,
progress_callback: modelCallback,
},
);
console.log(
gray(
`Model: ${
model ? cyan(model.split("/")[1]) : cyan("Llama-3.2-1B-Instruct")
}`,
),
);
const routes: Handler = router({
[args.openai ? "v1/completions" : "/api/completions"]: async (req, _) => {
try {
const body = await req.json();
const prompt = body.prompt;
const max_tokens = body.max_tokens ||
(config ? config.config?.max_new_tokens || 128 : 128);
const temperature = body.temperature || 1.0;
const top_p = body.top_p || 1.0;
if (!prompt) {
return new Response(
JSON.stringify({ error: "Prompt is required." }),
{
status: 400,
headers: { "Content-Type": "application/json" },
},
);
}
const messages = [
{
role: "system",
content: systemStuff
? systemStuff.join("\n")
: "You are a helpful assistant",
},
{
role: "user",
content: prompt,
},
];
const output = await generator(messages, {
max_new_tokens: max_tokens,
temperature,
top_p,
});
const responseText = (output[0] as any).generated_text?.at(-1)?.content ||
"";
const response = {
id: `cmpl-${crypto.randomUUID()}`,
object: "text_completion",
created: Math.floor(Date.now() / 1000),
model: model || "onnx-community/Llama-3.2-1B-Instruct",
choices: [
{
text: responseText,
index: 0,
logprobs: null,
finish_reason: "stop",
},
],
usage: {
prompt_tokens: prompt.length,
completion_tokens: responseText.length,
total_tokens: prompt.length + responseText.length,
},
};
return new Response(JSON.stringify(response), {
status: 200,
headers: { "Content-Type": "application/json" },
});
} catch (error) {
console.error("Error processing request:", error);
return new Response(
JSON.stringify({ error: "Internal Server Error" }),
{
status: 500,
headers: { "Content-Type": "application/json" },
},
);
}
},
[args.openai ? "v1/chat/completions" : "api/chat"]: async (req, _) => {
try {
const body = await req.json();
const messages = body.messages;
const max_tokens = body.max_tokens ||
(config ? config.config?.max_new_tokens || 128 : 128);
const temperature = body.temperature || 1.0;
const top_p = body.top_p || 1.0;
if (!messages) {
return new Response(
JSON.stringify({ error: "Messages are required." }),
{
status: 400,
headers: { "Content-Type": "application/json" },
},
);
}
const output = await generator(messages, {
max_new_tokens: max_tokens,
temperature,
top_p,
});
const responseText = (output[0] as any).generated_text?.at(-1)?.content ||
"";
const response = {
id: `cmpl-${crypto.randomUUID()}`,
object: "text_completion",
created: Math.floor(Date.now() / 1000),
model: model || "onnx-community/Llama-3.2-1B-Instruct",
choices: [
{
text: responseText,
index: 0,
logprobs: null,
finish_reason: "stop",
},
],
usage: {
prompt_tokens: prompt.length,
completion_tokens: responseText.length,
total_tokens: prompt.length + responseText.length,
},
};
return new Response(JSON.stringify(response), {
status: 200,
headers: { "Content-Type": "application/json" },
});
} catch (error) {
console.error("Error processing request:", error);
return new Response(
JSON.stringify({ error: "Internal Server Error" }),
{
status: 500,
headers: { "Content-Type": "application/json" },
},
);
}
},
});
export default {
/**
* @description Fetch completions from the model
*/
fetch: routes,
};