Certainly! Let's help you create a very advanced user interface (UI) for your Cloudflare AI. We'll build a web application that allows users to interact with your AI models seamlessly, providing both simple prompt completions and chat-style interactions.
Overview
We'll develop:
-
A Cloudflare Worker API: To handle requests from the frontend UI, process input prompts or messages, and return AI responses.
-
A Modern Frontend Application: Using React (or any framework of your choice) to create an interactive and responsive UI.
-
Advanced UI Features: Including a chat interface, syntax highlighting for code, conversation history, and responsive design.
1. Enhance Your Cloudflare Worker Script
First, we'll modify your Cloudflare Worker script to handle API requests from the frontend.
Worker Script:
export default {
async fetch(request, env) {
const url = new URL(request.url);
if (request.method === 'OPTIONS') {
// Handle CORS preflight requests
return handleOptions(request);
}
if (request.method === 'POST') {
const { pathname } = url;
const requestData = await request.json();
if (pathname === '/api/simple') {
// Simple prompt completion
const { prompt } = requestData;
const response = await env.AI.run('@cf/meta/llama-3-8b-instruct', { prompt });
return createJsonResponse({ response });
} else if (pathname === '/api/chat') {
// Chat-style interaction
const { messages } = requestData;
const response = await env.AI.run('@cf/meta/llama-3-8b-instruct', { messages });
return createJsonResponse({ response });
} else {
return new Response('Not Found', { status: 404 });
}
}
return new Response('Method Not Allowed', { status: 405 });
},
};
function handleOptions(request) {
// Handle CORS preflight requests
return new Response(null, {
status: 204,
headers: {
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Methods': 'GET,POST,OPTIONS',
'Access-Control-Allow-Headers': 'Content-Type',
},
});
}
function createJsonResponse(data) {
return new Response(JSON.stringify(data), {
headers: {
'Content-Type': 'application/json',
'Access-Control-Allow-Origin': '*',
},
});
}
Key Enhancements:
- CORS Support: Added headers to handle Cross-Origin Resource Sharing, allowing the frontend to make requests to the Worker API.
- API Endpoints: Established
/api/simple and /api/chat endpoints to handle different interaction styles.
- Error Handling: Basic error responses for unsupported methods or paths.
2. Develop the Frontend Application
We'll create a React application with an advanced UI.
Setup React Project:
npx create-react-app cloudflare-ai-ui
cd cloudflare-ai-ui
Install Dependencies:
# Material-UI for UI components
npm install @mui/material @emotion/react @emotion/styled
# Axios for HTTP requests
npm install axios
# React Router for navigation (optional)
npm install react-router-dom
# Syntax highlighting
npm install react-syntax-highlighter
App Structure
src/
- components/
ChatInterface.js
SimplePrompt.js
MessageList.js
MessageInput.js
- App.js
- index.js
Implementing Components
App.js
Set up routing between the Simple Prompt and Chat Interface.
import React from 'react';
import { BrowserRouter as Router, Routes, Route, Link } from 'react-router-dom';
import SimplePrompt from './components/SimplePrompt';
import ChatInterface from './components/ChatInterface';
import { AppBar, Toolbar, Button } from '@mui/material';
function App() {
return (
<Router>
<AppBar position="static">
<Toolbar>
<Button color="inherit" component={Link} to="/">
Simple Prompt
</Button>
<Button color="inherit" component={Link} to="/chat">
Chat Interface
</Button>
</Toolbar>
</AppBar>
<Routes>
<Route path="/" element={<SimplePrompt />} />
<Route path="/chat" element={<ChatInterface />} />
</Routes>
</Router>
);
}
export default App;
SimplePrompt.js
Component for handling simple prompts.
import React, { useState } from 'react';
import { TextField, Button, Typography, Container, CircularProgress } from '@mui/material';
import axios from 'axios';
const SimplePrompt = () => {
const [prompt, setPrompt] = useState('');
const [response, setResponse] = useState('');
const [loading, setLoading] = useState(false);
const handlePromptSubmit = async () => {
setLoading(true);
try {
const res = await axios.post('https://your-worker-url/api/simple', { prompt });
setResponse(res.data.response.completion.content);
} catch (error) {
console.error(error);
setResponse('An error occurred.');
}
setLoading(false);
};
return (
<Container maxWidth="md">
<Typography variant="h4" gutterBottom>
Simple Prompt Completion
</Typography>
<TextField
label="Enter your prompt"
multiline
rows={4}
fullWidth
variant="outlined"
value={prompt}
onChange={(e) => setPrompt(e.target.value)}
/>
<Button
variant="contained"
color="primary"
onClick={handlePromptSubmit}
style={{ marginTop: '10px' }}
disabled={loading}
>
{loading ? <CircularProgress size={24} /> : 'Submit'}
</Button>
{response && (
<Typography variant="h6" style={{ marginTop: '20px' }}>
AI Response:
</Typography>
)}
{response && (
<Typography variant="body1" style={{ whiteSpace: 'pre-wrap' }}>
{response}
</Typography>
)}
</Container>
);
};
export default SimplePrompt;
Features:
- Input field for the prompt.
- Submit button with a loading indicator.
- Display of the AI's response.
ChatInterface.js
Component for the chat-style interface.
import React, { useState, useEffect } from 'react';
import { Container, TextField, Button, List, ListItem, ListItemText, Typography, CircularProgress } from '@mui/material';
import axios from 'axios';
import MessageList from './MessageList';
import MessageInput from './MessageInput';
const ChatInterface = () => {
const [messages, setMessages] = useState([
{ role: 'system', content: 'You are a helpful assistant.' }
]);
const [loading, setLoading] = useState(false);
const sendMessage = async (input) => {
const userMessage = { role: 'user', content: input };
const updatedMessages = [...messages, userMessage];
setMessages(updatedMessages);
setLoading(true);
try {
const res = await axios.post('https://your-worker-url/api/chat', { messages: updatedMessages });
const aiMessage = { role: 'assistant', content: res.data.response.completion.content };
setMessages([...updatedMessages, aiMessage]);
} catch (error) {
console.error(error);
const errorMessage = { role: 'assistant', content: 'An error occurred while processing your request.' };
setMessages([...updatedMessages, errorMessage]);
}
setLoading(false);
};
return (
<Container maxWidth="md">
<Typography variant="h4" gutterBottom>
Chat Interface
</Typography>
<MessageList messages={messages} />
{loading && <CircularProgress />}
<MessageInput onSend={sendMessage} disabled={loading} />
</Container>
);
};
export default ChatInterface;
MessageList.js
Display the conversation history.
import React from 'react';
import { List, ListItem, ListItemText, Paper } from '@mui/material';
import { Prism as SyntaxHighlighter } from 'react-syntax-highlighter';
import { materialLight } from 'react-syntax-highlighter/dist/esm/styles/prism';
const MessageList = ({ messages }) => {
return (
<List>
{messages.filter(msg => msg.role !== 'system').map((msg, index) => (
<ListItem key={index} style={{ justifyContent: msg.role === 'user' ? 'flex-end' : 'flex-start' }}>
<Paper style={{
padding: '10px',
backgroundColor: msg.role === 'user' ? '#DCF8C6' : '#E6E6E6',
maxWidth: '75%',
}}>
{renderContent(msg.content)}
</Paper>
</ListItem>
))}
</List>
);
};
const renderContent = (content) => {
if (content.includes('```')) {
// Extract code block
const codeMatch = content.match(/```(.*?)\n([\s\S]*?)```/);
if (codeMatch) {
const language = codeMatch[1];
const code = codeMatch[2];
return (
<SyntaxHighlighter language={language || 'text'} style={materialLight}>
{code}
</SyntaxHighlighter>
);
}
}
// Regular text
return <ListItemText primary={content} />;
};
export default MessageList;
Features:
- Syntax Highlighting: Detects code blocks enclosed in triple backticks and highlights them.
- Message Styling: Differentiates between user and assistant messages with alignment and background colors.
MessageInput.js
Input field for user messages.
import React, { useState } from 'react';
import { TextField, Button } from '@mui/material';
const MessageInput = ({ onSend, disabled }) => {
const [input, setInput] = useState('');
const handleSend = () => {
if (input.trim()) {
onSend(input.trim());
setInput('');
}
};
return (
<div style={{ marginTop: '20px', display: 'flex' }}>
<TextField
label="Type your message"
fullWidth
variant="outlined"
value={input}
onChange={(e) => setInput(e.target.value)}
disabled={disabled}
onKeyPress={(e) => {
if (e.key === 'Enter' && !e.shiftKey) {
e.preventDefault();
handleSend();
}
}}
/>
<Button
variant="contained"
color="primary"
onClick={handleSend}
disabled={disabled}
style={{ marginLeft: '10px' }}
>
Send
</Button>
</div>
);
};
export default MessageInput;
3. Implement Advanced UI Features
Responsive Design:
- Use Material-UI's components and Grid system to ensure the application looks great on all screen sizes.
- Test the application on multiple devices and browsers.
Theming and Dark Mode:
- Implement theme switching using Material-UI's theming capabilities.
// In your main App component or index.js
import { createTheme, ThemeProvider } from '@mui/material/styles';
const darkTheme = createTheme({
palette: {
mode: 'dark',
},
});
// Wrap your app with the ThemeProvider
<ThemeProvider theme={darkTheme}>
<App />
</ThemeProvider>
Error Handling and Validation:
- Provide user feedback when errors occur.
- Validate user input before sending it to the backend.
4. Deploy Your Application
Deploying the Frontend:
Deploying the Backend:
- Your Cloudflare Worker can be deployed using the Wrangler CLI.
# Install Wrangler if not already installed
npm install -g wrangler
# Login to Cloudflare
wrangler login
# Publish your Worker
wrangler publish
Ensure your Worker is configured correctly in the wrangler.toml file, including setting up any environment variables or bindings required.
5. Testing and Iteration
- Testing: Thoroughly test the application to ensure all features work as expected.
- User Feedback: If possible, gather feedback from real users to identify areas for improvement.
- Continuous Integration: Set up CI/CD pipelines to automate testing and deployment.
- Performance Optimization: Monitor the performance and optimize as needed, e.g., lazy loading components, minimizing API calls.
Additional Enhancements
- User Authentication: Implement authentication if you want to restrict access.
- Session Persistence: Save conversations for users, possibly using local storage or a backend database.
- Voice Input/Output: Integrate speech recognition and text-to-speech for a more interactive experience.
- Analytics: Track usage patterns to understand how users interact with your AI.
Final Thoughts
By integrating your Cloudflare AI with a modern, responsive frontend, you create an engaging platform for users to interact with AI in advanced ways. The architecture is scalable and can be extended with more features as needed.
Feel free to ask if you need further assistance or have any specific requirements you'd like to implement!