GeezerVison is showing github.com — feat(gateway): add ReassembleFromEvents for SSE stream reassembly · majorcontext/keep@9619995
File treeExpand file treeCollapse file tree Open diff view settings internal/gateway/anthropic
Expand file treeCollapse file tree Open diff view settings Collapse file Copy file name to clipboard +127Lines changed: 127 additions & 0 deletions | Original file line number | Diff line number | Diff line change |
|---|
| | 1 | +package anthropic | | 2 | + | | 3 | +import ( | | 4 | + "encoding/json" | | 5 | + "errors" | | 6 | + "fmt" | | 7 | + "strings" | | 8 | + | | 9 | + "github.com/majorcontext/keep/internal/sse" | | 10 | +) | | 11 | + | | 12 | +// ReassembleFromEvents builds a MessagesResponse from a sequence of Anthropic | | 13 | +// streaming SSE events. It accumulates text deltas and input_json_delta fragments | | 14 | +// into complete content blocks. | | 15 | +func ReassembleFromEvents(events []sse.Event) (*MessagesResponse, error) { | | 16 | + var resp *MessagesResponse | | 17 | + var blocks []ContentBlock | | 18 | + inputJSON := make(map[int]*strings.Builder) | | 19 | + textBuf := make(map[int]*strings.Builder) | | 20 | + | | 21 | + for _, ev := range events { | | 22 | + switch ev.Type { | | 23 | + case "message_start": | | 24 | + var envelope struct { | | 25 | + Message MessagesResponse `json:"message"` | | 26 | + } | | 27 | + if err := json.Unmarshal([]byte(ev.Data), &envelope); err != nil { | | 28 | + return nil, fmt.Errorf("parse message_start: %w", err) | | 29 | + } | | 30 | + resp = &envelope.Message | | 31 | + | | 32 | + case "content_block_start": | | 33 | + var payload struct { | | 34 | + Index int `json:"index"` | | 35 | + ContentBlock ContentBlock `json:"content_block"` | | 36 | + } | | 37 | + if err := json.Unmarshal([]byte(ev.Data), &payload); err != nil { | | 38 | + return nil, fmt.Errorf("parse content_block_start: %w", err) | | 39 | + } | | 40 | + for len(blocks) <= payload.Index { | | 41 | + blocks = append(blocks, ContentBlock{}) | | 42 | + } | | 43 | + blocks[payload.Index] = payload.ContentBlock | | 44 | + if payload.ContentBlock.Type == "tool_use" { | | 45 | + inputJSON[payload.Index] = &strings.Builder{} | | 46 | + } | | 47 | + if payload.ContentBlock.Type == "text" { | | 48 | + textBuf[payload.Index] = &strings.Builder{} | | 49 | + } | | 50 | + | | 51 | + case "content_block_delta": | | 52 | + var payload struct { | | 53 | + Index int `json:"index"` | | 54 | + Delta struct { | | 55 | + Type string `json:"type"` | | 56 | + Text string `json:"text"` | | 57 | + PartialJSON string `json:"partial_json"` | | 58 | + } `json:"delta"` | | 59 | + } | | 60 | + if err := json.Unmarshal([]byte(ev.Data), &payload); err != nil { | | 61 | + return nil, fmt.Errorf("parse content_block_delta: %w", err) | | 62 | + } | | 63 | + switch payload.Delta.Type { | | 64 | + case "text_delta": | | 65 | + if buf, ok := textBuf[payload.Index]; ok { | | 66 | + buf.WriteString(payload.Delta.Text) | | 67 | + } | | 68 | + case "input_json_delta": | | 69 | + if buf, ok := inputJSON[payload.Index]; ok { | | 70 | + buf.WriteString(payload.Delta.PartialJSON) | | 71 | + } | | 72 | + } | | 73 | + | | 74 | + case "content_block_stop": | | 75 | + // No action needed. | | 76 | + | | 77 | + case "message_delta": | | 78 | + var payload struct { | | 79 | + Delta struct { | | 80 | + StopReason string `json:"stop_reason"` | | 81 | + } `json:"delta"` | | 82 | + Usage *Usage `json:"usage"` | | 83 | + } | | 84 | + if err := json.Unmarshal([]byte(ev.Data), &payload); err != nil { | | 85 | + return nil, fmt.Errorf("parse message_delta: %w", err) | | 86 | + } | | 87 | + if resp != nil { | | 88 | + resp.StopReason = payload.Delta.StopReason | | 89 | + if payload.Usage != nil { | | 90 | + if resp.Usage == nil { | | 91 | + resp.Usage = &Usage{} | | 92 | + } | | 93 | + resp.Usage.OutputTokens = payload.Usage.OutputTokens | | 94 | + } | | 95 | + } | | 96 | + | | 97 | + case "message_stop", "ping": | | 98 | + // No action needed. | | 99 | + } | | 100 | + } | | 101 | + | | 102 | + if resp == nil { | | 103 | + return nil, errors.New("no message_start event found") | | 104 | + } | | 105 | + | | 106 | + for idx, buf := range textBuf { | | 107 | + if idx < len(blocks) { | | 108 | + blocks[idx].Text = buf.String() | | 109 | + } | | 110 | + } | | 111 | + | | 112 | + for idx, buf := range inputJSON { | | 113 | + if idx < len(blocks) { | | 114 | + raw := buf.String() | | 115 | + if raw != "" { | | 116 | + var input map[string]any | | 117 | + if err := json.Unmarshal([]byte(raw), &input); err != nil { | | 118 | + return nil, fmt.Errorf("parse tool_use input at index %d: %w", idx, err) | | 119 | + } | | 120 | + blocks[idx].Input = input | | 121 | + } | | 122 | + } | | 123 | + } | | 124 | + | | 125 | + resp.Content = blocks | | 126 | + return resp, nil | | 127 | +} |
Collapse file Copy file name to clipboard +206Lines changed: 206 additions & 0 deletions | Original file line number | Diff line number | Diff line change |
|---|
| | 1 | +package anthropic | | 2 | + | | 3 | +import ( | | 4 | + "strings" | | 5 | + "testing" | | 6 | + | | 7 | + "github.com/majorcontext/keep/internal/sse" | | 8 | +) | | 9 | + | | 10 | +func TestReassembleFromEvents_TextOnly(t *testing.T) { | | 11 | + events := []sse.Event{ | | 12 | + {Type: "message_start", Data: `{"type":"message_start","message":{"id":"msg_01","type":"message","role":"assistant","content":[],"model":"claude-sonnet-4-20250514","stop_reason":null,"usage":{"input_tokens":25,"output_tokens":0}}}`}, | | 13 | + {Type: "content_block_start", Data: `{"type":"content_block_start","index":0,"content_block":{"type":"text","text":""}}`}, | | 14 | + {Type: "content_block_delta", Data: `{"type":"content_block_delta","index":0,"delta":{"type":"text_delta","text":"Hello"}}`}, | | 15 | + {Type: "content_block_delta", Data: `{"type":"content_block_delta","index":0,"delta":{"type":"text_delta","text":" world"}}`}, | | 16 | + {Type: "content_block_stop", Data: `{"type":"content_block_stop","index":0}`}, | | 17 | + {Type: "message_delta", Data: `{"type":"message_delta","delta":{"stop_reason":"end_turn"},"usage":{"output_tokens":10}}`}, | | 18 | + {Type: "message_stop", Data: `{"type":"message_stop"}`}, | | 19 | + } | | 20 | + | | 21 | + resp, err := ReassembleFromEvents(events) | | 22 | + if err != nil { | | 23 | + t.Fatalf("ReassembleFromEvents: %v", err) | | 24 | + } | | 25 | + | | 26 | + if resp.ID != "msg_01" { | | 27 | + t.Errorf("ID = %q, want %q", resp.ID, "msg_01") | | 28 | + } | | 29 | + if resp.Role != "assistant" { | | 30 | + t.Errorf("Role = %q, want %q", resp.Role, "assistant") | | 31 | + } | | 32 | + if resp.Model != "claude-sonnet-4-20250514" { | | 33 | + t.Errorf("Model = %q, want %q", resp.Model, "claude-sonnet-4-20250514") | | 34 | + } | | 35 | + if resp.StopReason != "end_turn" { | | 36 | + t.Errorf("StopReason = %q, want %q", resp.StopReason, "end_turn") | | 37 | + } | | 38 | + if len(resp.Content) != 1 { | | 39 | + t.Fatalf("len(Content) = %d, want 1", len(resp.Content)) | | 40 | + } | | 41 | + if resp.Content[0].Type != "text" { | | 42 | + t.Errorf("Content[0].Type = %q, want %q", resp.Content[0].Type, "text") | | 43 | + } | | 44 | + if resp.Content[0].Text != "Hello world" { | | 45 | + t.Errorf("Content[0].Text = %q, want %q", resp.Content[0].Text, "Hello world") | | 46 | + } | | 47 | + if resp.Usage == nil { | | 48 | + t.Fatal("Usage is nil") | | 49 | + } | | 50 | + if resp.Usage.InputTokens != 25 { | | 51 | + t.Errorf("InputTokens = %d, want 25", resp.Usage.InputTokens) | | 52 | + } | | 53 | + if resp.Usage.OutputTokens != 10 { | | 54 | + t.Errorf("OutputTokens = %d, want 10", resp.Usage.OutputTokens) | | 55 | + } | | 56 | +} | | 57 | + | | 58 | +func TestReassembleFromEvents_ToolUse(t *testing.T) { | | 59 | + events := []sse.Event{ | | 60 | + {Type: "message_start", Data: `{"type":"message_start","message":{"id":"msg_02","type":"message","role":"assistant","content":[],"model":"claude-sonnet-4-20250514","stop_reason":null,"usage":{"input_tokens":30,"output_tokens":0}}}`}, | | 61 | + {Type: "content_block_start", Data: `{"type":"content_block_start","index":0,"content_block":{"type":"tool_use","id":"toolu_01","name":"get_weather","input":{}}}`}, | | 62 | + {Type: "content_block_delta", Data: `{"type":"content_block_delta","index":0,"delta":{"type":"input_json_delta","partial_json":"{\"loc"}}`}, | | 63 | + {Type: "content_block_delta", Data: `{"type":"content_block_delta","index":0,"delta":{"type":"input_json_delta","partial_json":"ation\": \"SF\"}"}}`}, | | 64 | + {Type: "content_block_stop", Data: `{"type":"content_block_stop","index":0}`}, | | 65 | + {Type: "message_delta", Data: `{"type":"message_delta","delta":{"stop_reason":"tool_use"},"usage":{"output_tokens":15}}`}, | | 66 | + {Type: "message_stop", Data: `{"type":"message_stop"}`}, | | 67 | + } | | 68 | + | | 69 | + resp, err := ReassembleFromEvents(events) | | 70 | + if err != nil { | | 71 | + t.Fatalf("ReassembleFromEvents: %v", err) | | 72 | + } | | 73 | + | | 74 | + if len(resp.Content) != 1 { | | 75 | + t.Fatalf("len(Content) = %d, want 1", len(resp.Content)) | | 76 | + } | | 77 | + block := resp.Content[0] | | 78 | + if block.Type != "tool_use" { | | 79 | + t.Errorf("Type = %q, want %q", block.Type, "tool_use") | | 80 | + } | | 81 | + if block.ID != "toolu_01" { | | 82 | + t.Errorf("ID = %q, want %q", block.ID, "toolu_01") | | 83 | + } | | 84 | + if block.Name != "get_weather" { | | 85 | + t.Errorf("Name = %q, want %q", block.Name, "get_weather") | | 86 | + } | | 87 | + loc, ok := block.Input["location"] | | 88 | + if !ok || loc != "SF" { | | 89 | + t.Errorf("Input[location] = %v, want %q", loc, "SF") | | 90 | + } | | 91 | + if resp.StopReason != "tool_use" { | | 92 | + t.Errorf("StopReason = %q, want %q", resp.StopReason, "tool_use") | | 93 | + } | | 94 | +} | | 95 | + | | 96 | +func TestReassembleFromEvents_MultiBlock(t *testing.T) { | | 97 | + events := []sse.Event{ | | 98 | + {Type: "message_start", Data: `{"type":"message_start","message":{"id":"msg_03","type":"message","role":"assistant","content":[],"model":"claude-sonnet-4-20250514","stop_reason":null,"usage":{"input_tokens":20,"output_tokens":0}}}`}, | | 99 | + {Type: "content_block_start", Data: `{"type":"content_block_start","index":0,"content_block":{"type":"text","text":""}}`}, | | 100 | + {Type: "content_block_delta", Data: `{"type":"content_block_delta","index":0,"delta":{"type":"text_delta","text":"Let me check."}}`}, | | 101 | + {Type: "content_block_stop", Data: `{"type":"content_block_stop","index":0}`}, | | 102 | + {Type: "content_block_start", Data: `{"type":"content_block_start","index":1,"content_block":{"type":"tool_use","id":"toolu_02","name":"bash","input":{}}}`}, | | 103 | + {Type: "content_block_delta", Data: `{"type":"content_block_delta","index":1,"delta":{"type":"input_json_delta","partial_json":"{\"command\": \"ls\"}"}}`}, | | 104 | + {Type: "content_block_stop", Data: `{"type":"content_block_stop","index":1}`}, | | 105 | + {Type: "message_delta", Data: `{"type":"message_delta","delta":{"stop_reason":"tool_use"},"usage":{"output_tokens":20}}`}, | | 106 | + {Type: "message_stop", Data: `{"type":"message_stop"}`}, | | 107 | + } | | 108 | + | | 109 | + resp, err := ReassembleFromEvents(events) | | 110 | + if err != nil { | | 111 | + t.Fatalf("ReassembleFromEvents: %v", err) | | 112 | + } | | 113 | + | | 114 | + if len(resp.Content) != 2 { | | 115 | + t.Fatalf("len(Content) = %d, want 2", len(resp.Content)) | | 116 | + } | | 117 | + if resp.Content[0].Type != "text" || resp.Content[0].Text != "Let me check." { | | 118 | + t.Errorf("Content[0] = %+v, want text 'Let me check.'", resp.Content[0]) | | 119 | + } | | 120 | + if resp.Content[1].Type != "tool_use" || resp.Content[1].Name != "bash" { | | 121 | + t.Errorf("Content[1] = %+v, want tool_use 'bash'", resp.Content[1]) | | 122 | + } | | 123 | + cmd, _ := resp.Content[1].Input["command"] | | 124 | + if cmd != "ls" { | | 125 | + t.Errorf("Input[command] = %v, want %q", cmd, "ls") | | 126 | + } | | 127 | +} | | 128 | + | | 129 | +func TestReassembleFromEvents_PingIgnored(t *testing.T) { | | 130 | + events := []sse.Event{ | | 131 | + {Type: "message_start", Data: `{"type":"message_start","message":{"id":"msg_04","type":"message","role":"assistant","content":[],"model":"claude-sonnet-4-20250514","stop_reason":null,"usage":{"input_tokens":10,"output_tokens":0}}}`}, | | 132 | + {Type: "ping", Data: `{"type":"ping"}`}, | | 133 | + {Type: "content_block_start", Data: `{"type":"content_block_start","index":0,"content_block":{"type":"text","text":""}}`}, | | 134 | + {Type: "content_block_delta", Data: `{"type":"content_block_delta","index":0,"delta":{"type":"text_delta","text":"Hi"}}`}, | | 135 | + {Type: "content_block_stop", Data: `{"type":"content_block_stop","index":0}`}, | | 136 | + {Type: "message_delta", Data: `{"type":"message_delta","delta":{"stop_reason":"end_turn"},"usage":{"output_tokens":1}}`}, | | 137 | + {Type: "message_stop", Data: `{"type":"message_stop"}`}, | | 138 | + } | | 139 | + | | 140 | + resp, err := ReassembleFromEvents(events) | | 141 | + if err != nil { | | 142 | + t.Fatalf("ReassembleFromEvents: %v", err) | | 143 | + } | | 144 | + if resp.Content[0].Text != "Hi" { | | 145 | + t.Errorf("Text = %q, want %q", resp.Content[0].Text, "Hi") | | 146 | + } | | 147 | +} | | 148 | + | | 149 | +func TestReassembleFromEvents_NoMessageStart(t *testing.T) { | | 150 | + events := []sse.Event{ | | 151 | + {Type: "content_block_start", Data: `{"type":"content_block_start","index":0,"content_block":{"type":"text","text":""}}`}, | | 152 | + } | | 153 | + | | 154 | + _, err := ReassembleFromEvents(events) | | 155 | + if err == nil { | | 156 | + t.Fatal("expected error for missing message_start") | | 157 | + } | | 158 | +} | | 159 | + | | 160 | +func TestReassembleFromEvents_EmptyContent(t *testing.T) { | | 161 | + events := []sse.Event{ | | 162 | + {Type: "message_start", Data: `{"type":"message_start","message":{"id":"msg_empty","type":"message","role":"assistant","content":[],"model":"claude-sonnet-4-20250514","stop_reason":null,"usage":{"input_tokens":5,"output_tokens":0}}}`}, | | 163 | + {Type: "message_delta", Data: `{"type":"message_delta","delta":{"stop_reason":"end_turn"},"usage":{"output_tokens":0}}`}, | | 164 | + {Type: "message_stop", Data: `{"type":"message_stop"}`}, | | 165 | + } | | 166 | + | | 167 | + resp, err := ReassembleFromEvents(events) | | 168 | + if err != nil { | | 169 | + t.Fatalf("ReassembleFromEvents: %v", err) | | 170 | + } | | 171 | + if len(resp.Content) != 0 { | | 172 | + t.Errorf("len(Content) = %d, want 0", len(resp.Content)) | | 173 | + } | | 174 | +} | | 175 | + | | 176 | +func TestReassembleFromEvents_MissingMessageStop(t *testing.T) { | | 177 | + events := []sse.Event{ | | 178 | + {Type: "message_start", Data: `{"type":"message_start","message":{"id":"msg_trunc","type":"message","role":"assistant","content":[],"model":"claude-sonnet-4-20250514","stop_reason":null,"usage":{"input_tokens":5,"output_tokens":0}}}`}, | | 179 | + {Type: "content_block_start", Data: `{"type":"content_block_start","index":0,"content_block":{"type":"text","text":""}}`}, | | 180 | + {Type: "content_block_delta", Data: `{"type":"content_block_delta","index":0,"delta":{"type":"text_delta","text":"partial"}}`}, | | 181 | + {Type: "content_block_stop", Data: `{"type":"content_block_stop","index":0}`}, | | 182 | + {Type: "message_delta", Data: `{"type":"message_delta","delta":{"stop_reason":"end_turn"},"usage":{"output_tokens":3}}`}, | | 183 | + } | | 184 | + | | 185 | + resp, err := ReassembleFromEvents(events) | | 186 | + if err != nil { | | 187 | + t.Fatalf("ReassembleFromEvents: %v", err) | | 188 | + } | | 189 | + if resp.Content[0].Text != "partial" { | | 190 | + t.Errorf("Text = %q, want %q", resp.Content[0].Text, "partial") | | 191 | + } | | 192 | +} | | 193 | + | | 194 | +func TestReassembleFromEvents_MalformedJSON(t *testing.T) { | | 195 | + events := []sse.Event{ | | 196 | + {Type: "message_start", Data: `{not json}`}, | | 197 | + } | | 198 | + | | 199 | + _, err := ReassembleFromEvents(events) | | 200 | + if err == nil { | | 201 | + t.Fatal("expected error for malformed JSON") | | 202 | + } | | 203 | + if !strings.Contains(err.Error(), "parse message_start") { | | 204 | + t.Errorf("error = %q, want it to mention 'parse message_start'", err.Error()) | | 205 | + } | | 206 | +} |
|