Skip to content

Commit

Permalink
genai: add convenience client.UploadFileFromPath method (#203)
Browse files Browse the repository at this point in the history
Sketch for a new convenience method to upload a file from a path. This
would let us remove the `uploadFile` helpers from tests and examples.
Examples & snippets would all be "inline" without calling out to a
function.
  • Loading branch information
eliben authored Aug 5, 2024
1 parent fb56fc2 commit 7d222a0
Show file tree
Hide file tree
Showing 3 changed files with 16 additions and 2 deletions.
2 changes: 1 addition & 1 deletion genai/example_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -566,7 +566,7 @@ func ExampleGenerativeModel_CountTokens_imageUploadFile() {

model := client.GenerativeModel("gemini-1.5-flash")
prompt := "Tell me about this image"
file, err := uploadFile(ctx, client, filepath.Join(testDataDir, "personWorkingOnComputer.jpg"), "")
file, err := client.UploadFileFromPath(ctx, filepath.Join(testDataDir, "personWorkingOnComputer.jpg"), nil)
if err != nil {
log.Fatal(err)
}
Expand Down
14 changes: 14 additions & 0 deletions genai/files.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ package genai
import (
"context"
"io"
"os"
"strings"

gl "cloud.google.com/go/ai/generativelanguage/apiv1beta"
Expand Down Expand Up @@ -83,6 +84,19 @@ func (c *Client) UploadFile(ctx context.Context, name string, r io.Reader, opts
return c.GetFile(ctx, res.File.Name)
}

// UploadFileFromPath is a convenience method wrapping [UploadFile]. It takes
// a path to read the file from, and uses a default auto-generated ID for the
// uploaded file.
func (c *Client) UploadFileFromPath(ctx context.Context, path string, opts *UploadFileOptions) (*File, error) {
osf, err := os.Open(path)
if err != nil {
return nil, err
}
defer osf.Close()

return c.UploadFile(ctx, "", osf, opts)
}

// GetFile returns the named file.
func (c *Client) GetFile(ctx context.Context, name string) (*File, error) {
req := &pb.GetFileRequest{Name: userNameToServiceName(name)}
Expand Down
2 changes: 1 addition & 1 deletion genai/internal/samples/docs-snippets_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -584,7 +584,7 @@ func ExampleGenerativeModel_CountTokens_imageUploadFile() {
// [START tokens_multimodal_image_file_api]
model := client.GenerativeModel("gemini-1.5-flash")
prompt := "Tell me about this image"
file, err := uploadFile(ctx, client, filepath.Join(testDataDir, "personWorkingOnComputer.jpg"), "")
file, err := client.UploadFileFromPath(ctx, filepath.Join(testDataDir, "personWorkingOnComputer.jpg"), nil)
if err != nil {
log.Fatal(err)
}
Expand Down

0 comments on commit 7d222a0

Please sign in to comment.