DEV Community

Cover image for Hướng Dẫn Từng Bước Sử Dụng API Grok Chuyển Ảnh Thành Video
Sebastian Petrus
Sebastian Petrus

Posted on • Originally published at apidog.com

Hướng Dẫn Từng Bước Sử Dụng API Grok Chuyển Ảnh Thành Video

Tóm tắt

API chuyển đổi hình ảnh thành video của Grok sử dụng mô hình grok-imagine-video để chuyển hóa một ảnh tĩnh thành một đoạn video động. Bạn chỉ cần gửi (POST) URL hình ảnh, một prompt mô tả, cùng các tham số tuỳ chọn đến https://api.x.ai/v1/videos/generations. API trả về request_id ngay lập tức; tiếp theo, bạn truy vấn (poll) endpoint GET /v1/videos/{request_id} cho đến khi status chuyển thành "done". Video có thể có độ dài từ 1 đến 15 giây, chi phí bắt đầu từ 0.05 USD/giây cho đầu ra 480p.

Dùng thử Apidog ngay hôm nay

Giới thiệu

Ngày 28/01/2026, xAI công bố mô hình grok-imagine-video qua API công khai. Chỉ trong tháng đầu, mô hình đã tạo 1.2 tỷ video và dẫn đầu bảng xếp hạng chuyển đổi văn bản thành video của Artificial Analysis. Chuyển đổi hình ảnh thành video là một trong các năng lực nổi bật: bạn cung cấp ảnh và prompt, API sẽ tạo hoạt ảnh và xuất ra video MP4 sẵn sàng tải về.

Luồng bất đồng bộ (async flow) này – gửi tác vụ rồi phải poll để biết hoàn thành – chính là thách thức kiểm thử thường bị bỏ qua. Việc tích hợp chỉ thực sự hoàn thiện khi bạn xác nhận vòng lặp polling xử lý đúng các trạng thái "processing", "done", "failed" trong các điều kiện mạng thực tế.

Kịch bản kiểm thử của Apidog giúp giải quyết trực tiếp: bạn có thể tạo chuỗi tuần tự gồm gửi POST /v1/videos/generations, trích xuất request_id, lặp poll cho đến khi status == "done", rồi assert URL video có mặt.

API Grok chuyển đổi hình ảnh thành video là gì?

API này thuộc bộ sản phẩm video của xAI, sử dụng mô hình grok-imagine-video. Bạn cung cấp hình ảnh để làm khung bắt đầu cho video. API phân tích nội dung ảnh, prompt, rồi tạo chuyển động tự nhiên.

  • Endpoint:
  POST https://api.x.ai/v1/videos/generations
Enter fullscreen mode Exit fullscreen mode
  • Header xác thực:
  Authorization: Bearer YOUR_XAI_API_KEY
Enter fullscreen mode Exit fullscreen mode

API cũng hỗ trợ chuyển văn bản thành video, mở rộng và chỉnh sửa video.

Quá trình chuyển đổi hình ảnh thành video hoạt động như thế nào

Tham số image chỉ định khung hình đầu tiên của video. Mô hình sẽ dự đoán chuyển động tiếp theo dựa trên prompt.

Ví dụ:

  • Ảnh: Hồ núi lúc bình minh
  • Prompt: "những gợn sóng nhẹ lan tỏa trên mặt nước khi sương mù buổi sáng trôi qua."
  • Khung đầu là ảnh bạn cung cấp, các khung sau thể hiện chuyển động theo prompt.

Khi nào nên dùng image-to-video:

  • Có sẵn ảnh sản phẩm, phong cảnh, chân dung cần thêm motion
  • Cần đồng nhất nhận diện hình ảnh ở khung đầu tiên
  • Muốn motion dựa trên bối cảnh thực

Khi nào nên dùng text-to-video:

  • Không có hình ảnh tham chiếu, muốn mô hình tự tạo cảnh
  • Ưu tiên tốc độ lặp hơn độ chính xác khung hình đầu

Điều kiện tiên quyết

Cần chuẩn bị:

  1. Tài khoản xAI: console.x.ai
  2. API Key: Không hardcode, lưu vào biến môi trường.
  3. Python 3.8+ hoặc Node.js 18+.
  4. URL ảnh công khai hoặc ảnh base64 dạng data URI.
export XAI_API_KEY="your_key_here"
Enter fullscreen mode Exit fullscreen mode

Cài SDK Python nếu cần:

