fix: Anthropic streaming - correct stop_reason and add content_block_start/stop for text
- stop_reason now correctly returns 'end_turn' for non-tool responses (was always 'tool_use') - Added content_block_start event before first text delta - Added content_block_stop event for text blocks - Fixes Claude Code compatibility
This commit is contained in:
1 parent
ffbcdf753b
commit
4c222c036a
1 file changed
+14
-1
@@ -460,6 +460,7 @@ export async function handleAnthropicMessages(request: Request): Promise<Respons
|
||||
let currentToolCallId = "";
|
||||
let currentToolName = "";
|
||||
let currentToolArgs = "";
|
||||
let textBlockStarted = false;
|
||||
|
||||
try {
|
||||
while (true) {
|
||||
@@ -476,6 +477,11 @@ export async function handleAnthropicMessages(request: Request): Promise<Respons
|
||||
const data = line.slice(6);
|
||||
|
||||
if (data === "[DONE]") {
|
||||
// Close text block if open
|
||||
if (textBlockStarted && !currentToolCallId) {
|
||||
const textStop = "data: " + JSON.stringify({ type: "content_block_stop", index: 0 });
|
||||
controller.enqueue(encoder.encode(textStop.concat("\n\n")));
|
||||
}
|
||||
// If we have a pending tool call, send it
|
||||
if (currentToolCallId) {
|
||||
const toolInputDelta = "data: " + JSON.stringify({
|
||||
@@ -492,7 +498,9 @@ export async function handleAnthropicMessages(request: Request): Promise<Respons
|
||||
controller.enqueue(encoder.encode(toolStopDelta.concat("\n\n")));
|
||||
}
|
||||
|
||||
const deltaLine = "data: " + JSON.stringify({ type: "message_delta", delta: { stop_reason: "tool_use", stop_sequence: null }, usage: { output_tokens: 0 } });
|
||||
// Use "tool_use" stop reason only if we had tool calls, otherwise "end_turn"
|
||||
const stopReason = currentToolCallId ? "tool_use" : "end_turn";
|
||||
const deltaLine = "data: " + JSON.stringify({ type: "message_delta", delta: { stop_reason: stopReason, stop_sequence: null }, usage: { output_tokens: 0 } });
|
||||
controller.enqueue(encoder.encode(deltaLine.concat("\n\n")));
|
||||
const stopLine = "data: " + JSON.stringify({ type: "message_stop" });
|
||||
controller.enqueue(encoder.encode(stopLine.concat("\n\n")));
|
||||
@@ -505,6 +513,11 @@ export async function handleAnthropicMessages(request: Request): Promise<Respons
|
||||
|
||||
// Handle text content
|
||||
if (delta?.content) {
|
||||
if (!textBlockStarted) {
|
||||
const textStart = "data: " + JSON.stringify({ type: "content_block_start", index: 0, content_block: { type: "text", text: "" } });
|
||||
controller.enqueue(encoder.encode(textStart.concat("\n\n")));
|
||||
textBlockStarted = true;
|
||||
}
|
||||
const contentLine = "data: " + JSON.stringify({ type: "content_block_delta", delta: { type: "text_delta", text: delta.content }, index: 0 });
|
||||
controller.enqueue(encoder.encode(contentLine.concat("\n\n")));
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user