游戏 AI / 系统课时
先做一个最小剧情闭环
先做一个最小剧情闭环
本篇用一次最小动态对话,把游戏状态、LLM 请求与结构化结果串成闭环。完成后,你能稳定拿到可校验的剧情结果,而不是一段无法驱动游戏的自由文本。
学习目标
- 理解最小动态剧情链路中的状态、请求、生成与校验关系
- 验证模型适配器的结构化输出,并把结果映射为候选游戏动作
- 为失败响应和非法结果建立可验证的降级路径
先确定最小输入和输出
最小闭环不需要完整任务系统,只保留能影响当前剧情的一小组状态。例如玩家正在酒馆、任务仍未完成、NPC 对玩家保持中立。把这些状态作为上下文输入,再让模型只负责生成语言与有限的剧情意图。
输出也不要直接接受一整段自然语言。更适合先约束为固定字段,例如 dialogue、emotion 和 nextAction。这样游戏代码可以读取字段并决定是否继续任务、播放动作或切换场景。

调用模型时固定协议边界
下面的 Python 标准库示例不依赖账号或模型。fetch 代表实际 HTTP 适配器,示例用夹具替代。真实接入时由适配器按供应商协议读取候选正文,检查超时、拒绝、截断和空响应,再转换为 result 字段。JSON 请求选项和外层字段不能在不同接口间直接通用。
import json
FALLBACK = {"dialogue": "这件事稍后再谈。", "emotion": "neutral", "nextAction": "continue_dialogue"}
EMOTIONS = {"neutral", "curious"}
def parse_reply(response, allowed_actions):
# 适配器将供应商特有的响应信封转换为 result 字段。
if not isinstance(response, dict) or not isinstance(response.get("result"), str):
raise ValueError("缺少生成内容")
raw = response["result"]
if len(raw) > 4000:
raise ValueError("返回内容过长")
candidate = json.loads(raw)
if not isinstance(candidate, dict) or set(candidate) != set(FALLBACK):
raise ValueError("剧情字段缺失或多余")
text, emotion, action = (candidate[field] for field in FALLBACK)
if (not isinstance(text, str) or not 0 < len(text.strip()) <= 120
or not isinstance(emotion, str) or emotion not in EMOTIONS
or not isinstance(action, str) or action not in allowed_actions):
raise ValueError("台词、情绪或动作不符合规则")
return {"dialogue": text.strip(), "emotion": emotion, "nextAction": action}
def choose_reply(fetch, state):
allowed = {"continue_dialogue"}
if state["quest_status"] == "active":
allowed.add("offer_hint")
try:
return parse_reply(fetch(state, sorted(allowed)), allowed)
except (ValueError, OSError):
return FALLBACK.copy()
def fixture(state, allowed):
assert state["player_location"] == "tavern"
assert "offer_hint" in allowed
return {"result": json.dumps({"dialogue": "问问吧台旁的旅人。", "emotion": "curious", "nextAction": "offer_hint"}, ensure_ascii=False)}
state = {"player_location": "tavern", "quest_status": "active", "npc_disposition": "neutral"}
print(choose_reply(fixture, state)["nextAction"])
print(choose_reply(lambda *_: {"result": "invalid JSON"}, state)["nextAction"])保存为 story_reply.py 并运行 python story_reply.py。第一行来自正常候选,第二行演示格式错误时的安全降级。
offer_hint
continue_dialogue这里的关键不是某个厂商 SDK,而是协议边界:输入状态必须可序列化,模型输出必须可解析,游戏逻辑必须有明确字段可消费。示例检查字段、枚举和当前状态允许的动作。通过校验只是得到候选动作,真正执行前仍要校验授权与最新状态;自由台词中的虚构事实也应单独审核。
让异常响应也能走完闭环
动态剧情最容易失败的地方不是模型完全没有回复,而是回复格式偶尔不符合预期。例如缺少 nextAction、枚举值拼错,或接口超时。此时不要把异常文本直接交给游戏状态机,应把模型视为“不可靠的内容提供者”,让校验层决定是否接受。
最小降级策略可以是:请求失败则使用预设台词;JSON 解析失败则丢弃本次生成;字段非法则采用安全默认动作。这样一次模型异常不会直接改变任务进度、库存或角色关系。
用一次可验证结果验收
完成闭环后,至少验证四件事:状态确实被送入请求;模型返回值能解析为 JSON;必需字段都存在且值合法;游戏只根据经过校验的结果执行下一步。只要这四项能稳定通过,你就拥有了一个真正可扩展的动态剧情最小原型。