首页 理论 架构 工程 文档 白皮书 著作 研究 案例 下载 博客 关于 开始使用 →

第106章 如何开发 SAI Engine

第106章 如何开发 SAI Engine

第105章建立了 SAI Module

Module 解决的是:

如何把一个功能组织成独立、可注册、可加载、可管理的功能单元。

Engine 更进一步。

Engine 解决的是:

一个具体功能到底如何接收 Input、进行 Processing,并产生 Result。

因此:

Module = 功能单元
Engine = 具体功能执行器

基本关系:

Individual
   ↓
Module
   ↓
Engine
   ↓
Input
   ↓
Processing
   ↓
Result

本章建立一个完整的 SAI Engine。


1. Engine Interface

1.1 Engine Interface 定义

Engine 必须具有统一的基本接口。

<?php

interface EngineInterface
{
    public function getId();

    public function getName();

    public function getVersion();

    public function initialize();

    public function execute($input);

    public function getState();

    public function shutdown();
}

1.2 Interface 的作用

不同 Engine 可以执行不同任务:

PerceptionEngine
CognitionEngine
ReasoningEngine
DecisionEngine
LearningEngine
DetectionEngine
DiagnosisEngine
RepairEngine

但是它们都可以通过统一接口:

initialize()
execute()
getState()
shutdown()

进行管理。


1.3 Engine Interface 不定义具体算法

Interface 只规定:

Engine 有什么基本能力

而不规定:

具体如何计算

例如:

TemperatureEngine

可以进行:

temperature > limit

而:

DistanceEngine

可以进行:

distance < threshold

两者处理方式不同,但接口一致。


2. Engine Class

2.1 Engine Class

Engine Class 是 EngineInterface 的具体实现。

例如创建:

TemperatureEngine

负责判断温度状态。

<?php

require_once 'EngineInterface.php';

class TemperatureEngine implements EngineInterface
{
    protected $id = 'temperature_engine';

    protected $name = 'Temperature Engine';

    protected $version = '1.0.0';

    protected $state = 'NEW';

    public function getId()
    {
        return $this->id;
    }

    public function getName()
    {
        return $this->name;
    }

    public function getVersion()
    {
        return $this->version;
    }

    public function initialize()
    {
        $this->state = 'READY';

        return true;
    }

    public function execute($input)
    {
        return array(
            'state' => 'SUCCESS'
        );
    }

    public function getState()
    {
        return $this->state;
    }

    public function shutdown()
    {
        $this->state = 'SHUTDOWN';

        return true;
    }
}

2.2 Engine 状态

基本生命周期:

NEW
 ↓
INITIALIZING
 ↓
READY
 ↓
RUNNING
 ↓
COMPLETED

结束:

SHUTDOWN

异常:

ERROR
CONFLICT
UNKNOWN

3. Engine Input

3.1 Input 定义

Engine Input 是 Engine 接收的数据。

例如 TemperatureEngine:

$input = array(
    'temperature' => 92,
    'limit' => 80
);

Engine 得到:

temperature = 92
limit = 80

3.2 Input 应该结构化

不要把 Engine 输入设计成无法识别的混合数据。

推荐:

$input = array(
    'source' => 'TemperatureSensor_A',

    'type' => 'TEMPERATURE',

    'target' => 'Machine_A',

    'data' => array(
        'temperature' => 92,
        'limit' => 80
    ),

    'timestamp' => time()
);

这样 Engine 可以知道:

Source
Type
Target
Data
Time

3.3 Input Validation

Engine 不应该直接处理任何输入。

首先检查:

Input
 ↓
Validation
 ↓
Processing

例如:

if (!isset($input['data'])) {
    return array(
        'state' => 'INVALID',
        'error' => 'DATA_MISSING'
    );
}

继续检查:

if (!isset($input['data']['temperature'])) {
    return array(
        'state' => 'INVALID',
        'error' => 'TEMPERATURE_MISSING'
    );
}

4. Engine Processing

4.1 Processing 定义

Processing 是 Engine 对 Input 执行具体功能的过程。

例如:

temperature = 92
limit = 80

执行:

92 > 80

结果:

TRUE

再映射:

TRUE → HIGH

4.2 Processing 流程

Input
 ↓
Validate
 ↓
Extract Data
 ↓
Calculate
 ↓
Evaluate
 ↓
Build Result

4.3 Temperature Processing

$temperature = $input['data']['temperature'];

$limit = $input['data']['limit'];

if ($temperature > $limit) {
    $level = 'HIGH';
} else {
    $level = 'NORMAL';
}

这是明确的离散条件判断:

IF temperature > limit
THEN HIGH
ELSE NORMAL

它属于 Engine 的具体功能计算。


4.4 Engine Processing 不等于 Cognition

例如:

TemperatureEngine

执行:

92 > 80

得到:

HIGH

这是一个功能计算结果。

Cognition 再使用这个结果理解:

Machine_A temperature is HIGH

然后 Reasoning 可以继续使用规则:

temperature HIGH
AND
machine RUNNING
→
risk HIGH

因此:

Engine = 执行具体功能

Cognition = 理解结构化信息

Reasoning = 根据规则推导结论

5. Engine Result

5.1 Result 定义

Engine 执行以后必须返回结构化 Result。

例如:

$result = array(
    'engine_id' => 'temperature_engine',

    'state' => 'SUCCESS',

    'output' => array(
        'temperature' => 92,
        'limit' => 80,
        'level' => 'HIGH'
    )
);

5.2 EngineResult 完整结构

可以进一步定义:

EngineResult
│
├── id
├── engine_id
├── state
├── input
├── output
├── changes
├── error
├── message
├── started_at
└── completed_at

例如:

$result = array(
    'id' => 'Result_001',

    'engine_id' => 'temperature_engine',

    'state' => 'SUCCESS',

    'input' => $input,

    'output' => array(
        'level' => 'HIGH'
    ),

    'changes' => array(),

    'error' => null,

    'message' => 'Temperature analysis completed',

    'started_at' => time(),

    'completed_at' => time()
);

5.3 SUCCESS 不等于业务目标完成

例如:

EngineResult:
state = SUCCESS

只说明:

Engine 的执行过程完成。

不一定说明:

机器已经恢复正常
机器人已经停止
设备问题已经解决

这些需要后续:

Verification

进行确认。


6. Engine Registration

6.1 为什么需要 Registration

如果系统拥有:

TemperatureEngine
DistanceEngine
StateEngine
ReasoningEngine

Kernel 或 ModuleManager 必须知道:

有哪些 Engine
Engine Class 是什么
Engine 在哪里
Engine 是否启用
Engine 版本是多少

因此建立 Engine Registry。


6.2 Engine Registry

$engineRegistry = array(
    'temperature_engine' => array(
        'id' => 'temperature_engine',
        'name' => 'Temperature Engine',
        'version' => '1.0.0',
        'class' => 'TemperatureEngine',
        'path' => 'engines/TemperatureEngine.php',
        'enabled' => true,
        'state' => 'REGISTERED'
    )
);

6.3 Registration 与 Loading

两者不同。

Registration
=
告诉系统“有什么”
Loading
=
把 Engine Class 加载到运行环境

因此:

REGISTERED
≠
LOADED

6.4 EngineManager

可以建立统一管理器:

class EngineManager
{
    protected $engines = array();

    public function register($engine)
    {
        $this->engines[$engine->getId()] = $engine;
    }

    public function get($id)
    {
        if (!isset($this->engines[$id])) {
            return null;
        }

        return $this->engines[$id];
    }

    public function execute($id, $input)
    {
        $engine = $this->get($id);

        if (!$engine) {
            return array(
                'state' => 'NOT_FOUND'
            );
        }

        return $engine->execute($input);
    }
}

这样上层系统可以:

$manager->execute(
    'temperature_engine',
    $input
);

7. Engine 调用

7.1 直接调用

最简单的方式:

$engine = new TemperatureEngine();

$engine->initialize();

$result = $engine->execute($input);

7.2 通过 EngineManager

更完整的方式:

Individual
 ↓
Module
 ↓
EngineManager
 ↓