pip install xai-sdk
Enter fullscreen mode Exit fullscreen mode

Gọi HTTP thô chỉ cần requests (Python) hoặc fetch (Node.js).

Bảng điều khiển xAI để lấy khóa API.

Thực hiện yêu cầu chuyển hình ảnh thành video đầu tiên

Sử dụng curl

curl -X POST https://api.x.ai/v1/videos/generations \
  -H "Authorization: Bearer $XAI_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "grok-imagine-video",
    "prompt": "Gentle waves move across the surface, morning mist rises slowly",
    "image": {
      "url": "https://upload.wikimedia.org/wikipedia/commons/thumb/1/1a/24701-nature-natural-beauty.jpg/1280px-24701-nature-natural-beauty.jpg"
    },
    "duration": 6,
    "resolution": "720p",
    "aspect_ratio": "16:9"
  }'
Enter fullscreen mode Exit fullscreen mode

Phản hồi:

{
  "request_id": "d97415a1-5796-b7ec-379f-4e6819e08fdf"
}
Enter fullscreen mode Exit fullscreen mode

Video chưa sẵn sàng. Cần poll để lấy kết quả.

Sử dụng Python (yêu cầu thô)

import os
import requests

api_key = os.environ["XAI_API_KEY"]

payload = {
    "model": "grok-imagine-video",
    "prompt": "Gentle waves move across the surface, morning mist rises slowly",
    "image": {
        "url": "https://upload.wikimedia.org/wikipedia/commons/thumb/1/1a/24701-nature-natural-beauty.jpg/1280px-24701-nature-natural-beauty.jpg"
    },
    "duration": 6,
    "resolution": "720p",
    "aspect_ratio": "16:9"
}

headers = {
    "Authorization": f"Bearer {api_key}",
    "Content-Type": "application/json"
}

response = requests.post(
    "https://api.x.ai/v1/videos/generations",
    json=payload,
    headers=headers
)

data = response.json()
request_id = data["request_id"]
print(f"Job started: {request_id}")
Enter fullscreen mode Exit fullscreen mode

Sử dụng hình ảnh base64

Nếu ảnh cục bộ hoặc không công khai, mã hóa thành data URI:

import base64

with open("my_image.jpg", "rb") as f:
    encoded = base64.b64encode(f.read()).decode("utf-8")

payload["image"] = {
    "url": f"data:image/jpeg;base64,{encoded}"
}
Enter fullscreen mode Exit fullscreen mode

Truy vấn kết quả

Tạo video diễn ra bất đồng bộ. Truy vấn endpoint:

GET https://api.x.ai/v1/videos/{request_id}
Enter fullscreen mode Exit fullscreen mode

Các trạng thái:

Trạng thái Ý nghĩa
"processing" Video đang render
"done" Video hoàn tất, có URL
"failed" Có lỗi xảy ra

Phản hồi mẫu:

{
  "status": "done",
  "video": {
    "url": "https://vidgen.x.ai/....mp4",
    "duration": 6
  },
  "progress": 100
}
Enter fullscreen mode Exit fullscreen mode

Vòng lặp truy vấn Python hoàn chỉnh

import time

def poll_video(request_id: str, api_key: str, interval: int = 5) -> dict:
    url = f"https://api.x.ai/v1/videos/{request_id}"
    headers = {"Authorization": f"Bearer {api_key}"}

    while True:
        response = requests.get(url, headers=headers)
        data = response.json()
        status = data.get("status")

        print(f"Status: {status} | Progress: {data.get('progress', 0)}%")

        if status == "done":
            return data["video"]
        elif status == "failed":
            raise RuntimeError(f"Video generation failed for {request_id}")

        time.sleep(interval)

# Sử dụng
video = poll_video(request_id, api_key)
print(f"Video URL: {video['url']}")
print(f"Duration: {video['duration']}s")
Enter fullscreen mode Exit fullscreen mode

Khuyến nghị để polling interval tối thiểu 5 giây để tránh vượt giới hạn 60 requests/phút.

Sử dụng xAI Python SDK

Thư viện xai-sdk tự động hóa polling và xử lý lỗi:

from xai_sdk import Client
import os

client = Client(api_key=os.environ["XAI_API_KEY"])

video = client.video.generate(
    model="grok-imagine-video",
    prompt="Gentle waves move across the surface, morning mist rises slowly",
    image={"url": "https://example.com/landscape.jpg"},
    duration=6,
    resolution="720p",
    aspect_ratio="16:9"
)

