Spaces:
Runtime error
Runtime error
File size: 12,343 Bytes
cd8bd0a | 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 | /**
* Conversation normalizer — converts OpenAI / Anthropic / Gemini request +
* response payloads into a single provider-agnostic shape.
*
* MIT — port from https://github.com/chouzz/llm-interceptor (ui/utils.ts)
*
* Returns `null` for non-LLM requests or payloads we cannot understand —
* never throws — so the renderer can fall back to the raw view.
*/
import { mergeStream, parseSseStream } from "./sseMerger.ts";
import type {
InterceptedRequest,
NormalizedBlock,
NormalizedConversation,
NormalizedTurn,
} from "./types.ts";
type NormalizedRole = NormalizedTurn["role"];
function asRecord(value: unknown): Record<string, unknown> | null {
if (value && typeof value === "object" && !Array.isArray(value)) {
return value as Record<string, unknown>;
}
return null;
}
function tryParseJson(value: string | null | undefined): unknown {
if (!value) return null;
try {
return JSON.parse(value);
} catch {
return null;
}
}
function normalizeRole(raw: unknown): NormalizedRole {
if (raw === "system" || raw === "user" || raw === "assistant" || raw === "tool") {
return raw;
}
if (raw === "model") return "assistant";
if (raw === "function") return "tool";
return "user";
}
/**
* OpenAI / Anthropic message content can be a string, or an array of blocks.
* Returns a list of normalized blocks.
*/
function blocksFromOpenAiContent(content: unknown): NormalizedBlock[] {
if (content == null) return [];
if (typeof content === "string") {
if (content.length === 0) return [];
return [{ type: "text", text: content }];
}
if (!Array.isArray(content)) return [];
const out: NormalizedBlock[] = [];
for (const raw of content) {
if (typeof raw === "string") {
out.push({ type: "text", text: raw });
continue;
}
const block = asRecord(raw);
if (!block) continue;
const type = block.type;
if (type === "text" || type === "output_text") {
const text = typeof block.text === "string" ? block.text : "";
out.push({ type: "text", text });
} else if (type === "input_text") {
const text = typeof block.text === "string" ? block.text : "";
out.push({ type: "text", text });
} else if (type === "tool_use") {
out.push({
type: "tool_use",
id: typeof block.id === "string" ? block.id : "",
name: typeof block.name === "string" ? block.name : "",
input: block.input ?? {},
});
} else if (type === "tool_result") {
out.push({
type: "tool_result",
tool_use_id:
typeof block.tool_use_id === "string" ? block.tool_use_id : "",
content: block.content ?? null,
});
} else if (typeof block.text === "string") {
out.push({ type: "text", text: block.text });
}
}
return out;
}
/**
* OpenAI assistant messages may declare `tool_calls`. Each becomes a
* `tool_use` block alongside any text content.
*/
function appendOpenAiToolCalls(
blocks: NormalizedBlock[],
toolCalls: unknown
): NormalizedBlock[] {
if (!Array.isArray(toolCalls)) return blocks;
for (const raw of toolCalls) {
const tc = asRecord(raw);
if (!tc) continue;
const fn = asRecord(tc.function) ?? {};
let parsedInput: unknown = {};
if (typeof fn.arguments === "string") {
try {
parsedInput = JSON.parse(fn.arguments);
} catch {
parsedInput = fn.arguments;
}
} else if (fn.arguments != null) {
parsedInput = fn.arguments;
}
blocks.push({
type: "tool_use",
id: typeof tc.id === "string" ? tc.id : "",
name: typeof fn.name === "string" ? fn.name : "",
input: parsedInput,
});
}
return blocks;
}
/**
* Build NormalizedTurn[] from OpenAI / Anthropic chat messages.
*/
function turnsFromOpenAiMessages(messages: unknown[]): NormalizedTurn[] {
const out: NormalizedTurn[] = [];
for (const raw of messages) {
const msg = asRecord(raw);
if (!msg) continue;
const role = normalizeRole(msg.role);
if (msg.role === "tool" || msg.role === "function") {
const content = msg.content;
out.push({
role: "tool",
blocks: [
{
type: "tool_result",
tool_use_id:
typeof msg.tool_call_id === "string"
? msg.tool_call_id
: typeof msg.name === "string"
? msg.name
: "",
content,
},
],
});
continue;
}
const blocks = blocksFromOpenAiContent(msg.content);
if ("tool_calls" in msg) {
appendOpenAiToolCalls(blocks, msg.tool_calls);
}
if (blocks.length === 0 && msg.content == null && !("tool_calls" in msg)) {
continue;
}
out.push({ role, blocks });
}
return out;
}
/**
* Gemini contents have a different shape: `[{role, parts: [{text|...}]}]`.
*/
function turnsFromGeminiContents(contents: unknown[]): NormalizedTurn[] {
const out: NormalizedTurn[] = [];
for (const raw of contents) {
const turn = asRecord(raw);
if (!turn) continue;
const role = normalizeRole(turn.role);
const blocks: NormalizedBlock[] = [];
if (Array.isArray(turn.parts)) {
for (const partRaw of turn.parts) {
const part = asRecord(partRaw);
if (!part) continue;
if (typeof part.text === "string") {
blocks.push({ type: "text", text: part.text });
} else if (part.functionCall) {
const fc = asRecord(part.functionCall) ?? {};
blocks.push({
type: "tool_use",
id: typeof fc.name === "string" ? fc.name : "",
name: typeof fc.name === "string" ? fc.name : "",
input: fc.args ?? {},
});
} else if (part.functionResponse) {
const fr = asRecord(part.functionResponse) ?? {};
blocks.push({
type: "tool_result",
tool_use_id: typeof fr.name === "string" ? fr.name : "",
content: fr.response ?? null,
});
}
}
}
if (blocks.length > 0) out.push({ role, blocks });
}
return out;
}
/**
* Anthropic Messages API requests carry a top-level `system` field (string
* or array of `{type:"text"|text}` blocks). Convert to a `system` turn.
*/
function systemTurnFromAnthropic(system: unknown): NormalizedTurn | null {
if (!system) return null;
if (typeof system === "string") {
return system.length === 0
? null
: { role: "system", blocks: [{ type: "text", text: system }] };
}
if (!Array.isArray(system)) return null;
const blocks: NormalizedBlock[] = [];
for (const raw of system) {
const item = asRecord(raw);
if (item && typeof item.text === "string") {
blocks.push({ type: "text", text: item.text });
} else if (typeof raw === "string") {
blocks.push({ type: "text", text: raw });
}
}
if (blocks.length === 0) return null;
return { role: "system", blocks };
}
function buildRequestTurns(body: unknown): NormalizedTurn[] | null {
const obj = asRecord(body);
if (!obj) return null;
if (Array.isArray(obj.messages)) {
const turns: NormalizedTurn[] = [];
const systemTurn = systemTurnFromAnthropic(obj.system);
if (systemTurn) turns.push(systemTurn);
turns.push(...turnsFromOpenAiMessages(obj.messages));
return turns;
}
if (Array.isArray(obj.contents)) {
const turns: NormalizedTurn[] = [];
const sysObj = asRecord(obj.systemInstruction);
if (sysObj && Array.isArray(sysObj.parts)) {
const parts: NormalizedBlock[] = [];
for (const partRaw of sysObj.parts) {
const p = asRecord(partRaw);
if (p && typeof p.text === "string") parts.push({ type: "text", text: p.text });
}
if (parts.length > 0) turns.push({ role: "system", blocks: parts });
}
turns.push(...turnsFromGeminiContents(obj.contents));
return turns;
}
if (typeof obj.prompt === "string") {
return [{ role: "user", blocks: [{ type: "text", text: obj.prompt }] }];
}
if (typeof obj.input === "string") {
return [{ role: "user", blocks: [{ type: "text", text: obj.input }] }];
}
if (Array.isArray(obj.input)) {
return turnsFromOpenAiMessages(obj.input);
}
return null;
}
function isSseResponse(req: InterceptedRequest): boolean {
const accept = req.requestHeaders["accept"] ?? req.requestHeaders["Accept"] ?? "";
const ct = req.responseHeaders["content-type"] ?? req.responseHeaders["Content-Type"] ?? "";
return (
accept.includes("event-stream") ||
ct.includes("event-stream") ||
/^\s*event:|^\s*data:/m.test(req.responseBody ?? "")
);
}
function extractAnthropicResponseTurn(message: unknown): NormalizedTurn | null {
const obj = asRecord(message);
if (!obj) return null;
const content = obj.content;
if (!Array.isArray(content)) return null;
const blocks: NormalizedBlock[] = [];
for (const raw of content) {
const block = asRecord(raw);
if (!block) continue;
if (block.type === "text" && typeof block.text === "string") {
blocks.push({ type: "text", text: block.text });
} else if (block.type === "tool_use") {
blocks.push({
type: "tool_use",
id: typeof block.id === "string" ? block.id : "",
name: typeof block.name === "string" ? block.name : "",
input: block.input ?? {},
});
} else if (block.type === "thinking" && typeof block.thinking === "string") {
blocks.push({ type: "text", text: block.thinking });
}
}
if (blocks.length === 0) return null;
return { role: "assistant", blocks };
}
function extractOpenAiResponseTurn(message: unknown): NormalizedTurn | null {
const obj = asRecord(message);
if (!obj || !Array.isArray(obj.choices)) return null;
const first = asRecord(obj.choices[0]);
if (!first) return null;
const msg = asRecord(first.message) ?? asRecord(first.delta);
if (!msg) return null;
const blocks = blocksFromOpenAiContent(msg.content);
if ("tool_calls" in msg) appendOpenAiToolCalls(blocks, msg.tool_calls);
if (blocks.length === 0) return null;
return { role: "assistant", blocks };
}
function extractGeminiResponseTurn(message: unknown): NormalizedTurn | null {
const obj = asRecord(message);
if (!obj || !Array.isArray(obj.candidates)) return null;
const first = asRecord(obj.candidates[0]);
if (!first) return null;
const content = asRecord(first.content);
if (!content || !Array.isArray(content.parts)) return null;
const blocks: NormalizedBlock[] = [];
for (const partRaw of content.parts) {
const part = asRecord(partRaw);
if (!part) continue;
if (typeof part.text === "string") {
blocks.push({ type: "text", text: part.text });
} else if (part.functionCall) {
const fc = asRecord(part.functionCall) ?? {};
blocks.push({
type: "tool_use",
id: typeof fc.name === "string" ? fc.name : "",
name: typeof fc.name === "string" ? fc.name : "",
input: fc.args ?? {},
});
}
}
if (blocks.length === 0) return null;
return { role: "assistant", blocks };
}
function buildResponseTurns(req: InterceptedRequest): NormalizedTurn[] {
const raw = req.responseBody ?? "";
if (!raw) return [];
let payload: unknown = null;
if (isSseResponse(req)) {
const merged = mergeStream(parseSseStream(raw));
payload = merged.message ?? null;
} else {
payload = tryParseJson(raw);
}
if (!payload) return [];
const anth = extractAnthropicResponseTurn(payload);
if (anth) return [anth];
const oai = extractOpenAiResponseTurn(payload);
if (oai) return [oai];
const gem = extractGeminiResponseTurn(payload);
if (gem) return [gem];
return [];
}
/**
* Normalize an intercepted LLM request + response into a provider-agnostic
* conversation. Returns `null` for non-LLM requests or unparseable payloads.
*/
export function normalizeConversation(
req: InterceptedRequest
): NormalizedConversation | null {
if (req.detectedKind !== "llm") return null;
const requestBody = tryParseJson(req.requestBody);
const requestTurns = buildRequestTurns(requestBody);
if (!requestTurns) return null;
const responseTurns = buildResponseTurns(req);
return {
request: requestTurns,
response: responseTurns,
contextKey: req.contextKey ?? null,
};
}
|