TemperatureEngine
 ↓
Result

代码:

$manager = new EngineManager();

$engine = new TemperatureEngine();

$manager->register($engine);

$engine->initialize();

$result = $manager->execute(
    'temperature_engine',
    $input
);

7.3 Individual 调用 Engine

机器人 SAI 中:

Robot Sensor
 ↓
Information
 ↓
Individual
 ↓
PerceptionModule
 ↓
TemperatureEngine
 ↓
EngineResult
 ↓
Cognition

例如:

TemperatureSensor_A
        ↓
temperature = 92
        ↓
TemperatureEngine
        ↓
HIGH
        ↓
Cognition

8. 完整 Engine 示例

现在建立一个完整的:

TemperatureEngine

目标非常明确:

输入:
temperature
limit

处理:
temperature > limit

输出:
HIGH / NORMAL

8.1 EngineInterface.php

<?php

interface EngineInterface
{
    public function getId();

    public function getName();

    public function getVersion();

    public function initialize();

    public function execute($input);

    public function getState();

    public function shutdown();
}

8.2 TemperatureEngine.php

<?php

require_once 'EngineInterface.php';

class TemperatureEngine implements EngineInterface
{
    protected $id = 'temperature_engine';

    protected $name = 'Temperature Engine';

    protected $version = '1.0.0';

    protected $state = 'NEW';

    public function getId()
    {
        return $this->id;
    }

    public function getName()
    {
        return $this->name;
    }

    public function getVersion()
    {
        return $this->version;
    }

    public function initialize()
    {
        $this->state = 'READY';

        return true;
    }

    public function execute($input)
    {
        $this->state = 'RUNNING';

        if (!is_array($input)) {
            $this->state = 'ERROR';

            return array(
                'state' => 'INVALID',
                'error' => 'INPUT_NOT_ARRAY'
            );
        }

        if (!isset($input['temperature'])) {
            $this->state = 'ERROR';

            return array(
                'state' => 'INVALID',
                'error' => 'TEMPERATURE_MISSING'
            );
        }

        if (!isset($input['limit'])) {
            $this->state = 'ERROR';

            return array(
                'state' => 'INVALID',
                'error' => 'LIMIT_MISSING'
            );
        }

        $temperature = $input['temperature'];

        $limit = $input['limit'];

        if ($temperature > $limit) {
            $level = 'HIGH';
        } else {
            $level = 'NORMAL';
        }

        $this->state = 'READY';

        return array(
            'state' => 'SUCCESS',

            'engine_id' => $this->id,

            'output' => array(
                'temperature' => $temperature,
                'limit' => $limit,
                'level' => $level
            )
        );
    }

    public function getState()
    {
        return $this->state;
    }

    public function shutdown()
    {
        $this->state = 'SHUTDOWN';

        return true;
    }
}

9. 完整运行

建立:

index.php
<?php

require_once 'TemperatureEngine.php';

$engine = new TemperatureEngine();

echo "Engine: ";
echo $engine->getName();
echo "\n";

echo "State: ";
echo $engine->getState();
echo "\n";

$engine->initialize();

echo "State: ";
echo $engine->getState();
echo "\n";

$input = array(
    'temperature' => 92,
    'limit' => 80
);

$result = $engine->execute($input);

print_r($result);

echo "State: ";
echo $engine->getState();
echo "\n";

$engine->shutdown();

echo "State: ";
echo $engine->getState();
echo "\n";

运行逻辑:

NEW
 ↓
READY
 ↓
RUNNING
 ↓
temperature = 92
limit = 80
 ↓
92 > 80
 ↓
HIGH
 ↓
READY
 ↓
SHUTDOWN

结果:

Engine:
Temperature Engine

State:
NEW

State:
READY

state:
SUCCESS

engine_id:
temperature_engine

output:
temperature = 92
limit = 80
level = HIGH

State:
READY

State:
SHUTDOWN

10. Engine 加入 Robot SAI

现在把这个 Engine 放入第104章的机器人系统。

机器人:

Robot_A

传感器:

TemperatureSensor_A

获取:

temperature = 92

进入:

Information

然后:

Information
 ↓
