Ir al contenido

Создание мобильного приложения с ИИ

Пошаговый учебник по созданию родного мобильного приложения с искусственным интеллектом, интегрирующего API Gemini с помощью PNPM.

0просмотры

Это практическое руководство подробно описывает полный процесс разработки для создания мобильного конверсационного помощника с искусственной интеллектом для нескольких платформ, используя React Native, Expo Router, менеджер зависимостей PNPM и новый официальный SDK Google GenAI для подключения к API Gemini.


1. Планирование приложения

Sección titulada «1. Planificación de la Aplicación»

Целью этой сессии обучения является реализация премиум-интерфейса мобильного чата, соответствующего следующим функциональным и дизайнерским требованиям:

  • Сохранение истории: Сохранение памяти интерактивного диалога в локальной реактивной памяти
  • Жидкий дизайн: Заголовок с эффектом кристалла (Глассморфизм), округлые пузыри разговора с асимметричным контрастом и поддержка виртуальной клавиатуры мобильного телефона (KeyboardAvoidingView)
  • Безопасная интеграция: Безопасный доступ к API Gemini с использованием переменных среды в Expo

2. Установка зависимостей ИИ с помощью PNPM

Sección titulada «2. Instalación de Dependencias de IA con PNPM»

Убедитесь, что вы находитесь в корневом каталоге вашего проекта, и установите SDK Google GenAI и необходимые иконки через PNPM

Ventana de terminal
# Instalar el SDK oficial de Google Gen AI usando PNPM y Expo
pnpm expo install @google/genai
# Instalar iconos premium de forma ultra rápida
pnpm expo install lucide-react-native

Безопасность в производстве

Expo экспонирует переменные среды, которые начинаются с EXPO_PUBLIC_, в окончательной сборке клиента. Обеспечьте ограничение границ вашего ключа API в консоли Google Cloud, чтобы предотвратить злоупотребления в производстве


3. Настройка переменных среды

Sección titulada «3. Configuración de Variables de Entorno»

Создайте файл .env в корне вашего проекта, чтобы хранить ключи доступа в безопасности

# Clave API generada en Google AI Studio
EXPO_PUBLIC_GEMINI_API_KEY=AIzaSyA1B2C3D4E5...

Expo автоматически загрузит этот файл во время разработки и сопоставит токен с process.env.EXPO_PUBLIC_GEMINI_API_KEY


4. Реализация основного исходного кода

Sección titulada «4. Implementación del Código Fuente Principal»

Создайте или замените основной файл маршрута вашего приложения (app/index.tsx или App.tsx) следующим премиум-дизайном и оптимизированным реактивным кодом

