Ir al contenido

인공지능을 활용한 모바일 앱 개발

PNPM을 사용하여 Gemini API를 통합한 네이티브 모바일 앱을 개발하는 단계별 튜토리얼

0조회

이 실용적인 가이드는 React Native, Expo Router, PNPM 및 Google GenAI의 새로운 공식 SDK를 사용하여 다중 플랫폼 모바일 AI 챗봇을 개발하는 전체 개발 프로세스를 설명합니다.


이 학습 세션의 목적은 다음 기능 및 디자인 요구사항을 충족하는 고급 모바일 채팅 인터페이스를 구현하는 것입니다:

  • 대화 이력 저장: 반응형 로컬 메모리에서 대화 상호작용 기록을 유지합니다.
  • 유동적인 디자인: 유리 효과(Glassmorphism)를 가진 헤더, 비대칭 대비를 갖춘 둥근 대화 버블, 모바일 가상 키보드 지원(KeyboardAvoidingView).
  • 보안 통합: Expo에서 환경 변수를 사용하여 Gemini API에 안전하게 액세스합니다.

2. PNPM을 통한 인공지능 의존성 설치

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

프로젝트 루트 디렉토리에 위치한 상태에서 PNPM을 통해 Google GenAI SDK와 필요한 아이콘을 설치하세요:

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_로 시작하는 환경 변수를 노출합니다. Google Cloud 콘솔에서 API 키의 범위를 제한하여 생산 환경에서의 오용을 방지하세요.


프로젝트 루트에 .env 파일을 생성하여 보안을 위해 액세스 키를 저장하세요.

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

Expo는 개발 중에 이 파일을 자동으로 로드하고 process.env.EXPO_PUBLIC_GEMINI_API_KEY에 토큰을 연결할 것입니다.


앱의 주요 경로 파일 (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»
  • ✓ PNPM을 사용한 SDK 설치: 즉시 및 안전하게 통합되었습니다.
  • ✓ .env 변수 (ini 형식): 안전한 연결이 준비되고 검증되었습니다.
  • ✓ UI/UX 디자인: 유연성, 키보드 지원 및 자동 스크롤이 활성화되었습니다.
  • ✕ 앱 스토어 배포 (EAS Submit): 생산 컴파일을 위한 설정이 필요한 상태입니다.