print(f"Video URL: {video.url}")
print(f"Duration: {video.duration}s")
Enter fullscreen mode Exit fullscreen mode

Sử dụng SDK để có code sạch, không cần tự viết vòng lặp truy vấn. Nếu cần kiểm soát chi tiết hơn về retry, logging hoặc interval, dùng phương pháp HTTP thô.

Kiểm soát độ phân giải, thời lượng và tỷ lệ khung hình

Thời lượng

Tham số duration: 1–15 giây (mặc định 6).

"duration": 10
Enter fullscreen mode Exit fullscreen mode

Video dài hơn = chi phí cao hơn.

Độ phân giải

Giá trị Mô tả
"480p" Mặc định, rẻ và nhanh hơn
"720p" Chất lượng cao, $0.07/giây (vs $0.05/giây)
"resolution": "720p"
Enter fullscreen mode Exit fullscreen mode

Tỷ lệ khung hình

Giá trị Trường hợp sử dụng
"16:9" Mặc định, cảnh quay ngang
"9:16" Dọc, cho mobile/story
"1:1" Hình vuông, Instagram, thumbnail
"4:3" Ảnh cổ điển, trình chiếu
"3:4" Chân dung
"3:2" Cắt ảnh tiêu chuẩn
"2:3" Chân dung cao

Nếu cung cấp image, aspect_ratio sẽ mặc định khớp tỉ lệ ảnh nguồn. Đặt rõ ràng để override/crop.


Sử dụng hình ảnh tham chiếu để định hướng phong cách

Tham số reference_images KHÁC với image:

  • image: Khung hình đầu tiên của video, được animate.
  • reference_images: (tối đa 7) Định hướng style, context – KHÔNG là khung hình output.

Ví dụ kết hợp:

{
  "model": "grok-imagine-video",
  "prompt": "A product rotating slowly on a clean white surface",
  "image": {
    "url": "https://example.com/product-shot.jpg"
  },
  "reference_images": [
    {"url": "https://example.com/brand-style-reference-1.jpg"},
    {"url": "https://example.com/lighting-reference.jpg"}
  ],
  "duration": 6,
  "resolution": "720p"
}
Enter fullscreen mode Exit fullscreen mode

Bạn có thể chỉ dùng reference_images (không cần image) nếu muốn text-to-video nhưng vẫn kiểm soát style.

Mở rộng và chỉnh sửa video

Mở rộng video

POST /v1/videos/extensions nhận video sẵn có và tạo thêm thời lượng (tối đa 15 giây/lần call).

curl -X POST https://api.x.ai/v1/videos/extensions \
  -H "Authorization: Bearer $XAI_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "grok-imagine-video",
    "video_id": "your_original_request_id",
    "prompt": "The mist continues to lift as sunlight breaks through",
    "duration": 5
  }'
Enter fullscreen mode Exit fullscreen mode

Phản hồi cũng trả về request_id để bạn poll giống như tạo mới.

Chỉnh sửa video

POST /v1/videos/edits cho phép prompt chỉnh sửa nội dung/motion video có sẵn.

curl -X POST https://api.x.ai/v1/videos/edits \
  -H "Authorization: Bearer $XAI_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "grok-imagine-video",
    "video_id": "your_original_request_id",
    "prompt": "Change the sky to a dramatic sunset with deep orange tones"
  }'
Enter fullscreen mode Exit fullscreen mode

Cả hai action đều bất đồng bộ, cần poll để lấy kết quả.

Phân tích giá: chi phí của một video 10 giây

Thành phần Chi phí
Hình ảnh input $0.002/ảnh
480p $0.05/giây
720p $0.07/giây

Ví dụ:

  • 10 giây, 720p: 0.002 + 10 × 0.07 = 0.702 USD
  • 6 giây, 480p: 0.002 + 6 × 0.05 = 0.302 USD

Phí hình ảnh tính cho mỗi lần tạo, kể cả lặp lại cùng URL. Chuyển text-to-video (bỏ qua image) sẽ không tính phí input 0.002 USD.

Cách kiểm thử tích hợp API video Grok với Apidog

Async pattern đòi hỏi kiểm thử chuỗi gồm:

  • Tạo, lấy request_id
  • Poll trạng thái "processing"
  • Khi "done", assert URL video không rỗng

Hướng dẫn kiểm thử với Apidog:

