@umituz/react-native-ai-gemini-provider 1.14.28 → 1.14.30

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (49) hide show
  1. package/package.json +41 -3
  2. package/src/domain/README.md +232 -0
  3. package/src/domain/constants/README.md +191 -0
  4. package/src/domain/entities/README.md +238 -0
  5. package/src/infrastructure/README.md +252 -0
  6. package/src/infrastructure/cache/CACHE_SYSTEM.md +213 -0
  7. package/src/infrastructure/cache/README.md +213 -0
  8. package/src/infrastructure/content/CONTENT_BUILDER.md +175 -0
  9. package/src/infrastructure/content/README.md +175 -0
  10. package/src/infrastructure/interceptors/README.md +226 -0
  11. package/src/infrastructure/interceptors/REQUEST_INTERCEPTORS.md +171 -0
  12. package/src/infrastructure/job/JOB_MANAGER.md +174 -0
  13. package/src/infrastructure/job/README.md +194 -0
  14. package/src/infrastructure/response/README.md +187 -0
  15. package/src/infrastructure/response/RESPONSE_FORMATTER.md +185 -0
  16. package/src/infrastructure/services/CORE_CLIENT_SERVICE.md +202 -0
  17. package/src/infrastructure/services/FEATURE_MODEL_SELECTOR_SERVICE.md +206 -0
  18. package/src/infrastructure/services/GENERATION_EXECUTOR_SERVICE.md +176 -0
  19. package/src/infrastructure/services/IMAGE_EDIT_SERVICE.md +169 -0
  20. package/src/infrastructure/services/IMAGE_GENERATION_SERVICE.md +166 -0
  21. package/src/infrastructure/services/JOB_PROCESSOR_SERVICE.md +174 -0
  22. package/src/infrastructure/services/PROVIDER_INITIALIZER_SERVICE.md +176 -0
  23. package/src/infrastructure/services/README.md +233 -0
  24. package/src/infrastructure/services/RETRY_SERVICE.md +178 -0
  25. package/src/infrastructure/services/STREAMING_SERVICE.md +166 -0
  26. package/src/infrastructure/services/STRUCTURED_TEXT_SERVICE.md +175 -0
  27. package/src/infrastructure/services/TEXT_GENERATION_SERVICE.md +160 -0
  28. package/src/infrastructure/services/VEO_HTTP_CLIENT_SERVICE.md +179 -0
  29. package/src/infrastructure/services/VEO_POLLING_SERVICE.md +173 -0
  30. package/src/infrastructure/services/VIDEO_DOWNLOADER_SERVICE.md +166 -0
  31. package/src/infrastructure/services/VIDEO_ERROR_HANDLER_SERVICE.md +185 -0
  32. package/src/infrastructure/services/VIDEO_GENERATION_SERVICE.md +176 -0
  33. package/src/infrastructure/services/VIDEO_URL_EXTRACTOR_SERVICE.md +186 -0
  34. package/src/infrastructure/services/gemini-provider.ts +9 -2
  35. package/src/infrastructure/telemetry/README.md +203 -0
  36. package/src/infrastructure/telemetry/TELEMETRY_SYSTEM.md +200 -0
  37. package/src/infrastructure/utils/DATA_TRANSFORMER_UTILS.md +175 -0
  38. package/src/infrastructure/utils/ERROR_MAPPER.md +170 -0
  39. package/src/infrastructure/utils/ERROR_UTILITIES.md +208 -0
  40. package/src/infrastructure/utils/IMAGE_PREPARER_UTILS.md +185 -0
  41. package/src/infrastructure/utils/INPUT_BUILDERS.md +214 -0
  42. package/src/infrastructure/utils/MODEL_VALIDATION_UTILS.md +189 -0
  43. package/src/infrastructure/utils/PERFORMANCE_UTILITIES.md +477 -0
  44. package/src/infrastructure/utils/PERFORMANCE_UTILS.md +219 -0
  45. package/src/infrastructure/utils/README.md +289 -0
  46. package/src/presentation/README.md +187 -0
  47. package/src/presentation/hooks/README.md +188 -0
  48. package/src/presentation/hooks/USE_GEMINI_HOOK.md +226 -0
  49. package/src/providers/README.md +247 -0
