Below is a single–file Expo entry point (App.tsx) that delivers a snappy, modern AI-chat client.
• Switch between several LLMs from a drop-down in the header
• Stores the entire chat history locally with @react-native-async-storage/async-storage
• Clean, minimal UI (inspired by iMessage & Slack)
• “Typing …” indicator while the model is generating
• Runs fully offline (history) and only hits the network when a message is sent
• Easily wire up your own keys / endpoints (see the sendToLLM helper)
// App.tsx
import React, { useEffect, useState, useRef } from "react";
import {
ActivityIndicator,
FlatList,
Keyboard,
KeyboardAvoidingView,
Platform,
SafeAreaView,
StyleSheet,
Text,
TextInput,
TouchableOpacity,
View,
} from "react-native";
import AsyncStorage from "@react-native-async-storage/async-storage";
import { Picker } from "@react-native-picker/picker";
import * as Crypto from "expo-crypto";
////////////////////////////////////////////////////////////////////////////////
// 1. Type helpers
////////////////////////////////////////////////////////////////////////////////
type Role = "user" | "assistant";
type Message = { id: string; role: Role; content: string; model: string };
////////////////////////////////////////////////////////////////////////////////
// 2. Static data
////////////////////////////////////////////////////////////////////////////////
const STORAGE_KEY = "@chat_history_v1";
const MODELS = [
{ id: "gpt-4o", label: "GPT-4o" },
{ id: "gpt-3.5-turbo", label: "GPT-3.5" },
{ id: "claude-3-haiku",label: "Claude 3" },
{ id: "llama3-8b", label: "Llama 3" },
];
////////////////////////////////////////////////////////////////////////////////
// 3. Main component
////////////////////////////////////////////////////////////////////////////////
export default function App() {
const [messages, setMessages] = useState<Message[]>([]);
const [input, setInput] = useState("");
const [model, setModel] = useState(MODELS[0].id);
const [loading, setLoading] = useState(false);
const flatRef = useRef<FlatList>(null);
// -------------------------- Load / persist history ------------------------
useEffect(() => {
(async () => {
const saved = await AsyncStorage.getItem(STORAGE_KEY);
if (saved) setMessages(JSON.parse(saved));
})();
}, []);
const persist = (next: Message[]) =>
AsyncStorage.setItem(STORAGE_KEY, JSON.stringify(next));
// -------------------------- Send message ----------------------------------
const handleSend = async () => {
if (!input.trim() || loading) return;
Keyboard.dismiss();
const userMsg: Message = {
id: Crypto.randomUUID(),
role: "user",
content: input.trim(),
model,
};
const pendingAssistant: Message = {
id: Crypto.randomUUID(),
role: "assistant",
content: "",
model,
};
const nextMessages = [...messages, userMsg, pendingAssistant];
setMessages(nextMessages);
setInput("");
setLoading(true);
persist(nextMessages);
scrollToEnd();
try {
const assistantText = await sendToLLM(model, [...messages, userMsg]);
updateAssistant(pendingAssistant.id, assistantText);
} catch (e) {
updateAssistant(
pendingAssistant.id,
"❌ Error talking to the model. Check your key / connection."
);
}
setLoading(false);
};
const updateAssistant = (id: string, text: string) => {
const next = messages.map((m) =>
m.id === id ? { ...m, content: text } : m
);
// we also must include userMsg + pendingAssistant if not there
const idx = next.findIndex((m) => m.id === id);
if (idx === -1) return; // just safety
next[idx] = { ...next[idx], content: text };
setMessages(next);
persist(next);
};
const scrollToEnd = () =>
setTimeout(() => flatRef.current?.scrollToEnd({ animated: true }), 150);
// -------------------------- Render ----------------------------------------
return (
<SafeAreaView style={styles.container}>
{/* ------------ Header / Model Picker ------------- */}
<View style={styles.header}>
<Text style={styles.title}>AI Chat</Text>
<Picker
selectedValue={model}
style={styles.picker}
onValueChange={(m) => setModel(m)}
dropdownIconColor="#fff"
>
{MODELS.map((m) => (
<Picker.Item key={m.id} label={m.label} value={m.id} />
))}
</Picker>
</View>
{/* ------------ Messages List ------------- */}
<FlatList
ref={flatRef}
data={messages}
keyExtractor={(item) => item.id}
renderItem={({ item }) => <Bubble msg={item} />}
contentContainerStyle={styles.list}
onContentSizeChange={scrollToEnd}
onLayout={scrollToEnd}
/>
{/* ------------ Typing Indicator ------------- */}
{loading && (
<View style={styles.typing}>
<ActivityIndicator size="small" color="#aaa" />
<Text style={styles.typingText}>Model is thinking…</Text>
</View>
)}
{/* ------------ Composer ------------- */}
<KeyboardAvoidingView
behavior={Platform.OS === "ios" ? "padding" : undefined}
>
<View style={styles.composer}>
<TextInput
value={input}
onChangeText={setInput}
placeholder="Type a message"
multiline
style={styles.input}
/>
<TouchableOpacity
style={[
styles.sendBtn,
{ opacity: input.trim() ? 1 : 0.3 },
]}
onPress={handleSend}
disabled={!input.trim()}
>
<Text style={styles.sendTxt}>Send</Text>
</TouchableOpacity>
</View>
</KeyboardAvoidingView>
</SafeAreaView>
);
}
////////////////////////////////////////////////////////////////////////////////
// 4. Chat bubble component
////////////////////////////////////////////////////////////////////////////////
const Bubble = ({ msg }: { msg: Message }) => {
const isUser = msg.role === "user";
return (
<View
style={[
styles.bubble,
isUser ? styles.bubbleUser : styles.bubbleBot,
]}
>
<Text style={styles.bubbleTxt}>{msg.content || "…"}</Text>
</View>
);
};
////////////////////////////////////////////////////////////////////////////////
// 5. Network helper (plug in your own endpoint / key here)
////////////////////////////////////////////////////////////////////////////////
async function sendToLLM(
model: string,
history: Pick<Message, "role" | "content">[]
): Promise<string> {
// -------------------------------------------------------------------------
// ⚠️ Swap this out with the provider of your choice. Two examples below:
// -------------------------------------------------------------------------
// 1. OpenAI example (requires you to add an env var OPENAI_API_KEY):
/*
const res = await fetch("https://api.openai.com/v1/chat/completions", {
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${process.env.EXPO_PUBLIC_OPENAI_API_KEY}`,
},
body: JSON.stringify({
model,
messages: history.map((m) => ({ role: m.role, content: m.content })),
}),
});
const data = await res.json();
return data.choices[0].message.content.trim();
*/
// 2. Mock implementation so the app compiles/offline:
await new Promise((r) => setTimeout(r, 1500)); // fake latency
return `Echo (${model}): ${history[history.length - 1].content}`;
}
////////////////////////////////////////////////////////////////////////////////
// 6. Styles
////////////////////////////////////////////////////////////////////////////////
const PRIMARY = "#4A63E7";
const BG_USER = PRIMARY;
const BG_BOT = "#ECECEC";
const TXT_USER = "#fff";
const TXT_BOT = "#000";
const styles = StyleSheet.create({
container: { flex: 1, backgroundColor: "#F9F9F9" },
header: {
flexDirection: "row",
alignItems: "center",
backgroundColor: PRIMARY,
paddingHorizontal: 12,
paddingVertical: 8,
},
title: { color: "#fff", fontSize: 20, fontWeight: "600", flex: 1 },
picker: {
height: 32,
width: 140,
color: "#fff",
backgroundColor: "rgba(255,255,255,0.1)",
borderRadius: 6,
},
list: { padding: 12, paddingBottom: 80 },
bubble: {
maxWidth: "80%",
borderRadius: 18,
padding: 10,
marginVertical: 4,
},
bubbleUser: {
alignSelf: "flex-end",
backgroundColor: BG_USER,
},
bubbleBot: {
alignSelf: "flex-start",
backgroundColor: BG_BOT,
},
bubbleTxt: {
color: "#000",
},
typing: {
flexDirection: "row",
alignItems: "center",
paddingHorizontal: 14,
marginBottom: 6,
},
typingText: { marginLeft: 6, color: "#666" },
composer: {
flexDirection: "row",
alignItems: "flex-end",
padding: 12,
borderTopWidth: 1,
borderColor: "#ddd",
backgroundColor: "#fff",
},
input: {
flex: 1,
maxHeight: 110,
borderWidth: 1,
borderColor: "#ccc",
borderRadius: 16,
paddingHorizontal: 14,
paddingVertical: 8,
backgroundColor: "#fff",
},
sendBtn: {
marginLeft: 8,
backgroundColor: PRIMARY,
paddingHorizontal: 18,
paddingVertical: 10,
borderRadius: 16,
},
sendTxt: { color: "#fff", fontWeight: "600" },
});
How to run
expo init ai-chat ➜ blank (TypeScript)
cd ai-chat && expo install @react-native-async-storage/async-storage @react-native-picker/picker expo-crypto
- Replace
App.tsx with the file above
- (Optional)
expo install react-native-dotenv and expose your keys, then uncomment the OpenAI section in sendToLLM
expo start
Enjoy your slick, private, multi-LLM chat client!