import React, { useState } from 'react'; import { Paper, Typography, Grid, TextField, Button, Divider } from '@material-ui/core'; function OpenAIChat() { const [model, setModel] = useState('gpt-4o-mini'); const [apiKey, setApiKey] = useState(''); const [system, setSystem] = useState('You are a helpful assistant.'); const [prompt, setPrompt] = useState(''); const [response, setResponse] = useState(''); const [loading, setLoading] = useState(false); const [error, setError] = useState(''); const onSend = async () => { setError(''); setResponse(''); const p = (prompt || '').trim(); if (!p) { setError('Please enter a question.'); return; } setLoading(true); try { const res = await fetch('/api/openai/chat', { method: 'POST', headers: { 'Content-Type': 'application/json' }, credentials: 'include', body: JSON.stringify({ prompt: p, model: (model || '').trim() || 'gpt-4o-mini', api_key: (apiKey || undefined), system: (system || undefined) }) }); if (!res.ok) { let txt = await res.text(); try { txt = JSON.stringify(JSON.parse(txt), null, 2); } catch {} throw new Error(txt); } const data = await res.json(); const meta = `Model: ${data.model} | Latency: ${data.latency_sec}s` + (data.usage ? ` | Usage: ${JSON.stringify(data.usage)}` : ''); setResponse((data.response || '(Empty response)') + '\n\n---\n' + meta); } catch (e) { setError('Error: ' + e.message); } finally { setLoading(false); } }; const onClear = () => { setPrompt(''); setResponse(''); setError(''); }; return ( OpenAI Chat (OpenAI API) If the server env var OPENAI_API_KEY is set, the API Key field is optional. setModel(e.target.value)} fullWidth variant="outlined" size="small" /> setApiKey(e.target.value)} fullWidth variant="outlined" size="small" type="password" placeholder="sk-..." /> setSystem(e.target.value)} fullWidth variant="outlined" size="small" /> setPrompt(e.target.value)} fullWidth multiline rows={4} variant="outlined" /> {error && ( {error} )}
Response
{response}
); } export default OpenAIChat;