// AI Examiner Chat — simulates IELTS Speaking test via text conversation. // Uses the backend AI cascade (Gemini → Groq) to generate examiner questions // and score responses in real-time. function AIExaminer({ state, update }) { const [messages, setMessages] = useState([]); const [input, setInput] = useState(''); const [loading, setLoading] = useState(false); const [part, setPart] = useState(0); // 0=not started, 1/2/3=speaking parts const [questionCount, setQuestionCount] = useState(0); const [sessionScore, setSessionScore] = useState(null); const [topic, setTopic] = useState(''); const messagesEndRef = useRef(null); const hasBackend = state.auth?.user && window.apiClient.isConfigured(); const scrollToBottom = () => { messagesEndRef.current?.scrollIntoView({ behavior: 'smooth' }); }; useEffect(scrollToBottom, [messages]); // ── Voice input (real speaking practice) ── const [recording, setRecording] = useState(false); const [micError, setMicError] = useState(''); const recognitionRef = useRef(null); const SpeechRec = typeof window !== 'undefined' && (window.SpeechRecognition || window.webkitSpeechRecognition); const MIC_ERROR_MESSAGES = { 'not-allowed': "Microphone access is blocked. Check your browser's site permissions and try again.", 'audio-capture': 'No microphone found. Connect a microphone and try again.', 'network': 'Network error during speech recognition — please try again.', 'service-not-allowed': 'Speech recognition service unavailable — please try again.', }; // An active recording session (mic still open, browser still listening) // used to keep running after navigating away from this screen — the mic // indicator stays live in the tab/browser chrome with no way back to it. useEffect(() => () => { recognitionRef.current?.stop(); }, []); const toggleMic = () => { if (recording) { recognitionRef.current?.stop(); return; } if (!SpeechRec) return; setMicError(''); const rec = new SpeechRec(); rec.lang = 'en-US'; rec.interimResults = true; rec.continuous = true; const base = input.trim() ? input.trim() + ' ' : ''; let finalText = ''; rec.onresult = (e) => { let interim = ''; for (let i = e.resultIndex; i < e.results.length; i++) { const t = e.results[i][0].transcript; if (e.results[i].isFinal) finalText += t + ' '; else interim += t; } setInput((base + finalText + interim).replace(/\s+/g, ' ').trimStart()); }; rec.onend = () => { setRecording(false); recognitionRef.current = null; }; rec.onerror = (e) => { setRecording(false); recognitionRef.current = null; setMicError(MIC_ERROR_MESSAGES[e.error] || 'Voice input failed — you can still type your answer.'); }; recognitionRef.current = rec; try { rec.start(); setRecording(true); } catch (e) { setRecording(false); } }; const TOPICS = [ 'Your hometown', 'Food and cooking', 'Daily routine', 'Music and films', 'Education and learning', 'Travel and holidays', 'Sports and fitness', 'Technology in daily life', 'Books and reading', 'Work and career', 'Environment and nature', 'Social media', 'Shopping habits', 'Health and wellbeing', ]; const startExam = async (selectedTopic) => { if (!hasBackend) { alert('Sign in and set up the backend to use AI Examiner.'); return; } const t = selectedTopic || TOPICS[Math.floor(Math.random() * TOPICS.length)]; setTopic(t); setPart(1); setQuestionCount(0); setSessionScore(null); setMessages([]); await askExaminer(t, 1, [], 'start'); }; const askExaminer = async (currentTopic, currentPart, history, action = 'next') => { setLoading(true); try { const conversationContext = history.map(m => `${m.role === 'examiner' ? 'Examiner' : 'Candidate'}: ${m.text}`).join('\n'); const systemPrompt = `You are an IELTS Speaking examiner. You are conducting Part ${currentPart} of the test. Topic: ${currentTopic} ${currentPart === 1 ? 'Part 1: Ask short questions about familiar topics. Ask ONE question at a time. Be warm but professional. After 4-5 questions, say "[MOVE TO PART 2]".' : ''} ${currentPart === 2 ? 'Part 2: Give the candidate a cue card topic related to the theme. Format it as "Describe [topic]. You should say: - point 1 - point 2 - point 3 - and explain why/how...". Say they have 1 minute to prepare, then ask them to speak for 1-2 minutes. After their response, give brief feedback and say "[MOVE TO PART 3]".' : ''} ${currentPart === 3 ? 'Part 3: Ask abstract, analytical discussion questions related to the Part 2 topic. These should require opinion and analysis. Ask ONE question at a time. After 3-4 questions, say "[END OF TEST]" and give a brief overall assessment.' : ''} Return JSON ONLY: {"question":"your question or instruction","feedback":"brief feedback on the candidate's last answer (empty string if this is the first question)","fluency":0-9,"vocabulary":0-9,"grammar":0-9,"pronunciation_note":"any pronunciation-related advice","move_signal":"none|part2|part3|end"}`; const userMsg = action === 'start' ? `Start the test. Topic: ${currentTopic}. This is Part ${currentPart}. Ask the first question.` : `Conversation so far:\n${conversationContext}\n\nThe candidate just spoke. Generate the next examiner turn.`; const response = await window.apiClient.call('/api/ai/examiner-chat', { method: 'POST', body: { system: systemPrompt, user: userMsg, part: currentPart, topic: currentTopic }, }); const data = response.data || response; const examinerMsg = { role: 'examiner', text: data.question || data.text || 'Could you tell me more about that?', feedback: data.feedback || '', scores: data.fluency ? { fluency: data.fluency, vocabulary: data.vocabulary, grammar: data.grammar } : null, pronunciation_note: data.pronunciation_note || '', moveSignal: data.move_signal || 'none', }; setMessages(prev => [...prev, examinerMsg]); if (data.move_signal === 'end') { setSessionScore({ fluency: data.fluency || 6, vocabulary: data.vocabulary || 6, grammar: data.grammar || 6, }); } else if (data.move_signal === 'part2') { setPart(2); } else if (data.move_signal === 'part3') { setPart(3); } } catch (e) { setMessages(prev => [...prev, { role: 'examiner', text: 'I apologize — there was a technical issue. Let me ask another question. What do you enjoy most about ' + currentTopic.toLowerCase() + '?', feedback: '', moveSignal: 'none', }]); } setLoading(false); }; const sendMessage = async () => { if (!input.trim() || loading) return; const userMsg = { role: 'candidate', text: input.trim() }; const updatedMessages = [...messages, userMsg]; setMessages(updatedMessages); setInput(''); setQuestionCount(q => q + 1); // Word count check — encourage longer responses const wordCount = input.trim().split(/\s+/).length; if (part === 2 && wordCount < 40) { setMessages(prev => [...prev, { role: 'system', text: `💡 Tip: In Part 2, aim for at least 60–80 words. You wrote ${wordCount}. Try to elaborate more.`, }]); } // NLP analysis of the response const nlpMetrics = window.nlpAnalyzer.lexicalAnalysis(input); if (nlpMetrics.sophisticatedRatio < 0.03 && wordCount > 15) { setMessages(prev => [...prev, { role: 'system', text: '💡 Vocabulary tip: Try using more advanced words. Instead of "good" → "beneficial", "important" → "crucial", "big" → "substantial".', }]); } await askExaminer(topic, part, updatedMessages); }; return (
AI Examiner · Speaking Practice

