{"id":"firebase-ai","name":"firebase-ai","summary":"firebase_aiの設定、Geminiとのテキスト/チャット生成、AI出力のストリーミング、マルチモーダルプロンプトの作成、AIエラーの処理などに使えます。","body":"# Firebase AI Skill\n\nThis skill defines how to correctly use Firebase AI Logic in Flutter applications.\n\n## When to Use\n\nUse this skill when:\n\n* Setting up and configuring Firebase AI in a Flutter project.\n* Generating text content or chat responses with Gemini models.\n* Implementing streaming AI responses for real-time UI updates.\n* Sending multimodal prompts (text + images) to Gemini.\n* Handling errors, offline scenarios, and rate limits for AI operations.\n* Applying security and privacy considerations for AI features.\n\n---\n\n## 1. Setup and Configuration\n\n```\nflutter pub add firebase_ai\n```\n\n```dart\nimport 'package:firebase_ai/firebase_ai.dart';\nimport 'package:firebase_core/firebase_core.dart';\nimport 'firebase_options.dart';\n\n// Initialize FirebaseApp\nawait Firebase.initializeApp(\n  options: DefaultFirebaseOptions.currentPlatform,\n);\n\n// Initialize the Gemini Developer API backend service\nfinal model =\n    FirebaseAI.googleAI().generativeModel(model: 'gemini-2.5-flash');\n```\n\n- Ensure the Firebase project is configured for AI services via the Firebase AI Logic page in the Firebase Console.\n- Initialize Firebase before using any Firebase AI features.\n- Use `FirebaseAI.googleAI()` for the **Gemini Developer API** backend (recommended starting point).\n- Implement **App Check** to prevent abuse of Firebase AI endpoints.\n\n**Platform support:**\n\n| Platform | Support |\n|---|---|\n| iOS | Full |\n| Android | Full |\n| Web | Full |\n| macOS / other Apple | Beta |\n| Windows | Not supported |\n\n---\n\n## 2. Generating Content\n\n### Single-turn text generation\n\n```dart\nfinal response = await model.generateContent([\n  Content.text('Summarize the benefits of Flutter for mobile development'),\n]);\nfinal text = response.text; // The generated summary string\n```\n\n### Multi-turn chat\n\n```dart\nfinal chat = model.startChat();\nfinal response = await chat.sendMessage(\n  Content.text('What is the difference between StatelessWidget and StatefulWidget?'),\n);\nprint(response.text);\n\n// Follow-up in the same conversation\nfinal followUp = await chat.sendMessage(\n  Content.text('When should I use StatefulWidget?'),\n);\nprint(followUp.text);\n```\n\n### Streaming responses\n\nUse streaming to display partial results as they arrive:\n\n```dart\nfinal stream = model.generateContentStream([\n  Content.text('Write a step-by-step guide to implementing dark mode in Flutter'),\n]);\n\nawait for (final chunk in stream) {\n  // Append chunk.text to the UI progressively\n  setState(() => _output += chunk.text ?? '');\n}\n```\n\n### Multimodal prompts (text + image)\n\n```dart\nfinal imageBytes = await File('photo.jpg').readAsBytes();\nfinal response = await model.generateContent([\n  Content.multi([\n    TextPart('Describe what you see in this image'),\n    InlineDataPart('image/jpeg', imageBytes),\n  ]),\n]);\n```\n\n---\n\n## 3. Error Handling\n\nWrap AI calls in structured error handling:\n\n```dart\ntry {\n  final response = await model.generateContent([Content.text(prompt)]);\n  return response.text;\n} on FirebaseAIException catch (e) {\n  if (e.message?.contains('quota') ?? false) {\n    // Handle rate limiting — show retry message or queue the request\n    return 'Service is busy. Please try again shortly.';\n  }\n  return 'AI service error: ${e.message}';\n} catch (e) {\n  return 'Unexpected error: $e';\n}\n```\n\n- Provide meaningful error messages to users when AI operations fail.\n- Handle **offline scenarios** with appropriate fallback behavior (e.g., cached responses).\n- Implement **exponential backoff** for rate-limited or transient errors.\n\n---\n\n## 4. Security and Privacy\n\n- Follow Firebase Security Rules best practices when using AI services alongside other Firebase products.\n- Ensure proper **authentication and authorization** for AI feature access.\n- Sanitize user input before sending it to the model to prevent prompt injection.\n- Be mindful of **data privacy requirements** when processing user content with AI services.\n- Implement appropriate **content filtering and moderation** using safety settings:\n\n```dart\nfinal model = FirebaseAI.googleAI().generativeModel(\n  model: 'gemini-2.5-flash',\n  safetySettings: [\n    SafetySetting(HarmCategory.harassment, HarmBlockThreshold.medium),\n    SafetySetting(HarmCategory.dangerousContent, HarmBlockThreshold.high),\n  ],\n);\n```\n\n---\n\n## References\n\n- [Firebase AI Logic Flutter documentation](https://firebase.google.com/docs/ai-logic/get-started?platform=flutter)","author":"@evanca","ownerProfile":null,"authorContacts":null,"sourceUrl":"https://github.com/evanca/flutter-ai-rules/tree/main/skills/firebase-ai","license":"MIT","category":"security","lang":"en","tokens":948,"stars":0,"calls30d":1,"claimed":false,"visibility":"public","origin":"crawler","version":"0.1.0","createdAt":"2026-08-22","updatedAt":"2026-08-22","files":[],"requires":{"mcp":[],"tools":[]},"safety":{"flags":[],"scannedAt":"2026-08-22","hasScripts":false,"networkEndpoints":["firebase.google.com"]}}