@@ -0,0 +1,175 @@
1
+ # Structured Text Generation Service
2
+
3
+ Generates structured JSON output with schema validation. Produces type-safe content with defined structure.
4
+
5
+ ## 📍 Import Path
6
+
7
+ ```
8
+ import { geminiStructuredTextService } from '@umituz/react-native-ai-gemini-provider';
9
+ ```
10
+
11
+ ## 🎯 Purpose
12
+
13
+ Use this service to generate AI responses in structured JSON format with type safety and schema validation.
14
+
15
+ **When to use:**
16
+ - Generate JSON with specific structure
17
+ - Create type-safe AI responses
18
+ - Extract structured data from text
19
+ - Build forms and data entry with AI
20
+ - Generate configuration objects
21
+
22
+ ## 📌 Strategy
23
+
24
+ Structured generation ensures type safety and validates output. This service:
25
+ - Accepts JSON schema for output validation
26
+ - Returns typed responses matching schema
27
+ - Validates AI-generated JSON structure
28
+ - Provides type-safe interfaces
29
+ - Handles parsing and validation errors
30
+
31
+ **Key Decision**: Use JSON Schema for validation. The service validates AI output against the schema and returns typed results, ensuring data integrity.
32
+
33
+ ## ⚠️ Rules
34
+
35
+ ### Usage Rules
36
+ - **MUST** initialize provider with API key before use
37
+ - **MUST** provide valid JSON schema
38
+ - **SHOULD** define TypeScript interfaces for type safety
39
+ - **MUST** handle schema validation errors
40
+ - **SHOULD** specify required vs optional fields
41
+
42
+ ### Schema Rules
43
+ - **MUST** use valid JSON Schema format
44
+ - **SHOULD** include field descriptions
45
+ - **MUST** specify required fields explicitly
46
+ - **SHOULD** use appropriate types (string, number, boolean, array, object)
47
+ - **MUST NOT** create overly complex nested schemas
48
+
49
+ ### Error Handling Rules
50
+ - **MUST** catch and handle `GeminiError`
51
+ - **MUST** handle PARSING_ERROR for invalid JSON
52
+ - **MUST** handle VALIDATION errors for schema mismatches
53
+ - **SHOULD** provide fallback values when appropriate
54
+ - **MUST NOT** expose API keys in errors
55
+
56
+ ## 🤖 AI Agent Guidelines
57
+
58
+ ### When Modifying This Service
59
+ 1. **READ** the implementation file first
60
+ 2. **UNDERSTAND** schema validation logic
61
+ 3. **MAINTAIN** backward compatibility
62
+ 4. **ADD** tests for new functionality
63
+ 5. **UPDATE** type definitions
64
+
65
+ ### When Adding New Features
66
+ 1. **CHECK** if similar feature exists
67
+ 2. **FOLLOW** existing patterns
68
+ 3. **USE** established error handling
69
+ 4. **DOCUMENT** in type definitions
70
+ 5. **ADD** examples to tests (not docs)
71
+
72
+ ### When Fixing Bugs
73
+ 1. **REPRODUCE** bug locally first
74
+ 2. **IDENTIFY** root cause
75
+ 3. **FIX** with minimal changes
76
+ 4. **ADD** regression test
77
+ 5. **VERIFY** all tests pass
78
+
79
+ ### Code Style Rules
80
+ - **USE** async/await (no callbacks)
81
+ - **VALIDATE** inputs at function entry
82
+ - **THROW** typed errors (`GeminiError`)
83
+ - **LOG** important operations
84
+ - **COMMENT** complex logic only
85
+
86
+ ## 📦 Available Methods
87
+
88
+ ### `generateStructuredText<T>(model, prompt, schema, config?)`
89
+
90
+ Generate structured JSON output based on provided schema.
91
+
92
+ **Refer to**: [`gemini-structured-text.service.ts`](./gemini-structured-text.service.ts)
93
+
94
+ ## 🔗 Related Modules
95
+
96
+ - **Domain Types**: [`domain/entities/README.md`](../domain/entities/README.md)
97
+ - **Text Generation**: [`TEXT_GENERATION_SERVICE.md`](./TEXT_GENERATION_SERVICE.md)
98
+ - **Error Utilities**: [`ERROR_UTILITIES.md`](../infrastructure/utils/ERROR_UTILITIES.md)
99
+
100
+ ## 📋 Configuration Reference
101
+
102
+ ### JSON Schema Format
103
+
104
+ ```typescript
105
+ {
106
+ type: 'object',
107
+ properties: {
108
+ fieldName: {
109
+ type: 'string' | 'number' | 'boolean' | 'array' | 'object',
110
+ description?: string,
111
+ enum?: string[]
112
+ }
113
+ },
114
+ required: string[]
115
+ }
116
+ ```
117
+
118
+ ### Schema Best Practices
119
+ - Use detailed field descriptions
120
+ - Specify required fields explicitly
121
+ - Use appropriate data types
122
+ - Define nested objects clearly
123
+ - Add enum constraints for fixed values
124
+
125
+ ## 🎓 Usage Patterns
126
+
127
+ ### Simple JSON Generation
128
+ 1. Define TypeScript interface for result
129
+ 2. Create JSON schema matching interface
130
+ 3. Call `generateStructuredText()` with prompt and schema
131
+ 4. Receive typed result matching schema
132
+ 5. Handle validation errors if schema mismatch
133
+
134
+ ### Nested Objects
135
+ 1. Define nested interfaces
136
+ 2. Create nested schema structure
137
+ 3. Specify required fields at each level
138
+ 4. Generate and validate nested structure
139
+ 5. Handle result as typed object
140
+
141
+ ### Array Output Schema
142
+ 1. Define interface with array properties
143
+ 2. Create schema with array item types
144
+ 3. Specify array item structure
145
+ 4. Generate and validate array results
146
+ 5. Use typed results in application
147
+
148
+ ### Enum Validation
149
+ 1. Define interface with enum-like fields
150
+ 2. Create schema with enum constraints
151
+ 3. Specify allowed values
152
+ 4. Generate and validate against enum
153
+ 5. Handle type-safe results
154
+
155
+ ## 🚨 Common Pitfalls
156
+
157
+ ### Don't
158
+ - Use minimal schemas without descriptions
159
+ - Make all fields required (too strict)
160
+ - Use `any` type instead of proper interfaces
161
+ - Create overly complex nested schemas
162
+ - Ignore validation errors
163
+
164
+ ### Do
165
+ - Provide detailed field descriptions
166
+ - Explicitly mark required vs optional fields
167
+ - Use TypeScript interfaces for type safety
168
+ - Test schemas with sample data
169
+ - Handle parsing and validation errors
170
+ - Use fallback values for non-critical fields
171
+
172
+ ---
173
+
174
+ **Last Updated**: 2025-01-08
175
+ **See Also**: [AI_GUIDELINES.md](../../AI_GUIDELINES.md)
@@ -0,0 +1,160 @@
1
+ # Text Generation Service
2
+
3
+ Generates text content using Google Gemini API models.
4
+
5
+ ## 📍 Import Path
6
+
7
+ ```
8
+ import { geminiTextGenerationService } from '@umituz/react-native-ai-gemini-provider';
9
+ ```
10
+
11
+ ## 🎯 Purpose
12
+
13
+ Use this service to generate AI-powered text content. Supports single prompts, conversational interfaces, and multimodal input with images.
14
+
15
+ **When to use:**
16
+ - Text generation (stories, summaries, translations)
17
+ - Chat interfaces and conversational AI
18
+ - Content analysis with images
19
+ - Any text-based AI generation task
20
+
21
+ ## 📌 Strategy
22
+
23
+ Text generation is the foundation of most AI interactions. This service:
24
+ - Abstracts Gemini API complexity
25
+ - Provides type-safe interfaces
26
+ - Handles errors consistently
27
+ - Supports streaming for real-time responses
28
+ - Integrates with retry logic
29
+
30
+ **Key Decision**: We use streaming by default for better UX, but fallback to non-streaming for compatibility.
31
+
32
+ ## ⚠️ Rules
33
+
34
+ ### Usage Rules
35
+ - **MUST** initialize provider with API key before use
36
+ - **MUST** handle errors appropriately
37
+ - **MUST** validate model IDs before use
38
+ - **SHOULD** use streaming for long responses
39
+ - **MUST NOT** exceed rate limits
40
+
41
+ ### Configuration Rules
42
+ - **MUST** set appropriate `maxOutputTokens`
43
+ - **SHOULD** adjust `temperature` based on use case
44
+ - **MUST** use valid model IDs
45
+ - **SHOULD** implement retry logic for failures
46
+
47
+ ### Error Handling Rules
48
+ - **MUST** catch and handle `GeminiError`
49
+ - **MUST** provide user-friendly error messages
50
+ - **SHOULD** log errors for debugging
51
+ - **MUST NOT** expose API keys in errors
52
+
53
+ ## 🤖 AI Agent Guidelines
54
+
55
+ ### When Modifying This Service
56
+ 1. **READ** the implementation file first
57
+ 2. **UNDERSTAND** current error handling
58
+ 3. **MAINTAIN** backward compatibility
59
+ 4. **ADD** tests for new functionality
60
+ 5. **UPDATE** type definitions
61
+
62
+ ### When Adding New Features
63
+ 1. **CHECK** if similar feature exists
64
+ 2. **FOLLOW** existing patterns
65
+ 3. **USE** established error handling
66
+ 4. **DOCUMENT** in type definitions
67
+ 5. **ADD** examples to tests (not docs)
68
+
69
+ ### When Fixing Bugs
70
+ 1. **REPRODUCE** bug locally first
71
+ 2. **IDENTIFY** root cause
72
+ 3. **FIX** with minimal changes
73
+ 4. **ADD** regression test
74
+ 5. **VERIFY** all tests pass
75
+
76
+ ### Code Style Rules
77
+ - **USE** async/await (no callbacks)
78
+ - **VALIDATE** inputs at function entry
79
+ - **THROW** typed errors (`GeminiError`)
80
+ - **LOG** important operations
81
+ - **COMMENT** complex logic only
82
+
83
+ ## 📦 Available Methods
84
+
85
+ ### `generateText(model, prompt, config?)`
86
+ Generate text from a prompt.
87
+
88
+ **Refer to**: [`gemini-text-generation.service.ts`](./gemini-text-generation.service.ts)
89
+
90
+ ### `generateContent(model, contents, config?)`
91
+ Generate content with structured messages.
92
+
93
+ **Refer to**: [`gemini-text-generation.service.ts`](./gemini-text-generation.service.ts)
94
+
95
+ ### `generateWithImages(model, prompt, images, config?)`
96
+ Generate text with image context.
97
+
98
+ **Refer to**: [`gemini-text-generation.service.ts`](./gemini-text-generation.service.ts)
99
+
100
+ ### `generateTextStream(model, prompt, config?)`
101
+ Generate text with streaming response.
102
+
103
+ **Refer to**: [`gemini-text-generation.service.ts`](./gemini-text-generation.service.ts)
104
+
105
+ ## 🔗 Related Modules
106
+
107
+ - **Domain Types**: [`domain/entities/README.md`](../domain/entities/README.md)
108
+ - **Image Generation**: [`IMAGE_GENERATION_SERVICE.md`](./IMAGE_GENERATION_SERVICE.md)
109
+ - **Retry Service**: [`RETRY_SERVICE.md`](./RETRY_SERVICE.md)
110
+ - **Streaming Service**: [`STREAMING_SERVICE.md`](./STREAMING_SERVICE.md)
111
+
112
+ ## 📋 Configuration Reference
113
+
114
+ ### Generation Config
115
+ See: [`domain/entities/README.md`](../domain/entities/README.md)
116
+
117
+ ### Model Selection
118
+ See: [`FEATURE_MODEL_SELECTOR_SERVICE.md`](./FEATURE_MODEL_SELECTOR_SERVICE.md)
119
+
120
+ ### Error Types
121
+ See: [`ERROR_UTILITIES.md`](../infrastructure/utils/ERROR_UTILITIES.md)
122
+
123
+ ## 🎓 Usage Patterns
124
+
125
+ ### Basic Generation
126
+ 1. Import service
127
+ 2. Call `generateText()` with model and prompt
128
+ 3. Handle response or error
129
+ 4. Display result to user
130
+
131
+ ### With Retry Logic
132
+ 1. Use retry service wrapper
133
+ 2. Configure max retries and delays
134
+ 3. Handle retryable errors
135
+ 4. Provide feedback to user
136
+
137
+ ### Streaming
138
+ 1. Use `generateTextStream()`
139
+ 2. Handle chunks in callback
140
+ 3. Update UI progressively
141
+ 4. Handle stream completion
142
+
143
+ ## 🚨 Common Pitfalls
144
+
145
+ ### Don't
146
+ - Use hardcoded model IDs
147
+ - Ignore error handling
148
+ - Exceed rate limits
149
+ - Skip initialization
150
+
151
+ ### Do
152
+ - Use feature model selector
153
+ - Handle all errors
154
+ - Implement backoff
155
+ - Initialize provider
156
+
157
+ ---
158
+
159
+ **Last Updated**: 2025-01-08
160
+ **See Also**: [AI_GUIDELINES.md](../../AI_GUIDELINES.md)
@@ -0,0 +1,179 @@
1
+ # Veo HTTP Client Service
2
+
3
+ Makes HTTP requests to Google Veo API for video generation. Initiates video generation operations and queries status.
4
+
5
+ ## 📍 Import Path
6
+
7
+ ```
8
+ import { veoHttpClient } from '@umituz/react-native-ai-gemini-provider';
9
+ ```
10
+
11
+ ## 🎯 Purpose
12
+
13
+ Use this service to communicate directly with Veo API for video generation operations. Handles HTTP requests for starting and polling video generation.
14
+
15
+ **When to use:**
16
+ - Start video generation operations
17
+ - Query operation status
18
+ - Access raw Veo API responses
19
+ - Implement custom polling logic
20
+ - Debug video generation issues
21
+
22
+ ## 📌 Strategy
23
+
24
+ Veo API uses asynchronous operations with polling. This service:
25
+ - Sends HTTP requests to Veo API endpoints
26
+ - Initiates video generation operations
27
+ - Queries operation status
28
+ - Returns raw API responses
29
+ - Implements retry logic for network failures
30
+
31
+ **Key Decision**: Use `veo-polling.service.ts` for automatic polling instead of manually polling with this service. This service is for advanced use cases requiring custom polling logic.
32
+
33
+ ## ⚠️ Rules
34
+
35
+ ### Usage Rules
36
+ - **MUST** provide valid API key
37
+ - **MUST** use valid Veo model IDs
38
+ - **SHOULD** save operation names for polling
39
+ - **MUST** handle network errors appropriately
40
+ - **SHOULD NOT** poll manually (use polling service)
41
+
42
+ ### Request Rules
43
+ - **MUST** provide prompt in instances array
44
+ - **SHOULD** set appropriate aspect ratio
45
+ - **MUST** use supported parameters
46
+ - **SHOULD** include negative prompt when needed
47
+ - **MUST NOT** exceed request size limits
48
+
49
+ ### Error Handling Rules
50
+ - **MUST** catch and handle HTTP errors
51
+ - **SHOULD** check operation error field
52
+ - **MUST** validate operation responses
53
+ - **SHOULD** implement retry logic for failures
54
+ - **MUST NOT** expose API keys in errors
55
+
56
+ ## 🤖 AI Agent Guidelines
57
+
58
+ ### When Modifying This Service
59
+ 1. **READ** the implementation file first
60
+ 2. **UNDERSTAND** Veo API structure
61
+ 3. **MAINTAIN** backward compatibility
62
+ 4. **ADD** tests for new functionality
63
+ 5. **UPDATE** type definitions
64
+
65
+ ### When Adding New Features
66
+ 1. **CHECK** if feature exists in Veo API
67
+ 2. **FOLLOW** existing request patterns
68
+ 3. **USE** established error handling
69
+ 4. **DOCUMENT** in type definitions
70
+ 5. **ADD** examples to tests (not docs)
71
+
72
+ ### When Fixing Bugs
73
+ 1. **REPRODUCE** bug locally first
74
+ 2. **IDENTIFY** root cause
75
+ 3. **FIX** with minimal changes
76
+ 4. **ADD** regression test
77
+ 5. **VERIFY** all tests pass
78
+
79
+ ### Code Style Rules
80
+ - **USE** async/await (no callbacks)
81
+ - **VALIDATE** inputs at function entry
82
+ - **THROW** typed errors (`GeminiError`)
83
+ - **LOG** HTTP requests in development
84
+ - **COMMENT** complex logic only
85
+
86
+ ## 📦 Available Methods
87
+
88
+ ### `startOperation(model, apiKey, instances, parameters)`
89
+
90
+ Initiate video generation operation.
91
+
92
+ **Refer to**: [`veo-http-client.service.ts`](./veo-http-client.service.ts)
93
+
94
+ ### `getOperation(operationName, apiKey, model)`
95
+
96
+ Query operation status.
97
+
98
+ **Refer to**: [`veo-http-client.service.ts`](./veo-http-client.service.ts)
99
+
100
+ ## 🔗 Related Modules
101
+
102
+ - **Veo Polling**: [`VEO_POLLING_SERVICE.md`](./VEO_POLLING_SERVICE.md)
103
+ - **Video Generation**: [`VIDEO_GENERATION_SERVICE.md`](./VIDEO_GENERATION_SERVICE.md)
104
+ - **Video Downloader**: [`VIDEO_DOWNLOADER_SERVICE.md`](./VIDEO_DOWNLOADER_SERVICE.md)
105
+
106
+ ## 📋 Configuration Reference
107
+
108
+ ### VeoOperation
109
+
110
+ Operation response structure defined in: [`domain/entities/README.md`](../domain/entities/README.md)
111
+
112
+ **Fields:**
113
+ - `name`: string - Operation full path
114
+ - `done`: boolean - Completion status
115
+ - `response`: object - Video data (when complete)
116
+ - `metadata`: object - Progress information
117
+ - `error`: object - Error details (if failed)
118
+
119
+ ### API Endpoints
120
+
121
+ **Start Operation:**
122
+ - Method: POST
123
+ - URL: `https://generativelanguage.googleapis.com/v1beta/models/{model}:predict`
124
+ - Body: `{ instances: [{ prompt: string }], parameters: { aspectRatio: string } }`
125
+
126
+ **Get Operation:**
127
+ - Method: GET
128
+ - URL: `https://generativelanguage.googleapis.com/v1beta/{operationName}`
129
+
130
+ ### Model IDs
131
+
132
+ Supported Veo models: `veo-3.1-fast-generate-preview`, `veo-3.0-generate-001`
133
+
134
+ See: [`domain/constants/README.md`](../domain/constants/README.md)
135
+
136
+ ## 🎓 Usage Patterns
137
+
138
+ ### Start Video Generation
139
+ 1. Import service
140
+ 2. Call `startOperation()` with model, API key, and prompt
141
+ 3. Save returned operation name
142
+ 4. Use operation name for polling
143
+ 5. Handle network errors
144
+
145
+ ### Query Operation Status
146
+ 1. Import service
147
+ 2. Call `getOperation()` with operation name
148
+ 3. Check `done` field for completion
149
+ 4. Check `error` field for failures
150
+ 5. Extract video URL from response when complete
151
+
152
+ ### Custom Polling Logic
153
+ 1. Start operation with `startOperation()`
154
+ 2. Poll with `getOperation()` in loop
155
+ 3. Check completion status each iteration
156
+ 4. Handle progress updates
157
+ 5. Exit when complete or failed
158
+
159
+ ## 🚨 Common Pitfalls
160
+
161
+ ### Don't
162
+ - Poll manually (use veo-polling.service.ts)
163
+ - Forget to save operation name
164
+ - Ignore operation error field
165
+ - Expose API keys in logs
166
+ - Poll too frequently (rate limits)
167
+
168
+ ### Do
169
+ - Save operation name immediately
170
+ - Use polling service for automatic polling
171
+ - Check error field in responses
172
+ - Implement backoff between polls
173
+ - Handle network errors gracefully
174
+ - Validate API responses
175
+
176
+ ---
177
+
178
+ **Last Updated**: 2025-01-08
179
+ **See Also**: [AI_GUIDELINES.md](../../AI_GUIDELINES.md)
@@ -0,0 +1,173 @@
1
+ # Veo Polling Service
2
+
3
+ Tracks video generation operations using polling mechanism. Regularly checks operation status until completion.
4
+
5
+ ## 📍 Import Path
6
+
7
+ ```
8
+ import { veoPollingService } from '@umituz/react-native-ai-gemini-provider';
9
+ ```
10
+
11
+ ## 🎯 Purpose
12
+
13
+ Use this service to automatically poll video generation operations until completion. Provides progress updates and handles polling logic.
14
+
15
+ **When to use:**
16
+ - Wait for video generation to complete
17
+ - Track generation progress
18
+ - Provide progress feedback to users
19
+ - Handle long-running operations
20
+ - Implement video generation UI
21
+
22
+ ## 📌 Strategy
23
+
24
+ Video generation takes time and requires polling. This service:
25
+ - Implements automatic polling with backoff
26
+ - Provides progress callbacks for UI updates
27
+ - Handles operation completion and errors
28
+ - Manages polling intervals and timeouts
29
+ - Simplifies video generation workflow
30
+
31
+ **Key Decision**: Use this service instead of manual polling. It handles backoff, timeouts, and progress tracking automatically.
32
+
33
+ ## ⚠️ Rules
34
+
35
+ ### Usage Rules
36
+ - **MUST** provide valid operation name
37
+ - **MUST** provide API key and model ID
38
+ - **SHOULD** implement progress callback
39
+ - **MUST** handle polling completion appropriately
40
+ - **SHOULD NOT** implement custom polling logic
41
+
42
+ ### Polling Rules
43
+ - **MUST** wait between polls (automatic backoff)
44
+ - **SHOULD** provide progress updates to users
45
+ - **MUST** handle operation errors
46
+ - **SHOULD** implement timeout for long operations
47
+ - **MUST NOT** poll too frequently
48
+
49
+ ### Error Handling Rules
50
+ - **MUST** check operation error field
51
+ - **SHOULD** handle polling errors
52
+ - **MUST** throw errors on operation failure
53
+ - **SHOULD** provide user-friendly error messages
54
+ - **MUST NOT** ignore timeout errors
55
+
56
+ ## 🤖 AI Agent Guidelines
57
+
58
+ ### When Modifying This Service
59
+ 1. **READ** the implementation file first
60
+ 2. **UNDERSTAND** polling mechanism
61
+ 3. **MAINTAIN** backward compatibility
62
+ 4. **ADD** tests for new functionality
63
+ 5. **UPDATE** type definitions
64
+
65
+ ### When Adding New Features
66
+ 1. **CHECK** if similar feature exists
67
+ 2. **FOLLOW** existing polling patterns
68
+ 3. **USE** established error handling
69
+ 4. **DOCUMENT** in type definitions
70
+ 5. **ADD** examples to tests (not docs)
71
+
72
+ ### When Fixing Bugs
73
+ 1. **REPRODUCE** bug locally first
74
+ 2. **IDENTIFY** root cause
75
+ 3. **FIX** with minimal changes
76
+ 4. **ADD** regression test
77
+ 5. **VERIFY** all tests pass
78
+
79
+ ### Code Style Rules
80
+ - **USE** async/await (no callbacks except onProgress)
81
+ - **VALIDATE** inputs at function entry
82
+ - **THROW** typed errors (`GeminiError`)
83
+ - **LOG** polling operations in development
84
+ - **COMMENT** complex logic only
85
+
86
+ ## 📦 Available Methods
87
+
88
+ ### `pollOperation(operationName, apiKey, model, onProgress?)`
89
+
90
+ Poll operation until completion with progress updates.
91
+
92
+ **Refer to**: [`veo-polling.service.ts`](./veo-polling.service.ts)
93
+
94
+ ## 🔗 Related Modules
95
+
96
+ - **Veo HTTP Client**: [`VEO_HTTP_CLIENT_SERVICE.md`](./VEO_HTTP_CLIENT_SERVICE.md)
97
+ - **Video Generation**: [`VIDEO_GENERATION_SERVICE.md`](./VIDEO_GENERATION_SERVICE.md)
98
+ - **Error Handler**: [`VIDEO_ERROR_HANDLER_SERVICE.md`](./VIDEO_ERROR_HANDLER_SERVICE.md)
99
+
100
+ ## 📋 Configuration Reference
101
+
102
+ ### Polling Strategy
103
+
104
+ **Polling Intervals:**
105
+ - Initial: Every 2 seconds
106
+ - Backoff: Gradually increases based on progress
107
+ - Maximum: 5 minutes total wait time
108
+
109
+ **Polling Flow:**
110
+ 1. Start → Check status
111
+ 2. If not complete → Wait 2s → Check again
112
+ 3. If progress update → Call onProgress callback
113
+ 4. If complete or error → Return result
114
+ 5. If timeout → Throw error
115
+
116
+ ### Progress Callback
117
+
118
+ Callback receives `VideoGenerationProgress` with:
119
+ - `status`: Operation status (queued, processing, completed, failed)
120
+ - `progress`: Percentage (0-100)
121
+ - `message`: Optional status message
122
+
123
+ ## 🎓 Usage Patterns
124
+
125
+ ### Basic Polling
126
+ 1. Import service
127
+ 2. Call `pollOperation()` with operation name from HTTP client
128
+ 3. Wait for completion promise to resolve
129
+ 4. Extract video URL from result
130
+ 5. Handle errors appropriately
131
+
132
+ ### With Progress Updates
133
+ 1. Import service
134
+ 2. Implement `onProgress` callback
135
+ 3. Update UI with progress percentage
136
+ 4. Display status message to user
137
+ 5. Handle completion
138
+
139
+ ### With Timeout
140
+ 1. Calculate timeout duration
141
+ 2. Implement timeout check in progress callback
142
+ 3. Throw error if timeout exceeded
143
+ 4. Handle timeout error appropriately
144
+ 5. Provide user feedback
145
+
146
+ ### React Native Integration
147
+ 1. Create state for progress and video URL
148
+ 2. Start polling on user action
149
+ 3. Update state in progress callback
150
+ 4. Display progress to user
151
+ 5. Show video when complete
152
+
153
+ ## 🚨 Common Pitfalls
154
+
155
+ ### Don't
156
+ - Implement manual polling (use this service)
157
+ - Ignore progress updates (bad UX)
158
+ - Forget to handle errors
159
+ - Poll without backoff (rate limits)
160
+ - Block UI during polling
161
+
162
+ ### Do
163
+ - Always use progress callbacks
164
+ - Update UI with progress
165
+ - Handle all error states
166
+ - Implement cancellation support
167
+ - Provide user feedback
168
+ - Use reasonable timeouts
169
+
170
+ ---
171
+
172
+ **Last Updated**: 2025-01-08
173
+ **See Also**: [AI_GUIDELINES.md](../../AI_GUIDELINES.md)