firebase-ai — скилл для Claude Code: что делает и как установить
Скилл учит агента правильно подключать Firebase AI Logic в Flutter-проекте и писать код для генерации текста и чата через Gemini.
MIT ★ 674 обновлён 2026-10-29
/plugin marketplace add evanca/flutter-ai-rules
/plugin install flutter-ai-skills@flutter-ai-rulesЧто делает firebase-ai
Скилл задаёт шаблоны кода для firebase_ai в Flutter: инициализация Firebase.initializeApp, создание модели через FirebaseAI.googleAI().generativeModel, однократная генерация текста, многоходовый чат через model.startChat() и потоковый вывод через generateContentStream для построчного обновления интерфейса. Отдельно описаны мультимодальные запросы с текстом и изображением через Content.multi и InlineDataPart.
Есть блок про обработку ошибок — перехват FirebaseAIException, распознавание квот и экспоненциальный backoff, а также про безопасность: настройка safetySettings с HarmCategory и рекомендация включить App Check против злоупотреблений эндпоинтом. На Windows платформа Firebase AI не поддерживается, а на macOS и других Apple-устройствах статус — бета.
Агент опирается на эти сниппеты при правке Dart-кода, но для реальной работы нужен настроенный Firebase-проект с включённым Firebase AI Logic в консоли.
Какие задачи решает
- настроить
firebase_aiв Flutter-проекте - сгенерировать текстовый ответ через Gemini
- собрать многоходовый чат с историей сообщений
- вывести ответ модели построчно через стрим
- отправить в Gemini запрос с текстом и изображением
Примеры запросов агенту
- Настрой
firebase_aiв проекте и инициализируй Gemini-модель - Сделай потоковый вывод ответа Gemini в интерфейс
- Добавь обработку ошибок квоты для вызовов
generateContent
Как установить firebase-ai
1Через маркетплейс плагинов
/plugin marketplace add evanca/flutter-ai-rules/plugin install flutter-ai-skills@flutter-ai-rulesКоманда ставит плагин flutter-ai-skills целиком, со всеми его скиллами
2Через Skills CLI (Vercel)
npx skills add evanca/flutter-ai-rules --skill firebase-ai -a claude-code3Вручную: положить файлы
~/.claude/skills/firebase-ai/SKILL.mdПапка скилла целиком; для одного проекта — .claude/skills/firebase-ai/
1Через Skills CLI (Vercel)
npx skills add evanca/flutter-ai-rules --skill firebase-ai -a codex2Вручную: положить файлы
.agents/skills/firebase-ai/SKILL.mdДля всех проектов — ~/.agents/skills/
1Через Skills CLI (Vercel)
npx skills add evanca/flutter-ai-rules --skill firebase-ai -a cursor2Вручную: положить файлы
.cursor/skills/firebase-ai/SKILL.mdCursor читает и .agents/skills/, и .claude/skills/
1GitHub CLI
gh skill install evanca/flutter-ai-rules skills/firebase-ai2Вручную: положить файлы
.github/skills/firebase-ai/SKILL.md1Через Skills CLI (Vercel)
npx skills add evanca/flutter-ai-rules --skill firebase-ai -a gemini-cli2Командой платформы
gemini skills install https://github.com/evanca/flutter-ai-rules --path skills/firebase-aiВручную: положить файлы
.devin/skills/firebase-ai/SKILL.mdСтарый путь .windsurf/skills/ тоже читается
Claude.ai
Упакуйте папку в zip и загрузите в Settings → Capabilities → Skills
По шагам, с командами для каждой платформы: Как установить скилл в Claude Code: пять способов
Вопросы о firebase-ai
Как установить firebase-ai в Claude Code?
Выполните /plugin marketplace add evanca/flutter-ai-rules, затем /plugin install flutter-ai-skills@flutter-ai-rules.
Что делает скилл firebase-ai?
Он задаёт правильные шаблоны кода для настройки Firebase AI Logic в Flutter: инициализацию, генерацию текста и чата с Gemini, стриминг ответов, мультимодальные запросы и обработку ошибок.
На каких платформах работает Firebase AI Logic?
Полная поддержка на iOS, Android и Web, на macOS и других Apple-устройствах — бета, на Windows не поддерживается.
Исходный текст
SKILL.md · MIT
---
name: firebase-ai
description: "Use when setting up firebase_ai, generating text/chat with Gemini, streaming AI output, building multimodal prompts, or handling AI errors."
license: MIT
---
# Firebase AI Skill
This skill defines how to correctly use Firebase AI Logic in Flutter applications.
## When to Use
Use this skill when:
* Setting up and configuring Firebase AI in a Flutter project.
* Generating text content or chat responses with Gemini models.
* Implementing streaming AI responses for real-time UI updates.
* Sending multimodal prompts (text + images) to Gemini.
* Handling errors, offline scenarios, and rate limits for AI operations.
* Applying security and privacy considerations for AI features.
---
## 1. Setup and Configuration
```
flutter pub add firebase_ai
```
```dart
import 'package:firebase_ai/firebase_ai.dart';
import 'package:firebase_core/firebase_core.dart';
import 'firebase_options.dart';
// Initialize FirebaseApp
await Firebase.initializeApp(
options: DefaultFirebaseOptions.currentPlatform,
);
// Initialize the Gemini Developer API backend service
final model =
FirebaseAI.googleAI().generativeModel(model: 'gemini-2.5-flash');
```
- Ensure the Firebase project is configured for AI services via the Firebase AI Logic page in the Firebase Console.
- Initialize Firebase before using any Firebase AI features.
- Use `FirebaseAI.googleAI()` for the **Gemini Developer API** backend (recommended starting point).
- Implement **App Check** to prevent abuse of Firebase AI endpoints.
**Platform support:**
| Platform | Support |
|---|---|
| iOS | Full |
| Android | Full |
| Web | Full |
| macOS / other Apple | Beta |
| Windows | Not supported |
---
## 2. Generating Content
### Single-turn text generation
```dart
final response = await model.generateContent([
Content.text('Summarize the benefits of Flutter for mobile development'),
]);
final text = response.text; // The generated summary string
```
### Multi-turn chat
```dart
final chat = model.startChat();
final response = await chat.sendMessage(
Content.text('What is the difference between StatelessWidget and StatefulWidget?'),
);
print(response.text);
// Follow-up in the same conversation
final followUp = await chat.sendMessage(
Content.text('When should I use StatefulWidget?'),
);
print(followUp.text);
```
### Streaming responses
Use streaming to display partial results as they arrive:
```dart
final stream = model.generateContentStream([
Content.text('Write a step-by-step guide to implementing dark mode in Flutter'),
]);
await for (final chunk in stream) {
// Append chunk.text to the UI progressively
setState(() => _output += chunk.text ?? '');
}
```
### Multimodal prompts (text + image)
```dart
final imageBytes = await File('photo.jpg').readAsBytes();
final response = await model.generateContent([
Content.multi([
TextPart('Describe what you see in this image'),
InlineDataPart('image/jpeg', imageBytes),
]),
]);
```
---
## 3. Error Handling
Wrap AI calls in structured error handling:
```dart
try {
final response = await model.generateContent([Content.text(prompt)]);
return response.text;
} on FirebaseAIException catch (e) {
if (e.message?.contains('quota') ?? false) {
// Handle rate limiting — show retry message or queue the request
return 'Service is busy. Please try again shortly.';
}
return 'AI service error: ${e.message}';
} catch (e) {
return 'Unexpected error: $e';
}
```
- Provide meaningful error messages to users when AI operations fail.
- Handle **offline scenarios** with appropriate fallback behavior (e.g., cached responses).
- Implement **exponential backoff** for rate-limited or transient errors.
---
## 4. Security and Privacy
- Follow Firebase Security Rules best practices when using AI services alongside other Firebase products.
- Ensure proper **authentication and authorization** for AI feature access.
- Sanitize user input before sending it to the model to prevent prompt injection.
- Be mindful of **data privacy requirements** when processing user content with AI services.
- Implement appropriate **content filtering and moderation** using safety settings:
```dart
final model = FirebaseAI.googleAI().generativeModel(
model: 'gemini-2.5-flash',
safetySettings: [
SafetySetting(HarmCategory.harassment, HarmBlockThreshold.medium),
SafetySetting(HarmCategory.dangerousContent, HarmBlockThreshold.high),
],
);
```
---
## References
- [Firebase AI Logic Flutter documentation](https://firebase.google.com/docs/ai-logic/get-started?platform=flutter)
© Ivanna Kaceviča · MIT · evanca/flutter-ai-rules