You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

GraphMachine无法生成NarcolepticSuperhero快速入门示例状态图

问题原因

你代码的核心问题是重复初始化了状态机,且两次使用了不同的状态机类:

  1. 在NarcolepticSuperhero类的__init__方法中,你使用普通Machine类完成了状态定义、转换规则配置,这部分逻辑是正确的
  2. 但在类实例化完成后,你又重新创建了一个空白的GraphMachine实例绑定到batman对象上,新的状态机没有继承之前配置的任何状态和转换规则,因此生成的状态图只有默认的初始状态,没有你定义的其他状态和流转逻辑。
修复方案

直接在类初始化时使用GraphMachine替代普通Machine类,删除后续额外初始化GraphMachine的冗余代码即可。修改后的完整代码如下:

from transitions.extensions import GraphMachine
import random

class NarcolepticSuperhero(object):
    # 定义状态
    states = ['asleep', 'hanging out', 'hungry', 'sweaty', 'saving the world']

    def __init__(self, name):
        self.name = name
        self.kittens_rescued = 0

        # 初始化时直接使用GraphMachine,而非普通Machine
        self.machine = GraphMachine(model=self, states=NarcolepticSuperhero.states, initial='asleep')

        # 转换规则和原代码完全一致
        self.machine.add_transition(trigger='wake_up', source='asleep', dest='hanging out')
        self.machine.add_transition('work_out', 'hanging out', 'hungry')
        self.machine.add_transition('eat', 'hungry', 'hanging out')
        self.machine.add_transition('distress_call', '*', 'saving the world',
                            before='change_into_super_secret_costume')
        self.machine.add_transition('complete_mission', 'saving the world', 'sweaty',
                            after='update_journal')
        self.machine.add_transition('clean_up', 'sweaty', 'asleep', conditions=['is_exhausted'])
        self.machine.add_transition('clean_up', 'sweaty', 'hanging out')
        self.machine.add_transition('nap', '*', 'asleep')

    def update_journal(self):
        self.kittens_rescued += 1

    @property
    def is_exhausted(self):
        return random.random() < 0.5

    def change_into_super_secret_costume(self):
        print("Beauty, eh?")
        
batman = NarcolepticSuperhero("Batman")
batman.wake_up()
# 直接调用get_graph生成状态图,无需额外初始化GraphMachine
batman.get_graph().draw("test.png", prog='dot')

修改后重新运行脚本,生成的test.png就会包含你定义的所有状态和转换规则,依赖安装步骤无需调整。

内容的提问来源于stack exchange,提问作者kauedg

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.05 22:39:02