Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion go/adk/pkg/a2a/converter.go
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ func a2aPartConverter(_ context.Context, _ a2atype.Event, part *a2atype.Part) (*
}

// keepFileName copies a non-image file's name into PartMetadata, which survives ADK blanking DisplayName.
// Vertex rejects PartMetadata; this is safe only because the file wrapper replaces these parts.
// Vertex rejects PartMetadata, but Gemini never gets these parts: the file wrapper turns them into text.
func keepFileName(p *genai.Part) {
if p == nil || p.InlineData == nil || p.InlineData.DisplayName == "" || strings.HasPrefix(p.InlineData.MIMEType, "image/") {
return
Expand Down
104 changes: 76 additions & 28 deletions go/adk/pkg/fileextract/llm.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,8 @@ import (
"google.golang.org/genai"
)

// WithFileText wraps an LLM so every provider receives non-image file blobs as
// extracted text; images pass through for the adapter to handle.
// WithFileText wraps an LLM so user files that the provider cannot read reach it as text.
// Images, and parts the adapter sends itself (see FileSender), are not changed.
func WithFileText(llm model.LLM) model.LLM {
if g, ok := llm.(googleLLM); ok {
return googleFileTextLLM{fileTextLLM{llm}, g}
Expand All @@ -31,7 +31,34 @@ type googleFileTextLLM struct {
}

func (m fileTextLLM) GenerateContent(ctx context.Context, req *model.LLMRequest, stream bool) iter.Seq2[*model.LLMResponse, error] {
return m.LLM.GenerateContent(ctx, filesToText(req), stream)
return m.LLM.GenerateContent(ctx, filesToText(req, m.LLM), stream)
}

// FileSender is a model whose adapter sends some user file parts to its provider
// as they are: a document as bytes, or a link the provider fetches itself.
type FileSender interface{ ProviderAccepts(p *genai.Part) bool }

// providerAccepts reports whether llm's provider takes p as it is, through llm's adapter.
func providerAccepts(llm model.LLM, p *genai.Part) bool {
if s, ok := llm.(FileSender); ok {
return s.ProviderAccepts(p)
}
// Gemini takes a link as genai FileData, as it is.
_, google := llm.(googleLLM)
return google && p.FileData != nil
}

// newestUserTurn is the index of the last user content, or -1. Only a file there
// may fail the request: one in replayed history would fail every later turn.
// ADK sends tool results as user content, so those are not a user turn.
func newestUserTurn(contents []*genai.Content) int {
for i, c := range slices.Backward(contents) {
if c != nil && strings.TrimSpace(c.Role) == genai.RoleUser &&
!slices.ContainsFunc(c.Parts, func(p *genai.Part) bool { return p != nil && p.FunctionResponse != nil }) {
return i
}
}
return -1
}

// FilenameMetadataKey is the PartMetadata key the A2A converter stores a file's name under.
Expand All @@ -54,41 +81,62 @@ func isDataPart(b *genai.Blob) bool {
bytes.HasPrefix(data, []byte("<a2a_datapart_json>")) && bytes.HasSuffix(data, []byte("</a2a_datapart_json>"))
}

// filesToText returns req with user file blobs replaced by text, copying only the
// contents and parts it changes so the caller's session history is untouched.
func filesToText(req *model.LLMRequest) *model.LLMRequest {
// filesToText returns req with the files in each user turn changed to a form the
// provider reads (see turnFilesToText). It never changes req, which holds the
// session history, and returns req itself when there is nothing to change.
func filesToText(req *model.LLMRequest, llm model.LLM) *model.LLMRequest {
if req == nil {
return req
}
var contents []*genai.Content
out := *req
out.Contents = slices.Clone(req.Contents)
newest := newestUserTurn(req.Contents)
for i, c := range req.Contents {
if c == nil || c.Role != genai.RoleUser {
continue
}
var parts []*genai.Part
for j, p := range c.Parts {
if p == nil || p.InlineData == nil || strings.HasPrefix(p.InlineData.MIMEType, "image/") || isDataPart(p.InlineData) {
continue
}
if parts == nil {
parts = slices.Clone(c.Parts)
}
parts[j] = genai.NewPartFromText(inlineFileToText(p.InlineData, partFileName(p)))
}
if parts == nil {
continue
}
if contents == nil {
contents = slices.Clone(req.Contents)
if parts := turnFilesToText(c.Parts, llm, i == newest); !slices.Equal(parts, c.Parts) {
turn := *c
turn.Parts = parts
out.Contents[i] = &turn
}
changed := *c
changed.Parts = parts
contents[i] = &changed
}
if contents == nil {
if slices.Equal(out.Contents, req.Contents) {
return req
}
out := *req
out.Contents = contents
return &out
}

// turnFilesToText returns a new list of the parts of one user turn, with each file
// that the provider cannot read changed to text. A link stays a link only in the
// newest user turn: the provider fetches it on each request, so a link that breaks
// in an older turn would fail every later turn.
func turnFilesToText(parts []*genai.Part, llm model.LLM, newest bool) []*genai.Part {
var out []*genai.Part
for _, p := range parts {
switch {
case p == nil || providerAccepts(llm, p) && (newest || p.FileData == nil):
// The model's adapter sends it as it is.
out = append(out, p)
case p.FileData != nil:
// A link: the bare URL, so the agent's fetch tool can read it, or nothing when
// the text already has the URL. Not "File: name (url)": with that, models
// invented the file's contents.
if !hasText(parts, p.FileData.FileURI) {
out = append(out, genai.NewPartFromText(p.FileData.FileURI))
}
case p.InlineData != nil && !strings.HasPrefix(p.InlineData.MIMEType, "image/") && !isDataPart(p.InlineData):
// A document as bytes: its text, or a note that it could not be read.
out = append(out, genai.NewPartFromText(inlineFileToText(p.InlineData, partFileName(p))))
default:
// Text, images, A2A data parts and tool calls.
out = append(out, p)
}
}
return out
}

// hasText reports whether a text part in parts contains s.
func hasText(parts []*genai.Part, s string) bool {
return slices.ContainsFunc(parts, func(p *genai.Part) bool { return p != nil && strings.Contains(p.Text, s) })
}
104 changes: 104 additions & 0 deletions go/adk/pkg/fileextract/llm_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package fileextract
import (
"context"
"iter"
"slices"
"strings"
"testing"

Expand Down Expand Up @@ -96,6 +97,109 @@ func TestWithFileText_LeavesDataPartsNextToFiles(t *testing.T) {
}
}

// pdfSendingLLM sends pdf bytes and links itself, like the OpenAI Responses adapter.
type pdfSendingLLM struct{ recordingLLM }

func (*pdfSendingLLM) ProviderAccepts(p *genai.Part) bool {
return p.FileData != nil || p.InlineData != nil && p.InlineData.MIMEType == "application/pdf"
}

func TestWithFileText_LeavesFilesTheModelSends(t *testing.T) {
pdf := &genai.Part{InlineData: &genai.Blob{Data: []byte("%PDF"), MIMEType: "application/pdf", DisplayName: "report.pdf"}}
link := &genai.Part{FileData: &genai.FileData{FileURI: "https://files.example.com/report.pdf"}}
req := &model.LLMRequest{Contents: []*genai.Content{{Role: genai.RoleUser, Parts: []*genai.Part{pdf, link}}}}

sender := &pdfSendingLLM{}
for range WithFileText(sender).GenerateContent(t.Context(), req, false) {
}
if sender.got != req {
t.Errorf("request with files the model sends was changed: %+v", sender.got.Contents[0].Parts)
}

other := &recordingLLM{}
pdfOnly := &model.LLMRequest{Contents: []*genai.Content{{Role: genai.RoleUser, Parts: []*genai.Part{pdf}}}}
for range WithFileText(other).GenerateContent(t.Context(), pdfOnly, false) {
}
if got := other.got.Contents[0].Parts[0].Text; !strings.Contains(got, "could not be read") {
t.Errorf("pdf for a model that cannot send it = %q, want the could-not-be-read note", got)
}
}

func TestWithFileText_LinkStaysAfterToolCall(t *testing.T) {
link := &genai.Part{FileData: &genai.FileData{FileURI: "https://files.example.com/report.pdf"}}
req := &model.LLMRequest{Contents: []*genai.Content{
{Role: genai.RoleUser, Parts: []*genai.Part{genai.NewPartFromText("read this"), link}},
{Role: genai.RoleModel, Parts: []*genai.Part{genai.NewPartFromFunctionCall("fetch", nil)}},
{Role: genai.RoleUser, Parts: []*genai.Part{genai.NewPartFromFunctionResponse("fetch", nil)}},
}}
sender := &pdfSendingLLM{}
for range WithFileText(sender).GenerateContent(t.Context(), req, false) {
}
if sender.got != req {
t.Errorf("a tool result made the link turn an older turn: %+v", sender.got.Contents[0].Parts)
}
}

func TestWithFileText_Links(t *testing.T) {
const url = "https://files.example.com/report.pdf"
link := &genai.Part{FileData: &genai.FileData{FileURI: url}}
user := func(parts ...*genai.Part) *genai.Content { return &genai.Content{Role: genai.RoleUser, Parts: parts} }
texts := func(c *genai.Content) (out []string) {
for _, p := range c.Parts {
if p.FileData != nil {
p = genai.NewPartFromText("<link part>")
}
out = append(out, p.Text)
}
return out
}

sender, google, other := &pdfSendingLLM{}, &googleRecordingLLM{}, &recordingLLM{}
for _, m := range []struct {
name string
llm model.LLM
rec *recordingLLM
sendsLink bool
}{
{"model that sends links (OpenAI Responses)", sender, &sender.recordingLLM, true},
{"Gemini", google, &google.recordingLLM, true},
{"model that cannot send links", other, other, false},
} {
for name, tc := range map[string]struct {
turn *genai.Content
want []string
}{
"link becomes its URL": {user(genai.NewPartFromText("read this"), link), []string{"read this", url}},
"link already in the text is dropped": {user(genai.NewPartFromText("read "+url), link), []string{"read " + url}},
} {
t.Run(m.name+"/"+name, func(t *testing.T) {
// The same turn as replayed history and as the newest turn.
req := &model.LLMRequest{Contents: []*genai.Content{
tc.turn,
{Role: genai.RoleModel, Parts: []*genai.Part{genai.NewPartFromText("ok")}},
tc.turn,
}}
for range WithFileText(m.llm).GenerateContent(t.Context(), req, false) {
}
wantNewest := tc.want
if m.sendsLink {
wantNewest = texts(tc.turn) // the newest turn keeps its link
}
got := m.rec.got.Contents
if older := texts(got[0]); !slices.Equal(older, tc.want) {
t.Errorf("older turn = %q, want %q", older, tc.want)
}
if newest := texts(got[2]); !slices.Equal(newest, wantNewest) {
t.Errorf("newest turn = %q, want %q", newest, wantNewest)
}
if len(tc.turn.Parts) != 2 || tc.turn.Parts[1] != link {
t.Error("the session's own content was changed")
}
})
}
}
}

func TestWithFileText_NameFromPartMetadata(t *testing.T) {
file := &genai.Part{
InlineData: &genai.Blob{Data: []byte("remember the milk"), MIMEType: "application/octet-stream"},
Expand Down
7 changes: 6 additions & 1 deletion go/adk/pkg/models/openai_adk.go
Original file line number Diff line number Diff line change
Expand Up @@ -268,7 +268,7 @@ func genaiContentsToOpenAIMessages(contents []*genai.Content, config *genai.Gene
functionCalls = append(functionCalls, part.FunctionCall)
} else if part.InlineData != nil && strings.HasPrefix(part.InlineData.MIMEType, "image/") {
imageParts = append(imageParts, openai.ChatCompletionContentPartImageImageURLParam{
URL: fmt.Sprintf("data:%s;base64,%s", part.InlineData.MIMEType, base64.StdEncoding.EncodeToString(part.InlineData.Data)),
URL: dataURL(part.InlineData.MIMEType, part.InlineData.Data),
})
}
}
Expand Down Expand Up @@ -546,3 +546,8 @@ func chatCompletionToLLMResponse(completion *openai.ChatCompletion) *model.LLMRe
Content: &genai.Content{Role: string(genai.RoleModel), Parts: parts},
}
}

// dataURL is data as a base64 data: URL of the given media type.
func dataURL(mimeType string, data []byte) string {
return fmt.Sprintf("data:%s;base64,%s", mimeType, base64.StdEncoding.EncodeToString(data))
}
Loading
Loading