Skip to content

Text to vertical video in 100+ styles: AI codes each scene (HTML/SVG/WebGL), renders a 9:16 MP4 with music and English/Vietnamese voice. MCP, CLI and REST for AI agents.

Chọn model viết cảnh theo job: tự chọn Opus cho mẫu 3D/shader, Sonnet cho mẫu 2D

Lumtek3e1983316043
diff --git a/cli.mjs b/cli.mjs
index 2f99e3f..988b6d6 100644
--- a/cli.mjs
+++ b/cli.mjs
@@ -21,7 +21,7 @@ const audioOpts = () => ({ music: opt.music === true ? undefined : opt.music, vo
function usage() {
console.log(`LumReels CLI
- make --template <id> --content <file|chuỗi> [--duration 8] [--mode manual|claude|api|auto] [--at <giờ>] [--json]
+ make --template <id> --content <file|chuỗi> [--duration 8] [--mode manual|claude|api|auto] [--model auto|opus|sonnet|haiku] [--at <giờ>] [--json]
--music <style|auto|none> --voice <tên giọng|auto|none> --no-sfx : âm thanh (mặc định auto, auto, có sfx)
--duration: 3 giây → 10 phút, số giây (90) hoặc phút:giây (1:30, 10:00). Mặc định 8.
manual (mặc định): ghi jobs/<id>/PROMPT.md, job ở trạng thái waiting_agent. Agent viết
@@ -62,7 +62,7 @@ try {
if (!opt.template || !opt.content) { usage(); process.exit(2); }
const content = readContent(String(opt.content));
const mode = opt.mode || process.env.VIDEOAI_CLI_MODE || 'manual';
- const job = createJob({ templateId: String(opt.template), content, durationS: opt.duration === true ? undefined : opt.duration, mode, runAt: opt.at, source: 'cli',
+ const job = createJob({ templateId: String(opt.template), content, durationS: opt.duration === true ? undefined : opt.duration, mode, model: typeof opt.model === 'string' ? opt.model : undefined, runAt: opt.at, source: 'cli',
audio: (({ music, voice, sfx }) => ({ music: music ?? 'auto', voice: voice ?? 'auto', sfx: sfx ?? true }))(audioOpts()) });
const p = jobPaths(job.id);
const done = await runJob(job.id);
diff --git a/docs/CHI-TIET.md b/docs/CHI-TIET.md
index ae3f888..158c049 100644
--- a/docs/CHI-TIET.md
+++ b/docs/CHI-TIET.md
@@ -22,6 +22,7 @@ npm start # UI + API ở http://127.0.0.1:4400 (chỉ bind 127.0.0.1)
| `REWRITE_MODEL` / `REWRITE_ENGINE` | model cho nút "Viết lại kịch bản" ở chế độ api (mặc định `claude-haiku-5-5`) / ép engine `api` hoặc `claude` (mặc định `auto`) |
| `LUMREELS_HF_SLOTS` | số HyperFrames chạy song song trên máy (mặc định 3) |
| `VIDEOAI_FONTCHECK=0` | tắt kiểm font lúc preview/render |
+| Model theo job | ô "Model viết cảnh" trên UI, `model` trong `POST /api/jobs` / MCP `create_video`, CLI `--model`: `auto` (mặc định: Opus cho mẫu 3D/shader, Sonnet cho mẫu 2D), `opus`, `sonnet`, `haiku`. Áp cho chế độ `claude` và `api` (api dùng thay `GEN_MODEL`). Đo mẫu 010 (2D): Opus 1,25 USD → Sonnet 0,67 USD quy giá API |
| `LUMREELS_FULL_PROMPT=1` | nạp nguyên AUTHORING + guidance và cho 2 vòng sửa như bản cũ (mặc định: đề đã gọt theo kỹ thuật/font của mẫu, 1 vòng sửa, gom thao tác vào ít lượt; đo trên 3 mẫu: rẻ hơn ~20%) |
Hướng dẫn nối agent (có hình): [docs/HUONG-DAN-KET-NOI-AGENT.md](HUONG-DAN-KET-NOI-AGENT.md).
diff --git a/generator/api.mjs b/generator/api.mjs
index 3d27dc5..fb82891 100644
--- a/generator/api.mjs
+++ b/generator/api.mjs
@@ -76,7 +76,7 @@ export async function runApi(job, dir, prompt, log, saveUsage = () => {}) {
try {
// ---- 1. sinh cảnh ----
- const genModel = config.genModel();
+ const genModel = job.model?.id || config.genModel();
log(`api: sinh cảnh bằng ${genModel}`);
const genContent = [...(hasRef ? [img(refSheet)] : []), { type: 'text', text: prompt + API_NOTE }];
let text = await call(genModel, 'sinh cảnh', genContent);
diff --git a/generator/claude.mjs b/generator/claude.mjs
index cce3427..33d3cf4 100644
--- a/generator/claude.mjs
+++ b/generator/claude.mjs
@@ -61,8 +61,9 @@ export const ALLOWED_TOOLS = [
'Bash(node ../../engine/render.mjs:*)',
];
-export function claudeArgs({ maxTurns = 40 } = {}) {
+export function claudeArgs({ maxTurns = 40, model } = {}) {
return [
+ ...(model ? ['--model', model] : []),
'-p',
'--output-format', 'stream-json', '--verbose',
'--permission-mode', 'default',
@@ -76,12 +77,12 @@ export function claudeArgs({ maxTurns = 40 } = {}) {
}
/** Chạy claude headless, prompt qua stdin. Trả {ok, error?, result?}. */
-export function runClaude(cwd, prompt, log = console.log, { timeoutMs = 25 * 60 * 1000 } = {}) {
+export function runClaude(cwd, prompt, log = console.log, { timeoutMs = 25 * 60 * 1000, model } = {}) {
const bin = findClaude();
if (!bin) return Promise.resolve({ ok: false, error: 'Không tìm thấy lệnh claude (đặt CLAUDE_BIN hoặc thêm vào PATH)' });
return new Promise((resolve) => {
- log(`claude: ${bin} (cwd ${cwd})`);
- const p = spawnClaude(claudeArgs(), { cwd, windowsHide: true, env: (({ ANTHROPIC_API_KEY, ...e }) => e)(process.env) });
+ log(`claude: ${bin}${model ? ' · model ' + model : ''} (cwd ${cwd})`);
+ const p = spawnClaude(claudeArgs({ model }), { cwd, windowsHide: true, env: (({ ANTHROPIC_API_KEY, ...e }) => e)(process.env) });
const raw = fs.createWriteStream(path.join(cwd, 'claude.stream.jsonl'));
let buf = '';
let result = null;
diff --git a/generator/config.mjs b/generator/config.mjs
index 344b432..85b533b 100644
--- a/generator/config.mjs
+++ b/generator/config.mjs
@@ -37,6 +37,25 @@ export const PRICES = {
'claude-opus-5-5': { in: 4, out: 20, cacheRead: 0.20 },
'claude-fable-5-2': { in: 8, out: 40, cacheRead: 0.20 },
};
+// Model viết cảnh theo job. 'auto' = đề xuất theo mẫu: 3D/shader → Opus, 2D → Sonnet (rẻ hơn, đủ tốt cho DOM/SVG/Canvas).
+export const MODEL_IDS = { opus: 'claude-opus-5-5', sonnet: 'claude-sonnet-5-5', haiku: 'claude-haiku-5-5' };
+export const MODEL_CHOICES = ['auto', 'opus', 'sonnet', 'haiku'];
+export function isHeavyTechnique(technique = []) {
+ return (Array.isArray(technique) ? technique : [technique]).some((t) => /three|webgl|shader/i.test(String(t)));
+}
+export function recommendModel(technique) { return isHeavyTechnique(technique) ? 'opus' : 'sonnet'; }
+/** choice (auto|opus|sonnet|haiku|id đầy đủ) → { choice, alias, id, why } */
+export function resolveModel(choice, technique) {
+ const c = String(choice || 'auto').toLowerCase().trim();
+ if (c === 'auto' || !c) {
+ const alias = recommendModel(technique);
+ return { choice: 'auto', alias, id: MODEL_IDS[alias], why: alias === 'opus' ? 'mẫu 3D/shader' : 'mẫu 2D' };
+ }
+ if (MODEL_IDS[c]) return { choice: c, alias: c, id: MODEL_IDS[c], why: 'người dùng chọn' };
+ if (/^claude-[\w.-]+$/.test(c)) return { choice: c, alias: c, id: c, why: 'người dùng chọn' };
+ throw new Error(`Model không hợp lệ: ${choice} (auto|opus|sonnet|haiku)`);
+}
+
export function costOf(model, usage) {
const p = PRICES[model] || PRICES['claude-opus-5-5'];
const inTok = (usage.input_tokens || 0) + (usage.cache_creation_input_tokens || 0) * 1.25;
diff --git a/generator/jobs.mjs b/generator/jobs.mjs
index 0be0cab..4fca5d6 100644
--- a/generator/jobs.mjs
+++ b/generator/jobs.mjs
@@ -4,7 +4,7 @@ import fs from 'node:fs';
import path from 'node:path';
import crypto from 'node:crypto';
import { fileURLToPath } from 'node:url';
-import { config } from './config.mjs';
+import { config, resolveModel } from './config.mjs';
import { buildPrompt } from './prompt.mjs';
import { runClaude, findClaude } from './claude.mjs';
import { runApi } from './api.mjs';
@@ -128,6 +128,7 @@ export function createJob(input) {
if (!MODES.includes(mode)) throw new Error(`Chế độ không hợp lệ: ${mode} (auto|api|claude|manual|agent)`);
const runAt = parseRunAt(input.runAt);
const audio = normalizeAudioPrefs(input.audio); // {music, voice, sfx} — xem engine/audio/prefs.mjs
+ const model = resolveModel(input.model, tpl.technique); // auto → Opus (3D/shader) | Sonnet (2D)
const stamp = new Date().toISOString().replace(/[-:T]/g, '').slice(2, 14);
const id = `${stamp}-${templateId}-${crypto.randomBytes(2).toString('hex')}`;
const dir = path.join(JOBS, id);
@@ -136,13 +137,13 @@ export function createJob(input) {
const hasRef = fs.existsSync(sheet);
if (hasRef) fs.copyFileSync(sheet, path.join(dir, 'ref-sheet.jpg'));
const job = {
- id, templateId, templateTitle: tpl.name, content, durationS, aspect, mode, hasRef, audio,
+ id, templateId, templateTitle: tpl.name, content, durationS, aspect, mode, hasRef, audio, model,
status: runAt && new Date(runAt) > new Date() ? 'scheduled' : 'queued',
runAt, source: input.source || 'api', createdAt: new Date().toISOString(),
};
fs.writeFileSync(path.join(dir, 'PROMPT.md'), buildPrompt(job));
writeJob(job);
- logTo(job)(`tạo job: mẫu ${templateId} "${tpl.name}", ${durationS}s, chế độ ${mode}${runAt ? ', hẹn ' + runAt : ''} (từ ${job.source})`);
+ logTo(job)(`tạo job: mẫu ${templateId} "${tpl.name}", ${durationS}s, chế độ ${mode}, model ${model.alias} (${model.why})${runAt ? ', hẹn ' + runAt : ''} (từ ${job.source})`);
return job;
}
@@ -201,7 +202,7 @@ export async function runJob(id, { force = false } = {}) {
const prompt = fs.readFileSync(path.join(jobDir(id), 'PROMPT.md'), 'utf8');
const r = engine === 'api'
? await runApi(job, jobDir(id), prompt, log, (usage) => update(id, { usage }))
- : await runClaude(jobDir(id), prompt, log, { timeoutMs: claudeTimeoutMs(job.durationS) });
+ : await runClaude(jobDir(id), prompt, log, { timeoutMs: claudeTimeoutMs(job.durationS), model: job.model?.alias || job.model?.id }); // Claude Code nhận alias (opus/sonnet/haiku = bản mới nhất)
if (!r.ok) return setStatus(job, 'error', { error: r.error });
return await renderJob(id, { claimed: true });
} finally {
diff --git a/mcp/server.mjs b/mcp/server.mjs
index 8765b92..159a6fa 100644
--- a/mcp/server.mjs
+++ b/mcp/server.mjs
@@ -94,15 +94,16 @@ server.registerTool('create_video', {
templateId: z.string().regex(/^\d{1,3}$/),
content: z.string().min(5).max(4000),
mode: z.enum(['auto', 'agent']).default('auto'),
+ model: z.enum(['auto', 'opus', 'sonnet', 'haiku']).optional().describe('Model viết cảnh (chế độ auto). auto = Opus cho mẫu 3D/shader, Sonnet cho mẫu 2D.'),
durationS: z.union([z.number().min(3).max(MAX_DURATION_S), z.string().regex(/^\s*\d{1,4}\s*s?\s*$|^\s*\d{1,2}:[0-5]\d\s*$/)]).optional()
.describe('Thời lượng: 3 giây → 10 phút; số giây (90) hoặc "phút:giây" ("1:30"). Mặc định 8. > 60s: chia nhiều cảnh, render lâu (8s video ≈ 20–60s render) và tốn token hơn.'),
runAt: z.string().optional(),
audio: audioSchema.optional().describe('Âm thanh. Mặc định {music:"auto", voice:"auto", sfx:true}: AI chọn nhạc/tiếng động theo mẫu, chỉ đọc lời khi mẫu có narration.'),
},
-}, async ({ templateId, content, mode, durationS, runAt, audio }) => {
+}, async ({ templateId, content, mode, model, durationS, runAt, audio }) => {
let job;
try {
- job = createJob({ templateId, content, durationS, mode: mode === 'agent' ? 'manual' : 'auto', runAt, source: 'mcp', audio });
+ job = createJob({ templateId, content, durationS, mode: mode === 'agent' ? 'manual' : 'auto', model, runAt, source: 'mcp', audio });
} catch (e) { return fail(e.message); }
const p = jobPaths(job.id);
if (job.status === 'scheduled') {
diff --git a/server/public/app.js b/server/public/app.js
index fb62327..a4657cb 100644
--- a/server/public/app.js
+++ b/server/public/app.js
@@ -101,6 +101,7 @@
selected = t;
renderGrid();
$('#picked').className = 'picked';
+ window.dispatchEvent(new Event('lumreels:picked'));
$('#picked').innerHTML = `${t.thumb ? `<img src="${t.thumb}" alt="">` : ''}<div><div class="t">${t.id} · ${esc(t.name)}</div><div class="d">${esc(t.blurb || t.genre || '')}</div></div>`;
updateGo();
}
@@ -209,7 +210,7 @@
try {
const r = await fetch('/api/jobs', {
method: 'POST', headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({ templateId: selected.id, content: $('#content').value, durationS: durS(), mode: $('#mode').value, runAt: runAtValue(), audio: window.LumAudio?.value() }),
+ body: JSON.stringify({ templateId: selected.id, content: $('#content').value, durationS: durS(), mode: $('#mode').value, model: $('#model').value, runAt: runAtValue(), audio: window.LumAudio?.value() }),
});
const j = await r.json();
if (!r.ok) throw new Error(j.error || 'Tạo job lỗi');
@@ -282,7 +283,7 @@
<div>
<div class="head"><span class="st ${j.status} ${running ? 'run' : ''}">${STATUS[j.status] || j.status}</span>
<span class="tt">Mẫu ${j.templateId} · ${esc(j.templateTitle || '')}</span></div>
- <div class="jid">${j.id} · ${fmtDur(j.durationS)} · ${MODE_LABEL[j.engine || j.mode] || j.mode} ${out ? '· ' + out : ''}</div>
+ <div class="jid">${j.id} · ${fmtDur(j.durationS)} · ${MODE_LABEL[j.engine || j.mode] || j.mode}${j.model && j.model.alias && (j.engine || j.mode) !== 'manual' ? ' · ' + esc(j.model.alias) : ''} ${out ? '· ' + out : ''}</div>
${j.status === 'scheduled' ? `<div class="cost">Hẹn dựng lúc ${fmtTime(j.runAt)}</div>` : ''}
${j.usage ? `<div class="cost">API: ${(j.usage.inputTokens / 1000).toFixed(1)}k vào · ${(j.usage.outputTokens / 1000).toFixed(1)}k ra · ≈ $${j.usage.costUSD.toFixed(3)}</div>` : ''}
${j.output?.exported ? `<div class="cost">Đã chép ra: ${esc(j.output.exported)}</div>` : ''}
@@ -354,6 +355,21 @@
}[m] + (cfg.outputDir ? ' Xong sẽ chép MP4 ra thư mục xuất.' : '');
};
$('#mode').addEventListener('change', modeHint);
+ // Model: tự chọn = Opus cho mẫu 3D/shader, Sonnet cho mẫu 2D (rẻ hơn, đủ tốt cho DOM/SVG/Canvas)
+ const MODEL_NAME = { opus: 'Opus', sonnet: 'Sonnet', haiku: 'Haiku' };
+ const heavy = (t) => (t?.technique || []).some((x) => /three|webgl|shader/i.test(x));
+ function modelHint() {
+ const m = $('#model').value;
+ const rec = selected ? (heavy(selected) ? 'opus' : 'sonnet') : null;
+ const recTxt = rec ? `Mẫu này ${heavy(selected) ? 'dựng 3D/shader' : 'là 2D'} → đề xuất ${MODEL_NAME[rec]}.` : 'Chọn mẫu để xem đề xuất.';
+ const opt = $('#model').querySelector('[value=auto]');
+ opt.textContent = rec ? `Tự chọn theo mẫu (${MODEL_NAME[rec]})` : 'Tự chọn theo mẫu';
+ const warn = m === 'haiku' && rec === 'opus' ? ' Haiku hay làm phẳng cảnh 3D, nên dùng Opus.' : m !== 'auto' && rec && m !== rec ? ` (đang chọn ${MODEL_NAME[m]} thay vì đề xuất)` : '';
+ $('#modelHint').textContent = recTxt + warn + ' Agent ngoài thì model do agent đó quyết.';
+ }
+ $('#model').addEventListener('change', modelHint);
+ window.addEventListener('lumreels:picked', modelHint);
+ modelHint();
fetch('/api/config').then((r) => r.json()).then((c) => {
cfg = c;
$('#mode').value = c.defaultMode;
diff --git a/server/public/index.html b/server/public/index.html
index d482865..5dae790 100644
--- a/server/public/index.html
+++ b/server/public/index.html
@@ -80,7 +80,17 @@
<option value="manual">Agent ngoài</option>
</select>
</div>
+ <div class="span2">
+ <label class="field" for="model">Model viết cảnh</label>
+ <select id="model">
+ <option value="auto">Tự chọn theo mẫu</option>
+ <option value="opus">Opus (đẹp nhất, tốn nhất)</option>
+ <option value="sonnet">Sonnet (cân bằng)</option>
+ <option value="haiku">Haiku (rẻ nhất)</option>
+ </select>
+ </div>
</div>
+ <div class="hint" id="modelHint"></div>
<label class="field" for="runAt">Hẹn giờ dựng <span class="opt">(bỏ trống = dựng ngay)</span></label>
<div class="when">
<input id="runAt" type="datetime-local" step="60" />
diff --git a/server/server.mjs b/server/server.mjs
index 219737a..dc495fb 100644
--- a/server/server.mjs
+++ b/server/server.mjs
@@ -219,7 +219,7 @@ const server = http.createServer(async (req, res) => {
if (p === '/api/jobs' && req.method === 'GET') return send(res, 200, listJobs().map((j) => jobView(j)));
if (p === '/api/jobs' && req.method === 'POST') {
const body = await readBody(req);
- const job = createJob({ templateId: body.templateId, content: body.content, durationS: body.durationS, aspect: body.aspect, mode: body.mode || DEFAULT_MODE, runAt: body.runAt, source: body.source || 'web', audio: body.audio });
+ const job = createJob({ templateId: body.templateId, content: body.content, durationS: body.durationS, aspect: body.aspect, mode: body.mode || DEFAULT_MODE, model: body.model, runAt: body.runAt, source: body.source || 'web', audio: body.audio });
if (job.status === 'scheduled') { /* bộ hẹn giờ sẽ chạy khi tới giờ */ }
else if (resolveMode(job.mode) === 'manual') await runJob(job.id); // chỉ chuyển sang waiting_agent
else enqueueJob(job.id, () => runJob(job.id));