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 — fix(gateway): address P1 and P2 review findings · majorcontext/keep@9ad702e

File tree

Expand file treeCollapse file tree
Open diff view settings
Filter options
  • internal/gateway
    • anthropic
      • decompose.go
    • proxy.go
    • proxy_test.go
Expand file treeCollapse file tree
Open diff view settings
Collapse file

‎internal/gateway/anthropic/decompose.go‎

Copy file name to clipboardExpand all lines: internal/gateway/anthropic/decompose.go
+130-53Lines changed: 130 additions & 53 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,94 @@ import (
88
"github.com/majorcontext/keep/internal/gateway/config"
99
)
1010

11+
// BlockPosition identifies a content block within a request.
12+
type BlockPosition struct {
13+
MessageIndex int
14+
BlockIndex int
15+
Block ContentBlock
16+
Role string // role of the containing message
17+
CallIndex int // index into the calls slice returned by DecomposeRequest
18+
}
19+
20+
// WalkRequestBlocks returns the positions of all blocks that DecomposeRequest would emit calls for.
21+
func WalkRequestBlocks(req *MessagesRequest, cfg config.DecomposeConfig) []BlockPosition {
22+
var positions []BlockPosition
23+
callIdx := 0
24+
if cfg.RequestSummaryEnabled() {
25+
callIdx = 1 // account for the summary call at index 0
26+
}
27+
28+
for msgIdx, msg := range req.Messages {
29+
blocks := msg.ContentBlocks()
30+
for blockIdx, block := range blocks {
31+
switch block.Type {
32+
case "tool_result":
33+
if cfg.ToolResultEnabled() {
34+
positions = append(positions, BlockPosition{
35+
MessageIndex: msgIdx,
36+
BlockIndex: blockIdx,
37+
Block: block,
38+
Role: msg.Role,
39+
CallIndex: callIdx,
40+
})
41+
callIdx++
42+
}
43+
case "text":
44+
if cfg.TextEnabled() {
45+
positions = append(positions, BlockPosition{
46+
MessageIndex: msgIdx,
47+
BlockIndex: blockIdx,
48+
Block: block,
49+
Role: msg.Role,
50+
CallIndex: callIdx,
51+
})
52+
callIdx++
53+
}
54+
}
55+
}
56+
}
57+
58+
return positions
59+
}
60+
61+
// WalkResponseBlocks returns the positions of all blocks that DecomposeResponse would emit calls for.
62+
func WalkResponseBlocks(resp *MessagesResponse, cfg config.DecomposeConfig) []BlockPosition {
63+
var positions []BlockPosition
64+
callIdx := 0
65+
if cfg.ResponseSummaryEnabled() {
66+
callIdx = 1
67+
}
68+
69+
for blockIdx, block := range resp.Content {
70+
switch block.Type {
71+
case "tool_use":
72+
if cfg.ToolUseEnabled() {
73+
positions = append(positions, BlockPosition{
74+
MessageIndex: 0,
75+
BlockIndex: blockIdx,
76+
Block: block,
77+
Role: resp.Role,
78+
CallIndex: callIdx,
79+
})
80+
callIdx++
81+
}
82+
case "text":
83+
if cfg.TextEnabled() {
84+
positions = append(positions, BlockPosition{
85+
MessageIndex: 0,
86+
BlockIndex: blockIdx,
87+
Block: block,
88+
Role: resp.Role,
89+
CallIndex: callIdx,
90+
})
91+
callIdx++
92+
}
93+
}
94+
}
95+
96+
return positions
97+
}
98+
1199
// DecomposeRequest breaks an Anthropic Messages API request into flat Keep calls.
12100
// Returns one llm.request summary + one call per content block (based on decompose config).
13101
func DecomposeRequest(req *MessagesRequest, scope string, cfg config.DecomposeConfig) []keep.Call {
@@ -31,36 +119,29 @@ func DecomposeRequest(req *MessagesRequest, scope string, cfg config.DecomposeCo
31119
})
32120
}
33121

