Grok 4 API
เอกสารอ้างอิง API ฉบับสมบูรณ์สำหรับโมเดล LLM Grok 4 ที่ขับเคลื่อนโดย xAI
รูปแบบโมเดล {#}
API นี้รองรับโมเดล Grok 4 2 รูปแบบ:
การเปรียบเทียบอย่างรวดเร็ว
Grok 4 Text to Text
เอนด์พอยต์
POST /api/v1/chat/completions
พารามิเตอร์คำขอ
จำเป็น
การรองรับข้อความ
ไม่บังคับ
ตัวอย่างคำขอ
const response = await fetch('https://api.flaq.ai/api/v1/chat/completions', {
method: 'POST',
headers: {
'Authorization': 'Bearer YOUR_API_KEY',
'Accept': 'text/event-stream',
'Content-Type': 'application/json'
},
body: JSON.stringify({
model: 'grok-4-text-to-text',
messages: [
{
role: 'user',
content: 'Explain the key differences between REST and GraphQL APIs.'
}
],
stream: true,
max_tokens: 2048
})
});
Grok 4 Image to Text
เอนด์พอยต์
POST /api/v1/chat/completions
พารามิเตอร์คำขอ
จำเป็น
การรองรับข้อความ
ไม่บังคับ
ตัวอย่างคำขอ
const response = await fetch('https://api.flaq.ai/api/v1/chat/completions', {
method: 'POST',
headers: {
'Authorization': 'Bearer YOUR_API_KEY',
'Accept': 'text/event-stream',
'Content-Type': 'application/json'
},
body: JSON.stringify({
model: 'grok-4-image-to-text',
messages: [
{
role: 'user',
content: [
{ type: 'text', text: 'Describe the image and extract any visible text.' },
{
type: 'image_url',
image_url: {
url: 'https://example.com/sample-image.jpg'
}
}
]
}
],
stream: true,
max_tokens: 2048
})
});
รูปแบบการตอบกลับ
Grok 4 LLM models return OpenAI-compatible completion responses. With stream: true, the response is Server-Sent Events; with stream: false, the response is a single JSON object.
การตอบกลับสำเร็จ
data: {"id":"chatcmpl-...","object":"chat.completion.chunk","created":1710000000,"model":"grok-4-text-to-text","choices":[{"index":0,"delta":{"role":"assistant"},"finish_reason":null}]}
data: {"id":"chatcmpl-...","object":"chat.completion.chunk","created":1710000000,"model":"grok-4-text-to-text","choices":[{"index":0,"delta":{"content":"Here is a concise explanation"},"finish_reason":null}]}
data: {"id":"chatcmpl-...","object":"chat.completion.chunk","created":1710000000,"model":"grok-4-text-to-text","choices":[{"index":0,"delta":{},"finish_reason":"stop"}]}
data: {"id":"chatcmpl-...","object":"chat.completion.chunk","created":1710000000,"model":"grok-4-text-to-text","choices":[],"usage":{"prompt_tokens":12,"completion_tokens":8,"total_tokens":20}}
data: [DONE]
การตอบกลับข้อผิดพลาด
event: error
data: {"error":{"message":"API requests too frequent, exceeding rate limit","type":"rate_limit_error","code":"1302","param":null}}
แนวทางปฏิบัติที่ดีที่สุด
- ใช้ข้อความแบบมีโครงสร้าง: ส่งประวัติการสนทนาผ่าน
messages[] แทนการรวมบริบททั้งหมดไว้ใน prompt เดียว
- เลือกตัวแปรโมเดลให้เหมาะสม: ใช้ Text to Text สำหรับการให้เหตุผลด้วยข้อความเท่านั้น และใช้ Image to Text เมื่อต้องการทำความเข้าใจรูปภาพ
- ประมวลผลอีเวนต์ SSE: เพิ่ม
choices[0].delta.content สำหรับการแสดงผลแบบสตรีม และถือว่า data: [DONE] คือการเสร็จสิ้นสำเร็จ
- ส่งเฉพาะอินพุตที่รองรับ: Text to Text ไม่รองรับรูปภาพหรือไฟล์แนบ