0
# Long-Running Operations
1
2
Monitor and retrieve status of long-running operations like video generation, file imports, and other asynchronous tasks. Operations provide a way to track progress and retrieve results for tasks that take significant time to complete.
3
4
## Capabilities
5
6
### Get Operation
7
8
Retrieve the current status and result of a long-running operation.
9
10
```python { .api }
11
class Operations:
12
"""Synchronous long-running operations API."""
13
14
def get(self, operation: Union[Operation, str]) -> Operation:
15
"""
16
Get operation status and result.
17
18
Parameters:
19
operation (Union[Operation, str]): Operation to check. Can be:
20
- Operation: Operation object to refresh
21
- str: Operation name/resource name
22
23
Returns:
24
Operation: Updated operation with current status. Check operation.done
25
to see if complete. If done, check operation.error for errors or
26
operation.response for results.
27
28
Raises:
29
ClientError: For client errors including 404 if operation not found
30
ServerError: For server errors (5xx status codes)
31
"""
32
...
33
34
class AsyncOperations:
35
"""Asynchronous long-running operations API."""
36
37
async def get(self, operation: Union[Operation, str]) -> Operation:
38
"""Async version of get."""
39
...
40
```
41
42
**Usage Example - Video Generation:**
43
44
```python
45
import time
46
from google.genai import Client
47
48
client = Client(vertexai=True, project='PROJECT_ID', location='us-central1')
49
50
# Start video generation
51
operation = client.models.generate_videos(
52
model='veo-2.0-generate-001',
53
prompt='A cat playing with a ball'
54
)
55
56
print(f"Operation started: {operation.name}")
57
print(f"Done: {operation.done}")
58
59
# Poll for completion
60
while not operation.done:
61
print("Waiting for completion...")
62
time.sleep(10)
63
64
# Refresh operation status
65
operation = client.operations.get(operation)
66
print(f"Done: {operation.done}")
67
68
# Check result
69
if operation.error:
70
print(f"Operation failed: {operation.error.message}")
71
else:
72
print("Operation succeeded!")
73
response = operation.response
74
75
# Access video generation response
76
for i, video in enumerate(response.generated_videos):
77
with open(f'video_{i}.mp4', 'wb') as f:
78
f.write(video.video.data)
79
print(f"Saved video_{i}.mp4")
80
```
81
82
**Usage Example - File Import:**
83
84
```python
85
from google.genai import Client
86
from google.genai.types import ImportFileSource
87
88
client = Client(vertexai=True, project='PROJECT_ID', location='us-central1')
89
90
# Start file import
91
source = ImportFileSource(gcs_uri='gs://my-bucket/document.pdf')
92
operation = client.file_search_stores.import_file(
93
store='fileSearchStores/abc123',
94
source=source
95
)
96
97
print(f"Import operation: {operation.name}")
98
99
# Poll until done
100
while not operation.done:
101
import time
102
time.sleep(5)
103
operation = client.operations.get(operation)
104
105
if operation.error:
106
print(f"Import failed: {operation.error.message}")
107
else:
108
print("Import completed successfully")
109
```
110
111
**Usage Example - Async Polling:**
112
113
```python
114
import asyncio
115
from google.genai import Client
116
117
async def wait_for_operation():
118
client = Client(vertexai=True, project='PROJECT_ID', location='us-central1')
119
120
# Start operation
121
operation = await client.aio.models.generate_videos(
122
model='veo-2.0-generate-001',
123
prompt='A sunset over mountains'
124
)
125
126
print(f"Operation: {operation.name}")
127
128
# Poll asynchronously
129
while not operation.done:
130
print("Checking status...")
131
await asyncio.sleep(10)
132
operation = await client.aio.operations.get(operation)
133
134
if operation.error:
135
print(f"Failed: {operation.error.message}")
136
else:
137
print(f"Success! Generated {len(operation.response.generated_videos)} video(s)")
138
139
asyncio.run(wait_for_operation())
140
```
141
142
**Usage Example - Operation Metadata:**
143
144
```python
145
from google.genai import Client
146
147
client = Client(vertexai=True, project='PROJECT_ID', location='us-central1')
148
149
# Get operation
150
operation = client.operations.get('operations/abc123')
151
152
print(f"Operation: {operation.name}")
153
print(f"Done: {operation.done}")
154
155
# Check metadata for progress
156
if operation.metadata:
157
print(f"Metadata: {operation.metadata}")
158
# Metadata structure varies by operation type
159
# May include progress percentage, timestamps, etc.
160
161
# Check if operation completed
162
if operation.done:
163
if operation.error:
164
print(f"Error code: {operation.error.code}")
165
print(f"Error message: {operation.error.message}")
166
if operation.error.details:
167
print(f"Details: {operation.error.details}")
168
else:
169
print("Operation completed successfully")
170
# Access operation.response for results
171
```
172
173
## Types
174
175
```python { .api }
176
from typing import Optional, Union, Any, Dict
177
178
# Operation base class
179
class Operation:
180
"""
181
Long-running operation.
182
183
This is an abstract base class. Specific operation types inherit from it
184
(e.g., GenerateVideosOperation, ImportFileOperation).
185
186
Attributes:
187
name (str): Operation resource name for polling.
188
Format varies by operation type (e.g., 'operations/{id}').
189
done (bool): Whether operation has completed (successfully or with error).
190
error (OperationError, optional): Error if operation failed. Only set if
191
done=True and operation failed.
192
response (Any, optional): Operation result if successful. Only set if
193
done=True and operation succeeded. Type depends on operation:
194
- GenerateVideosOperation.response: GenerateVideosResponse
195
- ImportFileOperation.response: ImportFileResponse
196
- etc.
197
metadata (Dict[str, Any], optional): Operation metadata including:
198
- Progress information
199
- Timestamps
200
- Operation-specific data
201
Structure varies by operation type.
202
"""
203
name: str
204
done: bool
205
error: Optional[OperationError] = None
206
response: Optional[Any] = None
207
metadata: Optional[Dict[str, Any]] = None
208
209
class OperationError:
210
"""
211
Error information for failed operation.
212
213
Attributes:
214
code (int): Error code (HTTP status code or gRPC code).
215
message (str): Human-readable error message.
216
details (list, optional): Additional error details. Structure varies by
217
error type and may include:
218
- Error metadata
219
- Retry information
220
- Debugging information
221
"""
222
code: int
223
message: str
224
details: Optional[list] = None
225
226
# Specific operation types (inherit from Operation)
227
class GenerateVideosOperation(Operation):
228
"""
229
Video generation operation.
230
231
Attributes:
232
response (GenerateVideosResponse, optional): Video generation response when done.
233
"""
234
response: Optional[GenerateVideosResponse] = None
235
236
class ImportFileOperation(Operation):
237
"""
238
File import operation.
239
240
Attributes:
241
response (Dict, optional): Import response when done.
242
"""
243
response: Optional[Dict] = None
244
245
class UploadToFileSearchStoreOperation(Operation):
246
"""
247
File upload operation for file search stores.
248
249
Attributes:
250
response (Dict, optional): Upload response when done.
251
"""
252
response: Optional[Dict] = None
253
254
# Response types (referenced by operations)
255
class GenerateVideosResponse:
256
"""
257
Video generation response (from GenerateVideosOperation).
258
259
Attributes:
260
generated_videos (list[GeneratedVideo]): Generated videos.
261
rai_media_filtered_count (int, optional): Safety-filtered count.
262
rai_media_filtered_reasons (list[str], optional): Filter reasons.
263
"""
264
generated_videos: list[GeneratedVideo]
265
rai_media_filtered_count: Optional[int] = None
266
rai_media_filtered_reasons: Optional[list[str]] = None
267
268
class GeneratedVideo:
269
"""
270
Generated video with metadata.
271
272
Attributes:
273
video (Video): Video object with data.
274
generation_seed (int, optional): Generation seed.
275
"""
276
video: Video
277
generation_seed: Optional[int] = None
278
279
class Video:
280
"""
281
Video data.
282
283
Attributes:
284
data (bytes): Video binary data.
285
mime_type (str): MIME type (e.g., 'video/mp4').
286
"""
287
data: bytes
288
mime_type: str
289
```
290