React Native ile AI Entegrasyonu: Yapay Zeka Destekli Mobil Uygulamalar
Yapay zeka teknolojilerinin mobil uygulamalarda kullanımı hızla artıyor. Bu kapsamlı rehberde, React Native uygulamalarınızda AI servislerini nasıl entegre edeceğinizi öğreneceksiniz.
🤖 AI Entegrasyonu Seçenekleri
React Native'de AI entegrasyonu için birkaç farklı yaklaşım bulunmaktadır:
1. Cloud-based AI Services
- OpenAI API: GPT modelleri, DALL-E
- Google AI: Gemini, Vision API
- Azure Cognitive Services: Speech, Vision, Language
- AWS AI Services: Rekognition, Polly, Comprehend
2. On-Device AI
- TensorFlow.js: Browser ve React Native desteği
- ML Kit: Google'ın mobile AI SDK'sı
- Core ML: Apple'ın machine learning framework'ü
- MediaPipe: Google'ın media processing framework'ü
🔧 OpenAI API Entegrasyonu
1. OpenAI API Kurulumu
# OpenAI SDK kurulumu
npm install openai
# React Native için HTTP client
npm install axios
2. OpenAI Service Oluşturma
// services/openaiService.ts
import OpenAI from 'openai';
import AsyncStorage from '@react-native-async-storage/async-storage';
class OpenAIService {
private client: OpenAI;
private apiKey: string = '';
constructor() {
this.initializeClient();
}
private async initializeClient() {
try {
const storedApiKey = await AsyncStorage.getItem('openai_api_key');
if (storedApiKey) {
this.apiKey = storedApiKey;
this.client = new OpenAI({
apiKey: this.apiKey,
});
}
} catch (error) {
console.error('OpenAI initialization error:', error);
}
}
async setApiKey(apiKey: string) {
this.apiKey = apiKey;
await AsyncStorage.setItem('openai_api_key', apiKey);
this.client = new OpenAI({ apiKey });
}
async generateText(prompt: string, options?: {
model?: string;
maxTokens?: number;
temperature?: number;
}) {
try {
if (!this.client) {
throw new Error('OpenAI client not initialized');
}
const response = await this.client.chat.completions.create({
model: options?.model || 'gpt-3.5-turbo',
messages: [
{
role: 'user',
content: prompt,
},
],
max_tokens: options?.maxTokens || 150,
temperature: options?.temperature || 0.7,
});
return response.choices[0]?.message?.content || '';
} catch (error) {
console.error('OpenAI API error:', error);
throw error;
}
}
async generateImage(prompt: string, options?: {
size?: '256x256' | '512x512' | '1024x1024';
quality?: 'standard' | 'hd';
}) {
try {
if (!this.client) {
throw new Error('OpenAI client not initialized');
}
const response = await this.client.images.generate({
model: 'dall-e-3',
prompt,
size: options?.size || '1024x1024',
quality: options?.quality || 'standard',
n: 1,
});
return response.data[0]?.url || '';
} catch (error) {
console.error('OpenAI Image API error:', error);
throw error;
}
}
}
export const openAIService = new OpenAIService();
3. AI Chat Komponenti
// components/AIChat.tsx
import React, { useState, useRef } from 'react';
import {
View,
Text,
TextInput,
TouchableOpacity,
FlatList,
StyleSheet,
Alert,
ActivityIndicator,
} from 'react-native';
import { openAIService } from '../services/openaiService';
interface Message {
id: string;
text: string;
isUser: boolean;
timestamp: Date;
}
export function AIChat() {
const [messages, setMessages] = useState([]);
const [inputText, setInputText] = useState('');
const [isLoading, setIsLoading] = useState(false);
const flatListRef = useRef(null);
const sendMessage = async () => {
if (!inputText.trim() || isLoading) return;
const userMessage: Message = {
id: Date.now().toString(),
text: inputText,
isUser: true,
timestamp: new Date(),
};
setMessages(prev => [...prev, userMessage]);
setInputText('');
setIsLoading(true);
try {
const aiResponse = await openAIService.generateText(inputText);
const aiMessage: Message = {
id: (Date.now() + 1).toString(),
text: aiResponse,
isUser: false,
timestamp: new Date(),
};
setMessages(prev => [...prev, aiMessage]);
// Scroll to bottom
setTimeout(() => {
flatListRef.current?.scrollToEnd({ animated: true });
}, 100);
} catch (error) {
Alert.alert('Hata', 'AI servisi ile iletişim kurulamadı');
} finally {
setIsLoading(false);
}
};
const renderMessage = ({ item }: { item: Message }) => (
{item.text}
{item.timestamp.toLocaleTimeString('tr-TR', {
hour: '2-digit',
minute: '2-digit'
})}
);
return (
item.id}
style={styles.messagesList}
contentContainerStyle={styles.messagesContent}
/>
{isLoading ? (
) : (
Gönder
)}
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#f5f5f5',
},
messagesList: {
flex: 1,
},
messagesContent: {
padding: 16,
},
messageContainer: {
marginBottom: 12,
maxWidth: '80%',
},
userMessage: {
alignSelf: 'flex-end',
backgroundColor: '#007bff',
borderRadius: 20,
padding: 12,
},
aiMessage: {
alignSelf: 'flex-start',
backgroundColor: '#fff',
borderRadius: 20,
padding: 12,
borderWidth: 1,
borderColor: '#e0e0e0',
},
messageText: {
fontSize: 16,
lineHeight: 22,
},
userMessageText: {
color: '#fff',
},
aiMessageText: {
color: '#333',
},
timestamp: {
fontSize: 12,
color: '#666',
marginTop: 4,
textAlign: 'right',
},
inputContainer: {
flexDirection: 'row',
padding: 16,
backgroundColor: '#fff',
borderTopWidth: 1,
borderTopColor: '#e0e0e0',
},
textInput: {
flex: 1,
borderWidth: 1,
borderColor: '#e0e0e0',
borderRadius: 20,
paddingHorizontal: 16,
paddingVertical: 12,
marginRight: 12,
maxHeight: 100,
},
sendButton: {
backgroundColor: '#007bff',
borderRadius: 20,
paddingHorizontal: 20,
paddingVertical: 12,
justifyContent: 'center',
alignItems: 'center',
},
sendButtonDisabled: {
backgroundColor: '#ccc',
},
sendButtonText: {
color: '#fff',
fontWeight: 'bold',
},
});
📱 TensorFlow.js Entegrasyonu
1. TensorFlow.js Kurulumu
# TensorFlow.js kurulumu
npm install @tensorflow/tfjs
npm install @tensorflow/tfjs-react-native
npm install @tensorflow/tfjs-platform-react-native
# Platform-specific dependencies
npm install react-native-fs
npm install @react-native-community/netinfo
2. TensorFlow.js Platform Setup
// utils/tfSetup.ts
import '@tensorflow/tfjs-react-native';
import '@tensorflow/tfjs-platform-react-native';
import * as tf from '@tensorflow/tfjs';
import { bundleResourceIO } from '@tensorflow/tfjs-react-native';
export async function initializeTensorFlow() {
// Wait for TensorFlow.js to be ready
await tf.ready();
// Set platform for React Native
tf.env().set('WEBGL_PACK', false);
console.log('TensorFlow.js is ready!');
}
export async function loadModel(modelUrl: string) {
try {
const model = await tf.loadLayersModel(bundleResourceIO(modelUrl));
return model;
} catch (error) {
console.error('Model loading error:', error);
throw error;
}
}
3. Image Classification Komponenti
// components/ImageClassifier.tsx
import React, { useState, useEffect } from 'react';
import {
View,
Text,
TouchableOpacity,
Image,
StyleSheet,
Alert,
} from 'react-native';
import { launchImageLibrary } from 'react-native-image-picker';
import * as tf from '@tensorflow/tfjs';
import { initializeTensorFlow, loadModel } from '../utils/tfSetup';
interface ClassificationResult {
className: string;
probability: number;
}
export function ImageClassifier() {
const [selectedImage, setSelectedImage] = useState(null);
const [model, setModel] = useState(null);
const [predictions, setPredictions] = useState([]);
const [isLoading, setIsLoading] = useState(false);
useEffect(() => {
initializeTensorFlow();
}, []);
const selectImage = () => {
launchImageLibrary(
{
mediaType: 'photo',
quality: 0.8,
maxWidth: 224,
maxHeight: 224,
},
(response) => {
if (response.assets && response.assets[0]) {
setSelectedImage(response.assets[0].uri || null);
setPredictions([]);
}
}
);
};
const classifyImage = async () => {
if (!selectedImage || !model) return;
setIsLoading(true);
try {
// Load and preprocess image
const imageTensor = await loadAndPreprocessImage(selectedImage);
// Make prediction
const prediction = model.predict(imageTensor) as tf.Tensor;
const probabilities = await prediction.data();
// Process results
const results: ClassificationResult[] = [];
const classNames = ['Cat', 'Dog', 'Bird', 'Fish', 'Other'];
for (let i = 0; i < probabilities.length; i++) {
results.push({
className: classNames[i] || 'Unknown',
probability: probabilities[i],
});
}
// Sort by probability
results.sort((a, b) => b.probability - a.probability);
setPredictions(results.slice(0, 3)); // Top 3 predictions
} catch (error) {
Alert.alert('Hata', 'Görüntü sınıflandırma başarısız');
} finally {
setIsLoading(false);
}
};
const loadAndPreprocessImage = async (uri: string): Promise => {
// This is a simplified version
// In a real app, you'd need to properly load and preprocess the image
return tf.randomNormal([1, 224, 224, 3]);
};
return (
AI Görüntü Sınıflandırıcı
{selectedImage && (
)}
Görüntü Seç
{selectedImage && (
{isLoading ? 'Sınıflandırılıyor...' : 'Sınıflandır'}
)}
{predictions.length > 0 && (
Sonuçlar:
{predictions.map((prediction, index) => (
{prediction.className}: {(prediction.probability * 100).toFixed(1)}%
))}
)}
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
padding: 20,
backgroundColor: '#f5f5f5',
},
title: {
fontSize: 24,
fontWeight: 'bold',
textAlign: 'center',
marginBottom: 20,
},
image: {
width: 200,
height: 200,
alignSelf: 'center',
borderRadius: 10,
marginBottom: 20,
},
button: {
backgroundColor: '#007bff',
padding: 15,
borderRadius: 10,
marginBottom: 10,
},
classifyButton: {
backgroundColor: '#28a745',
},
buttonText: {
color: '#fff',
textAlign: 'center',
fontWeight: 'bold',
fontSize: 16,
},
predictionsContainer: {
marginTop: 20,
padding: 15,
backgroundColor: '#fff',
borderRadius: 10,
},
predictionsTitle: {
fontSize: 18,
fontWeight: 'bold',
marginBottom: 10,
},
predictionItem: {
padding: 8,
borderBottomWidth: 1,
borderBottomColor: '#e0e0e0',
},
predictionText: {
fontSize: 16,
},
});
🎤 Speech Recognition Entegrasyonu
1. Speech Recognition Kurulumu
# React Native Speech Recognition
npm install @react-native-voice/voice
# iOS için özel kurulum gerekli
cd ios && pod install
2. Speech Recognition Hook
// hooks/useSpeechRecognition.ts
import { useState, useEffect } from 'react';
import Voice from '@react-native-voice/voice';
export function useSpeechRecognition() {
const [isListening, setIsListening] = useState(false);
const [recognizedText, setRecognizedText] = useState('');
const [error, setError] = useState('');
useEffect(() => {
Voice.onSpeechStart = onSpeechStart;
Voice.onSpeechEnd = onSpeechEnd;
Voice.onSpeechResults = onSpeechResults;
Voice.onSpeechError = onSpeechError;
return () => {
Voice.destroy().then(Voice.removeAllListeners);
};
}, []);
const onSpeechStart = () => {
setIsListening(true);
setError('');
};
const onSpeechEnd = () => {
setIsListening(false);
};
const onSpeechResults = (e: any) => {
if (e.value && e.value.length > 0) {
setRecognizedText(e.value[0]);
}
};
const onSpeechError = (e: any) => {
setError(e.error?.message || 'Speech recognition error');
setIsListening(false);
};
const startListening = async () => {
try {
setRecognizedText('');
setError('');
await Voice.start('tr-TR'); // Turkish language
} catch (err) {
setError('Failed to start speech recognition');
}
};
const stopListening = async () => {
try {
await Voice.stop();
} catch (err) {
setError('Failed to stop speech recognition');
}
};
return {
isListening,
recognizedText,
error,
startListening,
stopListening,
};
}
🔮 Gelecek ve Best Practices
AI Entegrasyonu Best Practices
- API Key Güvenliği: API anahtarlarını güvenli şekilde saklayın
- Rate Limiting: API çağrılarını sınırlayın
- Offline Support: Temel AI işlevleri için offline modeller kullanın
- Privacy: Kullanıcı verilerini koruyun
- Performance: AI işlemlerini optimize edin
- Error Handling: Kapsamlı hata yönetimi uygulayın
Önerilen AI Kütüphaneleri
openai- OpenAI API entegrasyonu@tensorflow/tfjs- On-device machine learning@react-native-voice/voice- Speech recognitionreact-native-vision-camera- Camera integrationreact-native-image-picker- Image selection
🚀 Sonuç
React Native uygulamalarınızda AI entegrasyonu ile kullanıcı deneyimini önemli ölçüde geliştirebilirsiniz. Bu rehberdeki teknikleri kullanarak akıllı, interaktif ve gelecek odaklı mobil uygulamalar geliştirebilirsiniz.

