(res, response, enable_thinking, enable_web_search, model, requestBody = null, options = {})
| 503 | |
| 504 | let bufferedContent = output.content |
| 505 | const acceptedVisibleText = peelDeliverableText(attempt.visibleText, residueSpans) |
| 506 | if ( |
| 507 | streamedVisibleText && |
| 508 | acceptedVisibleText.startsWith(streamedVisibleText) && |
| 509 | bufferedContent.startsWith(acceptedVisibleText) |
| 510 | ) { |
| 511 | // 正式回复的包装体已经按上游节奏实时发送,只补发极少数尚未发送的尾部, |
| 512 | // 以及门禁通过后追加的搜索信息等派生内容。 |
| 513 | bufferedContent = `${acceptedVisibleText.slice(streamedVisibleText.length)}${bufferedContent.slice(acceptedVisibleText.length)}` |
| 514 | } else if (streamedVisibleText && finishReason !== 'stop' && attempt.streamedControlState?.opened) { |
| 515 | // length/content_filter 等中止发生在包装闭合前时,不能把带控制标签的原始 |
| 516 | // 缓冲再次作为正文回放;已发送的安全正文由对应 finish_reason 正常收尾。 |
| 517 | bufferedContent = '' |
| 518 | } |
| 519 | |
| 520 | if (bufferedReasoning) writeDelta({ reasoning_content: bufferedReasoning }) |
| 521 | if (bufferedContent) writeDelta({ content: bufferedContent }) |
| 522 | |
| 523 | const ARG_CHUNK_SIZE = 32 |
| 524 | for (const call of attempt.toolCalls || []) { |
| 525 | writeDelta({ |
| 526 | tool_calls: [{ |
| 527 | index: call.index, |
| 528 | id: call.id, |
| 529 | type: 'function', |
| 530 | function: { name: call.function.name, arguments: '' } |
| 531 | }] |
| 532 | }) |
| 533 | const args = call.function.arguments || '{}' |
| 534 | for (let offset = 0; offset < args.length; offset += ARG_CHUNK_SIZE) { |
| 535 | writeDelta({ |
| 536 | tool_calls: [{ |
| 537 | index: call.index, |
| 538 | function: { arguments: args.slice(offset, offset + ARG_CHUNK_SIZE) } |
| 539 | }] |
| 540 | }) |
| 541 | } |
| 542 | } |
| 543 | const completionText = `${output.reasoning}${output.content}${JSON.stringify(attempt.toolCalls || [])}` |
| 544 | const usage = normalizeAgentUsage(attempt, requestBody, completionText) |
| 545 | attributeChatUsage(runtime.currentAccount || options.currentAccount, usage) |
| 546 | res.write(`data: ${JSON.stringify({ |
| 547 | id: `chatcmpl-${messageId}`, |
| 548 | object: 'chat.completion.chunk', |
| 549 | created, |
| 550 | choices: [{ index: 0, delta: {}, finish_reason: finishReason }] |
| 551 | })}\n\n`) |
| 552 | res.write(`data: ${JSON.stringify({ |
| 553 | id: `chatcmpl-${messageId}`, |
| 554 | object: 'chat.completion.chunk', |
| 555 | created, |
| 556 | choices: [], |
| 557 | usage |
| 558 | })}\n\n`) |
| 559 | res.write('data: [DONE]\n\n') |
| 560 | if (typeof res.flush === 'function') res.flush() |
| 561 | res.end() |
| 562 | } |
no test coverage detected