or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

batches.mdcaching.mdchats.mdclient.mdcontent-generation.mdembeddings.mdfile-search-stores.mdfiles.mdimage-generation.mdindex.mdlive.mdmodels.mdoperations.mdtokens.mdtuning.mdvideo-generation.md

files.mddocs/

0

# File Management

1

2

Upload, manage, and download files for use with multimodal content generation. File management is available in the Gemini Developer API only. Files can be images, audio, video, or documents that are referenced in content generation requests.

3

4

## Capabilities

5

6

### Upload File

7

8

Upload a file to be used in content generation. Files are stored temporarily and automatically deleted after a retention period.

9

10

```python { .api }

11

class Files:

12

"""Synchronous file management API."""

13

14

def upload(

15

self,

16

*,

17

file: Union[str, Path, IO],

18

config: Optional[UploadFileConfig] = None

19

) -> File:

20

"""

21

Upload a file for use in generation requests.

22

23

Parameters:

24

file (Union[str, Path, IO]): File to upload. Can be:

25

- str or Path: File path to upload

26

- IO: File-like object (must be opened in binary mode)

27

config (UploadFileConfig, optional): Upload configuration including:

28

- mime_type: MIME type of the file (auto-detected if not provided)

29

- display_name: Display name for the file

30

31

Returns:

32

File: Uploaded file information including URI, name, and metadata.

33

34

Raises:

35

ClientError: For client errors (4xx status codes)

36

ServerError: For server errors (5xx status codes)

37

"""

38

...

39

40

class AsyncFiles:

41

"""Asynchronous file management API."""

42

43

async def upload(

44

self,

45

*,

46

file: Union[str, Path, IO],

47

config: Optional[UploadFileConfig] = None

48

) -> File:

49

"""Async version of upload."""

50

...

51

```

52

53

**Usage Example:**

54

55

```python

56

from google.genai import Client

57

from google.genai.types import UploadFileConfig

58

59

client = Client(api_key='YOUR_API_KEY')

60

61

# Upload from file path

62

config = UploadFileConfig(

63

mime_type='image/jpeg',

64

display_name='Product Photo'

65

)

66

67

file = client.files.upload(

68

file='product.jpg',

69

config=config

70

)

71

72

print(f"Uploaded file: {file.name}")

73

print(f"URI: {file.uri}")

74

print(f"State: {file.state}")

75

76

# Use in generation

77

from google.genai.types import Content, Part, FileData

78

79

content = Content(

80

parts=[

81

Part(text='Describe this image'),

82

Part(file_data=FileData(file_uri=file.uri, mime_type=file.mime_type))

83

]

84

)

85

86

response = client.models.generate_content(

87

model='gemini-2.0-flash',

88

contents=content

89

)

90

print(response.text)

91

```

92

93

### Get File

94

95

Retrieve information about an uploaded file.

96

97

```python { .api }

98

class Files:

99

"""Synchronous file management API."""

100

101

def get(self, *, name: str) -> File:

102

"""

103

Get file information.

104

105

Parameters:

106

name (str): File name (from File.name) in format 'files/{file_id}'.

107

108

Returns:

109

File: File information including state, size, and metadata.

110

111

Raises:

112

ClientError: For client errors including 404 if file not found

113

ServerError: For server errors (5xx status codes)

114

"""

115

...

116

117

class AsyncFiles:

118

"""Asynchronous file management API."""

119

120

async def get(self, *, name: str) -> File:

121

"""Async version of get."""

122

...

123

```

124

125

**Usage Example:**

126

127

```python

128

from google.genai import Client

129

130

client = Client(api_key='YOUR_API_KEY')

131

132

# Get file info

133

file = client.files.get(name='files/abc123')

134

135

print(f"Name: {file.display_name}")

136

print(f"Size: {file.size_bytes} bytes")

137

print(f"State: {file.state}")

138

print(f"Created: {file.create_time}")

139

print(f"Expires: {file.expiration_time}")

140

```

141

142

### Delete File

143

144

Delete an uploaded file. Files are automatically deleted after their expiration time, but you can delete them earlier if needed.