Chat with an AI examiner.

Simulates all 3 parts of the IELTS speaking test. Speak your answers with the mic, or type them — AI scores fluency, vocabulary, and grammar in real-time.

{!hasBackend && (
Sign in required
AI Examiner needs the backend. Sign in to use this feature.
)} {part === 0 && hasBackend && (
Choose a topic to start
{TOPICS.map(t => ( ))}
)} {part > 0 && (
{/* Part indicator */}
{[1, 2, 3].map(p => (
Part {p} {p < part && '✓'}
))}
Topic: {topic}
{/* Chat messages */}
{messages.map((m, i) => (
{m.role === 'examiner' &&
Examiner
}
{m.text}
{m.feedback &&
💬 {m.feedback}
} {m.scores && (
Fluency: {m.scores.fluency} Vocab: {m.scores.vocabulary} Grammar: {m.scores.grammar}
)} {m.pronunciation_note &&
🗣️ {m.pronunciation_note}
}
))} {loading && (
Examiner is thinking…
)}
{/* Input */} {!sessionScore && ( <>
{SpeechRec && ( )} setInput(e.target.value)} onKeyDown={e => { if (e.key === 'Enter' && !e.shiftKey) { e.preventDefault(); sendMessage(); } }} placeholder={recording ? 'Listening… speak now' : 'Speak with the mic, or type your answer (Enter to send)'} disabled={loading} autoFocus />
{recording &&
🔴 Recording — press ⏹ when you finish speaking, then Send.
} {!SpeechRec &&
Voice input is not supported in this browser — please type your answer. (Try Chrome or Edge.)
} {micError &&
{micError}
} )} {/* Session score */} {sessionScore && (
Test Complete
{Object.entries(sessionScore).map(([k, v]) => (
{v}
{k}
))}
Overall: {Math.round(((sessionScore.fluency + sessionScore.vocabulary + sessionScore.grammar) / 3) * 2) / 2}
)}
)}
); } Object.assign(window, { AIExaminer });