-
-
Notifications
You must be signed in to change notification settings - Fork 8.5k
Expand file tree
/
Copy pathlmarena.ts
More file actions
224 lines (205 loc) · 6.95 KB
/
Copy pathlmarena.ts
File metadata and controls
224 lines (205 loc) · 6.95 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
/**
* LMArenaExecutor — Arena (formerly LMArena) web-session provider.
*
* Routes requests through arena.ai create-evaluation with session cookies.
* Upstream sits behind Cloudflare; traffic goes through wreq-js Chrome
* impersonation with isolated ephemeral cookies (see services/lmarenaTlsClient.ts).
*
* Helpers: open-sse/executors/lmarena/{cookie,models,stream,response}.ts
*/
import { v7 as uuidv7 } from "uuid";
import { BaseExecutor, type ExecuteInput } from "./base.ts";
import { tlsFetchLMArena, TlsClientUnavailableError } from "../services/lmarenaTlsClient.ts";
import { readLMArenaCookie, reconstructLMArenaCookie } from "./lmarena/cookie.ts";
import {
LMARENA_STREAM_URL,
LMARENA_USER_AGENT,
buildLmarenaBrowserHeaders,
markLMArenaCatalogModelDead,
normalizeLMArenaModelsForCatalog,
parseLMArenaInitialModels,
pickLMArenaModelId,
resolveLMArenaModelId,
type LMArenaModelMetadata,
} from "./lmarena/models.ts";
import { formatArenaPrompt, parseArenaSSE } from "./lmarena/stream.ts";
import {
buildArenaUpstreamHttpResponse,
createOpenAIArenaStream,
handleNonStreamingArenaResponse,
mapFailedTlsResult,
mapNetworkError,
mapTlsUnavailable,
missingCookieResult,
} from "./lmarena/response.ts";
export {
reconstructLMArenaCookie,
normalizeLMArenaModelsForCatalog,
parseLMArenaInitialModels,
pickLMArenaModelId,
parseArenaSSE,
markLMArenaCatalogModelDead,
LMARENA_USER_AGENT,
};
export { clearLMArenaDeadCatalogModels } from "./lmarena/models.ts";
export type { LMArenaModelMetadata };
interface OpenAIMessage {
role?: string;
content?: unknown;
}
/** Optional browser-issued reCAPTCHA v3 token (operator-supplied). */
function readRecaptchaToken(credentials: unknown, body: unknown): string | null {
const fromObj = (v: unknown): string | null => {
if (!v || typeof v !== "object") return null;
const rec = v as Record<string, unknown>;
const direct = rec.recaptchaV3Token ?? rec.recaptchaToken;
if (typeof direct === "string" && direct.trim()) return direct.trim();
const psd = rec.providerSpecificData;
if (psd && typeof psd === "object") {
const nested = psd as Record<string, unknown>;
const t = nested.recaptchaV3Token ?? nested.recaptchaToken;
if (typeof t === "string" && t.trim()) return t.trim();
}
return null;
};
return fromObj(credentials) ?? fromObj(body);
}
export class LMArenaExecutor extends BaseExecutor {
constructor(providerConfig = {}) {
super("lmarena", { format: "openai", ...providerConfig });
}
// Public to match BaseExecutor.buildUrl — a subclass may widen visibility but not
// narrow it. This was masked behind the buildHeaders TS2416 until that one cleared.
buildUrl(_model: string, _credentials: unknown): string {
return LMARENA_STREAM_URL;
}
protected buildRequestHeaders(
_model: string,
credentials: unknown,
_body: unknown
): Record<string, string> {
const cookie = readLMArenaCookie(credentials);
const headers = buildLmarenaBrowserHeaders({
"Content-Type": "application/json",
Accept: "text/event-stream",
});
if (cookie) headers.Cookie = cookie;
return headers;
}
transformRequest(body: unknown, model: string, credentials?: unknown): unknown {
const openaiBody = body && typeof body === "object" ? (body as Record<string, unknown>) : {};
const messages = Array.isArray(openaiBody.messages)
? (openaiBody.messages as OpenAIMessage[])
: [];
return {
id: uuidv7(),
mode: "direct-battle",
modelAId: model,
userMessageId: uuidv7(),
modelAMessageId: uuidv7(),
userMessage: {
content: formatArenaPrompt(messages),
experimental_attachments: [],
metadata: {},
},
modality: "chat",
recaptchaV3Token: readRecaptchaToken(credentials, body),
};
}
async execute(input: ExecuteInput) {
const { model, body, stream, credentials, signal, log } = input;
const url = this.buildUrl(model, credentials);
const headers = this.buildRequestHeaders(model, credentials, body);
const cookie = readLMArenaCookie(credentials);
if (!cookie) {
return missingCookieResult(url, headers, this.transformRequest(body, model, credentials));
}
const arenaModelId = await resolveLMArenaModelId(model, log);
const transformedBody = this.transformRequest(body, arenaModelId, credentials) as Record<
string,
unknown
>;
log?.info?.(
"LMArenaExecutor",
arenaModelId === model
? `Executing request for model: ${model}`
: `Executing request for model: ${model} (${arenaModelId})`
);
try {
return await this.dispatchTls(url, headers, transformedBody, {
model,
arenaModelId,
stream: !!stream,
signal,
log,
});
} catch (error) {
if (error instanceof TlsClientUnavailableError) {
log?.error?.("LMArenaExecutor", `TLS client unavailable: ${error.message}`);
return mapTlsUnavailable(error, url, headers, transformedBody);
}
const message = error instanceof Error ? error.message : String(error);
log?.error?.("LMArenaExecutor", `Request failed: ${message}`);
return mapNetworkError(message, url, headers, transformedBody);
}
}
private async dispatchTls(
url: string,
headers: Record<string, string>,
transformedBody: Record<string, unknown>,
ctx: {
model: string;
arenaModelId: string;
stream: boolean;
signal?: AbortSignal;
log?: ExecuteInput["log"];
}
) {
const tlsResult = await tlsFetchLMArena(url, {
method: "POST",
headers,
body: JSON.stringify(transformedBody),
signal: ctx.signal,
stream: ctx.stream,
});
const failed = mapFailedTlsResult({
status: tlsResult.status,
text: tlsResult.text,
hasRecaptcha: transformedBody.recaptchaV3Token != null,
model: ctx.model,
arenaModelId: ctx.arenaModelId,
url,
headers,
transformedBody,
});
if (failed) return failed;
const upstream = buildArenaUpstreamHttpResponse({
stream: ctx.stream,
status: tlsResult.status,
text: tlsResult.text,
body: tlsResult.body,
});
const response = ctx.stream
? await this.handleStreamingResponse(upstream, ctx.model, ctx.signal, ctx.log)
: await handleNonStreamingArenaResponse(upstream, ctx.model);
return { response, url, headers, transformedBody };
}
private async handleStreamingResponse(
response: Response,
model: string,
signal?: AbortSignal,
log?: ExecuteInput["log"]
): Promise<Response> {
const reader = response.body?.getReader();
if (!reader) throw new Error("No response body for streaming");
const out = createOpenAIArenaStream({ reader, model, signal, log });
return new Response(out, {
status: 200,
headers: {
"Content-Type": "text/event-stream",
"Cache-Control": "no-cache",
Connection: "keep-alive",
},
});
}
}