| 289 | } |
| 290 | |
| 291 | function flow(item: Sse) { |
| 292 | const out: Flow[] = [] |
| 293 | for (const part of [...item.head, ...item.tail]) { |
| 294 | const choice = choices(part) |
| 295 | const delta = |
| 296 | choice && "delta" in choice && choice.delta && typeof choice.delta === "object" ? choice.delta : undefined |
| 297 | |
| 298 | if (delta && "content" in delta && typeof delta.content === "string") { |
| 299 | out.push({ type: "text", text: delta.content }) |
| 300 | } |
| 301 | |
| 302 | if (delta && "reasoning_content" in delta && typeof delta.reasoning_content === "string") { |
| 303 | out.push({ type: "reason", text: delta.reasoning_content }) |
| 304 | } |
| 305 | |
| 306 | if (delta && "tool_calls" in delta && Array.isArray(delta.tool_calls)) { |
| 307 | for (const tool of delta.tool_calls) { |
| 308 | if (!tool || typeof tool !== "object") continue |
| 309 | const fn = "function" in tool && tool.function && typeof tool.function === "object" ? tool.function : undefined |
| 310 | if ("id" in tool && typeof tool.id === "string" && fn && "name" in fn && typeof fn.name === "string") { |
| 311 | out.push({ type: "tool-start", id: tool.id, name: fn.name }) |
| 312 | } |
| 313 | if (fn && "arguments" in fn && typeof fn.arguments === "string" && fn.arguments) { |
| 314 | out.push({ type: "tool-args", text: fn.arguments }) |
| 315 | } |
| 316 | } |
| 317 | } |
| 318 | |
| 319 | if (part && typeof part === "object" && "usage" in part && part.usage && typeof part.usage === "object") { |
| 320 | const raw = part.usage as Record<string, unknown> |
| 321 | if (typeof raw.prompt_tokens === "number" && typeof raw.completion_tokens === "number") { |
| 322 | out.push({ |
| 323 | type: "usage", |
| 324 | usage: { input: raw.prompt_tokens, output: raw.completion_tokens }, |
| 325 | }) |
| 326 | } |
| 327 | } |
| 328 | } |
| 329 | return out |
| 330 | } |
| 331 | |
| 332 | function responses(item: Sse, model: string) { |
| 333 | let seq = 1 |