0
# Operations
1
2
The Operations class provides methods for managing and monitoring long-running operations in the Google Gen AI SDK. Long-running operations are used for tasks that take significant time to complete, such as video generation, file imports, and file uploads to search stores.
3
4
## Capabilities
5
6
### Get Operation Status (Videos)
7
8
Retrieves the current status of a video generation operation. This method is specifically designed for GenerateVideosOperation instances.
9
10
```typescript { .api }
11
/**
12
* Gets the status of a long-running video generation operation
13
* @param parameters - Parameters including the operation to check
14
* @returns Promise resolving to an updated GenerateVideosOperation with latest status
15
* @throws Error if operation name is missing or empty
16
*/
17
function getVideosOperation(
18
parameters: OperationGetParameters<GenerateVideosResponse, GenerateVideosOperation>
19
): Promise<GenerateVideosOperation>;
20
21
interface OperationGetParameters<T, U extends Operation<T>> {
22
operation: U;
23
config?: GetOperationConfig;
24
}
25
26
interface GetOperationConfig {
27
httpOptions?: HttpOptions;
28
abortSignal?: AbortSignal;
29
}
30
```
31
32
**Usage Example:**
33
34
```typescript
35
import { GoogleGenAI } from '@google/genai';
36
37
const client = new GoogleGenAI({
38
vertexai: true,
39
project: 'my-project',
40
location: 'us-central1'
41
});
42
43
// Start a video generation
44
const operation = await client.models.generateVideos({
45
model: 'veo-002',
46
contents: 'A cat playing piano'
47
});
48
49
console.log('Operation started:', operation.name);
50
51
// Check operation status
52
const updatedOperation = await client.operations.getVideosOperation({
53
operation: operation
54
});
55
56
if (updatedOperation.done) {
57
console.log('Video generation complete!');
58
console.log('Result:', updatedOperation.response);
59
} else {
60
console.log('Still processing...');
61
console.log('Metadata:', updatedOperation.metadata);
62
}
63
```
64
65
### Get Operation Status (Generic)
66
67
Retrieves the status of any long-running operation. This is a generic method that works with all operation types.
68
69
```typescript { .api }
70
/**
71
* Gets the status of a long-running operation
72
* @param parameters - Parameters including the operation to check
73
* @returns Promise resolving to an updated Operation with latest status
74
* @throws Error if operation name is missing or empty
75
*/
76
function get<T, U extends Operation<T>>(
77
parameters: OperationGetParameters<T, U>
78
): Promise<Operation<T>>;
79
```
80
81
**Usage Example:**
82
83
```typescript
84
// Generic operation status check
85
const operation = await client.fileSearchStores.importFile({
86
file_search_store_name: 'fileSearchStores/abc123',
87
file_name: 'files/xyz789'
88
});
89
90
// Check status using generic get method
91
const updatedOperation = await client.operations.get({
92
operation: operation
93
});
94
95
if (updatedOperation.done) {
96
console.log('Operation complete!');
97
if (updatedOperation.response) {
98
console.log('Response:', updatedOperation.response);
99
}
100
} else {
101
console.log('Operation in progress...');
102
}
103
104
// Check for errors
105
if (updatedOperation.error) {
106
console.error('Operation failed:', updatedOperation.error.message);
107
}
108
```
109
110
## Operation Types
111
112
### Base Operation Interface
113
114
All long-running operations implement the Operation interface.
115
116
```typescript { .api }
117
interface Operation<T> {
118
name?: string;
119
done?: boolean;
120
response?: T;
121
error?: Status;
122
metadata?: Record<string, unknown>;
123
_fromAPIResponse?(params: OperationFromAPIResponseParameters): Operation<T>;
124
}
125
126
interface OperationFromAPIResponseParameters {
127
apiResponse: Record<string, unknown>;
128
_isVertexAI: boolean;
129
}
130
```
131
132
### Generate Videos Operation
133
134
Specific operation type for video generation tasks.
135
136
```typescript { .api }
137
interface GenerateVideosOperation {
138
name?: string;
139
done?: boolean;
140
response?: GenerateVideosResponse;
141
error?: Status;
142
metadata?: GenerateVideosMetadata;
143
_fromAPIResponse?(params: OperationFromAPIResponseParameters): GenerateVideosOperation;
144
}
145
146
interface GenerateVideosResponse {
147
generatedVideos?: GeneratedVideo[];
148
raiMediaFilteredReasons?: string[];
149
raiMediaFilteredCount?: number;
150
}
151
152
interface GeneratedVideo {
153
video?: Blob;
154
videoUri?: string;
155
rai?: SafetyRating[];
156
}
157
158
interface GenerateVideosMetadata {
159
createTime?: string;
160
updateTime?: string;
161
progress?: number;
162
}
163
```
164
165
### Import File Operation
166
167
Operation type for importing files into File Search Stores.
168
169
```typescript { .api }
170
interface ImportFileOperation {
171
name?: string;
172
done?: boolean;
173
response?: ImportFileResponse;
174
error?: Status;
175
metadata?: Record<string, unknown>;
176
}
177
178
interface ImportFileResponse {
179
document?: Document;
180
}
181
```
182
183
### Upload to File Search Store Operation
184
185
Operation type for uploading files to File Search Stores.
186
187
```typescript { .api }
188
interface UploadToFileSearchStoreOperation {
189
name?: string;
190
done?: boolean;
191
response?: UploadToFileSearchStoreResponse;
192
error?: Status;
193
metadata?: Record<string, unknown>;
194
}
195
196
interface UploadToFileSearchStoreResponse {
197
document?: Document;
198
}
199
```
200
201
## Polling Patterns
202
203
Long-running operations typically require polling to check completion status. Here's a recommended pattern:
204
205
```typescript
206
import { GoogleGenAI } from '@google/genai';
207
208
const client = new GoogleGenAI({
209
vertexai: true,
210
project: 'my-project',
211
location: 'us-central1'
212
});
213
214
async function pollOperation(
215
operation: GenerateVideosOperation,
216
intervalMs: number = 5000,
217
timeoutMs: number = 300000
218
): Promise<GenerateVideosOperation> {
219
const startTime = Date.now();
220
221
while (!operation.done) {
222
// Check if timeout exceeded
223
if (Date.now() - startTime > timeoutMs) {
224
throw new Error('Operation polling timeout exceeded');
225
}
226
227
// Wait before next check
228
await new Promise(resolve => setTimeout(resolve, intervalMs));
229
230
// Get updated operation status
231
operation = await client.operations.getVideosOperation({
232
operation: operation
233
});
234
235
// Check for errors
236
if (operation.error) {
237
throw new Error(`Operation failed: ${operation.error.message}`);
238
}
239
240
// Log progress if available
241
if (operation.metadata?.progress !== undefined) {
242
console.log(`Progress: ${operation.metadata.progress}%`);
243
}
244
}
245
246
return operation;
247
}
248
249
// Usage
250
const videoOp = await client.models.generateVideos({
251
model: 'veo-002',
252
contents: 'A serene mountain landscape at sunset'
253
});
254
255
console.log('Video generation started...');
256
257
const completedOp = await pollOperation(videoOp);
258
259
console.log('Video generation complete!');
260
console.log('Generated videos:', completedOp.response?.generatedVideos);
261
```
262
263
## Error Handling
264
265
Operations can fail for various reasons. Always check the `error` field in the operation response.
266
267
```typescript
268
const operation = await client.operations.getVideosOperation({
269
operation: myOperation
270
});
271
272
if (operation.error) {
273
console.error('Operation failed!');
274
console.error('Error code:', operation.error.code);
275
console.error('Error message:', operation.error.message);
276
277
// Handle specific error codes
278
if (operation.error.code === 4) {
279
console.error('Deadline exceeded - operation took too long');
280
} else if (operation.error.code === 7) {
281
console.error('Permission denied');
282
}
283
284
// Additional error details
285
if (operation.error.details) {
286
console.error('Error details:', operation.error.details);
287
}
288
}
289
```
290
291
## Type Definitions
292
293
```typescript { .api }
294
interface Status {
295
code?: number;
296
message?: string;
297
details?: Array<Record<string, unknown>>;
298
}
299
300
interface FetchPredictOperationParameters {
301
operationName: string;
302
resourceName: string;
303
config?: FetchPredictOperationConfig;
304
}
305
306
interface FetchPredictOperationConfig {
307
httpOptions?: HttpOptions;
308
abortSignal?: AbortSignal;
309
}
310
311
interface GetOperationParameters {
312
operationName: string;
313
config?: GetOperationConfig;
314
}
315
```
316
317
## Platform Differences
318
319
### Vertex AI
320
- Uses `fetchPredictOperation` endpoint for checking operation status
321
- Requires `project` and `location` to be set in client initialization
322
- Operation names include full resource paths
323
324
### Gemini Developer API
325
- Uses standard operation GET endpoint
326
- Requires API key authentication
327
- Operation names use simplified format
328