add dbiz, add history
This commit is contained in:
@@ -16,6 +16,7 @@ export function WritingChecker() {
|
||||
const [text, setText] = useState('')
|
||||
const [improvedExpanded, setImprovedExpanded] = useState(false)
|
||||
const [remaining, setRemaining] = useState(getRemainingChecks)
|
||||
const [streamingText, setStreamingText] = useState('')
|
||||
|
||||
const { mutate: checkWriting, isPending, isError, error, data: feedback, reset: resetMutation } = useWritingCheck()
|
||||
const { requireAuth } = useRequireAuth()
|
||||
@@ -42,8 +43,12 @@ export function WritingChecker() {
|
||||
function handleSubmit() {
|
||||
if (!requireAuth()) return
|
||||
if (!canSubmit) return
|
||||
checkWriting(text, {
|
||||
setStreamingText('')
|
||||
checkWriting(
|
||||
{ content: text, onChunk: (chunk) => setStreamingText((prev) => prev + chunk) },
|
||||
{
|
||||
onSuccess: () => {
|
||||
setStreamingText('')
|
||||
if (user) {
|
||||
awardActivity({ xp: XP_REWARDS.writing })
|
||||
countTodayWritingSubmissions(user.id).then((used) => setRemaining(AUTH_LIMIT - used))
|
||||
@@ -52,9 +57,11 @@ export function WritingChecker() {
|
||||
}
|
||||
},
|
||||
onError: () => {
|
||||
setStreamingText('')
|
||||
if (!user) setRemaining(getRemainingChecks())
|
||||
},
|
||||
})
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
@@ -78,8 +85,9 @@ export function WritingChecker() {
|
||||
value={text}
|
||||
onChange={(e) => setText(e.target.value.slice(0, MAX_CHARS))}
|
||||
rows={12}
|
||||
dir="ltr"
|
||||
placeholder="Nhập bài writing của bạn vào đây... (TOEIC email, IELTS task, hoặc đoạn văn tự do)"
|
||||
className="w-full resize-none rounded-xl border border-slate-200 bg-slate-50 p-4 text-sm text-slate-800 placeholder:text-slate-400 focus:outline-none focus:border-blue-400 focus:bg-white transition-colors"
|
||||
className="w-full resize-none rounded-xl border border-slate-200 bg-slate-50 p-4 text-sm text-left text-slate-800 placeholder:text-slate-400 focus:outline-none focus:border-blue-400 focus:bg-white transition-colors"
|
||||
/>
|
||||
<div className="mt-3 flex items-center justify-between">
|
||||
<div className="flex items-center gap-1.5">
|
||||
@@ -142,10 +150,21 @@ export function WritingChecker() {
|
||||
)}
|
||||
|
||||
{isPending && (
|
||||
<div className="bg-white rounded-2xl border border-slate-200 p-6 flex flex-col items-center justify-center text-center h-full min-h-48">
|
||||
<div className="w-10 h-10 border-2 border-blue-100 border-t-blue-600 rounded-full animate-spin mb-4" />
|
||||
<p className="text-sm text-slate-500 font-medium">AI đang phân tích bài viết...</p>
|
||||
<p className="text-xs text-slate-400 mt-1">Thường mất 3–5 giây</p>
|
||||
<div className="bg-slate-900 rounded-2xl border border-slate-700 p-5 min-h-48 flex flex-col">
|
||||
<div className="flex items-center gap-2 mb-3 flex-shrink-0">
|
||||
<div className="w-2 h-2 rounded-full bg-blue-400 animate-pulse" />
|
||||
<span className="text-xs font-semibold text-slate-400 uppercase tracking-wider">AI đang phân tích...</span>
|
||||
</div>
|
||||
{streamingText ? (
|
||||
<pre className="text-xs text-green-300 font-mono whitespace-pre-wrap leading-relaxed overflow-auto flex-1">
|
||||
{streamingText}
|
||||
<span className="animate-pulse">▋</span>
|
||||
</pre>
|
||||
) : (
|
||||
<div className="flex items-center justify-center flex-1">
|
||||
<div className="w-6 h-6 border-2 border-slate-700 border-t-blue-400 rounded-full animate-spin" />
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
|
||||
134
src/features/writing/components/WritingHistory.tsx
Normal file
134
src/features/writing/components/WritingHistory.tsx
Normal file
@@ -0,0 +1,134 @@
|
||||
import { useState } from 'react'
|
||||
import { useWritingHistory } from '@/hooks/use-writing-history'
|
||||
import { useAuthStore } from '@/store/auth-store'
|
||||
import type { WritingSubmission } from '@/types'
|
||||
|
||||
function scoreColor(score: string) {
|
||||
const n = parseFloat(score)
|
||||
if (n >= 7) return 'bg-green-100 text-green-700'
|
||||
if (n >= 5) return 'bg-amber-100 text-amber-700'
|
||||
return 'bg-red-100 text-red-700'
|
||||
}
|
||||
|
||||
function relativeTime(iso: string) {
|
||||
const diff = Date.now() - new Date(iso).getTime()
|
||||
const mins = Math.floor(diff / 60_000)
|
||||
if (mins < 1) return 'vừa xong'
|
||||
if (mins < 60) return `${mins} phút trước`
|
||||
const hours = Math.floor(mins / 60)
|
||||
if (hours < 24) return `${hours} giờ trước`
|
||||
return `${Math.floor(hours / 24)} ngày trước`
|
||||
}
|
||||
|
||||
function SubmissionCard({ item }: { item: WritingSubmission }) {
|
||||
const [open, setOpen] = useState(false)
|
||||
const fb = item.feedback
|
||||
|
||||
return (
|
||||
<div className="bg-white rounded-xl border border-slate-200 overflow-hidden">
|
||||
<button
|
||||
onClick={() => setOpen((v) => !v)}
|
||||
className="w-full text-left p-4 flex items-start gap-3 hover:bg-slate-50 transition-colors"
|
||||
>
|
||||
<span className={`text-xs font-bold px-2 py-1 rounded-lg flex-shrink-0 mt-0.5 ${scoreColor(fb?.score ?? '0')}`}>
|
||||
{fb?.score ?? '–'}
|
||||
</span>
|
||||
<div className="flex-1 min-w-0">
|
||||
<p className="text-sm text-slate-700 line-clamp-1">{item.content}</p>
|
||||
<p className="text-xs text-slate-400 mt-0.5">{relativeTime(item.created_at)}</p>
|
||||
</div>
|
||||
<span className="material-symbols-outlined text-slate-400 flex-shrink-0 mt-0.5" style={{ fontSize: 18 }}>
|
||||
{open ? 'expand_less' : 'expand_more'}
|
||||
</span>
|
||||
</button>
|
||||
|
||||
{open && fb && (
|
||||
<div className="border-t border-slate-100 p-4 space-y-4">
|
||||
<div>
|
||||
<p className="text-xs text-slate-400 mb-2">Bài viết gốc</p>
|
||||
<p className="text-xs text-slate-600 leading-relaxed whitespace-pre-wrap">{item.content}</p>
|
||||
</div>
|
||||
|
||||
{fb.grammar?.length > 0 && (
|
||||
<div>
|
||||
<p className="text-xs font-semibold text-slate-600 mb-1.5 flex items-center gap-1.5">
|
||||
<span className="w-1.5 h-1.5 rounded-full bg-red-500 inline-block" />
|
||||
Ngữ pháp
|
||||
</p>
|
||||
<ul className="space-y-1">
|
||||
{fb.grammar.map((g, i) => (
|
||||
<li key={i} className="text-xs text-slate-600 flex gap-1.5">
|
||||
<span className="text-red-400 flex-shrink-0">•</span>{g}
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{fb.vocabulary?.length > 0 && (
|
||||
<div>
|
||||
<p className="text-xs font-semibold text-slate-600 mb-1.5 flex items-center gap-1.5">
|
||||
<span className="w-1.5 h-1.5 rounded-full bg-amber-500 inline-block" />
|
||||
Từ vựng
|
||||
</p>
|
||||
<ul className="space-y-1">
|
||||
{fb.vocabulary.map((v, i) => (
|
||||
<li key={i} className="text-xs text-slate-600 flex gap-1.5">
|
||||
<span className="text-amber-400 flex-shrink-0">•</span>{v}
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{fb.structure && (
|
||||
<div>
|
||||
<p className="text-xs font-semibold text-slate-600 mb-1">Cấu trúc</p>
|
||||
<p className="text-xs text-slate-600">{fb.structure}</p>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{fb.summary && (
|
||||
<div className="bg-green-50 rounded-lg p-3">
|
||||
<p className="text-xs font-semibold text-green-700 mb-1">Tổng nhận xét</p>
|
||||
<p className="text-xs text-slate-600">{fb.summary}</p>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export function WritingHistory() {
|
||||
const user = useAuthStore((s) => s.user)
|
||||
const { data: history, isLoading } = useWritingHistory()
|
||||
|
||||
if (!user) return null
|
||||
|
||||
return (
|
||||
<section className="px-4 lg:px-6 pb-10 max-w-6xl mx-auto">
|
||||
<h2 className="text-lg font-bold text-slate-800 mb-4">Lịch sử chấm bài</h2>
|
||||
|
||||
{isLoading && (
|
||||
<div className="flex items-center gap-2 text-sm text-slate-400">
|
||||
<div className="w-4 h-4 border-2 border-slate-200 border-t-blue-500 rounded-full animate-spin" />
|
||||
Đang tải...
|
||||
</div>
|
||||
)}
|
||||
|
||||
{!isLoading && !history?.length && (
|
||||
<div className="text-center py-10 text-slate-400">
|
||||
<span className="material-symbols-outlined mb-2 block" style={{ fontSize: 36 }}>history</span>
|
||||
<p className="text-sm">Chưa có bài nào được chấm.</p>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{!!history?.length && (
|
||||
<div className="space-y-2">
|
||||
{history.map((item) => <SubmissionCard key={item.id} item={item} />)}
|
||||
</div>
|
||||
)}
|
||||
</section>
|
||||
)
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
import { useMutation } from "@tanstack/react-query"
|
||||
import { useMutation, useQueryClient } from "@tanstack/react-query"
|
||||
import { canUseWritingCheck, recordWritingCheckUsage } from "@/utils/rate-limiter"
|
||||
import { useAuthStore } from "@/store/auth-store"
|
||||
import { supabase } from "@/lib/supabase"
|
||||
@@ -8,51 +8,119 @@ import type { WritingFeedback } from "@/types"
|
||||
const AUTH_DAILY_LIMIT = 10
|
||||
const GUEST_DAILY_LIMIT = 3
|
||||
|
||||
async function callEdgeFunction(content: string): Promise<WritingFeedback> {
|
||||
const { data, error } = await supabase.functions.invoke<WritingFeedback>("writing-check", {
|
||||
body: { content },
|
||||
const SUPABASE_URL = import.meta.env.VITE_SUPABASE_URL as string
|
||||
const SUPABASE_ANON_KEY = (
|
||||
import.meta.env.VITE_SUPABASE_ANON_KEY || import.meta.env.VITE_SUPABASE_PUBLISHABLE_KEY
|
||||
) as string
|
||||
|
||||
// Calls the edge function and streams SSE chunks, invoking onChunk for each text piece.
|
||||
// Accumulates the full response, then extracts and parses the JSON object.
|
||||
async function callEdgeFunction(
|
||||
content: string,
|
||||
onChunk?: (text: string) => void,
|
||||
): Promise<WritingFeedback> {
|
||||
const { data: { session } } = await supabase.auth.getSession()
|
||||
|
||||
const res = await fetch(`${SUPABASE_URL}/functions/v1/writing-check-dbiz`, {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
apikey: SUPABASE_ANON_KEY,
|
||||
Authorization: `Bearer ${session?.access_token ?? SUPABASE_ANON_KEY}`,
|
||||
},
|
||||
body: JSON.stringify({ content }),
|
||||
})
|
||||
|
||||
if (error) {
|
||||
// The Supabase SDK wraps non-2xx responses in a generic FunctionsHttpError.
|
||||
// Try to parse the actual error body returned by the edge function.
|
||||
if (!res.ok) {
|
||||
const body = await res.json().catch(() => ({}))
|
||||
throw new Error(body?.error ?? "Đã có lỗi khi chấm bài. Vui lòng thử lại.")
|
||||
}
|
||||
|
||||
const reader = res.body!.getReader()
|
||||
const decoder = new TextDecoder()
|
||||
let buffer = ""
|
||||
let accumulated = ""
|
||||
|
||||
while (true) {
|
||||
const { done, value } = await reader.read()
|
||||
if (done) break
|
||||
|
||||
buffer += decoder.decode(value, { stream: true })
|
||||
const lines = buffer.split("\n")
|
||||
buffer = lines.pop() ?? ""
|
||||
|
||||
for (const line of lines) {
|
||||
if (!line.startsWith("data: ")) continue
|
||||
const payload = line.slice(6).trim()
|
||||
if (payload === "[DONE]") continue
|
||||
|
||||
let event: { text?: string; error?: string }
|
||||
try {
|
||||
const body = await (error as unknown as { context: Response }).context.json()
|
||||
if (body?.error) throw new Error(body.error)
|
||||
event = JSON.parse(payload)
|
||||
} catch {
|
||||
// ignore parse failure, fall through to generic message
|
||||
}
|
||||
throw new Error("Đã có lỗi khi chấm bài. Vui lòng thử lại.")
|
||||
continue // skip malformed SSE lines
|
||||
}
|
||||
|
||||
if (!data) throw new Error("Phản hồi từ AI không hợp lệ. Vui lòng thử lại.")
|
||||
if (event.error) throw new Error(event.error)
|
||||
if (event.text) {
|
||||
accumulated += event.text
|
||||
onChunk?.(event.text)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return data
|
||||
// Extract the outermost JSON object from the accumulated stream
|
||||
const start = accumulated.indexOf("{")
|
||||
const end = accumulated.lastIndexOf("}")
|
||||
if (start === -1 || end === -1) {
|
||||
throw new Error("Phản hồi từ AI không hợp lệ. Vui lòng thử lại.")
|
||||
}
|
||||
|
||||
const raw = JSON.parse(accumulated.slice(start, end + 1))
|
||||
|
||||
// Normalize: model sometimes returns array fields as a plain string
|
||||
const toArray = (v: unknown): string[] => {
|
||||
if (Array.isArray(v)) return v
|
||||
if (typeof v === "string" && v.length > 0) return [v]
|
||||
return []
|
||||
}
|
||||
|
||||
return {
|
||||
...raw,
|
||||
grammar: toArray(raw.grammar),
|
||||
vocabulary: toArray(raw.vocabulary),
|
||||
improvedVersion: raw.improved_version ?? raw.improvedVersion ?? "",
|
||||
} as WritingFeedback
|
||||
}
|
||||
|
||||
export function useWritingCheck() {
|
||||
const queryClient = useQueryClient()
|
||||
return useMutation({
|
||||
mutationFn: async (content: string): Promise<WritingFeedback> => {
|
||||
mutationFn: async ({
|
||||
content,
|
||||
onChunk,
|
||||
}: {
|
||||
content: string
|
||||
onChunk?: (text: string) => void
|
||||
}): Promise<WritingFeedback> => {
|
||||
const user = useAuthStore.getState().user
|
||||
|
||||
if (user) {
|
||||
// Server-side rate limit for authenticated users (10/day)
|
||||
const usedToday = await countTodayWritingSubmissions(user.id)
|
||||
if (usedToday >= AUTH_DAILY_LIMIT) {
|
||||
throw new Error(`Bạn đã dùng hết ${AUTH_DAILY_LIMIT} lần kiểm tra hôm nay. Quay lại vào ngày mai!`)
|
||||
}
|
||||
} else {
|
||||
// localStorage rate limit for guests (3/day)
|
||||
if (!canUseWritingCheck()) {
|
||||
throw new Error(`Bạn đã dùng hết ${GUEST_DAILY_LIMIT} lần kiểm tra hôm nay. Đăng ký để được 10 lần/ngày!`)
|
||||
}
|
||||
}
|
||||
|
||||
const feedback = await callEdgeFunction(content)
|
||||
const feedback = await callEdgeFunction(content, onChunk)
|
||||
|
||||
if (user) {
|
||||
// Save submission to DB (fire-and-forget)
|
||||
saveWritingSubmission(user.id, content, feedback)
|
||||
queryClient.invalidateQueries({ queryKey: ["writing-history"] })
|
||||
} else {
|
||||
recordWritingCheckUsage()
|
||||
}
|
||||
|
||||
14
src/hooks/use-writing-history.ts
Normal file
14
src/hooks/use-writing-history.ts
Normal file
@@ -0,0 +1,14 @@
|
||||
import { useQuery } from "@tanstack/react-query"
|
||||
import { useAuthStore } from "@/store/auth-store"
|
||||
import { fetchWritingHistory } from "@/lib/progress-service"
|
||||
import type { WritingSubmission } from "@/types"
|
||||
|
||||
export function useWritingHistory() {
|
||||
const user = useAuthStore((s) => s.user)
|
||||
return useQuery<WritingSubmission[]>({
|
||||
queryKey: ["writing-history", user?.id],
|
||||
queryFn: () => fetchWritingHistory(user!.id) as Promise<WritingSubmission[]>,
|
||||
enabled: !!user,
|
||||
staleTime: 30_000,
|
||||
})
|
||||
}
|
||||
@@ -1,6 +1,16 @@
|
||||
import { createFileRoute } from "@tanstack/react-router"
|
||||
import { WritingChecker } from "@/features/writing/components/WritingChecker"
|
||||
import { WritingHistory } from "@/features/writing/components/WritingHistory"
|
||||
|
||||
function WritingPage() {
|
||||
return (
|
||||
<>
|
||||
<WritingChecker />
|
||||
<WritingHistory />
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
export const Route = createFileRoute("/writing")({
|
||||
component: WritingChecker,
|
||||
component: WritingPage,
|
||||
})
|
||||
|
||||
@@ -44,6 +44,13 @@ export interface WritingFeedback {
|
||||
summary: string
|
||||
}
|
||||
|
||||
export interface WritingSubmission {
|
||||
id: string
|
||||
content: string
|
||||
feedback: WritingFeedback
|
||||
created_at: string
|
||||
}
|
||||
|
||||
export interface ToeicPart {
|
||||
id: number
|
||||
name: string
|
||||
|
||||
92
supabase/functions/writing-check-dbiz/index.ts
Normal file
92
supabase/functions/writing-check-dbiz/index.ts
Normal file
@@ -0,0 +1,92 @@
|
||||
// Supabase Edge Function: writing-check-dbiz
|
||||
// Uses DBIZ LLM API (qwen-35b, OpenAI-compatible) to analyze English writing.
|
||||
// Deploy: supabase functions deploy writing-check-dbiz --no-verify-jwt
|
||||
// Secrets: supabase secrets set DBIZ_API_KEY=<your_key>
|
||||
|
||||
import OpenAI from "npm:openai@^4"
|
||||
|
||||
const dbiz = new OpenAI({
|
||||
apiKey: Deno.env.get("DBIZ_API_KEY") ?? "",
|
||||
baseURL: "https://ai-api.dbiz.com/v1",
|
||||
})
|
||||
|
||||
const CORS_HEADERS = {
|
||||
"Access-Control-Allow-Origin": "*",
|
||||
"Access-Control-Allow-Headers": "authorization, x-client-info, apikey, content-type",
|
||||
}
|
||||
|
||||
// Structure enforced via system prompt — qwen-35b via LiteLLM drops response_format params.
|
||||
const SYSTEM_PROMPT = `You are an expert English writing teacher specialising in TOEIC and IELTS assessment.
|
||||
Analyse the student's writing and respond ONLY with valid JSON — no markdown, no extra text:
|
||||
{
|
||||
"score": "<estimated band score, e.g. 6.5>",
|
||||
"grammar": ["<issue 1 with correction, mix English example + Vietnamese explanation>"],
|
||||
"vocabulary": ["<vocabulary observation in Vietnamese>"],
|
||||
"structure": "<2–3 sentence structure assessment in Vietnamese>",
|
||||
"improved_version": "<the full improved text in English>",
|
||||
"summary": "<2–3 sentence overall assessment in Vietnamese>"
|
||||
}
|
||||
All string values must use double quotes. Do not use single quotes or unquoted keys.`
|
||||
|
||||
Deno.serve(async (req: Request) => {
|
||||
if (req.method === "OPTIONS") {
|
||||
return new Response("ok", { headers: CORS_HEADERS })
|
||||
}
|
||||
|
||||
try {
|
||||
const { content } = await req.json() as { content: string }
|
||||
|
||||
if (!content || content.trim().length < 10) {
|
||||
return new Response(
|
||||
JSON.stringify({ error: "Bài viết quá ngắn. Vui lòng nhập ít nhất 10 ký tự." }),
|
||||
{ status: 400, headers: { ...CORS_HEADERS, "Content-Type": "application/json" } },
|
||||
)
|
||||
}
|
||||
|
||||
const stream = await dbiz.chat.completions.create({
|
||||
model: "qwen-35b",
|
||||
messages: [
|
||||
{ role: "system", content: SYSTEM_PROMPT },
|
||||
{ role: "user", content: `Analyse this writing:\n\n${content.slice(0, 2000)}` },
|
||||
],
|
||||
temperature: 0.3,
|
||||
max_tokens: 10000,
|
||||
stream: true,
|
||||
})
|
||||
|
||||
const encoder = new TextEncoder()
|
||||
const body = new ReadableStream({
|
||||
async start(controller) {
|
||||
try {
|
||||
for await (const chunk of stream) {
|
||||
const text = chunk.choices[0]?.delta?.content ?? ""
|
||||
if (text) {
|
||||
controller.enqueue(encoder.encode(`data: ${JSON.stringify({ text })}\n\n`))
|
||||
}
|
||||
}
|
||||
} catch (err) {
|
||||
console.error("writing-check-dbiz stream error:", err)
|
||||
controller.enqueue(
|
||||
encoder.encode(`data: ${JSON.stringify({ error: "Đã có lỗi khi chấm bài. Vui lòng thử lại." })}\n\n`),
|
||||
)
|
||||
}
|
||||
controller.enqueue(encoder.encode("data: [DONE]\n\n"))
|
||||
controller.close()
|
||||
},
|
||||
})
|
||||
|
||||
return new Response(body, {
|
||||
headers: {
|
||||
...CORS_HEADERS,
|
||||
"Content-Type": "text/event-stream",
|
||||
"Cache-Control": "no-cache",
|
||||
},
|
||||
})
|
||||
} catch (err) {
|
||||
console.error("writing-check-dbiz error:", err)
|
||||
return new Response(
|
||||
JSON.stringify({ error: "Đã có lỗi khi chấm bài. Vui lòng thử lại." }),
|
||||
{ status: 500, headers: { ...CORS_HEADERS, "Content-Type": "application/json" } },
|
||||
)
|
||||
}
|
||||
})
|
||||
@@ -1,6 +1,6 @@
|
||||
// Supabase Edge Function: writing-check
|
||||
// Uses GLM API (OpenAI-compatible) to analyze English writing submissions.
|
||||
// Deploy: supabase functions deploy writing-check
|
||||
// Deploy: supabase functions deploy writing-check --no-verify-jwt
|
||||
// Secrets: supabase secrets set GLM_API_KEY=<your_key>
|
||||
|
||||
import OpenAI from "npm:openai@^4"
|
||||
@@ -13,10 +13,8 @@ const glm = new OpenAI({
|
||||
const CORS_HEADERS = {
|
||||
"Access-Control-Allow-Origin": "*",
|
||||
"Access-Control-Allow-Headers": "authorization, x-client-info, apikey, content-type",
|
||||
"Content-Type": "application/json",
|
||||
}
|
||||
|
||||
// Instructs the model to return a strict JSON structure with Vietnamese feedback.
|
||||
const SYSTEM_PROMPT = `You are an expert English writing teacher specialising in TOEIC and IELTS assessment.
|
||||
Analyse the student's writing and respond ONLY with valid JSON — no markdown, no extra text:
|
||||
{
|
||||
@@ -29,7 +27,6 @@ Analyse the student's writing and respond ONLY with valid JSON — no markdown,
|
||||
}`
|
||||
|
||||
Deno.serve(async (req: Request) => {
|
||||
// Handle CORS pre-flight
|
||||
if (req.method === "OPTIONS") {
|
||||
return new Response("ok", { headers: CORS_HEADERS })
|
||||
}
|
||||
@@ -40,13 +37,11 @@ Deno.serve(async (req: Request) => {
|
||||
if (!content || content.trim().length < 10) {
|
||||
return new Response(
|
||||
JSON.stringify({ error: "Bài viết quá ngắn. Vui lòng nhập ít nhất 10 ký tự." }),
|
||||
{ status: 400, headers: CORS_HEADERS },
|
||||
{ status: 400, headers: { ...CORS_HEADERS, "Content-Type": "application/json" } },
|
||||
)
|
||||
}
|
||||
|
||||
const completion = await glm.chat.completions.create({
|
||||
// GLM-4-32B-0414-128K: cheapest paid model at $0.1/$0.1 per 1M tokens.
|
||||
// Override via: supabase secrets set GLM_MODEL=<other-model>
|
||||
const stream = await glm.chat.completions.create({
|
||||
model: Deno.env.get("GLM_MODEL") ?? "GLM-4.5-Flash",
|
||||
messages: [
|
||||
{ role: "system", content: SYSTEM_PROMPT },
|
||||
@@ -54,20 +49,42 @@ Deno.serve(async (req: Request) => {
|
||||
],
|
||||
temperature: 0.3,
|
||||
max_tokens: 1500,
|
||||
stream: true,
|
||||
})
|
||||
|
||||
const raw = completion.choices[0]?.message?.content ?? "{}"
|
||||
const encoder = new TextEncoder()
|
||||
const body = new ReadableStream({
|
||||
async start(controller) {
|
||||
try {
|
||||
for await (const chunk of stream) {
|
||||
const text = chunk.choices[0]?.delta?.content ?? ""
|
||||
if (text) {
|
||||
controller.enqueue(encoder.encode(`data: ${JSON.stringify({ text })}\n\n`))
|
||||
}
|
||||
}
|
||||
} catch (err) {
|
||||
console.error("writing-check stream error:", err)
|
||||
controller.enqueue(
|
||||
encoder.encode(`data: ${JSON.stringify({ error: "Đã có lỗi khi chấm bài. Vui lòng thử lại." })}\n\n`),
|
||||
)
|
||||
}
|
||||
controller.enqueue(encoder.encode("data: [DONE]\n\n"))
|
||||
controller.close()
|
||||
},
|
||||
})
|
||||
|
||||
// Strip markdown code fences if the model adds them despite instructions
|
||||
const cleaned = raw.replace(/^```(?:json)?\s*/i, "").replace(/\s*```$/, "").trim()
|
||||
const feedback = JSON.parse(cleaned)
|
||||
|
||||
return new Response(JSON.stringify(feedback), { headers: CORS_HEADERS })
|
||||
return new Response(body, {
|
||||
headers: {
|
||||
...CORS_HEADERS,
|
||||
"Content-Type": "text/event-stream",
|
||||
"Cache-Control": "no-cache",
|
||||
},
|
||||
})
|
||||
} catch (err) {
|
||||
console.error("writing-check error:", err)
|
||||
return new Response(
|
||||
JSON.stringify({ error: "Đã có lỗi khi chấm bài. Vui lòng thử lại." }),
|
||||
{ status: 500, headers: CORS_HEADERS },
|
||||
{ status: 500, headers: { ...CORS_HEADERS, "Content-Type": "application/json" } },
|
||||
)
|
||||
}
|
||||
})
|
||||
|
||||
Reference in New Issue
Block a user