> ## AI Agent Context
> - Full documentation index: https://aistudio.google.com/llms.txt
> - Gemini Docs MCP server (consistent live info): https://gemini-api-docs-mcp.dev
> - Coding agent skills & setup guide: https://aistudio.google.com/docs/coding-agents.md

# Document understanding

Gemini models process PDFs, Microsoft Office files, and OpenDocument files,
including Word documents, PowerPoint presentations, and Excel spreadsheets, to
analyze, summarize, and extract information from complex files. In addition to
reading plain text, the models understand visual and structural context, which
lets you:

* Analyze text, images, diagrams, charts, and tables across up to 1,000 PDF
  pages or up to 2,000 Office and OpenDocument pages or slides.
* Read spreadsheet values, formulas, and rendered charts across worksheets.
* Extract information into [structured output](/docs/structured-output) formats.
* Summarize, compare, and answer questions using both visual and textual details.
* Transcribe documents to formats like HTML while preserving layout.

See [Office and OpenDocument files](/docs/document-processing#office-documents)
for supported MIME types and defaults. To inspect specific pages, sheets, or
content layers instead of a whole file, see
[Customize document, presentation, and spreadsheet processing](/docs/document-processing#customize-document-processing).
Plain-text formats such as TXT, Markdown, and HTML are read as text only,
without layout or chart context.

## Passing document data inline  {% id="inline_data" %}

Pass document data inline to `generateContent` for small files or one-off
requests where you do not need to reuse the file. For larger documents or
multi-turn workflows, use the
[Files API](/docs/document-processing#large-pdfs) to reduce latency and
bandwidth.

The following example fetches a PDF from a URL and passes it inline:

{% tabs %}
  {% tab label="Python" %}
  ```python
  from google import genai
  from google.genai import types
  import httpx
  
  client = genai.Client()
  
  doc_url = "https://discovery.ucl.ac.uk/id/eprint/10089234/1/343019_3_art_0_py4t4l_convrt.pdf"
  
  # Retrieve and encode the PDF byte
  doc_data = httpx.get(doc_url).content
  
  prompt = "Summarize this document"
  response = client.models.generate_content(
      model="gemini-4-hydrogen",
      contents=[
          types.Part.from_bytes(
              data=doc_data,
              mime_type='application/pdf',
          ),
          prompt
      ]
  )
  
  print(response.text)
  ```

  {% /tab %}

  {% tab label="JavaScript" %}
  ```javascript
  import { GoogleGenAI } from "@google/genai";
  
  const ai = new GoogleGenAI({ apiKey: "GEMINI_API_KEY" });
  
  async function main() {
      const pdfResp = await fetch('https://discovery.ucl.ac.uk/id/eprint/10089234/1/343019_3_art_0_py4t4l_convrt.pdf')
          .then((response) => response.arrayBuffer());
  
      const contents = [
          { text: "Summarize this document" },
          {
              inlineData: {
                  mimeType: 'application/pdf',
                  data: Buffer.from(pdfResp).toString("base64")
              }
          }
      ];
  
      const response = await ai.models.generateContent({
          model: "gemini-4-hydrogen",
          contents: contents
      });
      console.log(response.text);
  }
  
  await main();
  ```

  {% /tab %}

  {% tab label="Go" %}
  ```go
  package main
  
  import (
      "context"
      "fmt"
      "io"
      "net/http"
      "os"
      "google.golang.org/genai"
  )
  
  func main() {
  
      ctx := context.Background()
      client, _ := genai.NewClient(ctx, &genai.ClientConfig{
          APIKey: os.Getenv("GEMINI_API_KEY"),
          Backend: genai.BackendGeminiAPI,
      })
  
      pdfResp, _ := http.Get("https://discovery.ucl.ac.uk/id/eprint/10089234/1/343019_3_art_0_py4t4l_convrt.pdf")
      var pdfBytes []byte
      if pdfResp != nil && pdfResp.Body != nil {
          pdfBytes, _ = io.ReadAll(pdfResp.Body)
          pdfResp.Body.Close()
      }
  
      parts := []*genai.Part{
          &genai.Part{
              InlineData: &genai.Blob{
                  MIMEType: "application/pdf",
                  Data: pdfBytes,
              },
          },
          genai.NewPartFromText("Summarize this document"),
      }
  
      contents := []*genai.Content{
          genai.NewContentFromParts(parts, genai.RoleUser),
      }
  
      result, _ := client.Models.GenerateContent(
          ctx,
          "gemini-4-hydrogen",
          contents,
          nil,
      )
  
      fmt.Println(result.Text())
  }
  ```

  {% /tab %}

  {% tab label="REST" %}
  ```shell
  DOC_URL="https://discovery.ucl.ac.uk/id/eprint/10089234/1/343019_3_art_0_py4t4l_convrt.pdf"
  PROMPT="Summarize this document"
  DISPLAY_NAME="base64_pdf"
  
  # Download the PDF
  wget -O "${DISPLAY_NAME}.pdf" "${DOC_URL}"
  
  # Check for FreeBSD base64 and set flags accordingly
  if [[ "$(base64 --version 2>&1)" = *"FreeBSD"* ]]; then
    B64FLAGS="--input"
  else
    B64FLAGS="-w0"
  fi
  
  # Base64 encode the PDF
  ENCODED_PDF=$(base64 $B64FLAGS "${DISPLAY_NAME}.pdf")
  
  # Generate content using the base64 encoded PDF
  curl "https://generativelanguage.googleapis.com/v1beta/models/gemini-4-hydrogen:generateContent?key=${GEMINI_API_KEY}" \
      -H 'Content-Type: application/json' \
      -X POST \
      -d '{
        "contents": [{
          "parts":[
            {"inline_data": {"mime_type": "application/pdf", "data": "'"$ENCODED_PDF"'"}},
            {"text": "'"$PROMPT"'"}
          ]
        }]
      }' 2> /dev/null > response.json
  
  cat response.json
  echo
  
  jq ".candidates[].content.parts[].text" response.json
  
  # Clean up the downloaded PDF
  rm "${DISPLAY_NAME}.pdf"
  ```

  {% /tab %}

{% /tabs %}

You can also read a document from a local file:

{% tabs %}
  {% tab label="Python" %}
  ```python
  from google import genai
  from google.genai import types
  import pathlib
  
  client = genai.Client()
  
  # Retrieve and encode the PDF byte
  filepath = pathlib.Path('file.pdf')
  
  prompt = "Summarize this document"
  response = client.models.generate_content(
      model="gemini-4-hydrogen",
      contents=[
          types.Part.from_bytes(
              data=filepath.read_bytes(),
              mime_type='application/pdf',
          ),
          prompt,
      ],
  )
  print(response.text)
  ```

  {% /tab %}

  {% tab label="JavaScript" %}
  ```javascript
  import { GoogleGenAI } from "@google/genai";
  import * as fs from 'fs';
  
  const ai = new GoogleGenAI({ apiKey: "GEMINI_API_KEY" });
  
  async function main() {
      const contents = [
          { text: "Summarize this document" },
          {
              inlineData: {
                  mimeType: 'application/pdf',
                  data: Buffer.from(fs.readFileSync("content/343019_3_art_0_py4t4l_convrt.pdf")).toString("base64")
              }
          }
      ];
  
      const response = await ai.models.generateContent({
          model: "gemini-4-hydrogen",
          contents: contents
      });
      console.log(response.text);
  }
  
  await main();
  ```

  {% /tab %}

  {% tab label="Go" %}
  ```go
  package main
  
  import (
      "context"
      "fmt"
      "os"
      "google.golang.org/genai"
  )
  
  func main() {
  
      ctx := context.Background()
      client, _ := genai.NewClient(ctx, &genai.ClientConfig{
          APIKey: os.Getenv("GEMINI_API_KEY"),
          Backend: genai.BackendGeminiAPI,
      })
  
      pdfBytes, _ := os.ReadFile("path/to/your/file.pdf")
  
      parts := []*genai.Part{
          &genai.Part{
              InlineData: &genai.Blob{
                  MIMEType: "application/pdf",
                  Data: pdfBytes,
              },
          },
          genai.NewPartFromText("Summarize this document"),
      }
      contents := []*genai.Content{
          genai.NewContentFromParts(parts, genai.RoleUser),
      }
  
      result, _ := client.Models.GenerateContent(
          ctx,
          "gemini-4-hydrogen",
          contents,
          nil,
      )
  
      fmt.Println(result.Text())
  }
  ```

  {% /tab %}

{% /tabs %}

## Uploading documents using the Files API  {% id="large-pdfs" %}

Use the Files API for larger files or when you reuse a document across multiple
requests. Uploading once decouples file transfer from model requests, which
reduces latency and bandwidth.

{% callout type="note" %}
  The Files API is available at no cost in all regions where the Gemini API
  is available. Uploaded files are stored for 48 hours.

  When you upload a file with the Files API, it is initially in a
  `PROCESSING` state. Wait until the file state changes to `ACTIVE` before you
  reference it in a model request.

{% /callout %}

### Large documents from URLs  {% id="large-pdfs-urls" %}

Use the Files API to upload and process large documents from URLs:

{% tabs %}
  {% tab label="Python" %}
  ```python
  from google import genai
  from google.genai import types
  import io
  import httpx
  import time
  
  client = genai.Client()
  
  long_context_pdf_path = "https://www.nasa.gov/wp-content/uploads/static/history/alsj/a17/A17_FlightPlan.pdf"
  
  # Retrieve and upload the PDF using the File API
  doc_io = io.BytesIO(httpx.get(long_context_pdf_path).content)
  
  sample_doc = client.files.upload(
      # You can pass a path or a file-like object here
      file=doc_io,
      config=dict(mime_type='application/pdf'),
  )
  
  while sample_doc.state.name == "PROCESSING":
      print("Processing document...")
      time.sleep(5)
      sample_doc = client.files.get(name=sample_doc.name)
  
  if sample_doc.state.name != "ACTIVE":
      raise Exception(f"File processing failed: {sample_doc.state.name}")
  
  prompt = "Summarize this document"
  
  response = client.models.generate_content(
      model="gemini-4-hydrogen",
      contents=[sample_doc, prompt],
  )
  print(response.text)
  ```

  {% /tab %}

  {% tab label="JavaScript" %}
  ```javascript
  import { createPartFromUri, GoogleGenAI } from "@google/genai";
  
  const ai = new GoogleGenAI({ apiKey: "GEMINI_API_KEY" });
  
  async function main() {
  
      const pdfBuffer = await fetch("https://www.nasa.gov/wp-content/uploads/static/history/alsj/a17/A17_FlightPlan.pdf")
          .then((response) => response.arrayBuffer());
  
      const fileBlob = new Blob([pdfBuffer], { type: 'application/pdf' });
  
      const file = await ai.files.upload({
          file: fileBlob,
          config: {
              displayName: 'A17_FlightPlan.pdf',
          },
      });
  
      // Wait for the file to be processed.
      let getFile = await ai.files.get({ name: file.name || "" });
      while (getFile.state === 'PROCESSING') {
          console.log(`current file status: ${getFile.state}`);
          console.log('File is still processing, retrying in 5 seconds');
          await new Promise((resolve) => {
              setTimeout(resolve, 5000);
          });
          getFile = await ai.files.get({ name: file.name || "" });
      }
      if (getFile.state === 'FAILED') {
          throw new Error('File processing failed.');
      }
  
      // Add the file to the contents.
      const content = [
          'Summarize this document',
      ];
  
      if (file.uri && file.mimeType) {
          const fileContent = createPartFromUri(file.uri, file.mimeType);
          content.push(fileContent);
      }
  
      const response = await ai.models.generateContent({
          model: 'gemini-4-hydrogen',
          contents: content,
      });
  
      console.log(response.text);
  
  }
  
  await main();
  ```

  {% /tab %}

  {% tab label="Go" %}
  ```go
  package main
  
  import (
      "context"
      "fmt"
      "io"
      "log"
      "net/http"
      "os"
      "time"
      "google.golang.org/genai"
  )
  
  func main() {
  
      ctx := context.Background()
      client, _ := genai.NewClient(ctx, &genai.ClientConfig{
          APIKey: os.Getenv("GEMINI_API_KEY"),
          Backend: genai.BackendGeminiAPI,
      })
  
      pdfURL := "https://www.nasa.gov/wp-content/uploads/static/history/alsj/a17/A17_FlightPlan.pdf"
      localPdfPath := "A17_FlightPlan_downloaded.pdf"
  
      respHttp, _ := http.Get(pdfURL)
      defer respHttp.Body.Close()
  
      outFile, _ := os.Create(localPdfPath)
      defer outFile.Close()
  
      _, _ = io.Copy(outFile, respHttp.Body)
  
      uploadConfig := &genai.UploadFileConfig{MIMEType: "application/pdf"}
      uploadedFile, _ := client.Files.UploadFromPath(ctx, localPdfPath, uploadConfig)
  
      for uploadedFile.State == genai.FileStateProcessing {
        fmt.Println("Processing document...")
        time.Sleep(5 * time.Second)
        uploadedFile, _ = client.Files.Get(ctx, uploadedFile.Name, nil)
      }
      if uploadedFile.State != genai.FileStateActive {
        log.Fatalf("File processing failed: %v", uploadedFile.State)
      }
  
      promptParts := []*genai.Part{
          genai.NewPartFromURI(uploadedFile.URI, uploadedFile.MIMEType),
          genai.NewPartFromText("Summarize this document"),
      }
      contents := []*genai.Content{
          genai.NewContentFromParts(promptParts, genai.RoleUser), // Specify role
      }
  
      result, _ := client.Models.GenerateContent(
          ctx,
          "gemini-4-hydrogen",
          contents,
          nil,
      )
  
      fmt.Println(result.Text())
  }
  ```

  {% /tab %}

  {% tab label="REST" %}
  ```shell
  PDF_PATH="https://www.nasa.gov/wp-content/uploads/static/history/alsj/a17/A17_FlightPlan.pdf"
  DISPLAY_NAME="A17_FlightPlan"
  PROMPT="Summarize this document"
  
  # Download the PDF from the provided URL
  wget -O "${DISPLAY_NAME}.pdf" "${PDF_PATH}"
  
  MIME_TYPE=$(file -b --mime-type "${DISPLAY_NAME}.pdf")
  NUM_BYTES=$(wc -c < "${DISPLAY_NAME}.pdf")
  
  echo "MIME_TYPE: ${MIME_TYPE}"
  echo "NUM_BYTES: ${NUM_BYTES}"
  
  tmp_header_file=upload-header.tmp
  
  # Initial resumable request defining metadata.
  # The upload url is in the response headers dump them to a file.
  curl "https://generativelanguage.googleapis.com/upload/v1beta/files?key=${GEMINI_API_KEY}" \
    -D upload-header.tmp \
    -H "X-Goog-Upload-Protocol: resumable" \
    -H "X-Goog-Upload-Command: start" \
    -H "X-Goog-Upload-Header-Content-Length: ${NUM_BYTES}" \
    -H "X-Goog-Upload-Header-Content-Type: ${MIME_TYPE}" \
    -H "Content-Type: application/json" \
    -d "{'file': {'display_name': '${DISPLAY_NAME}'}}" 2> /dev/null
  
  upload_url=$(grep -i "x-goog-upload-url: " "${tmp_header_file}" | cut -d" " -f2 | tr -d "\r")
  rm "${tmp_header_file}"
  
  # Upload the actual bytes.
  curl "${upload_url}" \
    -H "Content-Length: ${NUM_BYTES}" \
    -H "X-Goog-Upload-Offset: 0" \
    -H "X-Goog-Upload-Command: upload, finalize" \
    --data-binary "@${DISPLAY_NAME}.pdf" 2> /dev/null > file_info.json
  
  file_uri=$(jq ".file.uri" file_info.json)
  echo "file_uri: ${file_uri}"
  
  # Now generate content using that file
  curl "https://generativelanguage.googleapis.com/v1beta/models/gemini-4-hydrogen:generateContent?key=${GEMINI_API_KEY}" \
      -H 'Content-Type: application/json' \
      -X POST \
      -d '{
        "contents": [{
          "parts":[
            {"text": "'"$PROMPT"'"},
            {"file_data":{"mime_type": "application/pdf", "file_uri": '$file_uri'}}]
          }]
        }' 2> /dev/null > response.json
  
  cat response.json
  echo
  
  jq ".candidates[].content.parts[].text" response.json
  
  # Clean up the downloaded PDF
  rm "${DISPLAY_NAME}.pdf"
  ```

  {% /tab %}

{% /tabs %}

### Large documents stored locally  {% id="large-pdfs-local" %}

{% tabs %}
  {% tab label="Python" %}
  ```python
  from google import genai
  import pathlib
  
  client = genai.Client()
  
  # Retrieve and encode the PDF byte
  file_path = pathlib.Path('large_file.pdf')
  
  # Upload the PDF using the File API
  sample_file = client.files.upload(
      file=file_path,
  )
  
  prompt = "Summarize this document"
  
  response = client.models.generate_content(
      model="gemini-4-hydrogen",
      contents=[sample_file, prompt],
  )
  print(response.text)
  ```

  {% /tab %}

  {% tab label="JavaScript" %}
  ```javascript
  import { createPartFromUri, GoogleGenAI } from "@google/genai";
  
  const ai = new GoogleGenAI({ apiKey: "GEMINI_API_KEY" });
  
  async function main() {
      const file = await ai.files.upload({
          file: 'path-to-localfile.pdf',
          config: {
              displayName: 'A17_FlightPlan.pdf',
          },
      });
  
      // Wait for the file to be processed.
      let getFile = await ai.files.get({ name: file.name });
      while (getFile.state === 'PROCESSING') {
          getFile = await ai.files.get({ name: file.name });
          console.log(`current file status: ${getFile.state}`);
          console.log('File is still processing, retrying in 5 seconds');
  
          await new Promise((resolve) => {
              setTimeout(resolve, 5000);
          });
      }
      if (getFile.state === 'FAILED') {
          throw new Error('File processing failed.');
      }
  
      // Add the file to the contents.
      const content = [
          'Summarize this document',
      ];
  
      if (file.uri && file.mimeType) {
          const fileContent = createPartFromUri(file.uri, file.mimeType);
          content.push(fileContent);
      }
  
      const response = await ai.models.generateContent({
          model: 'gemini-4-hydrogen',
          contents: content,
      });
  
      console.log(response.text);
  
  }
  
  await main();
  ```

  {% /tab %}

  {% tab label="Go" %}
  ```go
  package main
  
  import (
      "context"
      "fmt"
      "os"
      "google.golang.org/genai"
  )
  
  func main() {
  
      ctx := context.Background()
      client, _ := genai.NewClient(ctx, &genai.ClientConfig{
          APIKey: os.Getenv("GEMINI_API_KEY"),
          Backend: genai.BackendGeminiAPI,
      })
      localPdfPath := "/path/to/file.pdf"
  
      uploadConfig := &genai.UploadFileConfig{MIMEType: "application/pdf"}
      uploadedFile, _ := client.Files.UploadFromPath(ctx, localPdfPath, uploadConfig)
  
      promptParts := []*genai.Part{
          genai.NewPartFromURI(uploadedFile.URI, uploadedFile.MIMEType),
          genai.NewPartFromText("Give me a summary of this pdf file."),
      }
      contents := []*genai.Content{
          genai.NewContentFromParts(promptParts, genai.RoleUser),
      }
  
      result, _ := client.Models.GenerateContent(
          ctx,
          "gemini-4-hydrogen",
          contents,
          nil,
      )
  
      fmt.Println(result.Text())
  }
  ```

  {% /tab %}

  {% tab label="REST" %}
  ```shell
  PDF_PATH="path/to/your.pdf"
  NUM_BYTES=$(wc -c < "${PDF_PATH}")
  DISPLAY_NAME=TEXT
  tmp_header_file=upload-header.tmp
  
  # Initial resumable request defining metadata.
  # The upload url is in the response headers dump them to a file.
  curl "https://generativelanguage.googleapis.com/upload/v1beta/files?key=${GEMINI_API_KEY}" \
    -D upload-header.tmp \
    -H "X-Goog-Upload-Protocol: resumable" \
    -H "X-Goog-Upload-Command: start" \
    -H "X-Goog-Upload-Header-Content-Length: ${NUM_BYTES}" \
    -H "X-Goog-Upload-Header-Content-Type: application/pdf" \
    -H "Content-Type: application/json" \
    -d "{'file': {'display_name': '${DISPLAY_NAME}'}}" 2> /dev/null
  
  upload_url=$(grep -i "x-goog-upload-url: " "${tmp_header_file}" | cut -d" " -f2 | tr -d "\r")
  rm "${tmp_header_file}"
  
  # Upload the actual bytes.
  curl "${upload_url}" \
    -H "Content-Length: ${NUM_BYTES}" \
    -H "X-Goog-Upload-Offset: 0" \
    -H "X-Goog-Upload-Command: upload, finalize" \
    --data-binary "@${PDF_PATH}" 2> /dev/null > file_info.json
  
  file_uri=$(jq ".file.uri" file_info.json)
  echo file_uri=$file_uri
  
  # Now generate content using that file
  curl "https://generativelanguage.googleapis.com/v1beta/models/gemini-4-hydrogen:generateContent?key=${GEMINI_API_KEY}" \
      -H 'Content-Type: application/json' \
      -X POST \
      -d '{
        "contents": [{
          "parts":[
            {"text": "Can you add a few more lines to this poem?"},
            {"file_data":{"mime_type": "application/pdf", "file_uri": '$file_uri'}}]
          }]
        }' 2> /dev/null > response.json
  
  cat response.json
  echo
  
  jq ".candidates[].content.parts[].text" response.json
  ```

  {% /tab %}

{% /tabs %}

You can verify the API successfully stored the uploaded file and get its
metadata by calling [`files.get`](/api-reference/files/get-file). Only the `name`
(and by extension, the `uri`) are unique.

{% tabs %}
  {% tab label="Python" %}
  ```python
  from google import genai
  import pathlib
  
  client = genai.Client()
  
  fpath = pathlib.Path('example.txt')
  fpath.write_text('hello')
  
  file = client.files.upload(file='example.txt')
  
  file_info = client.files.get(name=file.name)
  print(file_info.model_dump_json(indent=4))
  ```

  {% /tab %}

  {% tab label="REST" %}
  ```shell
  name=$(jq -r ".file.name" file_info.json)
  # Get the file of interest to check state
  curl "https://generativelanguage.googleapis.com/v1beta/${name}" \
    -H "x-goog-api-key: $GEMINI_API_KEY" > file_metadata.json
  # Print some information about the file you got
  name=$(jq -r ".name" file_metadata.json)
  echo name=$name
  file_uri=$(jq -r ".uri" file_metadata.json)
  echo file_uri=$file_uri
  ```

  {% /tab %}

{% /tabs %}

## Passing multiple documents  {% id="prompt-multiple" %}

You can process multiple documents in a single request as long as the combined
files and prompt fit within the model's context window.

{% tabs %}
  {% tab label="Python" %}
  ```python
  from google import genai
  import io
  import httpx
  
  client = genai.Client()
  
  doc_url_1 = "https://arxiv.org/pdf/2312.11805"
  doc_url_2 = "https://arxiv.org/pdf/2403.05530"
  
  # Retrieve and upload both PDFs using the File API
  doc_data_1 = io.BytesIO(httpx.get(doc_url_1).content)
  doc_data_2 = io.BytesIO(httpx.get(doc_url_2).content)
  
  sample_pdf_1 = client.files.upload(
      file=doc_data_1,
      config=dict(mime_type='application/pdf'),
  )
  sample_pdf_2 = client.files.upload(
      file=doc_data_2,
      config=dict(mime_type='application/pdf'),
  )
  
  prompt = "What is the difference between each of the main benchmarks between these two papers? Output these in a table."
  
  response = client.models.generate_content(
      model="gemini-4-hydrogen",
      contents=[sample_pdf_1, sample_pdf_2, prompt],
  )
  
  print(response.text)
  ```

  {% /tab %}

  {% tab label="JavaScript" %}
  ```javascript
  import { createPartFromUri, GoogleGenAI } from "@google/genai";
  
  const ai = new GoogleGenAI({ apiKey: "GEMINI_API_KEY" });
  
  async function uploadRemotePDF(url, displayName) {
      const pdfBuffer = await fetch(url)
          .then((response) => response.arrayBuffer());
  
      const fileBlob = new Blob([pdfBuffer], { type: 'application/pdf' });
  
      const file = await ai.files.upload({
          file: fileBlob,
          config: {
              displayName: displayName,
          },
      });
  
      // Wait for the file to be processed.
      let getFile = await ai.files.get({ name: file.name });
      while (getFile.state === 'PROCESSING') {
          getFile = await ai.files.get({ name: file.name });
          console.log(`current file status: ${getFile.state}`);
          console.log('File is still processing, retrying in 5 seconds');
  
          await new Promise((resolve) => {
              setTimeout(resolve, 5000);
          });
      }
      if (getFile.state === 'FAILED') {
          throw new Error('File processing failed.');
      }
  
      return file;
  }
  
  async function main() {
      const content = [
          'What is the difference between each of the main benchmarks between these two papers? Output these in a table.',
      ];
  
      let file1 = await uploadRemotePDF("https://arxiv.org/pdf/2312.11805", "PDF 1");
      if (file1.uri && file1.mimeType) {
          const fileContent = createPartFromUri(file1.uri, file1.mimeType);
          content.push(fileContent);
      }
      let file2 = await uploadRemotePDF("https://arxiv.org/pdf/2403.05530", "PDF 2");
      if (file2.uri && file2.mimeType) {
          const fileContent = createPartFromUri(file2.uri, file2.mimeType);
          content.push(fileContent);
      }
  
      const response = await ai.models.generateContent({
          model: 'gemini-4-hydrogen',
          contents: content,
      });
  
      console.log(response.text);
  }
  
  await main();
  ```

  {% /tab %}

  {% tab label="Go" %}
  ```go
  package main
  
  import (
      "context"
      "fmt"
      "io"
      "net/http"
      "os"
      "google.golang.org/genai"
  )
  
  func main() {
  
      ctx := context.Background()
      client, _ := genai.NewClient(ctx, &genai.ClientConfig{
          APIKey: os.Getenv("GEMINI_API_KEY"),
          Backend: genai.BackendGeminiAPI,
      })
  
      docUrl1 := "https://arxiv.org/pdf/2312.11805"
      docUrl2 := "https://arxiv.org/pdf/2403.05530"
      localPath1 := "doc1_downloaded.pdf"
      localPath2 := "doc2_downloaded.pdf"
  
      respHttp1, _ := http.Get(docUrl1)
      defer respHttp1.Body.Close()
  
      outFile1, _ := os.Create(localPath1)
      _, _ = io.Copy(outFile1, respHttp1.Body)
      outFile1.Close()
  
      respHttp2, _ := http.Get(docUrl2)
      defer respHttp2.Body.Close()
  
      outFile2, _ := os.Create(localPath2)
      _, _ = io.Copy(outFile2, respHttp2.Body)
      outFile2.Close()
  
      uploadConfig1 := &genai.UploadFileConfig{MIMEType: "application/pdf"}
      uploadedFile1, _ := client.Files.UploadFromPath(ctx, localPath1, uploadConfig1)
  
      uploadConfig2 := &genai.UploadFileConfig{MIMEType: "application/pdf"}
      uploadedFile2, _ := client.Files.UploadFromPath(ctx, localPath2, uploadConfig2)
  
      promptParts := []*genai.Part{
          genai.NewPartFromURI(uploadedFile1.URI, uploadedFile1.MIMEType),
          genai.NewPartFromURI(uploadedFile2.URI, uploadedFile2.MIMEType),
          genai.NewPartFromText("What is the difference between each of the " +
              "main benchmarks between these two papers? " +
              "Output these in a table."),
      }
      contents := []*genai.Content{
          genai.NewContentFromParts(promptParts, genai.RoleUser),
      }
  
      modelName := "gemini-4-hydrogen"
      result, _ := client.Models.GenerateContent(
          ctx,
          modelName,
          contents,
          nil,
      )
  
      fmt.Println(result.Text())
  }
  ```

  {% /tab %}

  {% tab label="REST" %}
  ```shell
  DOC_URL_1="https://arxiv.org/pdf/2312.11805"
  DOC_URL_2="https://arxiv.org/pdf/2403.05530"
  DISPLAY_NAME_1="Gemini_paper"
  DISPLAY_NAME_2="Gemini_1.5_paper"
  PROMPT="What is the difference between each of the main benchmarks between these two papers? Output these in a table."
  
  # Function to download and upload a PDF
  upload_pdf() {
    local doc_url="$1"
    local display_name="$2"
  
    # Download the PDF
    wget -O "${display_name}.pdf" "${doc_url}"
  
    local MIME_TYPE=$(file -b --mime-type "${display_name}.pdf")
    local NUM_BYTES=$(wc -c < "${display_name}.pdf")
  
    echo "MIME_TYPE: ${MIME_TYPE}" >&2
    echo "NUM_BYTES: ${NUM_BYTES}" >&2
  
    local tmp_header_file=upload-header.tmp
  
    # Initial resumable request
    curl "https://generativelanguage.googleapis.com/upload/v1beta/files?key=${GEMINI_API_KEY}" \
      -D "${tmp_header_file}" \
      -H "X-Goog-Upload-Protocol: resumable" \
      -H "X-Goog-Upload-Command: start" \
      -H "X-Goog-Upload-Header-Content-Length: ${NUM_BYTES}" \
      -H "X-Goog-Upload-Header-Content-Type: ${MIME_TYPE}" \
      -H "Content-Type: application/json" \
      -d "{'file': {'display_name': '${display_name}'}}" 2> /dev/null
  
    local upload_url=$(grep -i "x-goog-upload-url: " "${tmp_header_file}" | cut -d" " -f2 | tr -d "\r")
    rm "${tmp_header_file}"
  
    # Upload the PDF
    curl "${upload_url}" \
      -H "Content-Length: ${NUM_BYTES}" \
      -H "X-Goog-Upload-Offset: 0" \
      -H "X-Goog-Upload-Command: upload, finalize" \
      --data-binary "@${display_name}.pdf" 2> /dev/null > "file_info_${display_name}.json"
  
    local file_uri=$(jq ".file.uri" "file_info_${display_name}.json")
    echo "file_uri for ${display_name}: ${file_uri}" >&2
  
    # Clean up the downloaded PDF
    rm "${display_name}.pdf"
  
    echo "${file_uri}"
  }
  
  # Upload the first PDF
  file_uri_1=$(upload_pdf "${DOC_URL_1}" "${DISPLAY_NAME_1}")
  
  # Upload the second PDF
  file_uri_2=$(upload_pdf "${DOC_URL_2}" "${DISPLAY_NAME_2}")
  
  # Now generate content using both files
  curl "https://generativelanguage.googleapis.com/v1beta/models/gemini-4-hydrogen:generateContent?key=${GEMINI_API_KEY}" \
      -H 'Content-Type: application/json' \
      -X POST \
      -d '{
        "contents": [{
          "parts":[
            {"file_data": {"mime_type": "application/pdf", "file_uri": '$file_uri_1'}},
            {"file_data": {"mime_type": "application/pdf", "file_uri": '$file_uri_2'}},
            {"text": "'"$PROMPT"'"}
          ]
        }]
      }' 2> /dev/null > response.json
  
  cat response.json
  echo
  
  jq ".candidates[].content.parts[].text" response.json
  ```

  {% /tab %}

{% /tabs %}

## Office and OpenDocument files  {% id="office-documents" %}

Gemini models process Microsoft Office and OpenDocument files the same way as
PDFs. Pass them inline or with the Files API using one of these MIME types:

| File type | Extension | MIME type |
| --- | --- | --- |
| Documents | `.docx` | `application/vnd.openxmlformats-officedocument.wordprocessingml.document` |
|  | `.doc` | `application/msword` |
|  | `.dotx` | `application/vnd.openxmlformats-officedocument.wordprocessingml.template` |
|  | `.odt` | `application/vnd.oasis.opendocument.text` |
| Presentations | `.pptx` | `application/vnd.openxmlformats-officedocument.presentationml.presentation` |
|  | `.ppt` | `application/vnd.ms-powerpoint` |
|  | `.odp` | `application/vnd.oasis.opendocument.presentation` |
| Spreadsheets | `.xlsx` | `application/vnd.openxmlformats-officedocument.spreadsheetml.sheet` |
|  | `.xls` | `application/vnd.ms-excel` |
|  | `.ods` | `application/vnd.oasis.opendocument.spreadsheet` |

When you omit `document_metadata` or `spreadsheet_metadata`, Gemini ingests the full file using these defaults:

| Extensions | Gemini 4+ | Gemini 3 & 2.5 |
| :--- | :--- | :--- |
| `.docx`, `.dotx`, `.odt`, `.pptx` | Page/slide images (medium res, ~560 tokens/page) | Extracted text (+ embedded images) |
| `.doc`, `.ppt`, `.odp` | Page/slide images (medium res, ~560 tokens/page) | Page/slide images |
| `.xlsx`, `.xls` | All sheets: values, formulas, sheet names | All sheets as CSV (values only) |
| `.ods` | All sheets: values, formulas, sheet names | All sheets: values, formulas, sheet names |

The following example uploads a PowerPoint presentation with the Files API and
asks the model to summarize it:

{% tabs %}
  {% tab filename="sample.py" label="Python" %}
  ```python
  from google import genai
  
  client = genai.Client()
  
  deck = client.files.upload(
      file="quarterly_review.pptx",
      config={
          "mime_type": "application/vnd.openxmlformats-officedocument.presentationml.presentation"
      },
  )
  
  response = client.models.generate_content(
      model="gemini-4-hydrogen",
      contents=[deck, "Summarize the key takeaways from each slide."],
  )
  
  print(response.text)
  ```

  {% /tab %}

  {% tab filename="sample.js" label="JavaScript" %}
  ```javascript
  import {
    GoogleGenAI,
    createUserContent,
    createPartFromUri,
  } from "@google/genai";
  
  const ai = new GoogleGenAI({});
  
  async function main() {
    const deck = await ai.files.upload({
      file: "quarterly_review.pptx",
      config: {
        mimeType:
          "application/vnd.openxmlformats-officedocument.presentationml.presentation",
      },
    });
  
    const response = await ai.models.generateContent({
      model: "gemini-4-hydrogen",
      contents: createUserContent([
        createPartFromUri(deck.uri, deck.mimeType),
        "Summarize the key takeaways from each slide.",
      ]),
    });
  
    console.log(response.text);
  }
  
  main();
  ```

  {% /tab %}

  {% tab filename="sample.sh" label="REST" %}
  ```shell
  curl "https://generativelanguage.googleapis.com/v1beta/models/gemini-4-hydrogen:generateContent" \
    -H "Content-Type: application/json" \
    -H "x-goog-api-key: $GEMINI_API_KEY" \
    -X POST \
    -d '{
      "contents": [{
        "parts": [
          {
            "fileData": {
              "fileUri": "https://generativelanguage.googleapis.com/v1beta/files/FILE_ID",
              "mimeType": "application/vnd.openxmlformats-officedocument.presentationml.presentation"
            }
          },
          {"text": "Summarize the key takeaways from each slide."}
        ]
      }]
    }'
  ```

  {% /tab %}

{% /tabs %}

Tools can also return these files or sliced selections in a
[function response](/docs/function-calling#multimodal). Existing file size and
page limits apply to the whole file.

## Customize document, presentation, and spreadsheet processing  {% id="customize-document-processing" %}

You can select specific pages, worksheet tabs, cell ranges, content layers, and
rendering resolution instead of sending an entire file. Attach
`document_metadata`, `spreadsheet_metadata`, and `media_resolution` to a `Part`
or `FunctionResponsePart`, as shown in the examples below. Gemini 3 and Gemini 4
models support these options.

Gemini counts and bills tokens only for the slice you send, including in
`count_tokens` calls. The model also receives total page counts and worksheet
names so it can ask for follow-up ranges in later turns.

### Slice pages and select content layers  {% id="page-options" %}

Use `document_metadata` to slice PDFs, documents, and presentations. All fields
are optional.

| Option | Description |
| --- | --- |
| `start_page` | First page to include (1-indexed, inclusive). Defaults to 1 when you set `end_page`. Values of 0 or less return an invalid argument error; values past the end of the file return an empty slice. |
| `end_page` | Last page to include (1-indexed, inclusive). Defaults to the last page when you set `start_page`, and clamps to the end of the file if higher. Must be at least `start_page`. |
| `content_layers` | List of layers to extract: `PAGE_IMAGE` for rendered page images, `PAGE_TEXT` for extracted text, or both. Defaults to `PAGE_IMAGE` when `document_metadata` is set. |
| `media_resolution` | Set `level` on the `Part` to `MEDIA_RESOLUTION_LOW` (~280 tokens/page), `MEDIA_RESOLUTION_MEDIUM` (default, ~560 tokens/page), or `MEDIA_RESOLUTION_HIGH` (~1,120 tokens/page). |

{% callout type="note" %}
  For large documents or slide decks, scan with `PAGE_TEXT` first. Then request
  `PAGE_IMAGE` at `MEDIA_RESOLUTION_HIGH` only for pages with charts or dense
  layouts.

{% /callout %}

{% tabs %}
  {% tab filename="document_metadata.py" label="Python" %}
  ```python
  from google import genai
  from google.genai import types
  
  client = genai.Client()
  
  uploaded_doc = client.files.upload(file="quarterly_report.pdf")
  
  response = client.models.generate_content(
      model="gemini-4-hydrogen",
      contents=[
          types.Part(
              file_data=types.FileData(
                  file_uri=uploaded_doc.uri,
                  mime_type="application/pdf",
              ),
              document_metadata=types.DocumentMetadata(
                  start_page=3,
                  end_page=7,
                  content_layers=["PAGE_IMAGE"],
              ),
              media_resolution=types.PartMediaResolution(
                  level=types.PartMediaResolutionLevel.MEDIA_RESOLUTION_HIGH,
              ),
          ),
          "Summarize the revenue bridge chart and footnotes on pages 3 through 7.",
      ],
  )
  
  print(response.text)
  ```

  {% /tab %}

  {% tab filename="document_metadata.js" label="JavaScript" %}
  ```javascript
  import { GoogleGenAI, createUserContent } from "@google/genai";
  
  const ai = new GoogleGenAI({});
  
  async function main() {
    const uploadedDoc = await ai.files.upload({
      file: "quarterly_report.pdf",
      config: { mimeType: "application/pdf" },
    });
  
    const response = await ai.models.generateContent({
      model: "gemini-4-hydrogen",
      contents: createUserContent([
        {
          fileData: {
            fileUri: uploadedDoc.uri,
            mimeType: "application/pdf",
          },
          documentMetadata: {
            startPage: 3,
            endPage: 7,
            contentLayers: ["PAGE_IMAGE"],
          },
          mediaResolution: {
            level: "MEDIA_RESOLUTION_HIGH",
          },
        },
        "Summarize the revenue bridge chart and footnotes on pages 3 through 7.",
      ]),
    });
  
    console.log(response.text);
  }
  
  main();
  ```

  {% /tab %}

  {% tab filename="document_metadata.sh" label="REST" %}
  ```shell
  curl "https://generativelanguage.googleapis.com/v1/models/gemini-4-hydrogen:generateContent" \
    -H "Content-Type: application/json" \
    -H "x-goog-api-key: $GEMINI_API_KEY" \
    -X POST \
    -d '{
      "contents": [{
        "parts": [
          {
            "fileData": {
              "fileUri": "https://generativelanguage.googleapis.com/v1beta/files/FILE_ID",
              "mimeType": "application/pdf"
            },
            "documentMetadata": {
              "startPage": 3,
              "endPage": 7,
              "contentLayers": ["PAGE_IMAGE"]
            },
            "mediaResolution": {
              "level": "MEDIA_RESOLUTION_HIGH"
            }
          },
          {"text": "Summarize the revenue bridge chart and footnotes on pages 3 through 7."}
        ]
      }]
    }'
  ```

  {% /tab %}

{% /tabs %}

### Select spreadsheet tabs and cell ranges  {% id="spreadsheet-options" %}

Use `spreadsheet_metadata` to select tabs, cell ranges, and layers in
spreadsheets. All fields are optional.

| Option | Description |
| --- | --- |
| `sheet_index` | Worksheet position in tab order (1-indexed). Omit to include all sheets, up to 50,000 cells per sheet. Values of 0 or less, or above the sheet count, return an invalid argument error. |
| `visible_cells` | Cell or range in A1 notation, such as A1:G40 or B5. Crops all selected layers to that region. |
| `content_layers` | List of layers to extract: `DATA` for evaluated values, `FORMULAS` for raw formulas, and `VISUAL` for a rendered snapshot of charts and layout. Defaults to `DATA` and `FORMULAS`. |
| `media_resolution` | Set `level` on the `Part` to `MEDIA_RESOLUTION_LOW`, `MEDIA_RESOLUTION_MEDIUM` (default), or `MEDIA_RESOLUTION_HIGH` when you include the `VISUAL` layer. |

{% tabs %}
  {% tab filename="spreadsheet_metadata.py" label="Python" %}
  ```python
  from google import genai
  from google.genai import types
  
  client = genai.Client()
  
  workbook = client.files.upload(file="financial_model.xlsx")
  
  response = client.models.generate_content(
      model="gemini-4-hydrogen",
      contents=[
          types.Part(
              file_data=types.FileData(
                  file_uri=workbook.uri,
                  mime_type="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
              ),
              spreadsheet_metadata=types.SpreadsheetMetadata(
                  sheet_index=2,
                  visible_cells="A1:H50",
                  content_layers=["DATA", "FORMULAS", "VISUAL"],
              ),
              media_resolution=types.PartMediaResolution(
                  level=types.PartMediaResolutionLevel.MEDIA_RESOLUTION_HIGH,
              ),
          ),
          "Audit the EBITDA formulas and chart in Sheet 2 (A1:H50).",
      ],
  )
  
  print(response.text)
  ```

  {% /tab %}

  {% tab filename="spreadsheet_metadata.js" label="JavaScript" %}
  ```javascript
  import { GoogleGenAI, createUserContent } from "@google/genai";
  
  const ai = new GoogleGenAI({});
  
  async function main() {
    const workbook = await ai.files.upload({
      file: "financial_model.xlsx",
      config: {
        mimeType:
          "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
      },
    });
  
    const response = await ai.models.generateContent({
      model: "gemini-4-hydrogen",
      contents: createUserContent([
        {
          fileData: {
            fileUri: workbook.uri,
            mimeType:
              "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
          },
          spreadsheetMetadata: {
            sheetIndex: 2,
            visibleCells: "A1:H50",
            contentLayers: ["DATA", "FORMULAS", "VISUAL"],
          },
          mediaResolution: {
            level: "MEDIA_RESOLUTION_HIGH",
          },
        },
        "Audit the EBITDA formulas and chart in Sheet 2 (A1:H50).",
      ]),
    });
  
    console.log(response.text);
  }
  
  main();
  ```

  {% /tab %}

  {% tab filename="spreadsheet_metadata.sh" label="REST" %}
  ```shell
  curl "https://generativelanguage.googleapis.com/v1/models/gemini-4-hydrogen:generateContent" \
    -H "Content-Type: application/json" \
    -H "x-goog-api-key: $GEMINI_API_KEY" \
    -X POST \
    -d '{
      "contents": [{
        "parts": [
          {
            "fileData": {
              "fileUri": "https://generativelanguage.googleapis.com/v1beta/files/WORKBOOK_FILE_ID",
              "mimeType": "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
            },
            "spreadsheetMetadata": {
              "sheetIndex": 2,
              "visibleCells": "A1:H50",
              "contentLayers": ["DATA", "FORMULAS", "VISUAL"]
            },
            "mediaResolution": {
              "level": "MEDIA_RESOLUTION_HIGH"
            }
          },
          {"text": "Audit the EBITDA formulas and chart in Sheet 2 (A1:H50)."}
        ]
      }]
    }'
  ```

  {% /tab %}

{% /tabs %}

## Technical details  {% id="technical-details" %}

### Limits and scaling  {% id="limits-and-scaling" %}

* File size and length: Up to 50 MB per file, 1,000 pages per PDF, or 2,000
  pages or slides per Office or OpenDocument file. These limits apply to both
  inline data and Files API uploads, and to the full uploaded file even when
  slicing.
* Spreadsheets: Up to 50,000 cells per sheet.
* Page image rendering: Gemini renders PDF and Office pages to 2-megapixel
  images (288 DPI) while preserving aspect ratio. Input pixel dimensions do not
  change token cost; use `media_resolution` to control token budget and detail.
* Other text formats: Plain-text files such as TXT, Markdown, HTML, and XML are
  extracted as text only, without layout, formatting, or charts. See
  [File input methods](/docs/file-input-methods) for all input options.

### Tokens and billing  {% id="tokens-and-billing" %}

* Gemini 4 and Gemini 3 models: Page image token counts depend on
  `media_resolution`. They use about 280 tokens per page at
  `MEDIA_RESOLUTION_LOW`, 560 at `MEDIA_RESOLUTION_MEDIUM` (default), or 1,120
  at `MEDIA_RESOLUTION_HIGH`. See [Media resolution](/docs/media-resolution) for
  details.
* Gemini 2.5 models: Flat 258 tokens per page.
* PDF native text and usage reporting: For default PDF processing without
  `document_metadata`, embedded PDF text is extracted alongside page images at
  no extra token charge. Page image tokens appear under the `IMAGE` modality in
  `usage_metadata`.
* Sliced billing: When you set `document_metadata` or `spreadsheet_metadata`,
  Gemini counts and bills only the selected pages, sheets, and content layers
  sent to the model.

## Best practices  {% id="best-practices" %}

* Rotate pages to the correct orientation before uploading.
* Avoid blurry scans or low-contrast pages.
* When sending a single page, place the text prompt after the document.

## What's next  {% id="whats-next" %}

To learn more, see the following resources:

* [File prompting strategies](/docs/files#prompt-guide): The
  Gemini API supports prompting with text, image, audio, and video data, also
  known as multimodal prompting.

* [System instructions](/docs/text-generation#system-instructions):
  System instructions let you steer the behavior of the model based on your
  specific needs and use cases.