Bước 1: Tạo Kịch bản kiểm thử mới

  • Vào module Tests, nhấn +, đặt tên "Luồng bất đồng bộ Grok image-to-video".

Bước 2: Thêm yêu cầu tạo

  • POST: https://api.x.ai/v1/videos/generations
  • Header: Authorization: Bearer {{xai_api_key}}
  • Body:
{
  "model": "grok-imagine-video",
  "prompt": "Gentle mist rises from the water as light filters through the trees",
  "image": {
    "url": "https://example.com/your-test-image.jpg"
  },
  "duration": 6,
  "resolution": "480p"
}
Enter fullscreen mode Exit fullscreen mode

Bước 3: Trích xuất request_id

  • Extract Variable:
    • Tên: video_request_id
    • Nguồn: Response body
    • JSONPath: $.request_id

Bước 4: Xây dựng vòng lặp truy vấn

  • Thêm vòng lặp For
  • Bên trong, gửi GET: https://api.x.ai/v1/videos/{{video_request_id}}
  • Header: Authorization: Bearer {{xai_api_key}}
  • Trích xuất video_status: JSONPath $.status
  • Thêm Wait 5000ms để tránh rate limit
  • Điều kiện Break If: {{video_status}} == "done"

Bước 5: Xác nhận URL video

  • Sau vòng lặp, GET cuối cùng, assert trường $.video.url Is not empty

Chạy kịch bản: Nhấn Run, Apidog sẽ tự động thực hiện POST, poll, assert. Báo cáo thể hiện trạng thái từng bước.

Tích hợp CI/CD với CLI:

apidog run --scenario grok-video-async-flow --env production
Enter fullscreen mode Exit fullscreen mode

Lỗi thường gặp và cách khắc phục

  • 401 Unauthorized: Thiếu/sai API Key. Kiểm tra header Authorization.
  • 422 Unprocessable Entity: Body sai format; kiểm tra trường model, prompt, image.url.
  • Ảnh không truy cập được: Đảm bảo URL public hoặc dùng data URI.
  • Status "processing" mãi không đổi: Nếu quá 10 phút, thử lại bằng request mới.
  • 429 Rate limit: 60 requests/phút, 1 request/giây. Thêm delay giữa các polling.
  • Tải lên base64 lỗi: Đảm bảo data URI đúng prefix, ví dụ data:image/jpeg;base64,.
  • Aspect_ratio không khớp: Nếu aspect_ratio lệch nhiều so với ảnh, model sẽ crop/letterbox. Khuyến nghị khớp tỷ lệ.

Kết luận

API Grok image-to-video cho phép chuyển ảnh tĩnh thành video động chỉ qua một vài bước API: POST ảnh và prompt, nhận request_id, poll cho đến khi hoàn tất, tải về MP4. Mô hình grok-imagine-video đã chứng minh khả năng với hơn 1 tỷ video trong tháng đầu ra mắt.

Async polling là nơi tích hợp dễ gặp lỗi. Kịch bản kiểm thử Apidog giúp tự động hóa extract, loop, assert – tăng độ tin cậy tích hợp trước khi đưa vào sản xuất.

Bắt đầu xây dựng tích hợp với Apidog miễn phí. Không cần thẻ tín dụng.

Câu hỏi thường gặp

Tôi sử dụng tên mô hình nào cho API Grok chuyển đổi hình ảnh thành video?

Tên model là grok-imagine-video. Truyền vào trường model trong body POST.

Khác biệt giữa imagereference_images?

image: khung hình đầu tiên của video, animate từ đây.

reference_images: định hướng style, không xuất hiện trong video, tối đa 7 ảnh.

Tạo video mất bao lâu?

6 giây 480p: 1–3 phút. 15 giây 720p: 4–8 phút. Poll mỗi 5 giây là tối ưu.

Dùng file cục bộ làm ảnh nguồn được không?

Được. Mã hóa thành data URI base64, truyền vào image.url.

Không chỉ định aspect_ratio thì sao?

Nếu có image, mặc định lấy tỷ lệ ảnh nguồn. Nếu text-to-video, mặc định 16:9.

Video 10 giây 720p giá bao nhiêu?

0.002 + 10 × 0.07 = 0.702 USD.

Rate limit là gì?

60 requests/phút, 1 request/giây (bao gồm cả POST/GET).

Có thể mở rộng video quá 15 giây không?

Có. Dùng endpoint POST /v1/videos/extensions, mỗi lần mở rộng tối đa 15 giây, poll như bình thường.

Top comments (0)