GeezerVison is showing github.com — refactor(llm): polish library API surface · majorcontext/keep@2d424d5
File treeExpand file treeCollapse file tree Open diff view settings Expand file treeCollapse file tree Open diff view settings Collapse file Copy file name to clipboardExpand all lines: docs/plans/2026-03-27-llm-library-api.md +1,615Lines changed: 1615 additions & 0 deletions - Display the source diff
- Display the rich diff
Large diffs are not rendered by default. Collapse file Copy file name to clipboardExpand all lines: internal/gateway/config/config_test.go +37Lines changed: 37 additions & 0 deletions | Original file line number | Diff line number | Diff line change |
|---|
@@ -3,7 +3,10 @@ package config | 3 | 3 | import ( | 4 | 4 | "os" | 5 | 5 | "path/filepath" | | 6 | + "reflect" | 6 | 7 | "testing" | | 8 | + | | 9 | + "github.com/majorcontext/keep/llm" | 7 | 10 | ) | 8 | 11 |
| 9 | 12 | func TestLoad_Valid(t *testing.T) { | @@ -199,6 +202,40 @@ decompose: | 199 | 202 | } | 200 | 203 | } | 201 | 204 |
| | 205 | +// TestDecomposeConfig_FieldParity ensures gateway's DecomposeConfig stays in | | 206 | +// sync with llm.DecomposeConfig. If a field is added to one but not the other, | | 207 | +// this test will catch the drift at compile time (via reflect). | | 208 | +func TestDecomposeConfig_FieldParity(t *testing.T) { | | 209 | + gwType := reflect.TypeOf(DecomposeConfig{}) | | 210 | + llmType := reflect.TypeOf(llm.DecomposeConfig{}) | | 211 | + | | 212 | + // Build a map of llm fields. | | 213 | + llmFields := make(map[string]reflect.Type, llmType.NumField()) | | 214 | + for i := 0; i < llmType.NumField(); i++ { | | 215 | + f := llmType.Field(i) | | 216 | + llmFields[f.Name] = f.Type | | 217 | + } | | 218 | + | | 219 | + // Every gateway field must exist in llm with the same type. | | 220 | + for i := 0; i < gwType.NumField(); i++ { | | 221 | + f := gwType.Field(i) | | 222 | + lt, ok := llmFields[f.Name] | | 223 | + if !ok { | | 224 | + t.Errorf("gateway DecomposeConfig has field %q not present in llm.DecomposeConfig", f.Name) | | 225 | + continue | | 226 | + } | | 227 | + if f.Type != lt { | | 228 | + t.Errorf("field %q: gateway type %v != llm type %v", f.Name, f.Type, lt) | | 229 | + } | | 230 | + delete(llmFields, f.Name) | | 231 | + } | | 232 | + | | 233 | + // Every llm field must exist in gateway. | | 234 | + for name := range llmFields { | | 235 | + t.Errorf("llm.DecomposeConfig has field %q not present in gateway DecomposeConfig", name) | | 236 | + } | | 237 | +} | | 238 | + | 202 | 239 | // writeTempYAML writes content to a temp file and returns its path. | 203 | 240 | func writeTempYAML(t *testing.T, content string) string { | 204 | 241 | t.Helper() | |
Collapse file Copy file name to clipboardExpand all lines: internal/gateway/proxy.go +4-8Lines changed: 4 additions & 8 deletions | Original file line number | Diff line number | Diff line change |
|---|
@@ -389,19 +389,15 @@ func (p *Proxy) handleStreamingResponse(w http.ResponseWriter, r *http.Request, | 389 | 389 | p.logDebug("upstream stream", "status", upstreamResp.StatusCode, "events", len(events)) | 390 | 390 |
| 391 | 391 | // 4. Evaluate stream via pipeline (reassemble, decompose, evaluate, reassemble/synthesize). | 392 | | - // Verbose: log reassembled response before policy. | 393 | | - if p.verbose != nil { | 394 | | - // Reassemble just for logging — the pipeline will do it again internally. | 395 | | - if assembled, logErr := p.codec.ReassembleStream(events); logErr == nil { | 396 | | - p.verbose.ResponseRaw(assembled) | 397 | | - } | 398 | | - } | 399 | | - | 400 | 392 | streamResult, err := llm.EvaluateStream(p.engine, p.codec, events, p.scope, p.llmCfg) | 401 | 393 | if err != nil { | 402 | 394 | writeInternalError(w, "stream policy evaluation error") | 403 | 395 | return | 404 | 396 | } | | 397 | + // Verbose: log pre-policy reassembled body (avoids double-reassemble). | | 398 | + if p.verbose != nil { | | 399 | + p.verbose.ResponseRaw(streamResult.RawBody) | | 400 | + } | 405 | 401 | if p.logger != nil { | 406 | 402 | for _, a := range streamResult.Audits { | 407 | 403 | p.logger.Log(a) | |
Collapse file Copy file name to clipboardExpand all lines: internal/gateway/proxy_test.go +14-4Lines changed: 14 additions & 4 deletions | Original file line number | Diff line number | Diff line change |
|---|
@@ -440,9 +440,14 @@ func TestProxy_StreamingAllowed(t *testing.T) { | 440 | 440 | t.Fatalf("expected 7 SSE events (original replay), got %d", len(events)) | 441 | 441 | } | 442 | 442 |
| 443 | | - assembled, err := anthropic.ReassembleFromEvents(events) | | 443 | + codec := anthropic.NewCodec() | | 444 | + body, err := codec.ReassembleStream(events) | 444 | 445 | if err != nil { | 445 | | - t.Fatalf("ReassembleFromEvents: %v", err) | | 446 | + t.Fatalf("ReassembleStream: %v", err) | | 447 | + } | | 448 | + var assembled anthropic.MessagesResponse | | 449 | + if err := json.Unmarshal(body, &assembled); err != nil { | | 450 | + t.Fatalf("unmarshal: %v", err) | 446 | 451 | } | 447 | 452 | if assembled.Content[0].Text != "Hello from upstream" { | 448 | 453 | t.Errorf("Text = %q, want %q", assembled.Content[0].Text, "Hello from upstream") | @@ -547,9 +552,14 @@ func TestProxy_StreamingRedactResponse(t *testing.T) { | 547 | 552 | events = append(events, ev) | 548 | 553 | } | 549 | 554 |
| 550 | | - assembled, err := anthropic.ReassembleFromEvents(events) | | 555 | + codec := anthropic.NewCodec() | | 556 | + body, err := codec.ReassembleStream(events) | 551 | 557 | if err != nil { | 552 | | - t.Fatalf("ReassembleFromEvents: %v", err) | | 558 | + t.Fatalf("ReassembleStream: %v", err) | | 559 | + } | | 560 | + var assembled anthropic.MessagesResponse | | 561 | + if err := json.Unmarshal(body, &assembled); err != nil { | | 562 | + t.Fatalf("unmarshal: %v", err) | 553 | 563 | } | 554 | 564 |
| 555 | 565 | text := assembled.Content[0].Text | |
Collapse file Copy file name to clipboardExpand all lines: llm/anthropic/codec.go +14-14Lines changed: 14 additions & 14 deletions | Original file line number | Diff line number | Diff line change |
|---|
@@ -20,15 +20,15 @@ func NewCodec() *Codec { return &Codec{} } | 20 | 20 | type requestHandle struct { | 21 | 21 | req *MessagesRequest | 22 | 22 | body []byte | 23 | | - blockMap []BlockPosition | | 23 | + blockMap []blockPosition | 24 | 24 | cfg llm.DecomposeConfig | 25 | 25 | } | 26 | 26 |
| 27 | 27 | // responseHandle carries parsed state from DecomposeResponse to ReassembleResponse. | 28 | 28 | type responseHandle struct { | 29 | 29 | resp *MessagesResponse | 30 | 30 | body []byte | 31 | | - blockMap []BlockPosition | | 31 | + blockMap []blockPosition | 32 | 32 | cfg llm.DecomposeConfig | 33 | 33 | } | 34 | 34 |
| @@ -40,8 +40,8 @@ func (c *Codec) DecomposeRequest(body []byte, scope string, cfg llm.DecomposeCon | 40 | 40 | return nil, nil, fmt.Errorf("anthropic: unmarshal request: %w", err) | 41 | 41 | } | 42 | 42 |
| 43 | | - calls := DecomposeRequest(&req, scope, cfg) | 44 | | - blockMap := WalkRequestBlocks(&req, cfg) | | 43 | + calls := decomposeRequest(&req, scope, cfg) | | 44 | + blockMap := walkRequestBlocks(&req, cfg) | 45 | 45 |
| 46 | 46 | h := &requestHandle{ | 47 | 47 | req: &req, | @@ -60,8 +60,8 @@ func (c *Codec) DecomposeResponse(body []byte, scope string, cfg llm.DecomposeCo | 60 | 60 | return nil, nil, fmt.Errorf("anthropic: unmarshal response: %w", err) | 61 | 61 | } | 62 | 62 |
| 63 | | - calls := DecomposeResponse(&resp, scope, cfg) | 64 | | - blockMap := WalkResponseBlocks(&resp, cfg) | | 63 | + calls := decomposeResponse(&resp, scope, cfg) | | 64 | + blockMap := walkResponseBlocks(&resp, cfg) | 65 | 65 |
| 66 | 66 | h := &responseHandle{ | 67 | 67 | resp: &resp, | @@ -85,7 +85,7 @@ func (c *Codec) ReassembleRequest(handle any, results []keep.EvalResult) ([]byte | 85 | 85 | return h.body, nil | 86 | 86 | } | 87 | 87 |
| 88 | | - patched := ReassembleRequest(h.req, blockResults) | | 88 | + patched := reassembleRequest(h.req, blockResults) | 89 | 89 | out, err := json.Marshal(patched) | 90 | 90 | if err != nil { | 91 | 91 | return nil, fmt.Errorf("anthropic: marshal patched request: %w", err) | @@ -106,7 +106,7 @@ func (c *Codec) ReassembleResponse(handle any, results []keep.EvalResult) ([]byt | 106 | 106 | return h.body, nil | 107 | 107 | } | 108 | 108 |
| 109 | | - patched := ReassembleResponse(h.resp, blockResults) | | 109 | + patched := reassembleResponse(h.resp, blockResults) | 110 | 110 | out, err := json.Marshal(patched) | 111 | 111 | if err != nil { | 112 | 112 | return nil, fmt.Errorf("anthropic: marshal patched response: %w", err) | @@ -116,7 +116,7 @@ func (c *Codec) ReassembleResponse(handle any, results []keep.EvalResult) ([]byt | 116 | 116 |
| 117 | 117 | // ReassembleStream reassembles SSE events into a complete response body. | 118 | 118 | func (c *Codec) ReassembleStream(events []sse.Event) ([]byte, error) { | 119 | | - resp, err := ReassembleFromEvents(events) | | 119 | + resp, err := reassembleFromEvents(events) | 120 | 120 | if err != nil { | 121 | 121 | return nil, fmt.Errorf("anthropic: reassemble stream: %w", err) | 122 | 122 | } | @@ -133,19 +133,19 @@ func (c *Codec) SynthesizeEvents(patchedBody []byte) ([]sse.Event, error) { | 133 | 133 | if err := json.Unmarshal(patchedBody, &resp); err != nil { | 134 | 134 | return nil, fmt.Errorf("anthropic: unmarshal for synthesize: %w", err) | 135 | 135 | } | 136 | | - return SynthesizeEvents(&resp), nil | | 136 | + return synthesizeEvents(&resp), nil | 137 | 137 | } | 138 | 138 |
| 139 | 139 | // buildBlockResults maps eval results back to block positions using CallIndex. | 140 | 140 | // The offset for summary calls is already baked into BlockPosition.CallIndex | 141 | 141 | // by WalkRequestBlocks / WalkResponseBlocks. | 142 | | -func buildBlockResults(blockMap []BlockPosition, results []keep.EvalResult) []BlockResult { | 143 | | - out := make([]BlockResult, 0, len(blockMap)) | | 142 | +func buildBlockResults(blockMap []blockPosition, results []keep.EvalResult) []blockResult { | | 143 | + out := make([]blockResult, 0, len(blockMap)) | 144 | 144 | for _, pos := range blockMap { | 145 | 145 | if pos.CallIndex < 0 || pos.CallIndex >= len(results) { | 146 | 146 | continue | 147 | 147 | } | 148 | | - out = append(out, BlockResult{ | | 148 | + out = append(out, blockResult{ | 149 | 149 | MessageIndex: pos.MessageIndex, | 150 | 150 | BlockIndex: pos.BlockIndex, | 151 | 151 | Result: results[pos.CallIndex], | @@ -155,7 +155,7 @@ func buildBlockResults(blockMap []BlockPosition, results []keep.EvalResult) []Bl | 155 | 155 | } | 156 | 156 |
| 157 | 157 | // hasMutations reports whether any block result contains mutations. | 158 | | -func hasMutations(results []BlockResult) bool { | | 158 | +func hasMutations(results []blockResult) bool { | 159 | 159 | for _, br := range results { | 160 | 160 | if len(br.Result.Mutations) > 0 { | 161 | 161 | return true | |
Collapse file Copy file name to clipboardExpand all lines: llm/anthropic/codec_test.go +2-2Lines changed: 2 additions & 2 deletions | Original file line number | Diff line number | Diff line change |
|---|
@@ -127,9 +127,9 @@ func TestCodec_ReassembleStream(t *testing.T) { | 127 | 127 | Usage: &Usage{InputTokens: 10, OutputTokens: 5}, | 128 | 128 | } | 129 | 129 |
| 130 | | - events := SynthesizeEvents(resp) | | 130 | + events := synthesizeEvents(resp) | 131 | 131 | if len(events) == 0 { | 132 | | - t.Fatal("expected non-empty events from SynthesizeEvents") | | 132 | + t.Fatal("expected non-empty events from synthesizeEvents") | 133 | 133 | } | 134 | 134 |
| 135 | 135 | c := NewCodec() | |
Collapse file Copy file name to clipboardExpand all lines: llm/anthropic/decompose.go +19-19Lines changed: 19 additions & 19 deletions | Original file line number | Diff line number | Diff line change |
|---|
@@ -8,18 +8,18 @@ import ( | 8 | 8 | "github.com/majorcontext/keep/llm" | 9 | 9 | ) | 10 | 10 |
| 11 | | -// BlockPosition identifies a content block within a request. | 12 | | -type BlockPosition struct { | | 11 | +// blockPosition identifies a content block within a request. | | 12 | +type blockPosition struct { | 13 | 13 | MessageIndex int | 14 | 14 | BlockIndex int | 15 | 15 | Block ContentBlock | 16 | 16 | Role string // role of the containing message | 17 | | - CallIndex int // index into the calls slice returned by DecomposeRequest | | 17 | + CallIndex int // index into the calls slice returned by decomposeRequest | 18 | 18 | } | 19 | 19 |
| 20 | | -// WalkRequestBlocks returns the positions of all blocks that DecomposeRequest would emit calls for. | 21 | | -func WalkRequestBlocks(req *MessagesRequest, cfg llm.DecomposeConfig) []BlockPosition { | 22 | | - var positions []BlockPosition | | 20 | +// walkRequestBlocks returns the positions of all blocks that decomposeRequest would emit calls for. | | 21 | +func walkRequestBlocks(req *MessagesRequest, cfg llm.DecomposeConfig) []blockPosition { | | 22 | + var positions []blockPosition | 23 | 23 | callIdx := 0 | 24 | 24 | if cfg.RequestSummaryEnabled() { | 25 | 25 | callIdx = 1 // account for the summary call at index 0 | @@ -31,7 +31,7 @@ func WalkRequestBlocks(req *MessagesRequest, cfg llm.DecomposeConfig) []BlockPos | 31 | 31 | switch block.Type { | 32 | 32 | case "tool_result": | 33 | 33 | if cfg.ToolResultEnabled() { | 34 | | - positions = append(positions, BlockPosition{ | | 34 | + positions = append(positions, blockPosition{ | 35 | 35 | MessageIndex: msgIdx, | 36 | 36 | BlockIndex: blockIdx, | 37 | 37 | Block: block, | @@ -42,7 +42,7 @@ func WalkRequestBlocks(req *MessagesRequest, cfg llm.DecomposeConfig) []BlockPos | 42 | 42 | } | 43 | 43 | case "text": | 44 | 44 | if cfg.TextEnabled() { | 45 | | - positions = append(positions, BlockPosition{ | | 45 | + positions = append(positions, blockPosition{ | 46 | 46 | MessageIndex: msgIdx, | 47 | 47 | BlockIndex: blockIdx, | 48 | 48 | Block: block, | @@ -58,9 +58,9 @@ func WalkRequestBlocks(req *MessagesRequest, cfg llm.DecomposeConfig) []BlockPos | 58 | 58 | return positions | 59 | 59 | } | 60 | 60 |
| 61 | | -// WalkResponseBlocks returns the positions of all blocks that DecomposeResponse would emit calls for. | 62 | | -func WalkResponseBlocks(resp *MessagesResponse, cfg llm.DecomposeConfig) []BlockPosition { | 63 | | - var positions []BlockPosition | | 61 | +// walkResponseBlocks returns the positions of all blocks that decomposeResponse would emit calls for. | | 62 | +func walkResponseBlocks(resp *MessagesResponse, cfg llm.DecomposeConfig) []blockPosition { | | 63 | + var positions []blockPosition | 64 | 64 | callIdx := 0 | 65 | 65 | if cfg.ResponseSummaryEnabled() { | 66 | 66 | callIdx = 1 | @@ -70,7 +70,7 @@ func WalkResponseBlocks(resp *MessagesResponse, cfg llm.DecomposeConfig) []Block | 70 | 70 | switch block.Type { | 71 | 71 | case "tool_use": | 72 | 72 | if cfg.ToolUseEnabled() { | 73 | | - positions = append(positions, BlockPosition{ | | 73 | + positions = append(positions, blockPosition{ | 74 | 74 | MessageIndex: 0, | 75 | 75 | BlockIndex: blockIdx, | 76 | 76 | Block: block, | @@ -81,7 +81,7 @@ func WalkResponseBlocks(resp *MessagesResponse, cfg llm.DecomposeConfig) []Block | 81 | 81 | } | 82 | 82 | case "text": | 83 | 83 | if cfg.TextEnabled() { | 84 | | - positions = append(positions, BlockPosition{ | | 84 | + positions = append(positions, blockPosition{ | 85 | 85 | MessageIndex: 0, | 86 | 86 | BlockIndex: blockIdx, | 87 | 87 | Block: block, | @@ -96,9 +96,9 @@ func WalkResponseBlocks(resp *MessagesResponse, cfg llm.DecomposeConfig) []Block | 96 | 96 | return positions | 97 | 97 | } | 98 | 98 |
| 99 | | -// DecomposeRequest breaks an Anthropic Messages API request into flat Keep calls. | | 99 | +// decomposeRequest breaks an Anthropic Messages API request into flat Keep calls. | 100 | 100 | // Returns one llm.request summary + one call per content block (based on decompose config). | 101 | | -func DecomposeRequest(req *MessagesRequest, scope string, cfg llm.DecomposeConfig) []keep.Call { | | 101 | +func decomposeRequest(req *MessagesRequest, scope string, cfg llm.DecomposeConfig) []keep.Call { | 102 | 102 | var calls []keep.Call | 103 | 103 |
| 104 | 104 | // Build a map from tool_use_id to tool name for resolving tool_result references. | @@ -120,7 +120,7 @@ func DecomposeRequest(req *MessagesRequest, scope string, cfg llm.DecomposeConfi | 120 | 120 | } | 121 | 121 |
| 122 | 122 | // 2. Walk messages for content blocks using the shared iterator. | 123 | | - for _, pos := range WalkRequestBlocks(req, cfg) { | | 123 | + for _, pos := range walkRequestBlocks(req, cfg) { | 124 | 124 | switch pos.Block.Type { | 125 | 125 | case "tool_result": | 126 | 126 | toolName := toolNameMap[pos.Block.ToolUseID] | @@ -148,8 +148,8 @@ func DecomposeRequest(req *MessagesRequest, scope string, cfg llm.DecomposeConfi | 148 | 148 | return calls | 149 | 149 | } | 150 | 150 |
| 151 | | -// DecomposeResponse breaks an Anthropic Messages API response into flat Keep calls. | 152 | | -func DecomposeResponse(resp *MessagesResponse, scope string, cfg llm.DecomposeConfig) []keep.Call { | | 151 | +// decomposeResponse breaks an Anthropic Messages API response into flat Keep calls. | | 152 | +func decomposeResponse(resp *MessagesResponse, scope string, cfg llm.DecomposeConfig) []keep.Call { | 153 | 153 | var calls []keep.Call | 154 | 154 |
| 155 | 155 | // 1. Summary call. | @@ -165,7 +165,7 @@ func DecomposeResponse(resp *MessagesResponse, scope string, cfg llm.DecomposeCo | 165 | 165 | } | 166 | 166 |
| 167 | 167 | // 2. Walk response content blocks using the shared iterator. | 168 | | - for _, pos := range WalkResponseBlocks(resp, cfg) { | | 168 | + for _, pos := range walkResponseBlocks(resp, cfg) { | 169 | 169 | switch pos.Block.Type { | 170 | 170 | case "tool_use": | 171 | 171 | calls = append(calls, keep.Call{ | |
|