Perception
 ↓
TemperatureEngine

Engine:

92 > 80

得到:

HIGH

再进入:

Cognition
 ↓
Reasoning

例如规则:

IF
temperature = HIGH

THEN
risk = HIGH

然后:

Reasoning
 ↓
Decision
 ↓
Behavior
 ↓
Action
 ↓
RobotAdapter

这样 Engine 成为了 SAI 内部具体功能执行的一部分。


11. Engine 与 Module 的关系

现在可以更加清楚地区分:

Individual
    ↓
Module
    ↓
Engine

例如:

PerceptionModule
│
├── TemperatureEngine
├── DistanceEngine
├── PositionEngine
└── ObjectEngine

而:

ReasoningModule
│
├── RuleEngine
├── ConditionEngine
└── ReasoningEngine

所以:

Module 是功能组织边界,Engine 是具体执行单元。

一个 Module 可以拥有多个 Engine。

一个 Engine 也可以被规定只能属于一个 Module,或者根据架构设计由多个 Module 共享,但共享时必须明确生命周期和依赖关系。


12. Engine 的标准运行模型

完整 Engine:

Engine
 ↓
Input
 ↓
Validation
 ↓
State Check
 ↓
Processing
 ↓
Result
 ↓
State Update

异常:

Input Error
     ↓
Validation Failed
     ↓
EngineResult
     ↓
ERROR / INVALID

运行错误:

Processing
 ↓
Exception
 ↓
ERROR
 ↓
Error Log
 ↓
Detection

13. Engine 与 SAI 核心流程

Engine 并不是另外建立一套独立智能流程,而是嵌入 SAI 的功能体系。

例如 Perception:

Information
 ↓
Perception
 ↓
PerceptionEngine
 ↓
PerceptionResult
 ↓
Cognition

Reasoning:

Memory
 ↓
Facts + Rules
 ↓
ReasoningEngine
 ↓
ReasoningResult
 ↓
Decision

Learning:

Experience
 ↓
LearningEngine
 ↓
LearningResult
 ↓
Knowledge / Memory Update

Self-Maintenance:

Detection
 ↓
Diagnosis
 ↓
RepairEngine
 ↓
RepairResult
 ↓
Verification

本章核心定义

Engine Interface

规定 SAI Engine 的统一基本接口。

Engine Class

EngineInterface 的具体实现类,负责实现一个明确的功能。

Engine Input

Engine 执行功能所接收的结构化输入数据。

Engine Processing

Engine 对 Input 进行验证、提取、计算、判断和处理的过程。

Engine Result

Engine 完成功能执行后产生的结构化结果。

Engine Registration

将 Engine 的身份、Class、路径、版本、状态和配置登记到 Registry。

Engine 调用

Individual、Module 或 Manager 根据 Engine ID 将输入交给指定 Engine 执行。


本章最终模型

             Engine
                │
                ↓
              Input
                │
                ↓
           Validation
                │
                ↓
        State / Condition
                │
                ↓
           Processing
                │
                ↓
             Result
                │
        ┌───────┴────────┐
        ↓                ↓
   Normal Result      Error Result
        │                │
        ↓                ↓
   Next Component     Detection

而在 SAI 中:

Individual
    ↓
Module
    ↓
EngineManager
    ↓
Engine
    ↓
Input
    ↓
Processing
    ↓
EngineResult
    ↓
Cognition / Reasoning / Decision / Learning

最终可以概括为:

Module = 功能组织
Engine = 功能执行
Input = 执行输入
Processing = 执行过程
Result = 执行结果
Registry = Engine登记
Manager = Engine管理与调用

这样,第105章的 SAI Module 与第106章的 SAI Engine 就形成了清晰的上下层关系:

SAI Framework
      ↓
   Individual
      ↓
    Module
      ↓
    Engine
      ↓
Input → Processing → Result

这也为后续把 PerceptionEngine、CognitionEngine、ReasoningEngine、DecisionEngine、LearningEngine、RobotEngine 等具体 Engine 按统一标准组织起来建立了基础。

Leave a Reply

Your email address will not be published. Required fields are marked *