Compare commits
3
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
da70a4dcff | ||
|
|
572cd0a2f6 | ||
|
|
714c969e8c |
No files matched your search
@@ -22,6 +22,7 @@ const (
|
||||
OllamaCompactionPayloadVersion = 1
|
||||
CreateSummaryToolName = "create_summary"
|
||||
compactionSummaryToolName = "ollama_compaction_summary"
|
||||
compactionImageOmissionNotice = "%d older image(s) were omitted from the transcript because the request was too large."
|
||||
compactionOmissionNotice = "Compaction warning: %d older transcript items were omitted before summarization because the model's context limit was exceeded."
|
||||
)
|
||||
|
||||
@@ -92,11 +93,12 @@ type ResponsesCompactionPlan struct {
|
||||
Model string
|
||||
Stream bool
|
||||
|
||||
items []CompactionTranscriptItem
|
||||
tools []compactionToolMetadata
|
||||
groups []compactionToolGroup
|
||||
forcedRefs map[string]struct{}
|
||||
omittedItems int
|
||||
items []CompactionTranscriptItem
|
||||
tools []compactionToolMetadata
|
||||
groups []compactionToolGroup
|
||||
forcedRefs map[string]struct{}
|
||||
omittedItems int
|
||||
omittedImages int
|
||||
}
|
||||
|
||||
// ResponsesCompactionResult is the validated result of a compaction-model call.
|
||||
@@ -821,6 +823,54 @@ func (p *ResponsesCompactionPlan) TrimForContextLimit() int {
|
||||
return len(removed)
|
||||
}
|
||||
|
||||
// DropImagesForBodyLimit removes images from the oldest items until at least
|
||||
// half of the image payload bytes are gone, for upstreams that reject large
|
||||
// request bodies (HTTP 413) independent of the context window. Images in the
|
||||
// latest item and active tool state are always preserved. It returns the number
|
||||
// of images removed, or zero when no progress is possible.
|
||||
func (p *ResponsesCompactionPlan) DropImagesForBodyLimit() int {
|
||||
if len(p.items) < 2 {
|
||||
return 0
|
||||
}
|
||||
var total, text int
|
||||
for _, item := range p.items {
|
||||
message := item.Message
|
||||
message.Images = nil
|
||||
metadata, err := json.Marshal(compactionTranscriptItemWire{
|
||||
Ref: item.Ref, Type: item.Type, Message: message, StandaloneName: item.StandaloneName, ImageCount: len(item.Message.Images),
|
||||
})
|
||||
if err != nil {
|
||||
return 0
|
||||
}
|
||||
text += len(metadata)
|
||||
for _, image := range item.Message.Images {
|
||||
total += len(image)
|
||||
}
|
||||
}
|
||||
// Only shed images while they make up most of the body; otherwise the
|
||||
// body limit is driven by text and the caller should trim items instead.
|
||||
if total == 0 || total < text {
|
||||
return 0
|
||||
}
|
||||
|
||||
var removedBytes, removedImages int
|
||||
for i := range p.items[:len(p.items)-1] {
|
||||
if removedBytes >= (total+1)/2 {
|
||||
break
|
||||
}
|
||||
if _, protected := p.forcedRefs[p.items[i].Ref]; protected {
|
||||
continue
|
||||
}
|
||||
for _, image := range p.items[i].Message.Images {
|
||||
removedBytes += len(image)
|
||||
removedImages++
|
||||
}
|
||||
p.items[i].Message.Images = nil
|
||||
}
|
||||
p.omittedImages += removedImages
|
||||
return removedImages
|
||||
}
|
||||
|
||||
// SummaryRequest returns an ordinary non-streaming Responses request. A repair
|
||||
// request includes the validation error from the first model response.
|
||||
func (p *ResponsesCompactionPlan) SummaryRequest(repairError string) ([]byte, error) {
|
||||
@@ -834,6 +884,9 @@ func (p *ResponsesCompactionPlan) SummaryRequest(repairError string) ([]byte, er
|
||||
if p.omittedItems > 0 {
|
||||
prompt += " " + fmt.Sprintf(compactionOmissionNotice, p.omittedItems)
|
||||
}
|
||||
if p.omittedImages > 0 {
|
||||
prompt += " " + fmt.Sprintf(compactionImageOmissionNotice, p.omittedImages)
|
||||
}
|
||||
if repairError != "" {
|
||||
prompt += " Your previous create_summary call was invalid: " + repairError + ". Return one corrected create_summary call."
|
||||
}
|
||||
@@ -978,6 +1031,9 @@ func (p *ResponsesCompactionPlan) Complete(body []byte) (ResponsesCompactionResu
|
||||
if p.omittedItems > 0 {
|
||||
payload.Summary = fmt.Sprintf(compactionOmissionNotice, p.omittedItems) + "\n\n" + payload.Summary
|
||||
}
|
||||
if p.omittedImages > 0 {
|
||||
payload.Summary = fmt.Sprintf(compactionImageOmissionNotice, p.omittedImages) + "\n\n" + payload.Summary
|
||||
}
|
||||
payloadJSON, err := json.Marshal(payload)
|
||||
if err != nil {
|
||||
return ResponsesCompactionResult{}, err
|
||||
|
||||
@@ -2,8 +2,11 @@ package openai
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
stdimage "image"
|
||||
"image/png"
|
||||
"slices"
|
||||
"strings"
|
||||
"testing"
|
||||
@@ -578,11 +581,24 @@ func TestCompactionReplaysRetainedToolOutputImagesWithTheirCall(t *testing.T) {
|
||||
}
|
||||
|
||||
func TestCompactionForcesActiveToolOutputImage(t *testing.T) {
|
||||
img := stdimage.NewNRGBA(stdimage.Rect(0, 0, 32, 32))
|
||||
seed := uint32(19266)
|
||||
for i := range img.Pix {
|
||||
seed = 1664525*seed + 1013904223
|
||||
img.Pix[i] = byte(seed >> 24)
|
||||
}
|
||||
var encoded bytes.Buffer
|
||||
if err := png.Encode(&encoded, img); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
imageURL := "data:image/png;base64," + base64.StdEncoding.EncodeToString(encoded.Bytes())
|
||||
body := []byte(`{
|
||||
"model":"test","stream":true,
|
||||
"input":[
|
||||
{"type":"function_call","call_id":"call_1","name":"screenshot","arguments":"{}"},
|
||||
{"type":"function_call_output","call_id":"call_1","output":[{"type":"input_image","detail":"auto","image_url":"` + compactionTestPNG + `"}]},
|
||||
{"type":"function_call","call_id":"call_2","name":"screenshot","arguments":"{}"},
|
||||
{"type":"function_call_output","call_id":"call_1","output":[{"type":"input_image","detail":"auto","image_url":"` + imageURL + `"}]},
|
||||
{"type":"function_call_output","call_id":"call_2","output":[{"type":"input_image","detail":"auto","image_url":"` + imageURL + `"}]},
|
||||
{"type":"compaction_trigger"}
|
||||
]
|
||||
}`)
|
||||
@@ -590,6 +606,9 @@ func TestCompactionForcesActiveToolOutputImage(t *testing.T) {
|
||||
if err != nil || !requested {
|
||||
t.Fatalf("prepare: requested=%v err=%v", requested, err)
|
||||
}
|
||||
if removed := plan.DropImagesForBodyLimit(); removed != 0 {
|
||||
t.Errorf("removed %d protected images", removed)
|
||||
}
|
||||
result, err := plan.Complete(compactionResponseBody(t, map[string]any{
|
||||
"summary": "The screenshot tool just completed.", "retain_item_ids": []string{},
|
||||
}))
|
||||
@@ -597,9 +616,28 @@ func TestCompactionForcesActiveToolOutputImage(t *testing.T) {
|
||||
t.Fatal(err)
|
||||
}
|
||||
payload := decodeResultPayload(t, result)
|
||||
if len(payload.Retained) != 2 || len(payload.Retained[1].Images) != 1 {
|
||||
if len(payload.Retained) != 4 {
|
||||
t.Fatalf("active tool state and its image must be forced: %+v", payload.Retained)
|
||||
}
|
||||
for i, callID := range []string{"call_1", "call_2"} {
|
||||
message := payload.Retained[i+2]
|
||||
if message.ToolCallID != callID || len(message.Images) != 1 || !bytes.Equal(message.Images[0], encoded.Bytes()) {
|
||||
t.Errorf("active result %s lost its image", callID)
|
||||
}
|
||||
}
|
||||
continuation, err := json.Marshal(map[string]any{"model": "test", "input": []any{
|
||||
result.Item, map[string]any{"role": "user", "content": "Continue from both screenshots."},
|
||||
}})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
expanded, changed, err := ExpandResponsesCompactionInput(continuation)
|
||||
if err != nil || !changed {
|
||||
t.Fatalf("continuation: changed=%v err=%v", changed, err)
|
||||
}
|
||||
if bytes.Count(expanded, []byte(imageURL)) != 2 || !bytes.Contains(expanded, []byte("Continue from both screenshots.")) {
|
||||
t.Fatal("continuation lost protected screenshots or the next user message")
|
||||
}
|
||||
}
|
||||
|
||||
func TestCompactionRejectsUnsupportedImageSources(t *testing.T) {
|
||||
@@ -957,3 +995,80 @@ func TestCompactionMessageAgentMessage(t *testing.T) {
|
||||
t.Fatalf("kind=%q msg=%#v", kind, msg)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDropImagesForBodyLimit(t *testing.T) {
|
||||
plan := &ResponsesCompactionPlan{items: []CompactionTranscriptItem{
|
||||
{Ref: "a", Message: api.Message{Role: "user", Images: []api.ImageData{make([]byte, 100)}}},
|
||||
{Ref: "b", Message: api.Message{Role: "user", Images: []api.ImageData{make([]byte, 100)}}},
|
||||
{Ref: "c", Message: api.Message{Role: "user", Images: []api.ImageData{make([]byte, 100)}}},
|
||||
{Ref: "d", Message: api.Message{Role: "user", Images: []api.ImageData{make([]byte, 100)}}},
|
||||
}}
|
||||
if removed := plan.DropImagesForBodyLimit(); removed != 2 {
|
||||
t.Fatalf("removed %d images, want 2", removed)
|
||||
}
|
||||
if len(plan.items[0].Message.Images) != 0 || len(plan.items[1].Message.Images) != 0 || len(plan.items[3].Message.Images) != 1 {
|
||||
t.Fatalf("wrong images dropped")
|
||||
}
|
||||
if plan.omittedImages != 2 {
|
||||
t.Fatalf("omittedImages=%d", plan.omittedImages)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDropImagesForBodyLimitBoundaries(t *testing.T) {
|
||||
img := func(n int) []api.ImageData { return []api.ImageData{make([]byte, n)} }
|
||||
t.Run("empty and single", func(t *testing.T) {
|
||||
if got := (&ResponsesCompactionPlan{}).DropImagesForBodyLimit(); got != 0 {
|
||||
t.Fatalf("empty removed %d", got)
|
||||
}
|
||||
plan := &ResponsesCompactionPlan{items: []CompactionTranscriptItem{{Ref: "a", Message: api.Message{Images: img(10)}}}}
|
||||
if got := plan.DropImagesForBodyLimit(); got != 0 {
|
||||
t.Fatalf("single removed %d", got)
|
||||
}
|
||||
})
|
||||
t.Run("images only in latest item", func(t *testing.T) {
|
||||
plan := &ResponsesCompactionPlan{items: []CompactionTranscriptItem{
|
||||
{Ref: "a", Message: api.Message{Role: "user", Content: "old"}},
|
||||
{Ref: "b", Message: api.Message{Role: "user", Images: img(100)}},
|
||||
}}
|
||||
if got := plan.DropImagesForBodyLimit(); got != 0 || len(plan.items[1].Message.Images) != 1 {
|
||||
t.Fatalf("removed %d, latest images=%d", got, len(plan.items[1].Message.Images))
|
||||
}
|
||||
})
|
||||
t.Run("text dominated body", func(t *testing.T) {
|
||||
plan := &ResponsesCompactionPlan{items: []CompactionTranscriptItem{
|
||||
{Ref: "a", Message: api.Message{Role: "user", Images: img(10), Content: strings.Repeat("x", 1000)}},
|
||||
{Ref: "b", Message: api.Message{Role: "user", Content: "latest"}},
|
||||
}}
|
||||
if got := plan.DropImagesForBodyLimit(); got != 0 {
|
||||
t.Fatalf("removed %d images from text-dominated body", got)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func TestSummaryRequestImageOmissionNotice(t *testing.T) {
|
||||
plan := &ResponsesCompactionPlan{Model: "m", omittedImages: 3, items: []CompactionTranscriptItem{{Ref: "a", Message: api.Message{Role: "user", Content: "hi"}}}}
|
||||
body, err := plan.SummaryRequest("")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !strings.Contains(string(body), "3 older image(s) were omitted") {
|
||||
t.Fatalf("missing notice: %s", body)
|
||||
}
|
||||
result, err := plan.Complete(compactionResponseBody(t, map[string]any{
|
||||
"summary": "Continue.", "retain_item_ids": []string{},
|
||||
}))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
payload := decodeResultPayload(t, result)
|
||||
if !strings.Contains(payload.Summary, "3 older image(s) were omitted") {
|
||||
t.Fatal("continuation does not disclose omitted images")
|
||||
}
|
||||
items, err := payloadToResponsesItems(payload)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(items) != 2 || !bytes.Contains(items[1], []byte("3 older image(s) were omitted")) {
|
||||
t.Fatal("replayed continuation lost the image omission warning")
|
||||
}
|
||||
}
|
||||
@@ -101,6 +101,7 @@ func resetResponsesRequestBody(r *http.Request, body []byte) {
|
||||
func (s *Server) handleResponsesCompaction(c *gin.Context, plan *openai.ResponsesCompactionPlan, stream bool) {
|
||||
var validationErr error
|
||||
overflowRetried := false
|
||||
bodyRetries := 0
|
||||
for {
|
||||
repair := ""
|
||||
if validationErr != nil {
|
||||
@@ -114,7 +115,23 @@ func (s *Server) handleResponsesCompaction(c *gin.Context, plan *openai.Response
|
||||
|
||||
response := s.runResponsesCompactionInference(c, request)
|
||||
if response.status < http.StatusOK || response.status >= http.StatusMultipleChoices {
|
||||
if !overflowRetried && c.Request.Context().Err() == nil && isCompactionContextLimit(response) {
|
||||
ctxErr := c.Request.Context().Err()
|
||||
if ctxErr == nil && response.status == http.StatusRequestEntityTooLarge && !isCompactionContextLimit(response) && bodyRetries < maxCompactionBodyRetries {
|
||||
// A bare 413 comes from a front proxy limiting request body
|
||||
// size regardless of context window. Shed images first, then
|
||||
// older items, and retry.
|
||||
removedImages := plan.DropImagesForBodyLimit()
|
||||
removedItems := 0
|
||||
if removedImages == 0 {
|
||||
removedItems = plan.TrimForContextLimit()
|
||||
}
|
||||
if removedImages > 0 || removedItems > 0 {
|
||||
bodyRetries++
|
||||
slog.WarnContext(c.Request.Context(), "retrying compaction after request body too large", "model", plan.Model, "omitted_images", removedImages, "omitted_items", removedItems)
|
||||
continue
|
||||
}
|
||||
}
|
||||
if !overflowRetried && ctxErr == nil && isCompactionContextLimit(response) {
|
||||
if removed := plan.TrimForContextLimit(); removed > 0 {
|
||||
overflowRetried = true
|
||||
slog.WarnContext(c.Request.Context(), "retrying compaction after context overflow", "model", plan.Model, "omitted_items", removed)
|
||||
@@ -146,6 +163,8 @@ func (s *Server) handleResponsesCompaction(c *gin.Context, plan *openai.Response
|
||||
writeResponsesCompactionError(c, http.StatusInternalServerError, "compaction_failed", "compaction failed; the selected model did not return a valid summary and the original conversation is unchanged")
|
||||
}
|
||||
|
||||
const maxCompactionBodyRetries = 4
|
||||
|
||||
var compactionContextLimitPattern = regexp.MustCompile(`^The prompt is too long: [0-9]+, model maximum context length: [0-9]+(?: \(ref: [^()]+\))?$`)
|
||||
|
||||
func isCompactionContextLimit(response *responsesInferenceRecorder) bool {
|
||||
|
||||
@@ -2,9 +2,13 @@ package server
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"image"
|
||||
"image/png"
|
||||
"io"
|
||||
"math/rand"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
@@ -1015,3 +1019,98 @@ func TestResponsesForeignCompactionHistory(t *testing.T) {
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestResponsesCompactionBodyTooLargeRecovery(t *testing.T) {
|
||||
const proxy413 = `<html>413 Request Entity Too Large</html>`
|
||||
img := image.NewNRGBA(image.Rect(0, 0, 64, 64))
|
||||
rng := rand.New(rand.NewSource(1))
|
||||
for i := range img.Pix {
|
||||
img.Pix[i] = byte(rng.Intn(256))
|
||||
}
|
||||
var encoded bytes.Buffer
|
||||
if err := png.Encode(&encoded, img); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
imageURL := "data:image/png;base64," + base64.StdEncoding.EncodeToString(encoded.Bytes())
|
||||
input := `[
|
||||
{"type":"message","role":"user","content":[{"type":"input_image","image_url":"` + imageURL + `"}]},
|
||||
{"type":"message","role":"assistant","content":"seen"},
|
||||
{"type":"message","role":"user","content":[{"type":"input_image","image_url":"` + imageURL + `"}]},
|
||||
{"type":"message","role":"assistant","content":"seen again"},
|
||||
{"type":"message","role":"user","content":"latest request"}
|
||||
]`
|
||||
run := func(t *testing.T, statuses []int) (int, [][]byte) {
|
||||
local, capture := newCompactionTestServer(t, func(attempt int, w http.ResponseWriter, _ *http.Request, _ []byte) {
|
||||
if attempt > len(statuses) {
|
||||
t.Errorf("unexpected attempt %d", attempt)
|
||||
w.WriteHeader(http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
w.WriteHeader(statuses[attempt-1])
|
||||
if statuses[attempt-1] == http.StatusOK {
|
||||
_, _ = w.Write(summaryResponse(t, "Continue.", nil))
|
||||
} else {
|
||||
_, _ = io.WriteString(w, proxy413)
|
||||
}
|
||||
})
|
||||
status, _, _ := postCompactionRequest(t, local, "/v1/responses/compact", `{"model":"fixture:cloud","input":`+input+`}`)
|
||||
_, requests := capture.snapshot()
|
||||
return status, requests
|
||||
}
|
||||
|
||||
t.Run("drops images then succeeds", func(t *testing.T) {
|
||||
status, requests := run(t, []int{413, 200})
|
||||
if status != http.StatusOK || len(requests) != 2 {
|
||||
t.Fatalf("status=%d attempts=%d", status, len(requests))
|
||||
}
|
||||
if len(requests[1]) >= len(requests[0]) || !bytes.Contains(requests[1], []byte("older image(s) were omitted")) {
|
||||
t.Fatal("retry did not shed images or add notice")
|
||||
}
|
||||
})
|
||||
t.Run("retry cap relays upstream 413", func(t *testing.T) {
|
||||
status, requests := run(t, []int{413, 413, 413, 413, 413, 413})
|
||||
if status != http.StatusRequestEntityTooLarge {
|
||||
t.Fatalf("status=%d", status)
|
||||
}
|
||||
if len(requests) > maxCompactionBodyRetries+1 {
|
||||
t.Fatalf("made %d attempts", len(requests))
|
||||
}
|
||||
})
|
||||
t.Run("large arguments are trimmed before images", func(t *testing.T) {
|
||||
var input []any
|
||||
for range 8 {
|
||||
input = append(input, map[string]any{"role": "user", "content": []any{
|
||||
map[string]any{"type": "input_image", "image_url": imageURL},
|
||||
}})
|
||||
}
|
||||
arguments, err := json.Marshal(map[string]string{"script": strings.Repeat("x", 1_000_000)})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
input = append(input,
|
||||
map[string]any{"type": "function_call", "call_id": "old", "name": "shell", "arguments": string(arguments)},
|
||||
map[string]any{"type": "function_call_output", "call_id": "old", "output": "ok"},
|
||||
map[string]any{"role": "assistant", "content": "done"},
|
||||
)
|
||||
body, err := json.Marshal(map[string]any{"model": "fixture:cloud", "input": input})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
local, capture := newCompactionTestServer(t, func(_ int, w http.ResponseWriter, _ *http.Request, body []byte) {
|
||||
if len(body) > 500_000 {
|
||||
w.WriteHeader(http.StatusRequestEntityTooLarge)
|
||||
_, _ = io.WriteString(w, proxy413)
|
||||
return
|
||||
}
|
||||
_, _ = w.Write(summaryResponse(t, "Continue.", nil))
|
||||
})
|
||||
status, _, _ := postCompactionRequest(t, local, "/v1/responses/compact", string(body))
|
||||
_, requests := capture.snapshot()
|
||||
if status != http.StatusOK || len(requests) != 2 {
|
||||
t.Fatalf("status=%d attempts=%d, want 200 after one retry", status, len(requests))
|
||||
}
|
||||
if bytes.Count(requests[1], []byte(imageURL)) != 8 || !bytes.Contains(requests[1], []byte("2 older transcript items were omitted")) {
|
||||
t.Fatal("retry lost images or failed to trim the completed tool pair")
|
||||
}
|
||||
})
|
||||
}
|
||||
Reference in new issue
Block a user