GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — refactor(llm): polish library API surface · majorcontext/keep@2d424d5

File tree

Expand file treeCollapse file tree
Open diff view settings
Filter options
  • docs/plans
    • 2026-03-27-llm-library-api.md
  • internal/gateway
    • config
      • config_test.go
    • proxy.go
    • proxy_test.go
  • llm
    • anthropic
      • codec.go
      • codec_test.go
      • decompose.go
      • decompose_test.go
      • doc.go
      • reassemble.go
      • reassemble_test.go
      • stream.go
      • stream_test.go
    • codec.go
    • pipeline.go
Expand file treeCollapse file tree
Open diff view settings
Collapse file

‎docs/plans/2026-03-27-llm-library-api.md‎

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

‎internal/gateway/config/config_test.go‎

Copy file name to clipboardExpand all lines: internal/gateway/config/config_test.go
+37Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,10 @@ package config
33
import (
44
"os"
55
"path/filepath"
6+
"reflect"
67
"testing"
8+
9+
"github.com/majorcontext/keep/llm"
710
)
811

912
func TestLoad_Valid(t *testing.T) {
@@ -199,6 +202,40 @@ decompose:
199202
}
200203
}
201204

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+
202239
// writeTempYAML writes content to a temp file and returns its path.
203240
func writeTempYAML(t *testing.T, content string) string {
204241
t.Helper()
Collapse file

‎internal/gateway/proxy.go‎

Copy file name to clipboardExpand all lines: internal/gateway/proxy.go
+4-8Lines changed: 4 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -389,19 +389,15 @@ func (p *Proxy) handleStreamingResponse(w http.ResponseWriter, r *http.Request,
389389
p.logDebug("upstream stream", "status", upstreamResp.StatusCode, "events", len(events))
390390

391391
// 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-
400392
streamResult, err := llm.EvaluateStream(p.engine, p.codec, events, p.scope, p.llmCfg)
401393
if err != nil {
402394
writeInternalError(w, "stream policy evaluation error")
403395
return
404396
}
397+
// Verbose: log pre-policy reassembled body (avoids double-reassemble).
398+
if p.verbose != nil {
399+
p.verbose.ResponseRaw(streamResult.RawBody)
400+
}
405401
if p.logger != nil {
406402
for _, a := range streamResult.Audits {
407403
p.logger.Log(a)
Collapse file

‎internal/gateway/proxy_test.go‎

Copy file name to clipboardExpand all lines: internal/gateway/proxy_test.go
+14-4Lines changed: 14 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -440,9 +440,14 @@ func TestProxy_StreamingAllowed(t *testing.T) {
440440
t.Fatalf("expected 7 SSE events (original replay), got %d", len(events))
441441
}
442442

443-
assembled, err := anthropic.ReassembleFromEvents(events)
443+
codec := anthropic.NewCodec()
444+
body, err := codec.ReassembleStream(events)
444445
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)
446451
}
447452
if assembled.Content[0].Text != "Hello from upstream" {
448453
t.Errorf("Text = %q, want %q", assembled.Content[0].Text, "Hello from upstream")
@@ -547,9 +552,14 @@ func TestProxy_StreamingRedactResponse(t *testing.T) {
547552
events = append(events, ev)
548553
}
549554

550-
assembled, err := anthropic.ReassembleFromEvents(events)
555+
codec := anthropic.NewCodec()
556+
body, err := codec.ReassembleStream(events)
551557
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)
553563
}
554564

555565
text := assembled.Content[0].Text
Collapse file

‎llm/anthropic/codec.go‎

Copy file name to clipboardExpand all lines: llm/anthropic/codec.go
+14-14Lines changed: 14 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -20,15 +20,15 @@ func NewCodec() *Codec { return &Codec{} }
2020
type requestHandle struct {
2121
req *MessagesRequest
2222
body []byte
23-
blockMap []BlockPosition
23+
blockMap []blockPosition
2424
cfg llm.DecomposeConfig
2525
}
2626

2727
// responseHandle carries parsed state from DecomposeResponse to ReassembleResponse.
2828
type responseHandle struct {
2929
resp *MessagesResponse
3030
body []byte
31-
blockMap []BlockPosition
31+
blockMap []blockPosition
3232
cfg llm.DecomposeConfig
3333
}
3434

@@ -40,8 +40,8 @@ func (c *Codec) DecomposeRequest(body []byte, scope string, cfg llm.DecomposeCon
4040
return nil, nil, fmt.Errorf("anthropic: unmarshal request: %w", err)
4141
}
4242

43-
calls := DecomposeRequest(&req, scope, cfg)
44-
blockMap := WalkRequestBlocks(&req, cfg)
43+
calls := decomposeRequest(&req, scope, cfg)
44+
blockMap := walkRequestBlocks(&req, cfg)
4545

4646
h := &requestHandle{
4747
req: &req,
@@ -60,8 +60,8 @@ func (c *Codec) DecomposeResponse(body []byte, scope string, cfg llm.DecomposeCo
6060
return nil, nil, fmt.Errorf("anthropic: unmarshal response: %w", err)
6161
}
6262

63-
calls := DecomposeResponse(&resp, scope, cfg)
64-
blockMap := WalkResponseBlocks(&resp, cfg)
63+
calls := decomposeResponse(&resp, scope, cfg)
64+
blockMap := walkResponseBlocks(&resp, cfg)
6565

6666
h := &responseHandle{
6767
resp: &resp,
@@ -85,7 +85,7 @@ func (c *Codec) ReassembleRequest(handle any, results []keep.EvalResult) ([]byte
8585
return h.body, nil
8686
}
8787

88-
patched := ReassembleRequest(h.req, blockResults)
88+
patched := reassembleRequest(h.req, blockResults)
8989
out, err := json.Marshal(patched)
9090
if err != nil {
9191
return nil, fmt.Errorf("anthropic: marshal patched request: %w", err)
@@ -106,7 +106,7 @@ func (c *Codec) ReassembleResponse(handle any, results []keep.EvalResult) ([]byt
106106
return h.body, nil
107107
}
108108

109-
patched := ReassembleResponse(h.resp, blockResults)
109+
patched := reassembleResponse(h.resp, blockResults)
110110
out, err := json.Marshal(patched)
111111
if err != nil {
112112
return nil, fmt.Errorf("anthropic: marshal patched response: %w", err)
@@ -116,7 +116,7 @@ func (c *Codec) ReassembleResponse(handle any, results []keep.EvalResult) ([]byt
116116

117117
// ReassembleStream reassembles SSE events into a complete response body.
118118
func (c *Codec) ReassembleStream(events []sse.Event) ([]byte, error) {
119-
resp, err := ReassembleFromEvents(events)
119+
resp, err := reassembleFromEvents(events)
120120
if err != nil {
121121
return nil, fmt.Errorf("anthropic: reassemble stream: %w", err)
122122
}
@@ -133,19 +133,19 @@ func (c *Codec) SynthesizeEvents(patchedBody []byte) ([]sse.Event, error) {
133133
if err := json.Unmarshal(patchedBody, &resp); err != nil {
134134
return nil, fmt.Errorf("anthropic: unmarshal for synthesize: %w", err)
135135
}
136-
return SynthesizeEvents(&resp), nil
136+
return synthesizeEvents(&resp), nil
137137
}
138138

139139
// buildBlockResults maps eval results back to block positions using CallIndex.
140140
// The offset for summary calls is already baked into BlockPosition.CallIndex
141141
// 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))
144144
for _, pos := range blockMap {
145145
if pos.CallIndex < 0 || pos.CallIndex >= len(results) {
146146
continue
147147
}
148-
out = append(out, BlockResult{
148+
out = append(out, blockResult{
149149
MessageIndex: pos.MessageIndex,
150150
BlockIndex: pos.BlockIndex,
151151
Result: results[pos.CallIndex],
@@ -155,7 +155,7 @@ func buildBlockResults(blockMap []BlockPosition, results []keep.EvalResult) []Bl
155155
}
156156

157157
// hasMutations reports whether any block result contains mutations.
158-
func hasMutations(results []BlockResult) bool {
158+
func hasMutations(results []blockResult) bool {
159159
for _, br := range results {
160160
if len(br.Result.Mutations) > 0 {
161161
return true
Collapse file

‎llm/anthropic/codec_test.go‎

Copy file name to clipboardExpand all lines: llm/anthropic/codec_test.go
+2-2Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -127,9 +127,9 @@ func TestCodec_ReassembleStream(t *testing.T) {
127127
Usage: &Usage{InputTokens: 10, OutputTokens: 5},
128128
}
129129

130-
events := SynthesizeEvents(resp)
130+
events := synthesizeEvents(resp)
131131
if len(events) == 0 {
132-
t.Fatal("expected non-empty events from SynthesizeEvents")
132+
t.Fatal("expected non-empty events from synthesizeEvents")
133133
}
134134

135135
c := NewCodec()
Collapse file

‎llm/anthropic/decompose.go‎

Copy file name to clipboardExpand all lines: llm/anthropic/decompose.go
+19-19Lines changed: 19 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -8,18 +8,18 @@ import (
88
"github.com/majorcontext/keep/llm"
99
)
1010

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 {
1313
MessageIndex int
1414
BlockIndex int
1515
Block ContentBlock
1616
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
1818
}
1919

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
2323
callIdx := 0
2424
if cfg.RequestSummaryEnabled() {
2525
callIdx = 1 // account for the summary call at index 0
@@ -31,7 +31,7 @@ func WalkRequestBlocks(req *MessagesRequest, cfg llm.DecomposeConfig) []BlockPos
3131
switch block.Type {
3232
case "tool_result":
3333
if cfg.ToolResultEnabled() {
34-
positions = append(positions, BlockPosition{
34+
positions = append(positions, blockPosition{
3535
MessageIndex: msgIdx,
3636
BlockIndex: blockIdx,
3737
Block: block,
@@ -42,7 +42,7 @@ func WalkRequestBlocks(req *MessagesRequest, cfg llm.DecomposeConfig) []BlockPos
4242
}
4343
case "text":
4444
if cfg.TextEnabled() {
45-
positions = append(positions, BlockPosition{
45+
positions = append(positions, blockPosition{
4646
MessageIndex: msgIdx,
4747
BlockIndex: blockIdx,
4848
Block: block,
@@ -58,9 +58,9 @@ func WalkRequestBlocks(req *MessagesRequest, cfg llm.DecomposeConfig) []BlockPos
5858
return positions
5959
}
6060

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
6464
callIdx := 0
6565
if cfg.ResponseSummaryEnabled() {
6666
callIdx = 1
@@ -70,7 +70,7 @@ func WalkResponseBlocks(resp *MessagesResponse, cfg llm.DecomposeConfig) []Block
7070
switch block.Type {
7171
case "tool_use":
7272
if cfg.ToolUseEnabled() {
73-
positions = append(positions, BlockPosition{
73+
positions = append(positions, blockPosition{
7474
MessageIndex: 0,
7575
BlockIndex: blockIdx,
7676
Block: block,
@@ -81,7 +81,7 @@ func WalkResponseBlocks(resp *MessagesResponse, cfg llm.DecomposeConfig) []Block
8181
}
8282
case "text":
8383
if cfg.TextEnabled() {
84-
positions = append(positions, BlockPosition{
84+
positions = append(positions, blockPosition{
8585
MessageIndex: 0,
8686
BlockIndex: blockIdx,
8787
Block: block,
@@ -96,9 +96,9 @@ func WalkResponseBlocks(resp *MessagesResponse, cfg llm.DecomposeConfig) []Block
9696
return positions
9797
}
9898

99-
// DecomposeRequest breaks an Anthropic Messages API request into flat Keep calls.
99+
// decomposeRequest breaks an Anthropic Messages API request into flat Keep calls.
100100
// 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 {
102102
var calls []keep.Call
103103

104104
// 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
120120
}
121121

122122
// 2. Walk messages for content blocks using the shared iterator.
123-
for _, pos := range WalkRequestBlocks(req, cfg) {
123+
for _, pos := range walkRequestBlocks(req, cfg) {
124124
switch pos.Block.Type {
125125
case "tool_result":
126126
toolName := toolNameMap[pos.Block.ToolUseID]
@@ -148,8 +148,8 @@ func DecomposeRequest(req *MessagesRequest, scope string, cfg llm.DecomposeConfi
148148
return calls
149149
}
150150

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 {
153153
var calls []keep.Call
154154

155155
// 1. Summary call.
@@ -165,7 +165,7 @@ func DecomposeResponse(resp *MessagesResponse, scope string, cfg llm.DecomposeCo
165165
}
166166

167167
// 2. Walk response content blocks using the shared iterator.
168-
for _, pos := range WalkResponseBlocks(resp, cfg) {
168+
for _, pos := range walkResponseBlocks(resp, cfg) {
169169
switch pos.Block.Type {
170170
case "tool_use":
171171
calls = append(calls, keep.Call{

0 commit comments

Comments
0 (0)
You are visitor 01402792 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.