import React, { useState, useRef } from 'react';
import {
StyleSheet,
Text,
View,
TextInput,
TouchableOpacity,
FlatList,
KeyboardAvoidingView,
Platform,
ActivityIndicator,
SafeAreaView
} from 'react-native';
import { GoogleGenAI } from '@google/genai';
import { Send, Bot, User, Trash2 } from 'lucide-react-native';
// Inicializar el cliente de IA con la clave de entorno
const ai = new GoogleGenAI({ apiKey: process.env.EXPO_PUBLIC_GEMINI_API_KEY });
interface Mensaje {
id: string;
role: 'user' | 'model';
text: string;
}
export default function AppChat() {
const [messages, setMessages] = useState<Mensaje[]>([]);
const [input, setInput] = useState('');
const [loading, setLoading] = useState(false);
const flatListRef = useRef<FlatList>(null);
const enviarMensaje = async () => {
if (!input.trim() || loading) return;
const userText = input.trim();
setInput('');
// Crear ID único para el mensaje del usuario
const nuevoMensajeUsuario: Mensaje = {
id: Date.now().toString(),
role: 'user',
text: userText,
};
const mensajesActualizados = [...messages, nuevoMensajeUsuario];
setMessages(mensajesActualizados);
setLoading(true);
try {
// Llamar al modelo de última generación optimizado para velocidad (Gemini 2.5 Flash)
const response = await ai.models.generateContent({
model: 'gemini-2.5-flash',
contents: userText,
});
const modelText = response.text || 'Sin respuesta.';
setMessages(prev => [
...prev,
{
id: (Date.now() + 1).toString(),
role: 'model',
text: modelText,
}
]);
} catch (error) {
console.error(error);
setMessages(prev => [
...prev,
{
id: (Date.now() + 1).toString(),
role: 'model',
text: 'Error de conexión: Verifica tu clave de API o conexión a red.',
}
]);
} finally {
setLoading(false);
// Hacer scroll suave automático hacia el último mensaje enviado
setTimeout(() => {
flatListRef.current?.scrollToEnd({ animated: true });
}, 100);
}
};
const limpiarChat = () => {
setMessages([]);
};
return (
<SafeAreaView style={styles.container}>
{/* Cabecera Premium */}
<View style={styles.header}>
<View style={styles.headerLeft}>
<Bot size={24} color="hsl(142, 70%, 45%)" style={{ marginRight: 8 }} />
<Text style={styles.headerTitle}>Portelcore AI</Text>
</View>
<TouchableOpacity onPress={limpiarChat} style={styles.clearButton} activeOpacity={0.7}>
<Trash2 size={18} color="#ef4444" />
</TouchableOpacity>
</View>
{/* Área del Chat */}
<FlatList
ref={flatListRef}
data={messages}
keyExtractor={(item) => item.id}
contentContainerStyle={styles.chatList}
renderItem={({ item }) => (
<View style={[styles.bubbleWrapper, item.role === 'user' ? styles.bubbleUser : styles.bubbleModel]}>
<View style={styles.bubbleHeader}>
{item.role === 'user' ? (
<User size={12} color="#94a3b8" style={{ marginRight: 4 }} />
) : (
<Bot size={12} color="hsl(142, 70%, 45%)" style={{ marginRight: 4 }} />
)}
<Text style={styles.bubbleRoleText}>{item.role === 'user' ? 'Tú' : 'Asistente IA'}</Text>
</View>
<Text style={styles.bubbleText}>{item.text}</Text>
</View>
)}
ListEmptyComponent={
<View style={styles.emptyContainer}>
<Bot size={48} color="#475569" style={{ marginBottom: 12 }} />
<Text style={styles.emptyText}>Inicia un diálogo con tu asistente móvil de Inteligencia Artificial.</Text>
</View>
}
/>
{/* Indicador de carga */}
{loading && (
<View style={styles.loadingContainer}>
<ActivityIndicator size="small" color="hsl(142, 70%, 45%)" />
<Text style={styles.loadingText}>Pensando...</Text>
</View>
)}
{/* Barra de Entrada interactiva */}
<KeyboardAvoidingView
behavior={Platform.OS === 'ios' ? 'padding' : 'height'}
keyboardVerticalOffset={Platform.OS === 'ios' ? 90 : 0}
>
<View style={styles.inputContainer}>
<TextInput
style={styles.textInput}
placeholder="Escribe tu consulta aquí..."
placeholderTextColor="#64748b"
value={input}
onChangeText={setInput}
onSubmitEditing={enviarMensaje}
/>
<TouchableOpacity onPress={enviarMensaje} style={styles.sendButton} activeOpacity={0.8}>
<Send size={18} color="#ffffff" />
</TouchableOpacity>
</View>
</KeyboardAvoidingView>
</SafeAreaView>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#0f172a', /* Fondo oscuro premium profundo */
},
header: {
flexDirection: 'row',
alignItems: 'center',
justifyContent: 'space-between',
paddingHorizontal: 16,
paddingVertical: 14,
borderBottomWidth: 1,
borderBottomColor: 'rgba(255,255,255,0.06)',
},
headerLeft: {
flexDirection: 'row',
alignItems: 'center',
},
headerTitle: {
fontSize: 18,
fontWeight: 'bold',
color: '#f8fafc',
},
clearButton: {
padding: 8,
borderRadius: 8,
backgroundColor: 'rgba(239,68,68,0.1)',
},
chatList: {
padding: 16,
paddingBottom: 24,
},
bubbleWrapper: {
maxWidth: '85%',
padding: 12,
borderRadius: 12,
marginBottom: 16,
boxShadow: '0 2px 4px rgba(0,0,0,0.1)',
},
bubbleUser: {
alignSelf: 'flex-end',
backgroundColor: '#1e293b',
borderTopRightRadius: 2,
},
bubbleModel: {
alignSelf: 'flex-start',
backgroundColor: '#1a3a35', /* Contraste verde jade oscuro muy premium */
borderTopLeftRadius: 2,
},
bubbleHeader: {
flexDirection: 'row',
alignItems: 'center',
marginBottom: 4,
},
bubbleRoleText: {
fontSize: 10,
fontWeight: 'bold',
color: '#94a3b8',
textTransform: 'uppercase',
},
bubbleText: {
fontSize: 14,
color: '#f1f5f9',
lineHeight: 20,
},
emptyContainer: {
alignItems: 'center',
justifyContent: 'center',
marginTop: 100,
paddingHorizontal: 32,
},
emptyText: {
fontSize: 14,
color: '#64748b',
textAlign: 'center',
lineHeight: 22,
},
loadingContainer: {
flexDirection: 'row',
alignItems: 'center',
justifyContent: 'center',
paddingVertical: 10,
},
loadingText: {
fontSize: 12,
color: 'hsl(142, 70%, 45%)',
marginLeft: 8,
},
inputContainer: {
flexDirection: 'row',
alignItems: 'center',
padding: 12,
borderTopWidth: 1,
borderTopColor: 'rgba(255,255,255,0.06)',
backgroundColor: '#0f172a',
},
textInput: {
flex: 1,
height: 44,
backgroundColor: '#1e293b',
borderRadius: 22,
paddingHorizontal: 16,
color: '#f8fafc',
fontSize: 14,
marginRight: 10,
borderWidth: 1,
borderColor: 'rgba(255,255,255,0.04)',
},
sendButton: {
width: 44,
height: 44,
borderRadius: 22,
backgroundColor: 'hsl(142, 70%, 45%)',
alignItems: 'center',
justifyContent: 'center',
},
});

5. Контроль прогресса и этапов выполнения с помощью PNPM

Sección titulada «5. Control de Progreso e Hitos de Ejecución con PNPM»
  • ✓ Установка SDK с PNPM: Интегрировано мгновенно и безопасно
  • ✓ Переменные .env (формат ini): Безопасное подключение готово и проверено
  • ✓ Дизайн UI/UX: Включена гибкость, поддержка клавиатуры и автоматическая прокрутка.
  • ✕ Распространение в магазинах (EAS Submit): Ожидает настройки для сборки производства.