Skip to content

Commit 4bd2efa

Browse files
committed
feat(gateway): reuse tools and inherit history mode in Responses continuations
1 parent 29f5fec commit 4bd2efa

2 files changed

Lines changed: 97 additions & 23 deletions

File tree

‎internal/server/app.go‎

Lines changed: 14 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -36,11 +36,20 @@ type stickyEntry struct {
3636
}
3737

3838
type responseEntry struct {
39-
Key string
40-
Affinity string
41-
History *responseHistory
42-
Response shared.M
43-
Bytes int
39+
Key string
40+
Affinity string
41+
InstructionMode string
42+
History *responseHistory
43+
Tools *responseToolSet
44+
ToolOptions shared.M
45+
Response shared.M
46+
Bytes int
47+
}
48+
49+
type responseToolSet struct {
50+
definitions []any
51+
bytes int
52+
refs int // Stored entries, guarded by App.mu.
4453
}
4554

4655
type responseHistory struct {

‎internal/server/gateway.go‎

Lines changed: 83 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -19,8 +19,8 @@ import (
1919
func (a *App) GatewayHandler() http.Handler {
2020
return a.guard(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
2121
w.Header().Set("Access-Control-Allow-Origin", "*")
22-
w.Header().Set("Access-Control-Allow-Headers", "authorization, content-type, x-api-key, anthropic-version, anthropic-beta, x-session-id, x-zcode-instruction-mode, x-zcode-session-type, x-zcode-query-source, x-zcode-template-mode")
23-
w.Header().Set("Access-Control-Expose-Headers", "X-Zcode-Instruction-Mode, X-Zcode-Compatibility, X-Zcode-Grammar-Validation, X-Zcode-Session-Type, X-Zcode-Query-Source, X-Zcode-Template-Mode, Retry-After, X-Retry-Attempts")
22+
w.Header().Set("Access-Control-Allow-Headers", "authorization, content-type, x-api-key, anthropic-version, anthropic-beta, x-session-id, x-zcode-instruction-mode, x-zcode-session-type, x-zcode-query-source, x-zcode-template-mode, x-zcode-reuse-tools")
23+
w.Header().Set("Access-Control-Expose-Headers", "X-Zcode-Instruction-Mode, X-Zcode-Compatibility, X-Zcode-Grammar-Validation, X-Zcode-Session-Type, X-Zcode-Query-Source, X-Zcode-Template-Mode, X-Zcode-Tools-Reused, Retry-After, X-Retry-Attempts")
2424
w.Header().Set("Access-Control-Allow-Methods", "GET, POST, PATCH, PUT, DELETE, OPTIONS")
2525
if r.Method == "OPTIONS" {
2626
w.WriteHeader(204)
@@ -291,8 +291,7 @@ func (a *App) handleInference(w http.ResponseWriter, r *http.Request, body, k sh
291291
w.Header().Set("X-Zcode-Query-Source", source.QuerySource)
292292
}
293293
payload := shared.Clone(body)
294-
var inheritedAffinity string
295-
var previousHistory *responseHistory
294+
var previous responseEntry
296295
if protocol == "responses" && shared.Truth(body["previous_response_id"]) {
297296
a.mu.Lock()
298297
entry, ok := a.responses[shared.Str(body["previous_response_id"])]
@@ -301,14 +300,30 @@ func (a *App) handleInference(w http.ResponseWriter, r *http.Request, body, k sh
301300
writeJSON(w, 404, shared.M{"error": shared.M{"type": "invalid_request_error", "code": "response_not_found", "message": "previous_response_id 不存在或不属于当前密钥"}})
302301
return
303302
}
304-
inheritedAffinity = entry.Affinity
305-
previousHistory = entry.History
306-
payload["input"] = previousHistory.withInput(inputItems(body["input"]))
303+
previous = entry
304+
payload["input"] = previous.History.withInput(inputItems(body["input"]))
305+
}
306+
var keepTools bool
307+
var reusedTools *responseToolSet
308+
if protocol == "responses" {
309+
switch strings.ToLower(strings.TrimSpace(r.Header.Get("X-Zcode-Reuse-Tools"))) {
310+
case "":
311+
keepTools = previous.Tools != nil
312+
case "true":
313+
keepTools = true
314+
case "false":
315+
default:
316+
a.sendFailure(w, &fault.Failure{Kind: "invalid", Code: "unsupported_request", Message: "X-Zcode-Reuse-Tools 只能为 true 或 false"}, protocol)
317+
return
318+
}
319+
if keepTools {
320+
reusedTools = previous.reuseTools(payload)
321+
}
307322
}
308323
level := a.effectiveEffort(body, k)
309324
mode := shared.Str(shared.Fallback(r.Header.Get("X-Zcode-Instruction-Mode"), payload["instruction_mode"]))
310325
if mode == "" && protocol != "anthropic" {
311-
mode = shared.Str(k["default_instruction_mode"])
326+
mode = shared.Str(shared.Fallback(previous.InstructionMode, k["default_instruction_mode"]))
312327
}
313328
instructions, e := wire.NewInstructionContext(mode)
314329
if e != nil {
@@ -325,6 +340,9 @@ func (a *App) handleInference(w http.ResponseWriter, r *http.Request, body, k sh
325340
a.sendFailure(w, e.(*fault.Failure), protocol)
326341
return
327342
}
343+
if reusedTools != nil {
344+
w.Header().Set("X-Zcode-Tools-Reused", "true")
345+
}
328346
if protocol != "anthropic" && instructions.Mode == "history" {
329347
w.Header().Set("X-Zcode-Instruction-Mode", "history")
330348
} else if instructions.Used {
@@ -350,7 +368,7 @@ func (a *App) handleInference(w http.ResponseWriter, r *http.Request, body, k sh
350368
affinity, sticky := a.affinity(r, body, k)
351369
if protocol == "responses" && affinity == shared.Str(k["id"]) {
352370
// The bare key means no explicit session was recognized by affinity().
353-
affinity = inheritedAffinity
371+
affinity = previous.Affinity
354372
if affinity == "" {
355373
affinity = shared.Str(k["id"]) + ":responses:" + shared.Hash(id)[:24]
356374
}
@@ -386,18 +404,53 @@ func (a *App) handleInference(w http.ResponseWriter, r *http.Request, body, k sh
386404
}
387405
}
388406
if protocol == "responses" && body["store"] != false {
389-
a.rememberResponse(shared.Str(k["id"]), affinity, previousHistory, inputItems(body["input"]), response)
407+
entry := responseEntry{Key: shared.Str(k["id"]), Affinity: affinity, Response: response}
408+
// Only the cache-friendly opt-in carries forward when the next turn omits a mode.
409+
if instructions.Mode == "history" {
410+
entry.InstructionMode = instructions.Mode
411+
}
412+
if keepTools {
413+
entry.Tools = reusedTools
414+
if definitions := shared.Arr(payload["tools"]); entry.Tools == nil && len(definitions) > 0 {
415+
entry.Tools = &responseToolSet{definitions: definitions, bytes: len(shared.JSON(definitions))}
416+
}
417+
if entry.Tools != nil {
418+
entry.ToolOptions = shared.M{}
419+
shared.CopyFields(entry.ToolOptions, payload, "tool_choice", "parallel_tool_calls")
420+
}
421+
}
422+
a.rememberResponse(entry, previous.History, inputItems(body["input"]))
390423
}
391424
if stream == nil {
392425
w.Header().Set("X-Retry-Attempts", fmt.Sprint(result.Attempts))
393426
writeJSON(w, 200, response)
394427
}
395428
}
396429

430+
func (e responseEntry) reuseTools(payload shared.M) *responseToolSet {
431+
// An explicit tools field, including an empty list, replaces the previous set.
432+
if _, explicit := payload["tools"]; explicit || e.Tools == nil {
433+
return nil
434+
}
435+
payload["tools"] = e.Tools.definitions
436+
for field, value := range e.ToolOptions {
437+
if _, explicit := payload[field]; !explicit {
438+
payload[field] = value
439+
}
440+
}
441+
return e.Tools
442+
}
443+
397444
func (a *App) forgetResponse(id string) {
398445
if e, ok := a.responses[id]; ok {
399446
a.responseBytes -= e.Bytes
400447
delete(a.responses, id)
448+
if e.Tools != nil {
449+
e.Tools.refs--
450+
if e.Tools.refs == 0 {
451+
a.responseBytes -= e.Tools.bytes
452+
}
453+
}
401454
for h := e.History; h != nil; h = h.parent {
402455
h.refs--
403456
if h.refs > 0 {
@@ -427,9 +480,9 @@ func (h *responseHistory) withInput(input []any) []any {
427480
return items
428481
}
429482

430-
func (a *App) rememberResponse(key, affinity string, parent *responseHistory, input []any, response shared.M) {
483+
func (a *App) rememberResponse(entry responseEntry, parent *responseHistory, input []any) {
431484
const maxResponseBytes = 64 << 20
432-
output := shared.Arr(response["output"])
485+
output := shared.Arr(entry.Response["output"])
433486
items := make([]any, 0, len(input)+len(output))
434487
items = append(append(items, input...), output...)
435488
// Share history across continuations and branches, including when a parent
@@ -441,19 +494,31 @@ func (a *App) rememberResponse(key, affinity string, parent *responseHistory, in
441494
history.totalBytes += parent.totalBytes
442495
}
443496
// The history node already accounts for the output items.
444-
envelope := maps.Clone(response)
497+
envelope := maps.Clone(entry.Response)
445498
envelope["output"] = []any{}
446-
size := len(shared.JSON(envelope)) + len(affinity)
447-
if size+history.totalBytes > maxResponseBytes {
499+
entry.Bytes = len(shared.JSON(envelope)) + len(entry.Affinity) + len(entry.InstructionMode)
500+
toolBytes := 0
501+
if entry.Tools != nil {
502+
entry.Bytes += len(shared.JSON(entry.ToolOptions))
503+
toolBytes = entry.Tools.bytes
504+
}
505+
if entry.Bytes+history.totalBytes+toolBytes > maxResponseBytes {
448506
return
449507
}
508+
entry.History = history
450509
a.mu.Lock()
451510
defer a.mu.Unlock()
452-
id := shared.Str(response["id"])
511+
id := shared.Str(entry.Response["id"])
453512
a.forgetResponse(id)
454-
a.responses[id] = responseEntry{Key: key, Affinity: affinity, History: history, Response: response, Bytes: size}
513+
a.responses[id] = entry
455514
a.responseOrder = append(a.responseOrder, id)
456-
a.responseBytes += size
515+
a.responseBytes += entry.Bytes
516+
if entry.Tools != nil {
517+
entry.Tools.refs++
518+
if entry.Tools.refs == 1 {
519+
a.responseBytes += toolBytes
520+
}
521+
}
457522
for h := history; h != nil; h = h.parent {
458523
h.refs++
459524
if h.refs > 1 {

0 commit comments

Comments
 (0)