游戏 AI / 系统课时
让模型调用受控的游戏动作
让模型调用受控的游戏动作
模型可以建议查询任务、赠送奖励或引导 NPC 移动,却不能直接修改任务、背包和角色坐标。本课以函数工具契约加服务端授权网关处理动作提案,让权限与世界状态由游戏服务判定,再把真实执行结果送回模型组织台词。
学习目标
- 定义任务查询、道具奖励和 NPC 移动的最小参数契约。
- 在服务端校验工具白名单、参数、角色权限和实时世界状态。
- 以幂等结果和工具回执阻止重复执行及模型虚报成功。
将工具分成查询与变更
给模型暴露的是“可申请的操作”,不是游戏引擎的任意命令。任务查询只读玩家可见进度;赠送物品是具备一次性约束的奖励变更;移动角色只是提交短距离移动意图,最终寻路、碰撞和到达由游戏模拟决定。工具参数尽量小,玩家身份与当前 NPC 必须由服务端会话提供。
| 工具名 | 模型提供 | 服务端必须再次判断 |
|---|---|---|
get_quest_status |
questId |
任务是否对该玩家可见 |
grant_item |
itemId |
是否完成任务、奖励是否已领取 |
move_npc |
x、y |
当前 NPC 是否可控、目标是否可达 |
明确模型与世界状态之间的边界
在 Responses 工具调用中,模型返回 function_call 项,其 arguments 是 JSON 字符串,call_id 用于关联执行回执。服务端必须等待完整参数、解析并重新校验,再执行可信业务接口;结果包装为 function_call_output 交回模型,最后展示回复。strict: true 约束模型的参数形状,不替代服务端鉴权与业务检查。参见官方函数工具调用说明。

