ユーティリティ
スクリプティング API には、よく使う処理のためのヘルパーが含まれます。乱数生成、トークナイズ、タイマー、ファイル操作、クリップボード、設定管理などです。
乱数生成
random API はランダム値を生成します。Math.random() も使えますが、便利関数として提供されています。
ランダムな真偽値
let coinFlip = api.v1.random.bool();
api.v1.log(`Coin flip: ${coinFlip ? 'heads' : 'tails'}`);
ランダムな整数
範囲内の整数(min/max ともに含む)を生成します。
// 1〜6 の乱数
let diceRoll = api.v1.random.int(1, 6);
api.v1.log(`Dice roll: ${diceRoll}`);
// 0〜99 の乱数
let percentage = api.v1.random.int(0, 99);
ランダムな浮動小数
範囲内の浮動小数(min は含む、max は含まない)を生成します。
let temperature = api.v1.random.float(0.5, 1.5);
ダイス記法(Dice Roll Notation)
一般的なダイス記法で乱数を生成できます。
// 6 面ダイスを 3 個
let result = api.v1.random.roll('3d6');
api.v1.log(`Rolled: ${result.total}`);
// 2d20 + 5
let attackRoll = api.v1.random.roll('2d20+5');
// 2d6+1d4+3
let damageRoll = api.v1.random.roll('2d6+1d4+3');
テキストのトークナイズ
tokenizer API は、テキストをトークン ID にエンコードしたり、トークン ID をテキストにデコードしたりできます。コンテキスト長の管理や、トークン ID を必要とする生成パラメータで役立ちます。
テキストをトークン ID にする
let text = 'When did we get here?';
let tokens = await api.v1.tokenizer.encode(text, 'glm-4-6');
api.v1.log(`Token count: ${tokens.length}`);
api.v1.log(`Token IDs: ${tokens.join(', ')}`);
使用するトークナイザーは、指定したモデルに依存します。モデル指定は必須です。
トークン ID をテキストに戻す
let tokens = [49955, 13];
let text = await api.v1.tokenizer.decode(tokens, 'glm-4-6');
api.v1.log(`Decoded text: ${text}`);
タイマーと遅延
timers API は遅延実行やスリープを提供します。スクリプト環境では標準の setTimeout / clearTimeout が使えないため、代替として提供されています。
setTimeout
let timeoutId = api.v1.timers.setTimeout(() => {
api.v1.log('This runs after 2 seconds');
}, 2000);
遅延はミリ秒指定です。返り値の timeout ID を使ってキャンセルできます。
clearTimeout
let timeoutId = api.v1.timers.setTimeout(() => {
api.v1.log('This will never run');
}, 5000);
// キャンセル
api.v1.timers.clearTimeout(timeoutId);
sleep
async function delayedAction() {
api.v1.log('Starting...');
await api.v1.timers.sleep(3000); // 3 秒待つ
api.v1.log('3 seconds later...');
}
sleep は指定時間後に解決する Promise を返します。
UUID 生成
let uniqueId = api.v1.uuid();
api.v1.log(`Generated UUID: ${uniqueId}`);
ファイル操作
file API は、ユーザーにファイル選択を促したり、データをファイルとして保存(ダウンロード)させたりできます。これはブラウザ上の操作であり、ユーザーのファイルシステムへ直接アクセスできるわけではありません。ファイルはユーザーが手動選択し、保存先もスクリプト側から制御できません。
ファイル選択を促す
readAs は ‘text’ / ‘dataURL’ / ‘arrayBuffer’ を指定できます。
// 1 ファイルを ArrayBuffer として取得
let file = await api.v1.file.prompt({
readAs: 'arrayBuffer'
});
if (file) {
api.v1.log(`Content: ${file.byteLength}`);
}
保存(ダウンロード)させる
let data = JSON.stringify({ name: 'My Data', value: 42 }, null, 2);
await api.v1.file.save('file.json', data);
保存できるのは文字列データのみです。
クリップボード
await api.v1.clipboard.writeText('This text is now on the clipboard!');
api.v1.ui.toast('Text copied to clipboard');
参考
- API リファレンス - API 全体(英語)