package requestplugin import ( "archive/zip" "bytes" "context" "encoding/base64" "encoding/binary" "fmt" "image" "image/png" "mime/multipart" "net/http" "net/http/httptest" "strings" "testing" "time" "github.com/QuantumNous/new-api/common" "github.com/QuantumNous/new-api/pkg/jsplugin" "github.com/QuantumNous/new-api/pkg/requestpatch" relaycommon "github.com/QuantumNous/new-api/relay/common" "github.com/QuantumNous/new-api/relaykit/types" "github.com/MoeForge/moego/webp" "github.com/gin-gonic/gin" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "github.com/tidwall/gjson" ) // attachmentPlugin lists, describes, reads, sends and rewrites attachments as // its config says, and writes what it saw into the body as /seen, with the // placeholders spelled " utils.media(ref)); if (c.read) seen.texts = c.read.map((ref) => utils.mediaText(ref, c.maxChars ? {maxChars: c.maxChars} : undefined)); if (c.send) seen.status = utils.fetch({url: c.url, method: "POST", headers: {"Content-Type": "application/json"}, body: JSON.stringify({input: c.send})}).status; const effects = (c.rewrite || []).map((item) => ({type: "media.text", media: item.media, text: item.text})); if (!c.quiet) effects.push({type: "json.patch", ops: [{op: "add", path: "/seen", value: JSON.stringify(seen).split("[media:").join(">", "<< /Type /Pages /Kids [3 0 R] /Count 1 >>", "<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] /Contents 4 0 R /Resources << /Font << /F1 5 0 R >> >> >>", fmt.Sprintf("<< /Length %d >>\nstream\n%s\nendstream", len(content), content), "<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica >>", } var pdf bytes.Buffer pdf.WriteString("%PDF-1.4\n") offsets := make([]int, len(objects)) for index, object := range objects { offsets[index] = pdf.Len() fmt.Fprintf(&pdf, "%d 0 obj\n%s\nendobj\n", index+1, object) } xref := pdf.Len() fmt.Fprintf(&pdf, "xref\n0 %d\n0000000000 65535 f \n", len(objects)+1) for _, offset := range offsets { fmt.Fprintf(&pdf, "%010d 00000 n \n", offset) } fmt.Fprintf(&pdf, "trailer\n<< /Size %d /Root 1 0 R %s>>\nstartxref\n%d\n%%%%EOF\n", len(objects)+1, trailer, xref) return pdf.Bytes() } // testDOCX is a DOCX file whose document holds paragraphs. func testDOCX(t *testing.T, paragraphs ...string) []byte { t.Helper() var document strings.Builder document.WriteString(``) for _, paragraph := range paragraphs { first, rest, _ := strings.Cut(paragraph, "\t") document.WriteString(`` + first + ``) if rest != "" { document.WriteString(`` + rest + ``) } document.WriteString(``) } document.WriteString(``) var archive bytes.Buffer writer := zip.NewWriter(&archive) part, err := writer.Create("word/document.xml") require.NoError(t, err) _, err = part.Write([]byte(document.String())) require.NoError(t, err) require.NoError(t, writer.Close()) return archive.Bytes() } func testPNG(t *testing.T, width, height int) []byte { t.Helper() var buffer bytes.Buffer require.NoError(t, png.Encode(&buffer, image.NewGray(image.Rect(0, 0, width, height)))) return buffer.Bytes() } // A hook lists the attachments in body order, inline ones by ref and the // rest by id or URL, and reads the text of text, PDF and DOCX files; the // record says what it did with each, never their names or content. func TestAttachmentsListAndRead(t *testing.T) { pngData := testPNG(t, 3, 2) body := `{"model":"gpt","messages":[{"role":"user","content":[ {"type":"text","text":"hi"}, ` + chatFile("notes.txt", dataURI("text/plain", []byte("plain notes"))) + `, {"type":"document","source":{"type":"base64","media_type":"application/pdf","data":"` + base64.StdEncoding.EncodeToString(testPDF("Hello PDF", "")) + `"}}, ` + chatFile("report.docx", dataURI(docxMime, testDOCX(t, "Hello\tDOCX", "Second"))) + `, {"type":"image_url","image_url":{"url":"` + dataURI("image/png", pngData) + `"}}, {"type":"file","file":{"file_id":"file-abc","filename":"remote.pdf"}}, {"type":"image_url","image_url":{"url":"https://example.com/cat.png"}}]}]}` outcome, seen := runAttachments(t, `{"list":true,"media":["[media:3]","[media:9]"],"read":["[media:0]","[media:1]","[media:2]","[media:3]"]}`, body) assert.JSONEq(t, `[ {"ref":">8), 0, byte(height-1), byte((height-1)>>8), 0) chunks := append(append([]byte("WEBP"), vp8x...), encoded.Bytes()[12:]...) file := append(binary.LittleEndian.AppendUint32([]byte("RIFF"), uint32(len(chunks))), chunks...) return inlineMedia{path: "/image", mime: "image/webp", data: base64.StdEncoding.EncodeToString(file)} } effect := requestpatch.Effect{Type: requestpatch.EffectMediaReencode, Format: "png"} _, _, err := reencodeMedia(context.Background(), withCanvas(64, 64), effect) require.NoError(t, err) _, _, err = reencodeMedia(context.Background(), withCanvas(1, 1), effect) assert.EqualError(t, err, "media /image cannot be decoded") } // A hook that does not use attachments costs nothing for them: no file is // extracted, decoded or listed, the record holds none, and a call's // attachment state is one small allocation whatever the body holds. func TestAttachmentsUnusedCostNothing(t *testing.T) { pdf := chatFile("a.pdf", dataURI("application/pdf", testPDF("Hello", ""))) before := extractions.Load() outcome, _ := runAttachments(t, `{"quiet":true}`, chatBody(pdf, pdf, pdf)) assert.Equal(t, before, extractions.Load()) assert.Empty(t, outcome.Record) view, media := scanMedia([]byte(chatBody(pdf, pdf, pdf))) require.Len(t, media, 3) form := &formBody{files: []formFile{{name: "file", filename: "a.txt"}}} allocs := testing.AllocsPerRun(100, func() { call := newCallMedia(&requestMedia{}, view, media, form) if items, more := call.record(); items != nil || more != 0 || call.files != nil { t.Fatal("an unused call recorded or read attachments") } }) assert.LessOrEqual(t, allocs, 1.0) }