145

146

```python { .api }

147

class Files:

148

"""Synchronous file management API."""

149

150

def delete(self, *, name: str) -> None:

151

"""

152

Delete a file.

153

154

Parameters:

155

name (str): File name in format 'files/{file_id}'.

156

157

Raises:

158

ClientError: For client errors including 404 if file not found

159

ServerError: For server errors (5xx status codes)

160

"""

161

...

162

163

class AsyncFiles:

164

"""Asynchronous file management API."""

165

166

async def delete(self, *, name: str) -> None:

167

"""Async version of delete."""

168

...

169

```

170

171

**Usage Example:**

172

173

```python

174

from google.genai import Client

175

176

client = Client(api_key='YOUR_API_KEY')

177

178

# Delete file

179

client.files.delete(name='files/abc123')

180

print("File deleted")

181

```

182

183

### Download File

184

185

Download the contents of an uploaded file.

186

187

```python { .api }

188

class Files:

189

"""Synchronous file management API."""

190

191

def download(self, *, name: str, path: Optional[str] = None) -> bytes:

192

"""

193

Download file contents.

194

195

Parameters:

196

name (str): File name in format 'files/{file_id}'.

197

path (str, optional): Local file path to save to. If not provided,

198

returns file contents as bytes without saving.

199

200

Returns:

201

bytes: File contents. If path is provided, also saves to file.

202

203

Raises:

204

ClientError: For client errors including 404 if file not found

205

ServerError: For server errors (5xx status codes)

206

"""

207

...

208

209

class AsyncFiles:

210

"""Asynchronous file management API."""

211

212

async def download(self, *, name: str, path: Optional[str] = None) -> bytes:

213

"""Async version of download."""

214

...

215

```

216

217

**Usage Example:**

218

219

```python

220

from google.genai import Client

221

222

client = Client(api_key='YOUR_API_KEY')

223

224

# Download to file

225

data = client.files.download(name='files/abc123', path='downloaded.jpg')

226

print(f"Downloaded {len(data)} bytes")

227

228

# Download to memory

229

data = client.files.download(name='files/abc123')

230

# Process data in memory

231

```

232

233

### List Files

234

235

List all uploaded files with optional pagination.

236

237

```python { .api }

238

class Files:

239

"""Synchronous file management API."""

240

241

def list(

242

self,

243

*,

244

config: Optional[ListFilesConfig] = None

245

) -> Union[Pager[File], Iterator[File]]:

246

"""

247

List uploaded files.

248

249

Parameters:

250

config (ListFilesConfig, optional): List configuration including:

251

- page_size: Number of files per page (default: 50, max: 100)

252

- page_token: Token for pagination

253

254

Returns:

255

Union[Pager[File], Iterator[File]]: Paginated file list. If page_size

256

is set, returns Pager for manual pagination. Otherwise, returns

257

Iterator that automatically handles pagination.

258

259

Raises:

260

ClientError: For client errors (4xx status codes)

261

ServerError: For server errors (5xx status codes)

262

"""

263

...

264

265

class AsyncFiles:

266

"""Asynchronous file management API."""

267

268

async def list(

269

self,

270

*,

271

config: Optional[ListFilesConfig] = None

272

) -> Union[AsyncPager[File], AsyncIterator[File]]:

273

"""Async version of list."""

274

...

275

```

276

277

**Usage Example:**

278

279

```python

280

from google.genai import Client

281

282

client = Client(api_key='YOUR_API_KEY')

283

284

# List all files (auto-pagination)

285

for file in client.files.list():

286

print(f"{file.display_name}: {file.name} ({file.state})")

287

288

# Manual pagination

289

from google.genai.types import ListFilesConfig

290

291

config = ListFilesConfig(page_size=10)

292

pager = client.files.list(config=config)

293

294

print(f"Page 1: {len(pager.page)} files")

295

for file in pager.page:

296

print(f" {file.display_name}")

297

298

# Get next page

299

pager.next_page()

300

print(f"Page 2: {len(pager.page)} files")

301

```

302

303

