-
-
Notifications
You must be signed in to change notification settings - Fork 8.5k
Expand file tree
/
Copy pathhuggingchat.ts
More file actions
679 lines (614 loc) · 22.6 KB
/
Copy pathhuggingchat.ts
File metadata and controls
679 lines (614 loc) · 22.6 KB
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
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
/**
* HuggingChatExecutor — HuggingChat (huggingface.co/chat) Web Provider
*
* Routes chat requests through HuggingChat's SvelteKit-based API.
* Requires a valid session cookie from huggingface.co/chat.
*
* API flow:
* 1. POST /chat/conversation { model } -> { conversationId }
* 2. GET /chat/api/v2/conversations/{id} -> { rootMessageId }
* 3. POST /chat/conversation/{id} (multipart: data = JSON{inputs, id}, optional files)
* -> JSONL stream of MessageUpdate objects
*
* Streaming format (JSONL, not SSE):
* - { type: "stream", token: "..." } -- text tokens (padded to 16 chars with \0)
* - { type: "status", status: "started" } -- generation started
* - { type: "status", status: "keepAlive" } -- heartbeat
* - { type: "finalAnswer", text: "..." } -- complete response
* - { type: "reasoning", subtype: "stream", token: "..." } -- thinking tokens
* - { type: "status", status: "error", message: "..." } -- error
*/
import {
BaseExecutor,
mergeAbortSignals,
mergeUpstreamExtraHeaders,
type ExecuteInput,
} from "./base.ts";
import { FETCH_TIMEOUT_MS } from "../config/constants.ts";
import { buildErrorBody, sanitizeErrorMessage } from "../utils/error.ts";
import { normalizeSessionCookieHeader } from "@/lib/providers/webCookieAuth";
import {
HuggingChatStreamError,
readJsonlResponse,
streamJsonlToOpenAi,
} from "./huggingchat/jsonlStream.ts";
const HUGGINGFACE_BASE = "https://huggingface.co";
const CONVERSATION_URL = `${HUGGINGFACE_BASE}/chat/conversation`;
const API_CONVERSATIONS_URL = `${HUGGINGFACE_BASE}/chat/api/v2/conversations`;
const DEFAULT_COOKIE_NAME = "hf-chat";
const USER_AGENT =
"Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/149.0.0.0 Safari/537.36";
const DEFAULT_MODEL = "baidu/ERNIE-4.5-VL-424B-A47B-Base-PT";
const HUGGINGCHAT_PUBLIC_STREAM_ERROR = "HuggingChat generation failed";
// -- Helpers -----------------------------------------------------------------
function normalizeHuggingChatCookieHeader(apiKey: string): string {
return normalizeSessionCookieHeader(apiKey, DEFAULT_COOKIE_NAME);
}
function isEncryptedCredentialBlob(value: unknown): boolean {
return typeof value === "string" && value.trim().startsWith("enc:v1:");
}
function extractTextFromContent(content: unknown): string {
if (typeof content === "string") return content.trim();
if (!Array.isArray(content)) return "";
return content
.map((part: unknown) => {
if (!part || typeof part !== "object") return "";
const item = part as Record<string, unknown>;
if (item.type === "text" && typeof item.text === "string") return item.text;
if (item.type === "input_text" && typeof item.text === "string") return item.text;
return "";
})
.filter((p: string) => p.trim().length > 0)
.join("\n")
.trim();
}
function buildConversationPrompt(messages: Array<Record<string, unknown>>): {
inputs: string;
systemPrompt: string | null;
} {
const systemParts: string[] = [];
const conversationParts: Array<{ role: string; content: string }> = [];
for (const msg of messages) {
const role = String(msg.role || "user");
const text = extractTextFromContent(msg.content);
if (!text) continue;
if (role === "system" || role === "developer") {
systemParts.push(text);
} else if (role === "user" || role === "assistant") {
conversationParts.push({ role, content: text });
}
}
if (conversationParts.length === 0) {
return { inputs: systemParts.join("\n\n"), systemPrompt: null };
}
if (conversationParts.length === 1 && conversationParts[0].role === "user") {
return {
inputs: conversationParts[0].content,
systemPrompt: systemParts.length > 0 ? systemParts.join("\n\n") : null,
};
}
const lines: string[] = [];
for (const part of conversationParts) {
const label = part.role === "user" ? "User" : "Assistant";
lines.push(`${label}: ${part.content}`);
}
lines.push("Assistant:");
return {
inputs: lines.join("\n\n"),
systemPrompt: systemParts.length > 0 ? systemParts.join("\n\n") : null,
};
}
function estimateTokens(text: string): number {
return Math.max(1, Math.ceil((text || "").length / 4));
}
function getLocalTimezone(): string {
try {
return Intl.DateTimeFormat().resolvedOptions().timeZone || "UTC";
} catch {
return "UTC";
}
}
async function readUpstreamErrorDetails(response: Response): Promise<{
message: string | null;
details: unknown;
}> {
const contentType = response.headers.get("content-type") || "";
const text = await response.text().catch(() => "");
if (!text) return { message: null, details: null };
if (contentType.includes("json")) {
try {
const parsed = JSON.parse(text) as Record<string, unknown>;
const message =
typeof parsed.message === "string"
? parsed.message
: typeof parsed.error === "string"
? parsed.error
: parsed.error &&
typeof parsed.error === "object" &&
typeof (parsed.error as Record<string, unknown>).message === "string"
? String((parsed.error as Record<string, unknown>).message)
: null;
return { message: message ? sanitizeErrorMessage(message) : null, details: parsed };
} catch {
// Fall through to text handling below.
}
}
return { message: sanitizeErrorMessage(text), details: { body: text } };
}
function unwrapSuperjsonPayload(value: unknown): unknown {
if (!value || typeof value !== "object" || Array.isArray(value)) return value;
const record = value as Record<string, unknown>;
return record.json && typeof record.json === "object" ? record.json : value;
}
function extractInitialParentMessageId(value: unknown): string | null {
const payload = unwrapSuperjsonPayload(value);
if (!payload || typeof payload !== "object" || Array.isArray(payload)) return null;
const record = payload as Record<string, unknown>;
if (typeof record.rootMessageId === "string" && record.rootMessageId.trim()) {
return record.rootMessageId;
}
const messages = Array.isArray(record.messages) ? record.messages : [];
const lastMessage = messages.at(-1);
if (lastMessage && typeof lastMessage === "object") {
const id = (lastMessage as Record<string, unknown>).id;
if (typeof id === "string" && id.trim()) return id;
}
return null;
}
async function fetchInitialParentMessageId(
conversationId: string,
headers: Record<string, string>,
signal: AbortSignal
): Promise<string | null> {
const res = await fetch(`${API_CONVERSATIONS_URL}/${conversationId}`, {
method: "GET",
headers,
signal,
});
if (!res.ok) return null;
const text = await res.text().catch(() => "");
if (!text) return null;
try {
return extractInitialParentMessageId(JSON.parse(text));
} catch {
return null;
}
}
function splitCombinedSetCookieHeader(header: string): string[] {
return header
.split(/,(?=\s*[^;,=\s]+=)/)
.map((value) => value.trim())
.filter(Boolean);
}
function getSetCookieHeaders(headers: Headers): string[] {
const maybeGetSetCookie = (headers as Headers & { getSetCookie?: () => string[] }).getSetCookie;
if (typeof maybeGetSetCookie === "function") {
return maybeGetSetCookie.call(headers).filter(Boolean);
}
const combined = headers.get("set-cookie");
return combined ? splitCombinedSetCookieHeader(combined) : [];
}
function parseSetCookiePair(setCookie: string): { name: string; value: string } | null {
const pair = setCookie.split(";", 1)[0]?.trim() || "";
const eq = pair.indexOf("=");
if (eq <= 0) return null;
return { name: pair.slice(0, eq).trim(), value: pair.slice(eq + 1) };
}
function mergeCookieHeaderWithSetCookie(cookieHeader: string, setCookieHeaders: string[]): string {
const cookieMap = new Map<string, string>();
for (const part of cookieHeader.split(";")) {
const trimmed = part.trim();
if (!trimmed) continue;
const eq = trimmed.indexOf("=");
if (eq <= 0) continue;
cookieMap.set(trimmed.slice(0, eq).trim(), trimmed.slice(eq + 1));
}
for (const setCookie of setCookieHeaders) {
const parsed = parseSetCookiePair(setCookie);
if (!parsed || !parsed.value) continue;
cookieMap.set(parsed.name, parsed.value);
}
return [...cookieMap.entries()].map(([name, value]) => `${name}=${value}`).join("; ");
}
// -- Executor ----------------------------------------------------------------
export class HuggingChatExecutor extends BaseExecutor {
constructor() {
super("huggingchat", { id: "huggingchat", baseUrl: HUGGINGFACE_BASE });
}
async execute(input: ExecuteInput): Promise<{
response: Response;
url: string;
headers: Record<string, string>;
transformedBody: unknown;
}> {
const { model, body, stream, credentials, signal, log, upstreamExtraHeaders } = input;
const messages = (body as Record<string, unknown>).messages as
Array<Record<string, unknown>> | undefined;
if (!messages || !Array.isArray(messages) || messages.length === 0) {
return {
response: new Response(
JSON.stringify({
error: { message: "Missing or empty messages array", type: "invalid_request" },
}),
{ status: 400, headers: { "Content-Type": "application/json" } }
),
url: CONVERSATION_URL,
headers: {},
transformedBody: body,
};
}
if (isEncryptedCredentialBlob(credentials.apiKey)) {
return {
response: new Response(
JSON.stringify({
error: {
message:
"HuggingChat credentials are encrypted but STORAGE_ENCRYPTION_KEY is not loaded. " +
"Restore the encryption key or re-save the HuggingChat cookie.",
type: "auth_error",
},
}),
{ status: 401, headers: { "Content-Type": "application/json" } }
),
url: CONVERSATION_URL,
headers: {},
transformedBody: body,
};
}
let cookieHeader = normalizeHuggingChatCookieHeader(credentials.apiKey || "");
if (!cookieHeader) {
return {
response: new Response(
JSON.stringify({
error: {
message:
"HuggingChat requires a session cookie. Log in to huggingface.co/chat, " +
"open DevTools > Application > Cookies, and copy the hf-chat cookie value.",
type: "auth_error",
},
}),
{ status: 401, headers: { "Content-Type": "application/json" } }
),
url: CONVERSATION_URL,
headers: {},
transformedBody: body,
};
}
const resolvedModel = model || DEFAULT_MODEL;
const { inputs, systemPrompt } = buildConversationPrompt(messages);
if (!inputs.trim()) {
return {
response: new Response(
JSON.stringify({
error: { message: "Empty prompt after processing messages", type: "invalid_request" },
}),
{ status: 400, headers: { "Content-Type": "application/json" } }
),
url: CONVERSATION_URL,
headers: {},
transformedBody: body,
};
}
const baseHeaders: Record<string, string> = {
Cookie: cookieHeader,
"User-Agent": USER_AGENT,
Origin: HUGGINGFACE_BASE,
Referer: `${HUGGINGFACE_BASE}/chat/`,
};
// -- Step 1: Create conversation ----------------------------------------
const timeoutSignal = AbortSignal.timeout(FETCH_TIMEOUT_MS);
const combinedSignal = signal ? mergeAbortSignals(signal, timeoutSignal) : timeoutSignal;
let conversationId: string;
try {
const createBody: Record<string, unknown> = { model: resolvedModel };
if (systemPrompt) createBody.preprompt = systemPrompt;
const createRes = await fetch(CONVERSATION_URL, {
method: "POST",
headers: { ...baseHeaders, "Content-Type": "application/json" },
body: JSON.stringify(createBody),
signal: combinedSignal,
});
if (!createRes.ok) {
const status = createRes.status;
const upstreamError = await readUpstreamErrorDetails(createRes);
let message = `HuggingChat conversation creation failed (HTTP ${status})`;
if (status === 401 || status === 403) {
message =
"HuggingChat auth failed -- your hf-chat session cookie may be missing or expired. " +
"Log in to huggingface.co/chat and re-paste your cookie.";
} else if (status === 429) {
message = "HuggingChat rate limited. Wait a moment and retry.";
}
if (upstreamError.message) {
message = `${message}: ${upstreamError.message}`;
}
return {
response: new Response(
JSON.stringify(buildErrorBody(status, message, upstreamError.details)),
{ status, headers: { "Content-Type": "application/json" } }
),
url: CONVERSATION_URL,
headers: baseHeaders,
transformedBody: body,
};
}
const createData = (await createRes.json()) as Record<string, unknown>;
conversationId = createData.conversationId as string;
const createSetCookieHeaders = getSetCookieHeaders(createRes.headers);
cookieHeader = mergeCookieHeaderWithSetCookie(cookieHeader, createSetCookieHeaders);
baseHeaders.Cookie = cookieHeader;
if (!conversationId) {
return {
response: new Response(
JSON.stringify({
error: {
message: "HuggingChat did not return a conversationId",
type: "upstream_error",
},
}),
{ status: 502, headers: { "Content-Type": "application/json" } }
),
url: CONVERSATION_URL,
headers: baseHeaders,
transformedBody: body,
};
}
} catch (err) {
const message = sanitizeErrorMessage(err instanceof Error ? err.message : String(err));
log?.error?.("HUGGINGCHAT", `Conversation creation failed: ${message}`);
return {
response: new Response(
JSON.stringify(
buildErrorBody(502, `HuggingChat connection failed: ${message}`, undefined, {
type: "upstream_error",
})
),
{ status: 502, headers: { "Content-Type": "application/json" } }
),
url: CONVERSATION_URL,
headers: baseHeaders,
transformedBody: body,
};
}
// -- Step 2: Send message -----------------------------------------------
const parentMessageId = await fetchInitialParentMessageId(
conversationId,
baseHeaders,
combinedSignal
);
if (!parentMessageId) {
return {
response: new Response(
JSON.stringify({
error: {
message: "HuggingChat did not return an initial parent message id",
type: "upstream_error",
},
}),
{ status: 502, headers: { "Content-Type": "application/json" } }
),
url: `${API_CONVERSATIONS_URL}/${conversationId}`,
headers: baseHeaders,
transformedBody: body,
};
}
const messageUrl = `${CONVERSATION_URL}/${conversationId}`;
const formData = new FormData();
const sendDataPayload: Record<string, unknown> = {
inputs,
is_retry: false,
is_continue: false,
generationId: crypto.randomUUID(),
selectedMcpServerNames: [],
selectedMcpServers: [],
timezone: getLocalTimezone(),
id: parentMessageId,
};
formData.append("data", JSON.stringify(sendDataPayload));
mergeUpstreamExtraHeaders(baseHeaders, upstreamExtraHeaders);
let upstreamResponse: Response;
try {
upstreamResponse = await fetch(messageUrl, {
method: "POST",
headers: baseHeaders,
body: formData,
signal: combinedSignal,
});
} catch (err) {
const message = sanitizeErrorMessage(err instanceof Error ? err.message : String(err));
log?.error?.("HUGGINGCHAT", `Message send failed: ${message}`);
return {
response: new Response(
JSON.stringify(
buildErrorBody(502, `HuggingChat connection failed: ${message}`, undefined, {
type: "upstream_error",
})
),
{ status: 502, headers: { "Content-Type": "application/json" } }
),
url: messageUrl,
headers: baseHeaders,
transformedBody: sendDataPayload,
};
}
if (!upstreamResponse.ok) {
const status = upstreamResponse.status;
const upstreamError = await readUpstreamErrorDetails(upstreamResponse);
let message = `HuggingChat returned HTTP ${status}`;
if (status === 401 || status === 403) {
message = "HuggingChat auth failed -- session cookie may be expired.";
} else if (status === 429) {
message = "HuggingChat rate limited. Wait a moment and retry.";
} else if (status === 404) {
message = `HuggingChat model not found: ${resolvedModel}. Check the model ID.`;
}
if (upstreamError.message) {
message = `${message}: ${upstreamError.message}`;
}
return {
response: new Response(
JSON.stringify(buildErrorBody(status, message, upstreamError.details)),
{ status, headers: { "Content-Type": "application/json" } }
),
url: messageUrl,
headers: baseHeaders,
transformedBody: sendDataPayload,
};
}
if (!upstreamResponse.body) {
return {
response: new Response(
JSON.stringify({
error: { message: "HuggingChat returned empty response body", type: "upstream_error" },
}),
{ status: 502, headers: { "Content-Type": "application/json" } }
),
url: messageUrl,
headers: baseHeaders,
transformedBody: sendDataPayload,
};
}
// -- Step 3: Build response ---------------------------------------------
const id = `chatcmpl-huggingchat-${crypto.randomUUID().slice(0, 12)}`;
const created = Math.floor(Date.now() / 1000);
if (stream) {
const encoder = new TextEncoder();
const streamCancellationController = new AbortController();
const jsonlStream = streamJsonlToOpenAi(
upstreamResponse.body,
resolvedModel,
id,
created,
signal,
streamCancellationController.signal
);
const primedChunks: string[] = [];
try {
const first = await jsonlStream.next();
if (!first.done) {
primedChunks.push(first.value);
if (first.value.includes('"role":"assistant"')) {
const content = await jsonlStream.next();
if (!content.done) primedChunks.push(content.value);
}
}
} catch (err) {
if (!(err instanceof HuggingChatStreamError)) throw err;
const message = err instanceof Error ? err.message : String(err);
const safeMessage = sanitizeErrorMessage(message);
log?.error?.("HUGGINGCHAT", `Stream failed before content: ${safeMessage}`);
return {
response: new Response(
JSON.stringify(
buildErrorBody(502, message, undefined, {
type: "upstream_error",
code: "huggingchat_generation_error",
})
),
{ status: 502, headers: { "Content-Type": "application/json" } }
),
url: messageUrl,
headers: baseHeaders,
transformedBody: sendDataPayload,
};
}
let primedChunkIndex = 0;
let streamCancelled = false;
const sseStream = new ReadableStream<Uint8Array>({
async pull(controller) {
if (streamCancelled) return;
if (primedChunkIndex < primedChunks.length) {
controller.enqueue(encoder.encode(primedChunks[primedChunkIndex]));
primedChunkIndex += 1;
return;
}
try {
const chunk = await jsonlStream.next();
if (streamCancelled) return;
if (chunk.done) {
controller.close();
return;
}
controller.enqueue(encoder.encode(chunk.value));
} catch (err) {
if (streamCancelled) return;
const message = err instanceof Error ? err.message : String(err);
const safeMessage = sanitizeErrorMessage(message);
log?.error?.("HUGGINGCHAT", `Stream error: ${safeMessage}`);
controller.error(
Object.assign(new Error(HUGGINGCHAT_PUBLIC_STREAM_ERROR), { statusCode: 502 })
);
}
},
cancel() {
streamCancelled = true;
streamCancellationController.abort();
void jsonlStream.return(undefined).catch(() => undefined);
},
});
return {
response: new Response(sseStream, {
status: 200,
headers: {
"Content-Type": "text/event-stream",
"Cache-Control": "no-cache",
"X-Accel-Buffering": "no",
},
}),
url: messageUrl,
headers: baseHeaders,
transformedBody: sendDataPayload,
};
}
let fullText: string;
try {
fullText = await readJsonlResponse(upstreamResponse.body, signal);
} catch (err) {
if (!(err instanceof HuggingChatStreamError)) throw err;
const message = err instanceof Error ? err.message : String(err);
const safeMessage = sanitizeErrorMessage(message);
log?.error?.("HUGGINGCHAT", `Generation error: ${safeMessage}`);
return {
response: new Response(
JSON.stringify(
buildErrorBody(502, message, undefined, {
type: "upstream_error",
code: "huggingchat_generation_error",
})
),
{ status: 502, headers: { "Content-Type": "application/json" } }
),
url: messageUrl,
headers: baseHeaders,
transformedBody: sendDataPayload,
};
}
const completionTokens = estimateTokens(fullText);
return {
response: new Response(
JSON.stringify({
id,
object: "chat.completion",
created,
model: resolvedModel,
choices: [
{
index: 0,
message: { role: "assistant", content: fullText },
finish_reason: "stop",
},
],
usage: {
prompt_tokens: estimateTokens(inputs),
completion_tokens: completionTokens,
total_tokens: estimateTokens(inputs) + completionTokens,
},
}),
{ status: 200, headers: { "Content-Type": "application/json" } }
),
url: messageUrl,
headers: baseHeaders,
transformedBody: sendDataPayload,
};
}
}