Skip to content
gemini-file-api logo

Gemini File API Integration

gemini-file-api

Work with Gemini File API for document caching and efficient multi-query workflows. Use when discussing file uploads, caching strategies, token optimization, or comparing File API vs inline document approaches.

SKILL.md

Full skill instructions

Gemini File API Integration

Purpose

Understand and work with Gemini's File API for efficient document processing.

Architecture Overview

┌─────────────────────────────────────────────┐
│  Document Upload                            │
│  UploadFile() -> Gemini File API           │
│  Returns: URI with 48hr TTL                │
└─────────────────┬───────────────────────────┘
                  │
                  ▼
┌─────────────────────────────────────────────┐
│  FileCache (in-memory)                      │
│  Prevents re-uploads within session        │
│  Key: file path, Value: FileReference      │
└─────────────────┬───────────────────────────┘
                  │
                  ▼
┌─────────────────────────────────────────────┐
│  GenerateContent()                          │
│  References files by URI (not bytes)       │
│  Reuse same URI for multiple queries       │
└─────────────────────────────────────────────┘

Client Usage

Creating a Client

// Reads GEMINI_API_KEY from environment
client, err := gemini.NewClient(ctx)
if err != nil {
    return err
}
defer client.Close()

Uploading Files

Single file:

ref, err := client.UploadFile(ctx, "/​path/​to/​doc.pdf", "application/​pdf")
// ref.URI is reusable for 48 hours

Multiple files (parallel upload):

paths := []string{"/​path/​to/​w2.pdf", "/​path/​to/​paystub.pdf"}
mimeTypes := map[string]string{
    "/​path/​to/​w2.pdf": "application/​pdf",
    "/​path/​to/​paystub.pdf": "application/​pdf",
}
refs, err := client.UploadFiles(ctx, paths, mimeTypes)
// refs is map[string]*FileReference

Generating Content

With File API (recommended for multiple queries):

resp, err := client.GenerateContent(ctx, &gemini.GenerateRequest{
    Model:        gemini.ModelFlash,
    Prompt:       "Analyze this W2 for annual income",
    SystemPrompt: "You are a mortgage underwriter...",
    FileURIs:     []string{ref.URI},
    FileMIMEs:    map[string]string{ref.URI: "application/​pdf"},
})

With Inline bytes (simpler for single queries):

resp, err := client.GenerateContent(ctx, &gemini.GenerateRequest{
    Model:  gemini.ModelFlash,
    Prompt: "Analyze this document",
    InlineFiles: []gemini.InlineFile{{
        Data:     fileBytes,
        MimeType: "application/​pdf",
    }},
})

Data Structures

FileReference

type FileReference struct {
    Name      string    // Gemini-assigned name
    URI       string    // Reusable URI for requests
    MimeType  string
    State     string    // Processing state
    CreatedAt time.Time
    ExpiresAt time.Time // 48 hours from creation
    SizeBytes int64
}

GenerateRequest

type GenerateRequest struct {
    Model        string              // ModelFlash or ModelPro
    Prompt       string              // User prompt
    SystemPrompt string              // System instructions
    FileURIs     []string            // Gemini file URIs
    FileMIMEs    map[string]string   // URI -> MIME type
    InlineFiles  []InlineFile        // Direct bytes (alternative)
    Temperature  *float32
    MaxTokens    *int32
}

GenerateResponse

type GenerateResponse struct {
    Text           string
    FinishReason   string
    TokensUsed     int64
    ModelUsed      string
    ProcessingTime time.Duration
}

Model Selection

ModelConstantUse Case
Gemini Flashgemini.ModelFlashFast, cheaper, most tasks
Gemini Progemini.ModelProComplex reasoning, escalation

File API vs Inline Comparison

AspectFile APIInline
UploadOnce (cached 48hr)Every request
Best forMultiple queries, same docsSingle query
Token costLower per queryHigher per query
LatencyHigher first queryConsistent
Break-even~7 queriesN/​A

