Here's a comprehensive TypeScript-based React implementation of a chat-first interface with text and voice mode, supporting OpenAI, Anthropic, and Google Gemini models using an AI SDK. It uses ShadCN UI, follows a dark-first, glassmorphic design, and includes entropic-style artifacts for displaying complex information.
🧠 Project Overview
- Framework: React (TypeScript)
- UI Library: ShadCN UI (Tailwind + Radix UI)
- AI SDK: Custom abstraction for OpenAI, Anthropic, Gemini
- Design: Glassmorphism with Apple-style liquid glass
- Features:
- Chat-first UI
- Switch between Text and Voice
- Accepts API keys for AI providers
- Supports multiple AI models
- Displays complex data (artifacts, code, tables, JSON, etc.)
- Dark-first, accessible design
📁 File Structure
/src
├── components/
│ ├── ChatInterface.tsx
│ ├── ChatMessage.tsx
│ ├── VoiceRecorder.tsx
│ ├── ModelSelector.tsx
│ ├── ApiKeyInput.tsx
│ └── ArtifactRenderer.tsx
├── lib/
│ ├── ai-sdk.ts
│ └── utils.ts
├── App.tsx
└── main.tsx
🔧 Prerequisites
Ensure you have the following installed:
- Node.js
- Vite (or Create React App)
- Tailwind CSS + ShadCN UI configured
- SpeechRecognition library (for voice input)
npm install @shadcn/ui
npm install react-speech-recognition
🧩 AI SDK Abstraction (lib/ai-sdk.ts)
// lib/ai-sdk.ts
import { Configuration, OpenAIApi } from 'openai';
import Anthropic from '@anthropic-ai/sdk';
import { GoogleGenerativeAI } from '@google/generative-ai';
export type ModelProvider = 'openai' | 'anthropic' | 'gemini';
export interface AIModel {
id: string;
provider: ModelProvider;
}
export class AIService {
private openai?: OpenAIApi;
private anthropic?: Anthropic;
private gemini?: GoogleGenerativeAI;
setApiKey(provider: ModelProvider, apiKey: string) {
switch (provider) {
case 'openai':
const openaiConfig = new Configuration({ apiKey });
this.openai = new OpenAIApi(openaiConfig);
break;
case 'anthropic':
this.anthropic = new Anthropic({ apiKey });
break;
case 'gemini':
this.gemini = new GoogleGenerativeAI(apiKey);
break;
}
}
async chat(model: AIModel, prompt: string): Promise<string> {
if (!model.provider) throw new Error('Model provider not set');
switch (model.provider) {
case 'openai':
const openaiRes = await this.openai!.createChatCompletion({
model: model.id,
messages: [{ role: 'user', content: prompt }],
});
return openaiRes.data.choices[0]?.message?.content || 'No response';
case 'anthropic':
const anthropicRes = await this.anthropic!.messages.create({
model: model.id,
max_tokens: 1000,
messages: [{ role: 'user', content: prompt }],
});
return anthropicRes.content[0].text;
case 'gemini':
const genAI = this.gemini!.getGenerativeModel({ model: model.id });
const result = await genAI.generateContent(prompt);
return result.response.text();
default:
throw new Error(`Unsupported provider: ${model.provider}`);
}
}
}
🎨 UI Components
components/ChatInterface.tsx
// components/ChatInterface.tsx
import React, { useState, useRef, useEffect } from 'react';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { ScrollArea } from '@/components/ui/scroll-area';
import { AIService } from '@/lib/ai-sdk';
import ArtifactRenderer from './ArtifactRenderer';
const aiService = new AIService();
interface Message {
text: string;
isUser: boolean;
artifact?: any;
}
export default function ChatInterface() {
const [messages, setMessages] = useState<Message[]>([]);
const [input, setInput] = useState('');
const [mode, setMode] = useState<'text' | 'voice'>('text');
const [apiKey, setApiKey] = useState('');
const [model, setModel] = useState<AIModel>({
id: 'gpt-3.5-turbo',
provider: 'openai',
});
const scrollRef = useRef<HTMLDivElement>(null);
useEffect(() => {
if (scrollRef.current) {
scrollRef.current.scrollTop = scrollRef.current.scrollHeight;
}
}, [messages]);
const sendMessage = async () => {
if (!input.trim()) return;
const userMessage = { text: input, isUser: true };
setMessages((prev) => [...prev, userMessage]);
setInput('');
try {
const response = await aiService.chat(model, input);
const artifact = tryParseArtifact(response);
setMessages((prev) => [
...prev,
{ text: response, isUser: false, artifact },
]);
} catch (err) {
setMessages((prev) => [
...prev,
{ text: 'Error contacting AI', isUser: false },
]);
}
};
const tryParseArtifact = (text: string): any | null => {
try {
return JSON.parse(text);
} catch (e) {
return null;
}
};
return (
<div className="flex flex-col h-full bg-black/70 backdrop-blur-lg border border-white/10 rounded-xl p-4">
<div className="flex justify-between mb-4">
<Button onClick={() => setMode('text')}>Text</Button>
<Button onClick={() => setMode('voice')}>Voice</Button>
</div>
<ScrollArea className="flex-1 p-2 mb-4" ref={scrollRef}>
{messages.map((msg, i) => (
<div
key={i}
className={`mb-2 p-3 rounded-lg max-w-[80%] ${msg.isUser ? 'ml-auto bg-blue-600' : 'bg-white/10'}`}
>
<p>{msg.text}</p>
{msg.artifact && <ArtifactRenderer artifact={msg.artifact} />}
</div>
))}
</ScrollArea>
<div className="flex gap-2">
<Input
value={input}
onChange={(e) => setInput(e.target.value)}
placeholder="Type a message..."
className="bg-black/30 border-white/20 text-white"
/>
<Button onClick={sendMessage}>Send</Button>
</div>
</div>
);
}
components/ArtifactRenderer.tsx
// components/ArtifactRenderer.tsx
import React from 'react';
interface Artifact {
type: 'code' | 'table' | 'json' | 'chart' | 'text';
content: string | Record<string, any>;
}
export default function ArtifactRenderer({ artifact }: { artifact: any }) {
if (typeof artifact === 'object' && artifact.type) {
switch (artifact.type) {
case 'code':
return (
<pre className="bg-black/50 p-2 rounded mt-2 overflow-x-auto">
<code>{artifact.content}</code>
</pre>
);
case 'json':
return (
<pre className="bg-black/50 p-2 rounded mt-2 overflow-x-auto">
<code>{JSON.stringify(artifact.content, null, 2)}</code>
</pre>
);
case 'table':
// Assume content is array of objects
const rows = artifact.content as Record<string, any>[];
const headers = Object.keys(rows[0] || {});
return (
<table className="mt-2 w-full border-collapse">
<thead>
<tr className="bg-white/10">
{headers.map((h) => (
<th key={h} className="border border-white/10 px-2 py-1">
{h}
</th>
))}
</tr>
</thead>
<tbody>
{rows.map((row, i) => (
<tr key={i} className="border border-white/10">
{headers.map((h) => (
<td key={h} className="px-2 py-1">
{row[h]}
</td>
))}
</tr>
))}
</tbody>
</table>
);
default:
return <p className="mt-2">{String(artifact.content)}</p>;
}
}
return (
<pre className="bg-black/50 p-2 rounded mt-2 overflow-x-auto">
<code>{JSON.stringify(artifact, null, 2)}</code>
</pre>
);
}
components/VoiceRecorder.tsx (Optional)
// components/VoiceRecorder.tsx
import React, { useState } from 'react';
import SpeechRecognition, { useSpeechRecognition } from 'react-speech-recognition';
export default function VoiceRecorder({ onTranscript }: { onTranscript: (text: string) => void }) {
const [isListening, setIsListening] = useState(false);
const startListening = () => {
SpeechRecognition.startListening({ language: 'en-US' });
setIsListening(true);
};
const stopListening = () => {
SpeechRecognition.stopListening();
setIsListening(false);
onTranscript(SpeechRecognition.getTranscript());
};
return (
<div>
<Button onClick={isListening ? stopListening : startListening}>
{isListening ? 'Stop Recording' : 'Start Recording'}
</Button>
</div>
);
}
🧪 API Key Input Component
// components/ApiKeyInput.tsx
import React, { useState } from 'react';
import { Input } from '@/components/ui/input';
export default function ApiKeyInput({ provider, onSetKey }: { provider: string; onSetKey: (key: string) => void }) {
const [key, setKey] = useState('');
return (
<div className="mb-4">
<label className="block text-sm mb-2">{provider} API Key</label>
<Input
type="password"
value={key}
onChange={(e) => setKey(e.target.value)}
placeholder={`Enter ${provider} API Key`}
className="bg-black/30 border-white/20 text-white"
/>
<button onClick={() => onSetKey(key)} className="mt-2 bg-blue-600 text-white px-4 py-1 rounded">
Set Key
</button>
</div>
);
}
🧭 Main App Component
// App.tsx
import React from 'react';
import ChatInterface from './components/ChatInterface';
function App() {
return (
<div className="h-screen w-screen flex items-center justify-center bg-gradient-to-br from-black to-gray-900">
<ChatInterface />
</div>
);
}
export default App;
🌟 Design Philosophy
- Glassmorphism: Transparent dark background with blur
- Liquid Glass: Smooth transitions, floating cards
- Dark-First: Light text on dark background
- Accessible: High contrast, semantic HTML
🛠️ Example Artifacts (Generated by AI)
{
"type": "table",
"content": [
{ "name": "Alice", "age": 30 },
{ "name": "Bob", "age": 25 }
]
}
{
"type": "code",
"content": "function hello() {\n console.log('Hello, world!');\n}"
}
🚀 Future Enhancements
- Voice-to-text streaming
- WebSocket-based streaming responses
- History persistence (localStorage or DB)
- Multi-modal support (image input/output)
- Markdown rendering
- Theme switching (light/dark)
✅ Accessibility Notes
- Use
aria-label and role="chat"
- Ensure sufficient color contrast
- Keyboard navigation support
- Screen reader support for dynamic messages
Would you like me to package this as a GitHub repo or generate a Vite template with all files included?