用本地审批器执行动作提案
以下为 Node.js 18+ 可运行演示,不发送真实模型请求。tools 是可提交给模型的工具声明,proposals 模拟模型返回的完整调用项。ctx 由可信游戏后端建立,不能从玩家消息或模型参数中取值。
const defineTool = (name, description, properties) => ({
type: 'function', name, description, strict: true,
parameters: { type: 'object', properties, required: Object.keys(properties), additionalProperties: false }
});
const tools = [
defineTool('get_quest_status', '读取玩家可见任务', { questId: { type: 'string' } }),
defineTool('grant_item', '申请发放已解锁任务奖励', { itemId: { type: 'string' } }),
defineTool('move_npc', '申请 NPC 移动到附近坐标', { x: { type: 'number' }, y: { type: 'number' } })
];
const world = {
quest: { id: 'quest-gate', owner: 'player-1', status: 'completed', rewardClaimed: false },
inventory: [],
npc: { id: 'guard-1', x: 0, y: 0 },
moveQueue: []
};
const ctx = { sessionId: 'session-1', playerId: 'player-1', npcId: 'guard-1', canMove: true };
const executed = new Map();
function exactKeys(args, keys) {
return args !== null && typeof args === 'object' && !Array.isArray(args)
&& Object.keys(args).length === keys.length && keys.every(k => Object.hasOwn(args, k));
}
function dispatch(call, ctx) {
if (call?.type !== 'function_call' || typeof call.call_id !== 'string' || !call.call_id) {
return { ok: false, code: 'BAD_CALL' };
}
const key = ctx.sessionId + ':' + call.call_id;
if (executed.has(key)) return executed.get(key); // 相同调用不重复产生世界副作用
let args;
try {
if (typeof call.arguments !== 'string' || call.arguments.length > 512) throw Error();
args = JSON.parse(call.arguments);
} catch {
return { ok: false, code: 'BAD_ARGS' };
}
let result;
switch (call.name) {
case 'get_quest_status':
if (!exactKeys(args, ['questId']) || typeof args.questId !== 'string') {
result = { ok: false, code: 'BAD_ARGS' };
} else if (args.questId !== world.quest.id || world.quest.owner !== ctx.playerId) {
result = { ok: false, code: 'NOT_VISIBLE' };
} else {
result = { ok: true, questId: world.quest.id, status: world.quest.status };
}
break;
case 'grant_item':
if (!exactKeys(args, ['itemId']) || typeof args.itemId !== 'string') {
result = { ok: false, code: 'BAD_ARGS' };
} else if (args.itemId !== 'potion-small' || ctx.npcId !== world.npc.id ||
world.quest.owner !== ctx.playerId || world.quest.status !== 'completed') {
result = { ok: false, code: 'DENIED' };
} else if (world.quest.rewardClaimed) {
result = { ok: false, code: 'ALREADY_CLAIMED' };
} else {
// 正式服务中须在同一数据库事务内完成资格判断、标记和入账
world.quest.rewardClaimed = true;
world.inventory.push({ owner: ctx.playerId, id: args.itemId });
result = { ok: true, granted: args.itemId, quantity: 1 };
}
break;
case 'move_npc':
if (!exactKeys(args, ['x', 'y']) || !Number.isFinite(args.x) || !Number.isFinite(args.y)) {
result = { ok: false, code: 'BAD_ARGS' };
} else if (!ctx.canMove || ctx.npcId !== world.npc.id) {
result = { ok: false, code: 'DENIED' };
} else if (Math.hypot(args.x - world.npc.x, args.y - world.npc.y) > 2) {
result = { ok: false, code: 'OUT_OF_RANGE' };
} else {
// 只排入权威移动队列;寻路、碰撞和最终坐标由游戏模拟决定
world.moveQueue.push({ npcId: ctx.npcId, x: args.x, y: args.y });
result = { ok: true, queued: true };
}
break;
default:
result = { ok: false, code: 'UNKNOWN_TOOL' };
}
executed.set(key, result);
return result;
}
const call = (call_id, name, args) => ({
type: 'function_call', call_id, name, arguments: JSON.stringify(args)
});
const proposals = [
call('call-q', 'get_quest_status', { questId: 'quest-gate' }),
call('call-g', 'grant_item', { itemId: 'potion-small' }),
call('call-g', 'grant_item', { itemId: 'potion-small' }),
call('call-spoof', 'grant_item', { itemId: 'potion-small', playerId: 'other' }),
call('call-far', 'move_npc', { x: 20, y: 0 }),
call('call-move', 'move_npc', { x: 1, y: 0 })
];
for (const proposal of proposals) {
const output = { type: 'function_call_output', call_id: proposal.call_id,
output: JSON.stringify(dispatch(proposal, ctx)) };
console.log(output.call_id, output.output);
}
console.log('物品数量', world.inventory.length, '移动指令数', world.moveQueue.length);保存为 actions.mjs 后运行:
node actions.mjs预期输出:
call-q {"ok":true,"questId":"quest-gate","status":"completed"}
call-g {"ok":true,"granted":"potion-small","quantity":1}
call-g {"ok":true,"granted":"potion-small","quantity":1}
call-spoof {"ok":false,"code":"BAD_ARGS"}
call-far {"ok":false,"code":"OUT_OF_RANGE"}
call-move {"ok":true,"queued":true}
物品数量 1 移动指令数 1两次相同 call_id 的赠礼都返回同一结果,但背包只新增一个道具。伪造额外 playerId 被字段白名单拦下;20 米移动越过演示设定的 2 米单次限制;合法 1 米移动只进入队列,没有直接篡改位置。
接回模型并处理生产边界
真实后端收到 response.output 中的完整 function_call 后,逐条调用审批器,将 {type: "function_call_output", call_id, output} 作为后续 Responses 输入;需要时继续循环,直到得到最终台词或触及调用次数上限。只有真实回执 {ok: true} 才能让 NPC 说“已经发放”;失败时只应说明拒绝或暂不可执行。
演示里的 Map 仅在单进程内防重复。生产环境应使用会话作用域的唯一调用键和数据库唯一约束,把奖励资格检查、领取标记和背包入账放在同一事务内;移动还须经过 NavMesh 与战斗状态检查,必要时对重要变更增加玩家确认。记录调用 ID、动作名、审批结果和世界版本,便于追查模型提议与游戏执行不一致的问题。