FileCache Details

Located in internal/​gemini/​cache.go:

  • Thread-safe: Uses RWMutex
  • Expiry-aware: Checks 48hr TTL before returning
  • Methods: Get, Set, Delete, Cleanup, GetAllURIs

Troubleshooting

"GEMINI_API_KEY not set"

export GEMINI_API_KEY="your-key"

Upload failures

  • Check file exists and is readable
  • Verify MIME type matches content
  • Check file size limits

Rate limits

Add delays between requests:

time.Sleep(500 * time.Millisecond)

Related Files

  • internal/​gemini/​client.go - Main client implementation
  • internal/​gemini/​cache.go - FileCache implementation
  • cmd/​benchmark/​main.go - Performance comparison tool

More Productivity & Planning skills

brainstorming logo
Productivity & Planning

brainstorming

Structured design dialogue that validates ideas before implementation begins.

295.4K 385.7K
View
ui-ux-pro-max logo
Productivity & Planning

ui-ux-pro-max

Comprehensive design intelligence for web and mobile UI/UX across 10 technology stacks.

133.1K 383.9K
View
writing-plans logo
Productivity & Planning

writing-plans

Comprehensive implementation plans for multi-step tasks, breaking down specs into bite-sized, testable steps.

295.4K 268K
View
using-superpowers logo
Productivity & Planning

using-superpowers

Introduction to the obra skills system with mandatory skill invocation rules and best practices.

295.4K 259.8K
View
executing-plans logo
Productivity & Planning

executing-plans

Execute a written implementation plan with critical review and task checkpoints.

295.4K 229.1K
View
dispatching-parallel-agents logo
Productivity & Planning

dispatching-parallel-agents

Delegate independent tasks to specialized agents working concurrently with isolated context.

295.4K 206.3K
View
using-git-worktrees logo
Productivity & Planning

using-git-worktrees

Isolated git worktrees with smart directory selection and safety verification.

295.4K 205.2K
View
webapp-testing logo
Productivity & Planning

webapp-testing

Toolkit for interacting with and testing local web applications using Playwright. Supports verifying frontend functionality, debugging UI behavior, capturing browser screenshots, and viewing browser logs.

179.7K 170.6K
View
content-strategy logo
Productivity & Planning

content-strategy

Plan searchable and shareable content that drives traffic, builds authority, and generates leads.

53.3K 150.9K
View
repo-intake-and-plan logo
Productivity & Planning

repo-intake-and-plan

README-first repository scanner that extracts commands and classifies reproduction candidates without executing them.

497 139.6K
View
marketing-ideas logo
Productivity & Planning

marketing-ideas

Brainstorm and prioritize marketing strategies tailored to your SaaS stage, budget, and goals.

53.3K 137.2K
View
site-architecture logo
Productivity & Planning

site-architecture

Plan and optimize your website's page hierarchy, navigation, URL structure, and internal linking.

53.3K 112.8K
View

Productivity AI tools

Vimcal logo
Productivity

Vimcal

The world's fastest calendar for remote work

Free
View
SaveDay logo
Productivity

SaveDay

Capture, organize, and utilize your knowledge effortlessly.

Free
View
A
Productivity

Any Summary

Instant Summaries of Audio & Video Interviews with AnySummary

Freemium
View
M
Productivity

Map This

Transform PDFs into engaging mind maps.

Freemium
View
ChatPDF logo
Productivity

ChatPDF

Chat with any PDF instantly

Free
View
I
Productivity

intellisay

Create an optimal daily plan using your voice

Paid
View
A
Productivity

Aurora AI

A productivity platform to centralize organizational knowledge and workflows with contextual AI assistance.

Paid
View
AskYourPDF logo
Productivity

AskYourPDF

AskYourPDF Pricing Plans: Tailored to Your Needs

Free
View