## Types

304

305

```python { .api }

306

from typing import Optional, Union, IO, Iterator, AsyncIterator

307

from pathlib import Path

308

from enum import Enum

309

from datetime import datetime

310

311

# Configuration types

312

class UploadFileConfig:

313

"""

314

Configuration for file upload.

315

316

Attributes:

317

mime_type (str, optional): MIME type of the file. If not provided, will be

318

auto-detected from file extension or content.

319

display_name (str, optional): Human-readable display name for the file.

320

"""

321

mime_type: Optional[str] = None

322

display_name: Optional[str] = None

323

324

class ListFilesConfig:

325

"""

326

Configuration for listing files.

327

328

Attributes:

329

page_size (int, optional): Number of files per page (1-100). Default: 50.

330

page_token (str, optional): Token from previous response for pagination.

331

"""

332

page_size: Optional[int] = None

333

page_token: Optional[str] = None

334

335

# Response types

336

class File:

337

"""

338

Uploaded file information.

339

340

Attributes:

341

name (str): File resource name in format 'files/{file_id}'.

342

display_name (str, optional): Display name for the file.

343

mime_type (str): MIME type of the file.

344

size_bytes (int): File size in bytes.

345

create_time (datetime): When file was created.

346

update_time (datetime): When file was last updated.

347

expiration_time (datetime): When file will be automatically deleted.

348

sha256_hash (bytes): SHA256 hash of file contents.

349

uri (str): URI for referencing the file in API requests.

350

state (FileState): Current processing state of the file.

351

error (FileError, optional): Error if file processing failed.

352

"""

353

name: str

354

display_name: Optional[str] = None

355

mime_type: str

356

size_bytes: int

357

create_time: datetime

358

update_time: datetime

359

expiration_time: datetime

360

sha256_hash: bytes

361

uri: str

362

state: FileState

363

error: Optional[FileError] = None

364

365

class FileState(Enum):

366

"""File processing state."""

367

STATE_UNSPECIFIED = 'STATE_UNSPECIFIED'

368

PROCESSING = 'PROCESSING'

369

ACTIVE = 'ACTIVE'

370

FAILED = 'FAILED'

371

372

class FileError:

373

"""

374

File processing error.

375

376

Attributes:

377

code (int): Error code.

378

message (str): Error message.

379

"""

380

code: int

381

message: str

382

383

class FileData:

384

"""

385

Reference to uploaded file for use in content.

386

387

Attributes:

388

file_uri (str): URI from File.uri.

389

mime_type (str): MIME type from File.mime_type.

390

"""

391

file_uri: str

392

mime_type: str

393

394

# Pager types

395

class Pager[T]:

396

"""

397

Synchronous pager for paginated results.

398

399

Attributes:

400

page (list[T]): Current page of items.

401

page_size (int): Number of items per page.

402

403

Methods:

404

next_page(): Fetch next page of results.

405

"""

406

page: list[T]

407

page_size: int

408

409

def next_page(self) -> None:

410

"""Fetch next page and update self.page."""

411

...

412

413

def __iter__(self) -> Iterator[T]:

414

"""Iterate over all items across pages."""

415

...

416

417

class AsyncPager[T]:

418

"""

419

Asynchronous pager for paginated results.

420

421

Attributes:

422

page (list[T]): Current page of items.

423

page_size (int): Number of items per page.

424

425

Methods:

426

next_page(): Fetch next page of results.

427

"""

428

page: list[T]

429

page_size: int

430

431

async def next_page(self) -> None:

432

"""Fetch next page and update self.page."""

433

...

434

435

async def __aiter__(self) -> AsyncIterator[T]:

436

"""Async iterate over all items across pages."""

437

...

438

439

# TypedDict variants

440

class UploadFileConfigDict(TypedDict, total=False):

441

"""TypedDict variant of UploadFileConfig."""

442

mime_type: str

443

display_name: str

444

445

class ListFilesConfigDict(TypedDict, total=False):

446

"""TypedDict variant of ListFilesConfig."""

447

page_size: int

448

page_token: str

449

```

450