From 62f3424f3066a9d3b3fab0d41922c316365e46db Mon Sep 17 00:00:00 2001 From: sausheong Date: Sat, 26 Sep 2026 00:41:54 +0800 Subject: [PATCH] feat: PDF attachments as Anthropic document blocks Reuses llm.ImageContent/session.ImageData with MimeType "application/pdf" rather than adding a new field: images already flow tool result -> session entry -> reload -> provider end to end, so a MIME check at the provider edge is the smallest change. - Anthropic provider emits a document block (source.type=base64, media_type=application/pdf) for a PDF attachment in a tool result or a user message; images are unaffected. Cache control now also applies to document blocks. - OpenAI provider replaces a PDF attachment with a text placeholder instead of an invalid image_url data URI; images still emitted. Gemini already accepts application/pdf inline and needs no change. --- llm/provider.go | 10 +- providers/anthropic/anthropic.go | 16 +++ providers/anthropic/anthropic_test.go | 95 +++++++++++++++ providers/openai/openai.go | 21 ++++ providers/openai/openai_test.go | 70 +++++++++++ runtime/pdf_attachment_test.go | 168 ++++++++++++++++++++++++++ 6 files changed, 377 insertions(+), 3 deletions(-) create mode 100644 runtime/pdf_attachment_test.go diff --git a/llm/provider.go b/llm/provider.go index a5470c0..0ea597a 100644 --- a/llm/provider.go +++ b/llm/provider.go @@ -22,10 +22,14 @@ const ( EventThinkingBlock ) -// ImageContent holds image data for multimodal messages. +// ImageContent holds image data for multimodal messages. MimeType +// "application/pdf" is carried as a PDF document (not an image) by +// providers that support it (e.g. Anthropic emits a `document` block); +// providers without PDF support report a clear error or placeholder +// instead of silently mishandling the bytes. type ImageContent struct { - MimeType string // "image/jpeg", "image/png", etc. - Data []byte // raw image bytes + MimeType string // "image/jpeg", "image/png", "application/pdf", etc. + Data []byte // raw bytes } // Message represents a conversation message. diff --git a/providers/anthropic/anthropic.go b/providers/anthropic/anthropic.go index 0f0c2b6..1475ea8 100644 --- a/providers/anthropic/anthropic.go +++ b/providers/anthropic/anthropic.go @@ -638,6 +638,10 @@ func buildAnthropicMessages(in []llm.Message, cacheLast bool) []anthropic.Messag var blocks []anthropic.ContentBlockParamUnion for _, img := range m.Images { encoded := base64.StdEncoding.EncodeToString(img.Data) + if img.MimeType == "application/pdf" { + blocks = append(blocks, anthropic.NewDocumentBlock(anthropic.Base64PDFSourceParam{Data: encoded})) + continue + } blocks = append(blocks, anthropic.NewImageBlockBase64(img.MimeType, encoded)) } if m.Content != "" { @@ -711,6 +715,8 @@ func setCacheControlOnBlock(block *anthropic.ContentBlockParamUnion, cache *llm. block.OfToolResult.CacheControl = cc case block.OfImage != nil: block.OfImage.CacheControl = cc + case block.OfDocument != nil: + block.OfDocument.CacheControl = cc case block.OfToolUse != nil: block.OfToolUse.CacheControl = cc } @@ -726,6 +732,16 @@ func buildToolResultBlock(m llm.Message) anthropic.ContentBlockParamUnion { var content []anthropic.ToolResultBlockParamContentUnion for _, img := range m.Images { encoded := base64.StdEncoding.EncodeToString(img.Data) + if img.MimeType == "application/pdf" { + content = append(content, anthropic.ToolResultBlockParamContentUnion{ + OfDocument: &anthropic.DocumentBlockParam{ + Source: anthropic.DocumentBlockParamSourceUnion{ + OfBase64: &anthropic.Base64PDFSourceParam{Data: encoded}, + }, + }, + }) + continue + } content = append(content, anthropic.ToolResultBlockParamContentUnion{ OfImage: &anthropic.ImageBlockParam{ Source: anthropic.ImageBlockParamSourceUnion{ diff --git a/providers/anthropic/anthropic_test.go b/providers/anthropic/anthropic_test.go index 4e62112..3b6f555 100644 --- a/providers/anthropic/anthropic_test.go +++ b/providers/anthropic/anthropic_test.go @@ -221,6 +221,101 @@ func TestAnthropic_ToolResultsWithImages(t *testing.T) { assert.True(t, p3.IsError.Value) } +// TestAnthropic_ToolResultWithPDFAttachment verifies that a tool result +// carrying a PDF attachment (MimeType "application/pdf") emits a +// document block with media_type application/pdf and the base64 data, +// alongside a separate image attachment's own image block. +func TestAnthropic_ToolResultWithPDFAttachment(t *testing.T) { + pngBytes := []byte{0x89, 0x50, 0x4E, 0x47} + pdfBytes := []byte("%PDF-1.4 fake pdf bytes") + in := []llm.Message{ + { + Role: "assistant", + ToolCalls: []llm.ToolCall{ + {ID: "R1", Name: "read_document", Input: []byte(`{}`)}, + }, + }, + { + Role: "user", + ToolCallID: "R1", + Content: "here are the pages", + Images: []llm.ImageContent{ + {MimeType: "image/png", Data: pngBytes}, + {MimeType: "application/pdf", Data: pdfBytes}, + }, + }, + } + + got := buildAnthropicMessages(in, false) + require.Len(t, got, 2) + toolResult := got[1].Content[0].OfToolResult + require.NotNil(t, toolResult) + require.Len(t, toolResult.Content, 3, "image + document + text caption") + + require.NotNil(t, toolResult.Content[0].OfImage) + assert.Equal(t, base64.StdEncoding.EncodeToString(pngBytes), toolResult.Content[0].OfImage.Source.OfBase64.Data) + + doc := toolResult.Content[1].OfDocument + require.NotNil(t, doc, "expected a document block for the PDF attachment") + require.NotNil(t, doc.Source.OfBase64) + assert.Equal(t, base64.StdEncoding.EncodeToString(pdfBytes), doc.Source.OfBase64.Data) + + require.NotNil(t, toolResult.Content[2].OfText) + assert.Equal(t, "here are the pages", toolResult.Content[2].OfText.Text) + + // Confirm the wire format: media_type defaults to "application/pdf" only + // on marshal (it's a zero-value constant type until then). + raw, err := json.Marshal(toolResult.Content[1]) + require.NoError(t, err) + assert.Contains(t, string(raw), `"media_type":"application/pdf"`) + assert.Contains(t, string(raw), `"type":"document"`) +} + +// TestAnthropic_UserMessageWithPDFAttachment verifies that a PDF attachment +// on a plain user message (not a tool result) also produces a document +// block rather than an image block. +func TestAnthropic_UserMessageWithPDFAttachment(t *testing.T) { + pdfBytes := []byte("%PDF-1.4 fake pdf bytes") + in := []llm.Message{ + { + Role: "user", + Content: "read this", + Images: []llm.ImageContent{ + {MimeType: "application/pdf", Data: pdfBytes}, + }, + }, + } + + got := buildAnthropicMessages(in, false) + require.Len(t, got, 1) + require.Len(t, got[0].Content, 2, "document block + text") + doc := got[0].Content[0].OfDocument + require.NotNil(t, doc, "expected a document block for the PDF attachment") + require.NotNil(t, doc.Source.OfBase64) + assert.Equal(t, base64.StdEncoding.EncodeToString(pdfBytes), doc.Source.OfBase64.Data) + require.Nil(t, got[0].Content[0].OfImage) + require.NotNil(t, got[0].Content[1].OfText) + assert.Equal(t, "read this", got[0].Content[1].OfText.Text) +} + +// TestAnthropic_ImageOnlyToolResultUnchanged pins the pre-PDF behavior: a +// tool result with only image attachments (no PDFs) is unaffected by the +// PDF branch added to buildToolResultBlock. +func TestAnthropic_ImageOnlyToolResultUnchanged(t *testing.T) { + pngBytes := []byte{0x89, 0x50, 0x4E, 0x47} + in := []llm.Message{ + {Role: "assistant", ToolCalls: []llm.ToolCall{{ID: "I1", Name: "snap", Input: []byte(`{}`)}}}, + {Role: "user", ToolCallID: "I1", Images: []llm.ImageContent{{MimeType: "image/png", Data: pngBytes}}}, + } + got := buildAnthropicMessages(in, false) + require.Len(t, got, 2) + tr := got[1].Content[0].OfToolResult + require.NotNil(t, tr) + require.Len(t, tr.Content, 1) + require.NotNil(t, tr.Content[0].OfImage) + require.Nil(t, tr.Content[0].OfDocument) +} + func TestAnthropicSystemPromptPartsEmitCacheControl(t *testing.T) { got := buildAnthropicSystem(llm.ChatRequest{ SystemPromptParts: []llm.SystemPromptPart{ diff --git a/providers/openai/openai.go b/providers/openai/openai.go index 332f022..64980e8 100644 --- a/providers/openai/openai.go +++ b/providers/openai/openai.go @@ -14,6 +14,13 @@ import ( "github.com/sausheong/harness/llm" ) +// pdfAttachmentPlaceholder replaces a PDF attachment (llm.ImageContent with +// MimeType "application/pdf") in outgoing messages: OpenAI's image_url part +// only accepts image MIME types, so sending a PDF that way would either be +// silently ignored or rejected by the API. Gemini accepts application/pdf +// inline natively and is not routed through this builder. +const pdfAttachmentPlaceholder = "[PDF attachment omitted: this provider can't read PDFs]" + // logOpenAIError unwraps the go-openai SDK error into a structured slog.WARN // record so we can see exactly why LiteLLM/OpenAI rejected the request — the // SDK's flat error string drops Param, Type, Code, and the raw response body @@ -129,6 +136,13 @@ func (p *OpenAIProvider) ChatStream(ctx context.Context, req llm.ChatRequest) (< if len(m.Images) > 0 { var parts []openai.ChatMessagePart for _, img := range m.Images { + if img.MimeType == "application/pdf" { + parts = append(parts, openai.ChatMessagePart{ + Type: openai.ChatMessagePartTypeText, + Text: pdfAttachmentPlaceholder, + }) + continue + } encoded := base64.StdEncoding.EncodeToString(img.Data) dataURI := fmt.Sprintf("data:%s;base64,%s", img.MimeType, encoded) parts = append(parts, openai.ChatMessagePart{ @@ -151,6 +165,13 @@ func (p *OpenAIProvider) ChatStream(ctx context.Context, req llm.ChatRequest) (< } else if len(m.Images) > 0 { var parts []openai.ChatMessagePart for _, img := range m.Images { + if img.MimeType == "application/pdf" { + parts = append(parts, openai.ChatMessagePart{ + Type: openai.ChatMessagePartTypeText, + Text: pdfAttachmentPlaceholder, + }) + continue + } encoded := base64.StdEncoding.EncodeToString(img.Data) dataURI := fmt.Sprintf("data:%s;base64,%s", img.MimeType, encoded) parts = append(parts, openai.ChatMessagePart{ diff --git a/providers/openai/openai_test.go b/providers/openai/openai_test.go index 7940c77..8c5c93c 100644 --- a/providers/openai/openai_test.go +++ b/providers/openai/openai_test.go @@ -6,6 +6,7 @@ import ( "io" "net/http" "net/http/httptest" + "strings" "testing" openai "github.com/sashabaranov/go-openai" @@ -74,6 +75,75 @@ func TestOpenAIChatStreamPartsBeatString(t *testing.T) { require.Equal(t, "new", captured.Messages[0].Content) } +// TestOpenAIChatStream_PDFToolResultOmittedWithPlaceholder verifies that a +// PDF attachment on a tool result is never emitted as an image_url data +// URI (which would be invalid — image_url expects an image MIME type) and +// that the placeholder text takes its place; a real image attachment in +// the same result is still emitted. +func TestOpenAIChatStream_PDFToolResultOmittedWithPlaceholder(t *testing.T) { + pngBytes := []byte{0x89, 0x50, 0x4E, 0x47} + pdfBytes := []byte("%PDF-1.4 fake") + captured := captureOpenAIRequest(t, llm.ChatRequest{ + Messages: []llm.Message{ + { + Role: "user", + ToolCallID: "T1", + Content: "see attached", + Images: []llm.ImageContent{ + {MimeType: "image/png", Data: pngBytes}, + {MimeType: "application/pdf", Data: pdfBytes}, + }, + }, + }, + }) + require.NotNil(t, captured) + + var sawImage, sawPlaceholder bool + for _, m := range captured.Messages { + for _, part := range m.MultiContent { + if part.Type == openai.ChatMessagePartTypeImageURL && part.ImageURL != nil { + require.NotContains(t, part.ImageURL.URL, "application/pdf", "a PDF must never be sent as image_url") + sawImage = true + } + if part.Type == openai.ChatMessagePartTypeText && strings.Contains(part.Text, pdfAttachmentPlaceholder) { + sawPlaceholder = true + } + } + } + require.True(t, sawImage, "the PNG attachment must still be emitted as image_url") + require.True(t, sawPlaceholder, "the PDF attachment must be replaced with the placeholder text") +} + +// TestOpenAIChatStream_PDFUserMessageOmittedWithPlaceholder covers the +// plain user-message image branch (not a tool result). +func TestOpenAIChatStream_PDFUserMessageOmittedWithPlaceholder(t *testing.T) { + pdfBytes := []byte("%PDF-1.4 fake") + captured := captureOpenAIRequest(t, llm.ChatRequest{ + Messages: []llm.Message{ + { + Role: "user", + Content: "read this", + Images: []llm.ImageContent{{MimeType: "application/pdf", Data: pdfBytes}}, + }, + }, + }) + require.NotNil(t, captured) + + var sawImageURL, sawPlaceholder bool + for _, m := range captured.Messages { + for _, part := range m.MultiContent { + if part.Type == openai.ChatMessagePartTypeImageURL { + sawImageURL = true + } + if part.Type == openai.ChatMessagePartTypeText && strings.Contains(part.Text, pdfAttachmentPlaceholder) { + sawPlaceholder = true + } + } + } + require.False(t, sawImageURL, "a PDF must never be sent as image_url") + require.True(t, sawPlaceholder, "the PDF attachment must be replaced with the placeholder text") +} + func TestEmitToolCalls_OrderedByIndex(t *testing.T) { mk := func(id, name string) *pendingTC { p := &pendingTC{id: id, name: name} diff --git a/runtime/pdf_attachment_test.go b/runtime/pdf_attachment_test.go new file mode 100644 index 0000000..bd59868 --- /dev/null +++ b/runtime/pdf_attachment_test.go @@ -0,0 +1,168 @@ +package runtime + +import ( + "context" + "encoding/base64" + "encoding/json" + "testing" + + "github.com/sausheong/harness/llm" + "github.com/sausheong/harness/llm/llmtest" + "github.com/sausheong/harness/session" + "github.com/sausheong/harness/tool" +) + +// TestConvertToolResultImages_PreservesPDFMimeType pins convertToolResultImages' +// behavior for a PDF attachment: the MimeType is carried through unchanged +// (it is not an image format convertToolResultImages inspects or rewrites). +func TestConvertToolResultImages_PreservesPDFMimeType(t *testing.T) { + pdfBytes := []byte("%PDF-1.4 fake") + out := convertToolResultImages([]llm.ImageContent{{MimeType: "application/pdf", Data: pdfBytes}}) + if len(out) != 1 { + t.Fatalf("len(out) = %d, want 1", len(out)) + } + if out[0].MimeType != "application/pdf" { + t.Fatalf("MimeType = %q, want application/pdf", out[0].MimeType) + } + decoded, err := base64.StdEncoding.DecodeString(out[0].Data) + if err != nil { + t.Fatalf("decode: %v", err) + } + if string(decoded) != string(pdfBytes) { + t.Fatalf("Data = %q, want %q", decoded, pdfBytes) + } +} + +// TestSessionRoundTrip_ToolResultPDFAttachment writes a +// ToolResultWithArtifactsEntry carrying a PDF attachment through +// session.ToolResultWithArtifactsEntry, round-trips it through JSON exactly +// as disk storage does, and confirms decoding it back reproduces the +// MimeType and bytes untouched. +func TestSessionRoundTrip_ToolResultPDFAttachment(t *testing.T) { + pdfBytes := []byte("%PDF-1.4 fake pdf") + images := []session.ImageData{{MimeType: "application/pdf", Data: base64.StdEncoding.EncodeToString(pdfBytes)}} + entry := session.ToolResultWithArtifactsEntry("tc_1", "showing pages", "", images, nil) + + raw, err := json.Marshal(entry) + if err != nil { + t.Fatalf("marshal: %v", err) + } + var decoded session.SessionEntry + if err := json.Unmarshal(raw, &decoded); err != nil { + t.Fatalf("unmarshal: %v", err) + } + var tr session.ToolResultData + if err := json.Unmarshal(decoded.Data, &tr); err != nil { + t.Fatalf("unmarshal tool result data: %v", err) + } + if len(tr.Images) != 1 || tr.Images[0].MimeType != "application/pdf" { + t.Fatalf("tr.Images = %+v, want one application/pdf image", tr.Images) + } + gotBytes, err := base64.StdEncoding.DecodeString(tr.Images[0].Data) + if err != nil { + t.Fatalf("decode: %v", err) + } + if string(gotBytes) != string(pdfBytes) { + t.Fatalf("Data = %q, want %q", gotBytes, pdfBytes) + } +} + +// pdfToolResultProvider issues one tool call on its first turn, then on the +// second turn records the images (and their MimeTypes) it received in the +// tool_result message. +type pdfToolResultProvider struct { + llmtest.Base + calls int + images []llm.ImageContent +} + +func (p *pdfToolResultProvider) ChatStream(_ context.Context, req llm.ChatRequest) (<-chan llm.ChatEvent, error) { + p.calls++ + events := make(chan llm.ChatEvent, 4) + if p.calls == 1 { + events <- llm.ChatEvent{Type: llm.EventToolCallStart, ToolCall: &llm.ToolCall{ID: "tc_1", Name: "read_document"}} + events <- llm.ChatEvent{Type: llm.EventToolCallDone, ToolCall: &llm.ToolCall{ID: "tc_1", Name: "read_document", Input: json.RawMessage(`{}`)}} + events <- llm.ChatEvent{Type: llm.EventDone, StopReason: "tool_use"} + close(events) + return events, nil + } + for _, msg := range req.Messages { + p.images = append(p.images, msg.Images...) + } + events <- llm.ChatEvent{Type: llm.EventTextDelta, Text: "done"} + events <- llm.ChatEvent{Type: llm.EventDone} + close(events) + return events, nil +} + +// pdfExecutor is a minimal tool.Executor whose one tool ("read_document") +// always returns a PDF attachment, standing in for readdoc_tool.go's real +// behavior for this harness-side round-trip test. +type pdfExecutor struct{ pdfBytes []byte } + +func newPDFTestRegistry(pdfBytes []byte) tool.Executor { return pdfExecutor{pdfBytes: pdfBytes} } + +func (e pdfExecutor) Execute(_ context.Context, name string, _ json.RawMessage) (tool.ToolResult, error) { + if name != "read_document" { + return tool.ToolResult{Error: "unknown tool"}, nil + } + return tool.ToolResult{ + Output: "showing pages", + Images: []llm.ImageContent{{MimeType: "application/pdf", Data: e.pdfBytes}}, + }, nil +} +func (e pdfExecutor) ToolDefs() []llm.ToolDef { return []llm.ToolDef{{Name: "read_document"}} } +func (e pdfExecutor) Names() []string { return []string{"read_document"} } +func (e pdfExecutor) Get(string) (tool.Tool, bool) { return nil, false } + +// TestRuntimePDFAttachmentSurvivesSessionAppendAndReachesNextTurn drives a +// full tool-call round trip: a tool returns a PDF attachment, the runtime +// appends it to the session as a ToolResultWithArtifactsEntry, and the very +// next LLM request (assembled from that same session) must carry the PDF +// back with MimeType "application/pdf" intact. +func TestRuntimePDFAttachmentSurvivesSessionAppendAndReachesNextTurn(t *testing.T) { + pdfBytes := []byte("%PDF-1.4 fake pdf pages") + sess := session.NewSession("agent", "key") + provider := &pdfToolResultProvider{} + reg := newPDFTestRegistry(pdfBytes) + + rt := &Runtime{Session: sess, LLM: provider, Tools: reg, Model: "model", MaxTurns: 3} + if _, err := rt.RunSync(context.Background(), "read this pdf", nil); err != nil { + t.Fatalf("RunSync() error = %v", err) + } + + if provider.calls != 2 { + t.Fatalf("provider.calls = %d, want 2", provider.calls) + } + if len(provider.images) != 1 { + t.Fatalf("len(provider.images) = %d, want 1", len(provider.images)) + } + if provider.images[0].MimeType != "application/pdf" { + t.Fatalf("MimeType = %q, want application/pdf", provider.images[0].MimeType) + } + if string(provider.images[0].Data) != string(pdfBytes) { + t.Fatalf("Data mismatch: got %d bytes, want %d bytes", len(provider.images[0].Data), len(pdfBytes)) + } + + // Confirm the session entry itself carries the PDF MimeType, not just + // the reconstructed message — i.e. the append path (not only assembly) + // preserved it. + var found bool + for _, e := range sess.History() { + if e.Type != session.EntryTypeToolResult { + continue + } + var tr session.ToolResultData + if err := json.Unmarshal(e.Data, &tr); err != nil { + continue + } + for _, img := range tr.Images { + if img.MimeType == "application/pdf" { + found = true + } + } + } + if !found { + t.Fatal("no application/pdf image found in session history's tool_result entry") + } +}