34-
// 2. Walk messages for content blocks.
35-
for _, msg := range req.Messages {
36-
blocks := msg.ContentBlocks()
37-
for _, block := range blocks {
38-
switch block.Type {
39-
case "tool_result":
40-
if cfg.ToolResultEnabled() {
41-
toolName := toolNameMap[block.ToolUseID]
42-
calls = append(calls, keep.Call{
43-
Operation: "llm.tool_result",
44-
Params: map[string]any{
45-
"tool_name": toolName,
46-
"tool_use_id": block.ToolUseID,
47-
"content": block.ToolResultContent(),
48-
},
49-
Context: keep.CallContext{Scope: scope, Direction: "request"},
50-
})
51-
}
52-
case "text":
53-
if cfg.TextEnabled() {
54-
calls = append(calls, keep.Call{
55-
Operation: "llm.text",
56-
Params: map[string]any{
57-
"text": block.Text,
58-
"role": msg.Role,
59-
},
60-
Context: keep.CallContext{Scope: scope, Direction: "request"},
61-
})
62-
}
63-
}
122+
// 2. Walk messages for content blocks using the shared iterator.
123+
for _, pos := range WalkRequestBlocks(req, cfg) {
124+
switch pos.Block.Type {
125+
case "tool_result":
126+
toolName := toolNameMap[pos.Block.ToolUseID]
127+
calls = append(calls, keep.Call{
128+
Operation: "llm.tool_result",
129+
Params: map[string]any{
130+
"tool_name": toolName,
131+
"tool_use_id": pos.Block.ToolUseID,
132+
"content": pos.Block.ToolResultContent(),
133+
},
134+
Context: keep.CallContext{Scope: scope, Direction: "request"},
135+
})
136+
case "text":
137+
calls = append(calls, keep.Call{
138+
Operation: "llm.text",
139+
Params: map[string]any{
140+
"text": pos.Block.Text,
141+
"role": pos.Role,
142+
},
143+
Context: keep.CallContext{Scope: scope, Direction: "request"},
144+
})
64145
}
65146
}
66147

@@ -83,31 +164,27 @@ func DecomposeResponse(resp *MessagesResponse, scope string, cfg config.Decompos
83164
})
84165
}
85166

