ISLAM-PO's picture
Upload 861 files
4655dd2 verified
Raw
History Blame Contribute Delete
9.21 kB
"use client"
import { useState, useRef, useEffect } from "react"
import { Card, CardHeader, CardTitle, CardContent } from "@/components/ui/card"
import { Button } from "@/components/ui/button"
import { Textarea } from "@/components/ui/textarea"
import { Input } from "@/components/ui/input"
import { Badge } from "@/components/ui/badge"
import { Select, SelectTrigger, SelectValue, SelectContent, SelectItem } from "@/components/ui/select"
import { streamGenerate } from "@/lib/api"
import { Send, Loader2, Zap, Clock, Cpu, Trash2, Copy, StopCircle } from "lucide-react"
type Msg = { role: "user"|"assistant"|"system"; content: string; stats?: any }
export function Playground() {
const [messages, setMessages] = useState<Msg[]>([
{ role: "system", content: "أنت مساعد ذكي يعمل محلياً من Safetensors Studio." }
])
const [input, setInput] = useState("")
const [temperature, setTemperature] = useState("0.7")
const [maxTokens, setMaxTokens] = useState("512")
const [topP, setTopP] = useState("0.9")
const [streaming, setStreaming] = useState(false)
const [liveStats, setLiveStats] = useState<any>(null)
const [currentStream, setCurrentStream] = useState("")
const bottomRef = useRef<HTMLDivElement>(null)
useEffect(()=>{ bottomRef.current?.scrollIntoView({behavior:"smooth"}) }, [messages, currentStream])
const handleSend = async () => {
if (!input.trim() || streaming) return
const userMsg: Msg = { role:"user", content: input }
setMessages(prev=>[...prev, userMsg])
setInput("")
setStreaming(true)
setCurrentStream("")
setLiveStats(null)
let full = ""
let stats: any = null
await streamGenerate(
{ messages: [...messages, userMsg].filter(m=>m.role!=="system" || true), temperature: parseFloat(temperature), top_p: parseFloat(topP), max_new_tokens: parseInt(maxTokens), stream: true },
(chunk)=>{
if (chunk.type==="ttft") {
setLiveStats((s:any)=>({...s, ttft: chunk.ttft_ms }))
} else if (chunk.type==="token") {
full += chunk.token
setCurrentStream(full)
setLiveStats({ tps: chunk.tokens_per_sec, tokens: chunk.tokens, ttft: chunk.ttft_ms || liveStats?.ttft })
} else if (chunk.type==="done") {
stats = chunk
setLiveStats({ tps: chunk.tokens_per_sec, tokens: chunk.tokens, ttft: chunk.ttft_ms, total: chunk.total_time_ms })
}
},
()=>{
setMessages(prev=>[...prev, { role:"assistant", content: full, stats }])
setCurrentStream("")
setStreaming(false)
},
(e)=>{ setMessages(prev=>[...prev, { role:"assistant", content: `❌ خطأ: ${e.message}` }]); setStreaming(false) }
)
}
const clearChat = ()=> setMessages([{role:"system", content:"أنت مساعد ذكي يعمل محلياً من Safetensors Studio."}])
return (
<div className="grid grid-cols-1 lg:grid-cols-4 gap-4">
{/* Chat */}
<Card className="lg:col-span-3 flex flex-col h-[640px]">
<CardHeader className="pb-3 flex-row items-center justify-between space-y-0">
<CardTitle className="text-base flex items-center gap-2"><Zap className="h-4 w-4 text-violet-600"/> الملعب المباشر - Live Playground</CardTitle>
<div className="flex gap-2">
<Button variant="ghost" size="sm" onClick={clearChat}><Trash2 className="h-4 w-4"/></Button>
<Badge variant={streaming?"warning":"secondary"}>{streaming?"جاري التوليد...":"جاهز"}</Badge>
</div>
</CardHeader>
<CardContent className="flex-1 flex flex-col gap-3 overflow-hidden">
{/* live stats bar */}
{liveStats && (
<div className="flex gap-2 text-xs flex-wrap">
<span className="px-2 py-1 rounded-full bg-violet-50 text-violet-700 border border-violet-200 flex items-center gap-1"><Zap className="h-3 w-3"/> {liveStats.tps?.toFixed(1) || "-"} tok/s</span>
<span className="px-2 py-1 rounded-full bg-amber-50 text-amber-700 border border-amber-200 flex items-center gap-1"><Clock className="h-3 w-3"/> TTFT {liveStats.ttft?.toFixed(0) || "-"} ms</span>
<span className="px-2 py-1 rounded-full bg-emerald-50 text-emerald-700 border border-emerald-200 flex items-center gap-1"><Cpu className="h-3 w-3"/> {liveStats.tokens || 0} tokens</span>
{liveStats.total && <span className="px-2 py-1 rounded-full bg-zinc-100 border">إجمالي {liveStats.total.toFixed(0)} ms</span>}
</div>
)}
<div className="flex-1 overflow-y-auto space-y-3 p-1">
{messages.filter(m=>m.role!=="system").map((m,i)=>(
<div key={i} className={`flex ${m.role==="user"?"justify-end":"justify-start"}`}>
<div className={`max-w-[85%] rounded-2xl px-4 py-3 text-sm whitespace-pre-wrap leading-relaxed ${m.role==="user"?"bg-zinc-900 text-white rounded-br-sm":"bg-zinc-100 dark:bg-zinc-800 rounded-bl-sm"}`}>
{m.content}
{m.stats && <div className="mt-2 text-xs opacity-60 border-t pt-2 flex gap-3"><span>{m.stats.tokens} tokens</span><span>{m.stats.tokens_per_sec} t/s</span><span>TTFT {m.stats.ttft_ms}ms</span></div>}
</div>
</div>
))}
{streaming && currentStream && (
<div className="flex justify-start"><div className="max-w-[85%] rounded-2xl px-4 py-3 text-sm bg-zinc-100 dark:bg-zinc-800 rounded-bl-sm whitespace-pre-wrap">{currentStream}<span className="inline-block w-2 h-4 bg-violet-600 animate-pulse ms-1 align-middle"/></div></div>
)}
{streaming && !currentStream && <div className="flex justify-start"><div className="bg-zinc-100 dark:bg-zinc-800 rounded-2xl px-4 py-3 text-sm flex items-center gap-2"><Loader2 className="h-4 w-4 animate-spin"/> جاري التفكير...</div></div>}
<div ref={bottomRef}/>
</div>
<div className="flex gap-2">
<Textarea value={input} onChange={e=>setInput(e.target.value)} placeholder="اكتب رسالتك هنا... (Shift+Enter لسطر جديد)" className="min-h-[56px] flex-1" onKeyDown={e=>{ if(e.key==="Enter" && !e.shiftKey){ e.preventDefault(); handleSend() } }}/>
<Button onClick={handleSend} disabled={streaming || !input.trim()} className="h-auto px-6 bg-gradient-to-r from-violet-600 to-indigo-600">
{streaming ? <StopCircle className="h-4 w-4"/> : <Send className="h-4 w-4"/>}
</Button>
</div>
</CardContent>
</Card>
{/* Controls */}
<div className="space-y-4">
<Card>
<CardHeader><CardTitle className="text-sm">إعدادات التوليد</CardTitle></CardHeader>
<CardContent className="space-y-4">
<div className="space-y-1.5">
<label className="text-xs font-medium">Temperature: {temperature}</label>
<Input type="range" min="0" max="2" step="0.1" value={temperature} onChange={e=>setTemperature(e.target.value)}/>
<div className="flex justify-between text-xs text-zinc-500"><span>دقيق</span><span>إبداعي</span></div>
</div>
<div className="space-y-1.5">
<label className="text-xs font-medium">Top-P: {topP}</label>
<Input type="range" min="0" max="1" step="0.05" value={topP} onChange={e=>setTopP(e.target.value)}/>
</div>
<div className="space-y-1.5">
<label className="text-xs font-medium">Max Tokens</label>
<Select value={maxTokens} onValueChange={setMaxTokens}>
<SelectTrigger><SelectValue placeholder="512"/></SelectTrigger>
<SelectContent>
<SelectItem value="128">128</SelectItem>
<SelectItem value="256">256</SelectItem>
<SelectItem value="512">512</SelectItem>
<SelectItem value="1024">1024</SelectItem>
<SelectItem value="2048">2048</SelectItem>
</SelectContent>
</Select>
</div>
<div className="rounded-lg bg-zinc-50 dark:bg-zinc-900 p-3 text-xs space-y-1 border">
<div>💡 Temperature المنخفض (0.2) للمهام الدقيقة</div>
<div>🎨 Temperature المرتفع (1.0+) للإبداع</div>
</div>
</CardContent>
</Card>
<Card>
<CardHeader><CardTitle className="text-sm">أمثلة سريعة</CardTitle></CardHeader>
<CardContent className="space-y-2">
{[
"مرحبا، من أنت؟",
"اكتب دالة Python لحساب فيبوناتشي",
"لخص أهمية الذكاء الاصطناعي في 3 نقاط",
"ما هو الرقم التالي: 2,4,8,16,؟"
].map((ex,i)=><button key={i} onClick={()=>setInput(ex)} className="w-full text-start text-xs p-2 rounded-lg border hover:bg-zinc-50 dark:hover:bg-zinc-800 transition-colors">{ex}</button>)}
</CardContent>
</Card>
</div>
</div>
)
}