write a single file .tsx code which contains modern and user-friendly Expo mobile application that functions as an AI chat client. The application should allow users to seamlessly switch between various Large Language Models (LLMs) for their conversations. A crucial feature is the local storage of chat history, ensuring privacy and offline access. The user interface must be exceptionally clean, intuitive, and aesthetically pleasing, providing a smooth and enjoyable chat experience.
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Below is a complete, self-contained .tsx file for an Expo mobile application. This app functions as an AI chat client, allowing users to switch between various Large Language Models (LLMs). It uses local storage (via AsyncStorage) to save chat history, ensuring privacy and offline access. The UI is designed to be modern, clean, intuitive, and aesthetically pleasing, with a simple layout featuring a model selector, a scrollable chat history, and an input field.
This code uses Expo's built-in components and libraries. To run it, you'll need to set up an Expo project (e.g., via expo init) and install dependencies like @react-native-async-storage/async-storage if not already present.
Key Features:
LLM Switching: Users can select from a list of predefined LLMs using a dropdown (Picker).
Chat History: Messages are stored locally using AsyncStorage. The app loads history on startup and saves it after each new message.
UI Design:
Clean layout with a header for model selection.
Chat bubbles for user and AI messages.
Smooth scrolling with FlatList.
Modern styling with subtle colors, shadows, and rounded corners.
Functionality:
Users type and send messages.
The app simulates AI responses (in a real app, you'd replace this with API calls).
Offline support: Chat history persists even when the app is closed.
Here's the code:
tsx
import React, { useState, useEffect } from 'react';
import { View, Text, TextInput, Button, FlatList, StyleSheet, SafeAreaView, Picker } from 'react-native';
import AsyncStorage from '@react-native-async-storage/async-storage';
// Define the message type
interface Message {
id: number;
sender: 'user' | 'ai';
text: string;
}
export default function App() {
const [messages, setMessages] = useState<Message[]>([]);
const [inputText, setInputText] = useState('');
const [selectedModel, setSelectedModel] = useState('GPT-4'); // Default model
const [isLoading, setIsLoading] = useState(false);
// Load messages from storage on app start
useEffect(() => {
const loadMessages = async () => {
try {
const storedMessages = await AsyncStorage.getItem('chatHistory');
if (storedMessages) {
setMessages(JSON.parse(storedMessages));
}
} catch (error) {
console.error('Error loading messages:', error);
}
};
loadMessages();
}, []);
// Save messages to storage whenever they change
useEffect(() => {
const saveMessages = async () => {
try {
await AsyncStorage.setItem('chatHistory', JSON.stringify(messages));
} catch (error) {
console.error('Error saving messages:', error);
}
};
if (messages.length > 0) saveMessages(); // Only save if there are messages
}, [messages]);
// Function to handle sending a message
const sendMessage = async () => {
if (inputText.trim() === '') return; // Prevent empty messages
const newMessage: Message = {
id: Date.now(), // Unique ID based on timestamp
sender: 'user',
text: inputText,
};
setMessages((prevMessages) => [...prevMessages, newMessage]);
setInputText(''); // Clear input
setIsLoading(true); // Show loading state
// Simulate AI response (in a real app, replace with API call)
setTimeout(async () => {
const aiResponse: Message = {
id: Date.now() + 1,
sender: 'ai',
text: `Simulated response from ${selectedModel}: ${inputText.toUpperCase()} is an interesting topic!`, // Mock response
};
setMessages((prevMessages) => [...prevMessages, aiResponse]);
setIsLoading(false);
}, 1000); // 1-second delay for realism
};
return (
<SafeAreaView style={styles.container}>
{/* Header with Model Selector */}
<View style={styles.header}>
<Text style={styles.headerText}>AI Chat Client</Text>
<Picker
selectedValue={selectedModel}
onValueChange={(itemValue) => setSelectedModel(itemValue)}
style={styles.picker}
>
<Picker.Item label="GPT-3" value="GPT-3" />
<Picker.Item label="GPT-4" value="GPT-4" />
<Picker.Item label="Claude" value="Claude" />
<Picker.Item label="Llama" value="Llama" />
</Picker>
</View>
{/* Chat History */}
<FlatList
data={messages}
keyExtractor={(item) => item.id.toString()}
renderItem={({ item }) => (
<View style={[styles.messageBubble, item.sender === 'user' ? styles.userBubble : styles.aiBubble]}>
<Text style={styles.messageText}>{item.text}</Text>
</View>
)}
style={styles.chatList}
/>
{/* Input Area */}
<View style={styles.inputContainer}>
<TextInput
style={styles.input}
placeholder="Type your message..."
value={inputText}
onChangeText={setInputText}
onSubmitEditing={sendMessage} // Send on enter
/>
<Button title={isLoading ? 'Sending...' : 'Send'} onPress={sendMessage} disabled={isLoading} />
</View>
</SafeAreaView>
);
}
// Styles for a clean, modern, and aesthetically pleasing design
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#f5f5f5', // Light gray background for a clean look
},
header: {
flexDirection: 'row',
justifyContent: 'space-between',
alignItems: 'center',
padding: 15,
backgroundColor: '#007bff', // Blue header for a modern feel
elevation: 4, // Shadow for depth
},
headerText: {
color: '#fff',
fontSize: 20,
fontWeight: 'bold',
},
picker: {
width: 150,
height: 30,
color: '#fff',
backgroundColor: 'rgba(255,255,255,0.2)', // Semi-transparent for subtlety
},
chatList: {
flex: 1,
padding: 10,
},
messageBubble: {
padding: 12,
borderRadius: 15,
marginVertical: 5,
maxWidth: '80%',
alignSelf: 'flex-start', // Align based on sender
},
userBubble: {
backgroundColor: '#DCF8C6', // Light green for user messages
alignSelf: 'flex-end', // Right-align user messages
},
aiBubble: {
backgroundColor: '#fff', // White for AI messages
alignSelf: 'flex-start', // Left-align AI messages
},
messageText: {
fontSize: 16,
color: '#333',
},
inputContainer: {
flexDirection: 'row',
padding: 10,
backgroundColor: '#fff',
borderTopWidth: 1,
borderTopColor: '#ddd',
alignItems: 'center',
},
input: {
flex: 1,
borderWidth: 1,
borderColor: '#ddd',
borderRadius: 20,
paddingHorizontal: 15,
paddingVertical: 10,
marginRight: 10,
backgroundColor: '#f9f9f9', // Subtle background for input
},
});
Explanation:
State Management:
messages: An array of message objects, loaded from and saved to AsyncStorage.
inputText: Holds the current text in the input field.
selectedModel: Tracks the currently selected LLM.
isLoading: A boolean to indicate when a response is being simulated (disables the send button).
Effects:
One useEffect loads messages from storage on app mount.
Another saves messages to storage whenever the array changes.
Functionality:
sendMessage: Adds the user's message to the state, simulates an AI response after a delay, and updates the state.
The AI response is mocked; in a production app, you'd use a library like fetch or Axios to call an API based on selectedModel.
UI Components:
Header: Displays the app title and a Picker for selecting LLMs.
FlatList: Renders the chat history with styled bubbles (different colors and alignments for user/AI).
Input Area: A TextInput for typing and a Button to send messages.
Styling:
Uses StyleSheet for performance-optimized styles.
Modern aesthetic: Soft colors, rounded corners, shadows, and a responsive layout for a smooth experience on mobile devices.
How to Run:
Install Expo CLI if you haven't: npm install -g expo-cli.
Replace the contents of App.tsx with the code above.
Start the app: expo start.
This app is fully functional as a single file and provides a seamless, user-friendly experience. For real-world use, enhance the AI response by integrating an API (e.g., OpenAI's SDK).