86-
// 2. Walk response content blocks.
87-
for _, block := range resp.Content {
88-
switch block.Type {
167+
// 2. Walk response content blocks using the shared iterator.
168+
for _, pos := range WalkResponseBlocks(resp, cfg) {
169+
switch pos.Block.Type {
89170
case "tool_use":
90-
if cfg.ToolUseEnabled() {
91-
calls = append(calls, keep.Call{
92-
Operation: "llm.tool_use",
93-
Params: map[string]any{
94-
"name": block.Name,
95-
"input": block.Input,
96-
},
97-
Context: keep.CallContext{Scope: scope, Direction: "response"},
98-
})
99-
}
171+
calls = append(calls, keep.Call{
172+
Operation: "llm.tool_use",
173+
Params: map[string]any{
174+
"name": pos.Block.Name,
175+
"input": pos.Block.Input,
176+
},
177+
Context: keep.CallContext{Scope: scope, Direction: "response"},
178+
})
100179
case "text":
101-
if cfg.TextEnabled() {
102-
calls = append(calls, keep.Call{
103-
Operation: "llm.text",
104-
Params: map[string]any{
105-
"text": block.Text,
106-
"role": resp.Role,
107-
},
108-
Context: keep.CallContext{Scope: scope, Direction: "response"},
109-
})
110-
}
180+
calls = append(calls, keep.Call{
181+
Operation: "llm.text",
182+
Params: map[string]any{
183+
"text": pos.Block.Text,
184+
"role": resp.Role,
185+
},
186+
Context: keep.CallContext{Scope: scope, Direction: "response"},
187+
})
111188
}
112189
}
113190

Collapse file

‎internal/gateway/proxy.go‎

Copy file name to clipboardExpand all lines: internal/gateway/proxy.go
+32-25Lines changed: 32 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@ import (
88
"net/http"
99
"net/http/httputil"
1010
"net/url"
11+
"strings"
1112
"time"
1213

1314
"github.com/majorcontext/keep"
@@ -19,6 +20,9 @@ import (
1920
// maxRequestBodySize is the maximum size of a request body we will read (4 MB).
2021
const maxRequestBodySize = 4 * 1024 * 1024
2122

23+
// maxResponseBodySize is the maximum size of an upstream response body we will read (16 MB).
24+
const maxResponseBodySize = 16 << 20 // 16 MB
25+
2226
// Proxy is the LLM gateway HTTP handler.
2327
type Proxy struct {
2428
engine *keep.Engine
@@ -46,7 +50,10 @@ func NewProxy(engine *keep.Engine, cfg *gwconfig.GatewayConfig, logger *audit.Lo
4650
decompose: cfg.Decompose,
4751
logger: logger,
4852
passthru: rp,
49-
client: &http.Client{Timeout: 120 * time.Second},
53+
// 110s client timeout is less than the server's 120s WriteTimeout,
54+
// ensuring the upstream error response has time to be written back
55+
// before the server closes the connection.
56+
client: &http.Client{Timeout: 110 * time.Second},
5057
}, nil
5158
}
5259

@@ -111,6 +118,20 @@ func (p *Proxy) handleMessages(w http.ResponseWriter, r *http.Request) {
111118
return
112119
}
113120

121+
// 2b. Reject streaming requests — the policy gateway cannot evaluate streamed responses.
122+
if req.Stream {
123+
w.Header().Set("Content-Type", "application/json")
124+
w.WriteHeader(http.StatusBadRequest)
125+
json.NewEncoder(w).Encode(map[string]any{
126+
"type": "error",
127+
"error": map[string]any{
128+
"type": "unsupported",
129+
"message": "Streaming is not supported by the policy gateway. Set stream: false.",
130+
},
131+
})
132+
return
133+
}
134+
114135
// 3. Decompose request into calls.
115136
calls := anthropic.DecomposeRequest(&req, p.scope, p.decompose)
116137

@@ -172,7 +193,8 @@ func (p *Proxy) handleMessages(w http.ResponseWriter, r *http.Request) {
172193
}
173194

174195
// 7. Forward to upstream.
175-
upstreamURL := p.upstream.String() + "/v1/messages"
196+
upstreamBase := strings.TrimRight(p.upstream.String(), "/")
197+
upstreamURL := upstreamBase + "/v1/messages"
176198
upstreamReq, err := http.NewRequestWithContext(r.Context(), "POST", upstreamURL, bytes.NewReader(forwardBody))
177199
if err != nil {
178200
writeInternalError(w, "failed to create upstream request")
@@ -194,7 +216,7 @@ func (p *Proxy) handleMessages(w http.ResponseWriter, r *http.Request) {
194216
defer upstreamResp.Body.Close()
195217

196218
// 8. Read response body.
197-
respBody, err := io.ReadAll(upstreamResp.Body)
219+
respBody, err := io.ReadAll(io.LimitReader(upstreamResp.Body, maxResponseBodySize))
198220
if err != nil {
199221
writeInternalError(w, "failed to read upstream response")
200222
return
@@ -283,31 +305,16 @@ type blockPosition struct {
283305

284306
// buildRequestBlockMap walks the request messages in the same order as DecomposeRequest
285307
// and returns the (MessageIndex, BlockIndex) for each content-block call.
308+
// Uses the shared WalkRequestBlocks iterator to ensure consistent traversal.
286309
func buildRequestBlockMap(req *anthropic.MessagesRequest, cfg gwconfig.DecomposeConfig) []blockPosition {
287-
var positions []blockPosition
288-
289-
for msgIdx, msg := range req.Messages {
290-
blocks := msg.ContentBlocks()
291-
for blockIdx, block := range blocks {
292-
switch block.Type {
293-
case "tool_result":
294-
if cfg.ToolResultEnabled() {
295-
positions = append(positions, blockPosition{
296-
MessageIndex: msgIdx,
297-
BlockIndex: blockIdx,
298-
})
299-
}
300-
case "text":
301-
if cfg.TextEnabled() {
302-
positions = append(positions, blockPosition{
303-
MessageIndex: msgIdx,
304-
BlockIndex: blockIdx,
305-
})
306-
}
307-
}
310+
walked := anthropic.WalkRequestBlocks(req, cfg)
311+
positions := make([]blockPosition, len(walked))
312+
for i, pos := range walked {
313+
positions[i] = blockPosition{
314+
MessageIndex: pos.MessageIndex,
315+
BlockIndex: pos.BlockIndex,
308316
}
309317
}
310-
311318
return positions
312319
}
313320

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.