Skip to content
Open
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
110 changes: 107 additions & 3 deletions internal/cli/custom/analyze.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,10 @@
package custom

import (
"encoding/json"
"errors"
"fmt"
"slices"
"strings"

"github.com/google-gemini/gemini-api-cli/internal/flagutil"
Expand All @@ -35,7 +37,7 @@ const defaultAnalyzeQuestion = "Describe this file in detail."
func attachAnalyze(cmd *cobra.Command) {
cmd.Use = "analyze [question]"
cmd.Short = "Ask questions about images, audio, video, documents, text files, or YouTube URLs (" + defaultTextModel + ")"
cmd.Long = "Ask a question about one or more images, audio files, videos, PDFs, CSV or text\nfiles, or YouTube URLs.\n\nPass each media source separately with --input. files/<id> references use the\nFiles API, and YouTube URLs are passed by URI. The optional question applies to\nall inputs; its default is \"" + defaultAnalyzeQuestion + "\"\nBy default, stdout prints only the model's answer. The request is not stored\nserver-side.\n\n" + inlineLimitNote
cmd.Long = "Ask a question about one or more images, audio files, videos, PDFs, CSV or text\nfiles, or YouTube URLs. Pass each source with --input: files/<id> uses the Files\nAPI and YouTube URLs go by URI. The question applies to every input; its default\nis \"" + defaultAnalyzeQuestion + "\" By default, stdout prints only the answer;\nnothing is stored. Video with a non-static --processing streams internally.\n\n" + inlineLimitNote
cmd.Example = " gemini-api analyze -i report.pdf \"Summarize the key findings\"\n" +
" gemini-api analyze -i photo.jpg\n" +
" gemini-api analyze -i files/abc123 \"List every speaker with timestamps\"\n" +
Expand All @@ -47,6 +49,9 @@ func attachAnalyze(cmd *cobra.Command) {
cmd.Args = cobra.ArbitraryArgs
cmd.Flags().StringArrayP("input", "i", nil, "Local path, files/<id>, or YouTube URL to analyze (repeatable)")
cmd.Flags().String("mime-type", "", "Override the detected MIME type (one input only)")
cmd.Flags().Bool("upload", false, uploadFlagHelp)
cmd.Flags().String("processing", "", processingFlagHelp)
cmd.Flags().String("resolution", "", resolutionFlagHelp)
cmd.Flags().String("system", "", "System instruction to steer the analysis")
cmd.Flags().Bool("stdin", false, "Read text to analyze from stdin to EOF (sent after the --input media, before the question)")
modelFlag(cmd, defaultTextModel, "text")
Expand Down Expand Up @@ -117,6 +122,10 @@ func runAnalyze(cmd *cobra.Command, args []string) error {
if sys, _ := flagutil.GetStringFlag(cmd, "system"); strings.TrimSpace(sys) != "" {
body.SystemInstruction = stringPtr(strings.TrimSpace(sys))
}
stream := streamsAnalysis(sources)
if stream {
body.Stream = boolPtr(true)
}
req := operations.CreateInteractionRequest{
Body: operations.CreateCreateInteractionRequestBodyCreateModelInteraction(body),
}
Expand All @@ -138,7 +147,13 @@ func runAnalyze(cmd *cobra.Command, args []string) error {
if err != nil {
return output.Error(cmd, err)
}
text, err := interactionText(res.Interaction)
interaction := res.Interaction
if stream {
if interaction, err = collectStreamedInteraction(cmd, res); err != nil {
return err
}
}
text, err := interactionText(interaction)
if err != nil {
return err
}
Expand All @@ -149,8 +164,97 @@ func runAnalyze(cmd *cobra.Command, args []string) error {
if len(mimeTypes) > 0 {
envelope["mime_types"] = mimeTypes
}
if u := usageEnvelope(res.Interaction.Usage); u != nil {
if u := usageEnvelope(interaction.Usage); u != nil {
envelope["usage"] = u
}
return emitResult(cmd, text, envelope)
}

// streamsAnalysis reports whether the request is sent as an SSE stream: a
// video input processed in a mode other than static runs long enough that a
// single unary response risks the connection and auth window. The stream is
// consumed internally; the command still prints one answer.
func streamsAnalysis(sources []*mediaSource) bool {
for _, src := range sources {
if src.class() == contentVideo && src.opts.agentic() {
return true
}
}
return false
}

// collectStreamedInteraction drains the event stream of a streaming create
// and returns the interaction its completed event carries, rebuilt as the
// full resource shape the text and usage readers expect. When the completed
// event omits model-output text steps, streamed text deltas are assembled
// into a model output step so interactionText still succeeds.
func collectStreamedInteraction(cmd *cobra.Command, res *operations.CreateInteractionResponse) (*interactions.Interaction, error) {
es := res.InteractionSSEStreamEvent
if es == nil {
return nil, runtimeError("the API did not return an event stream")
}
defer es.Close()
var completed *interactions.InteractionCompletedEvent
var deltaText strings.Builder
for es.Next() {
ev := es.Value()
if ev == nil {
continue
}
if e := ev.GetDataError(); e != nil {
if raw, err := json.Marshal(e); err == nil {
return nil, output.Error(cmd, &output.StreamEventError{Body: string(raw)})
}
msg := "the API reported an error while streaming"
if e.Error != nil && e.Error.Message != nil && strings.TrimSpace(*e.Error.Message) != "" {
msg = *e.Error.Message
}
return nil, runtimeError(msg)
}
if sd := ev.GetDataStepDelta(); sd != nil {
if td := sd.GetDeltaText(); td != nil {
deltaText.WriteString(td.Text)
}
}
if c := ev.GetDataInteractionCompleted(); c != nil {
completed = c
}
}
if err := es.Err(); err != nil {
return nil, output.Error(cmd, err)
}
if completed == nil {
return nil, runtimeError("the stream ended without an interaction.completed event")
}
it := completed.Interaction
steps := it.Steps
if !stepsHaveText(steps) && deltaText.Len() > 0 {
steps = append(slices.Clone(steps), interactions.CreateStepModelOutput(interactions.ModelOutputStep{
Content: []interactions.Content{textContentBlock(deltaText.String())},
}))
}
full := &interactions.Interaction{
ID: stringPtr(it.ID),
Status: interactions.InteractionStatus(it.Status),
Steps: steps,
Usage: it.Usage,
}
if it.Model != nil {
full.Model = modelPtr(*it.Model)
}
return full, nil
}

func stepsHaveText(steps []interactions.Step) bool {
for _, step := range steps {
if step.ModelOutputStep == nil {
continue
}
for _, block := range step.ModelOutputStep.Content {
if block.TextContent != nil && strings.TrimSpace(block.TextContent.Text) != "" {
return true
}
}
}
return false
}
74 changes: 44 additions & 30 deletions internal/cli/custom/files_upload.go
Original file line number Diff line number Diff line change
Expand Up @@ -108,57 +108,73 @@ func runFilesUpload(cmd *cobra.Command, args []string) error {
displayName = filepath.Base(path)
}

t, err := newRawTransport(cmd)
file, err := uploadSource(cmd, source, path, info.Size(), mimeType, displayName)
if err != nil {
return err
}
if isDryRun(cmd) {
if wait, _ := flagutil.GetBoolFlag(cmd, "wait"); wait {
progress(cmd, "[DRY-RUN] --wait polling is response-dependent and was not simulated.")
}
return nil
}
name := *file.Name

if wait, _ := flagutil.GetBoolFlag(cmd, "wait"); wait {
timeout, _ := cmd.Flags().GetDuration("wait-timeout")
waited, err := waitActive(cmd, name, timeout)
if err != nil {
return err
}
if waited != nil {
file = waited
}
}
return emitResult(cmd, name, fileEnvelope(file))
}

// uploadSource opens a resumable session for an already-open local file,
// streams its bytes, and returns the named File the finalize response carries.
// Under --dry-run the start request and every chunk are previewed and the
// returned File is nil.
func uploadSource(cmd *cobra.Command, source *os.File, path string, size int64, mimeType, displayName string) (*genai.File, error) {
t, err := newRawTransport(cmd)
if err != nil {
return nil, err
}

// Step 1: start the resumable session.
meta := map[string]any{"file": map[string]any{"display_name": displayName}}
metaBytes, _ := json.Marshal(meta)
startURL := t.apiURL("upload/" + t.apiVersion + "/files")
startReq, err := t.newRequest(cmd.Context(), http.MethodPost, startURL, bytes.NewReader(metaBytes))
if err != nil {
return err
return nil, err
}
startReq.Header.Set("Content-Type", "application/json")
setUploadStartHeaders(startReq, info.Size(), mimeType)
setUploadStartHeaders(startReq, size, mimeType)

if !isDryRun(cmd) {
progress(cmd, "Starting upload of %s (%d bytes, %s)...", path, info.Size(), mimeType)
progress(cmd, "Starting upload of %s (%d bytes, %s)...", path, size, mimeType)
}
// Step 2: send the start request, then stream the bytes in chunks; only
// the last chunk finalizes.
finalBody, err := t.resumableUpload(cmd, startReq, source, path, info.Size())
finalBody, err := t.resumableUpload(cmd, startReq, source, path, size)
if err != nil {
return err
return nil, err
}
if isDryRun(cmd) {
if wait, _ := flagutil.GetBoolFlag(cmd, "wait"); wait {
progress(cmd, "[DRY-RUN] --wait polling is response-dependent and was not simulated.")
}
return nil
return nil, nil
}
file, err := decodeUploadedFile(finalBody)
if err != nil {
return runtimeError(err.Error())
return nil, runtimeError(err.Error())
}
if file.Name == nil || *file.Name == "" {
return runtimeError("upload finished but the response had no file name")
}
name := *file.Name
progress(cmd, "Uploaded %s as %s.", path, name)

if wait, _ := flagutil.GetBoolFlag(cmd, "wait"); wait {
waited, err := t.waitActive(cmd, name)
if err != nil {
return err
}
if waited != nil {
file = *waited
}
return nil, runtimeError("upload finished but the response had no file name")
}
return emitResult(cmd, name, fileEnvelope(&file))
progress(cmd, "Uploaded %s as %s.", path, *file.Name)
return &file, nil
}

// setUploadStartHeaders declares the resumable session a start request opens.
Expand Down Expand Up @@ -345,10 +361,9 @@ func (t *rawTransport) streamUpload(ctx context.Context, uploadURL string, sourc
}
}

// waitActive polls files.get until the file is ACTIVE, fails, or the
// --wait-timeout deadline passes; every poll and sleep is bounded by that
// deadline.
func (t *rawTransport) waitActive(cmd *cobra.Command, name string) (*genai.File, error) {
// waitActive polls files.get until the file is ACTIVE, fails, or timeout
// passes; every poll and sleep is bounded by that deadline.
func waitActive(cmd *cobra.Command, name string, timeout time.Duration) (*genai.File, error) {
s, err := client.NewClient(cmd)
if err != nil {
return nil, err
Expand All @@ -357,7 +372,6 @@ func (t *rawTransport) waitActive(cmd *cobra.Command, name string) (*genai.File,
if err != nil {
return nil, err
}
timeout, _ := cmd.Flags().GetDuration("wait-timeout")
waitTimedOut := func() error {
return runtimeError(fmt.Sprintf("%s did not become ACTIVE within %s", name, timeout),
fmt.Sprintf("Check its state later: gemini-api files get %s", name))
Expand Down
52 changes: 22 additions & 30 deletions internal/cli/custom/hardening_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -83,12 +83,15 @@ func TestCheckLocalFileInlineBoundary(t *testing.T) {
for name, tc := range map[string]struct {
file string
size int64
upload bool
wantOK bool
}{
"media at the cap": {"a.mp4", largest, true},
"media over the cap": {"b.mp4", largest + 3, false},
"text at the cap": {"a.txt", maxInlineBytes, true},
"text over the cap": {"b.txt", maxInlineBytes + 1, false},
"media at the cap": {"a.mp4", largest, false, true},
"media over the cap": {"b.mp4", largest + 3, false, false},
"media over the cap with upload": {"c.mp4", largest + 3, true, true},
"text at the cap": {"a.txt", maxInlineBytes, false, true},
"text over the cap": {"b.txt", maxInlineBytes + 1, false, false},
"text over the cap with upload": {"c.txt", maxInlineBytes + 1, true, false},
} {
path := filepath.Join(t.TempDir(), tc.file)
f, err := os.Create(path)
Expand All @@ -100,10 +103,13 @@ func TestCheckLocalFileInlineBoundary(t *testing.T) {
t.Fatal(err)
}
f.Close()
_, _, err = checkLocalFile(path, "", "--input[1]", analyzePolicy)
cost, _, err := checkLocalFile(path, "", "--input[1]", analyzePolicy, tc.upload)
if (err == nil) != tc.wantOK {
t.Errorf("%s: checkLocalFile error = %v, want ok=%v", name, err, tc.wantOK)
}
if tc.upload && tc.wantOK && cost != 0 {
t.Errorf("%s: upload cost = %d, want 0", name, cost)
}
}
}

Expand All @@ -124,6 +130,7 @@ func TestCanonicalRemoteMIME(t *testing.T) {
func TestInteractionOutcome(t *testing.T) {
rejected := []interactions.InteractionStatus{
interactions.InteractionStatusIncomplete, interactions.InteractionStatusBudgetExceeded,
interactions.InteractionStatusRequiresContinuation,
interactions.InteractionStatusFailed, interactions.InteractionStatusCancelled,
interactions.InteractionStatusRequiresAction, interactions.InteractionStatusInProgress,
interactions.InteractionStatusQueued,
Expand Down Expand Up @@ -255,11 +262,8 @@ func TestWaitActiveCancellationAndDeadline(t *testing.T) {
_ = cmd.Flags().Set("wait-timeout", "5s")
cmd.SetContext(ctx)

tr, err := newRawTransport(cmd)
if err != nil {
t.Fatalf("newRawTransport: %v", err)
}
_, err = tr.waitActive(cmd, "files/xyz789")
timeout, _ := cmd.Flags().GetDuration("wait-timeout")
_, err := waitActive(cmd, "files/xyz789", timeout)
if err == nil {
t.Fatal("expected error on caller cancellation")
}
Expand Down Expand Up @@ -291,11 +295,8 @@ func TestWaitActiveCancellationAndDeadline(t *testing.T) {
_ = cmd.Flags().Set("wait-timeout", "5s")
cmd.SetContext(ctx)

tr, err := newRawTransport(cmd)
if err != nil {
t.Fatalf("newRawTransport: %v", err)
}
_, err = tr.waitActive(cmd, "files/xyz789")
timeout, _ := cmd.Flags().GetDuration("wait-timeout")
_, err := waitActive(cmd, "files/xyz789", timeout)
if !errors.Is(err, context.Canceled) {
t.Errorf("error = %v, want context.Canceled", err)
}
Expand All @@ -317,11 +318,8 @@ func TestWaitActiveCancellationAndDeadline(t *testing.T) {
_ = cmd.Flags().Set("wait-timeout", "0s")
cmd.SetContext(t.Context())

tr, err := newRawTransport(cmd)
if err != nil {
t.Fatalf("newRawTransport: %v", err)
}
_, err = tr.waitActive(cmd, "files/xyz789")
timeout, _ := cmd.Flags().GetDuration("wait-timeout")
_, err := waitActive(cmd, "files/xyz789", timeout)
if err == nil || !strings.Contains(err.Error(), "files/xyz789 did not become ACTIVE within 0s") {
t.Errorf("error = %v, want wait-timeout message", err)
}
Expand All @@ -340,11 +338,8 @@ func TestWaitActiveCancellationAndDeadline(t *testing.T) {
_ = cmd.Flags().Set("wait-timeout", "50ms")
cmd.SetContext(t.Context())

tr, err := newRawTransport(cmd)
if err != nil {
t.Fatalf("newRawTransport: %v", err)
}
_, err = tr.waitActive(cmd, "files/xyz789")
timeout, _ := cmd.Flags().GetDuration("wait-timeout")
_, err := waitActive(cmd, "files/xyz789", timeout)
if err == nil || !strings.Contains(err.Error(), "files/xyz789 did not become ACTIVE within 50ms") {
t.Errorf("error = %v, want wait-timeout message", err)
}
Expand All @@ -367,11 +362,8 @@ func TestWaitActiveCancellationAndDeadline(t *testing.T) {
_ = cmd.Flags().Set("wait-timeout", "5s")
cmd.SetContext(t.Context())

tr, err := newRawTransport(cmd)
if err != nil {
t.Fatalf("newRawTransport: %v", err)
}
file, err := tr.waitActive(cmd, "files/xyz789")
timeout, _ := cmd.Flags().GetDuration("wait-timeout")
file, err := waitActive(cmd, "files/xyz789", timeout)
if err != nil {
t.Fatalf("waitActive: %v", err)
}
Expand Down
Loading
Loading