Jev in PHP: Lightweight AI Decision Layer for Production Workflows
This article demonstrates integrating Jev, a structured decision model, into PHP 8.4 via the Neuron AI framework across four production scenarios—ticket classification, batch test-case labeling, UI automation step selection, and RAG retrieval filtering—showing sub-500ms latency, free output tokens, and type-safe probability outputs for reliable branching logic.
Introduction
In AI workflows, not every step requires a full generative LLM. Tasks such as routing a ticket to a department, flagging financial risk in a test case, or filtering irrelevant retrieval results often need only a category, a score, or a yes/no judgment. Calling a general-purpose LLM for each such decision adds latency (1.5–5 s) and token cost. This article shows how to insert a lightweight decision layer—Jev (TypeSafe System One)—into PHP 8.4 applications using the Neuron AI framework, covering four real-world scenarios with measured latency and cost.
Understanding Jev
How Jev Differs from General LLMs
General LLMs (GPT-4o, Claude, DeepSeek) produce free-form text. For the question "Is a bat a bird?" they return a paragraph. Engineering pain points: high latency, redundant tokens, and fragile parsing (regex or JSON Schema with retries).
Jev returns structured judgments directly from a predefined answer space. For the same question it outputs JSON with typed fields:
{
"model": "jev-1.14.0",
"answers": {
"is_bird": { "type": "noul", "noul": 0.02 },
"category": { "type": "choice", "choice": "mammal", "confidence": 1.0, "probabilities": { "mammal": 1.0, "bird": 0.0, "reptile": 0.0 } }
}
}Engineering advantages: deterministic format, end-to-end latency 70–500 ms, input cost ~$0.042/M tokens, output tokens free, and business code reads strongly typed properties (e.g., if ($isBird->probability < 0.05)) without parsing risk.
Core Decision Atoms
Boolean (noul): true/false probability 0–1.
Choice : pick one from up to 255 named options, with full probability distribution.
Score : ordered scale rating, returning weighted expected value and per-level distribution.
Typical Use Cases
Data sorting & labeling (priority, risk level).
RAG reranking (relevance verification, noise filtering).
Dynamic model routing (select mini/4o/o1 based on task difficulty).
Safety guardrails (prompt injection, unauthorized tool calls, compliance).
Scenario 1: Ticket Classification with Neuron AI (Official Example)
Using neuron-core/neuron-ai which implements ClassifierInterface for type-safe Jev calls. A single request classifies a ticket into department (Choice), severity (Score), and refund intent (Boolean).
Source Code (abridged)
use NeuronAI\Classifier\Boolean;
use NeuronAI\Classifier\Choice;
use NeuronAI\Classifier\Score;
use NeuronAI\Classifier\ClassificationRequest;
use NeuronAI\Classifier\TypeSafeAI\TypeSafeAI;
$classifier = new TypeSafeAI(key: getenv('TYPESAFE_API_KEY'));
$request = new ClassificationRequest(
input: ['ticket' => '我的包裹超过预计时间还没收到...'],
questions: [
'department' => new Choice(instructions: '该工单应该由哪个客服部门来处理?', options: ['billing'=>'账单与退款','shipping'=>'物流发货','other'=>'其他']),
'severity' => new Score(instructions: '客户反馈问题的严重受阻程度如何?', levels: ['轻微','中度','严重']),
'refund' => new Boolean('客户在工单中是否明确提出了退款诉求?'),
]
);
$result = $classifier->classify($request);
$department = $result->choice('department');
$severity = $result->score('severity');
$refund = $result->boolean('refund');Actual Output
Department: shipping (68% confidence; distribution: billing 32% / shipping 68% / other 0%).
Severity: score 1.65 / 2 (normalized 0.825); distribution: mild 2% / moderate 31% / severe 67%.
Refund intent: true, probability 98%.
Engineering note: $department->choice reads directly; $severity->score auto-computes weighted expectation (0×0.02 + 1×0.31 + 2×0.67 = 1.65). All properties are strongly typed, eliminating parsing errors.
Scenario 2: Batch Test-Case Labeling & Financial-Risk Triage
Test cases need priority (P1/P2/P3) and financial-loss risk flag. Jev labels each case; a probability threshold routes items to auto-accept, human review, or reject.
Source Code (key loop)
$questions = [
'priority' => new Choice(instructions: '评估测试用例的业务影响严重性...', options: ['P1'=>'核心主链路受阻','P2'=>'重要功能异常','P3'=>'次要界面缺陷']),
'is_financial_loss' => new Boolean('该用例验证的场景是否涉及资损风险?'),
];
foreach ($cases as $case) {
$result = $classifier->classify(new ClassificationRequest(input: ['case' => $case['content']], questions: $questions));
$priority = $result->choice('priority')->choice;
$financialLossProb = $result->boolean('is_financial_loss')->probability;
$lossTag = match (true) {
$financialLossProb >= 0.80 => '【确认资损】',
$financialLossProb >= 0.35 => '【疑似资损-待复核】',
default => '【非资损】',
};
}Actual Output (4 cases)
Case #101 (cross-border double charge): P1, risk 95% → 确认资损, 794 ms.
Case #102 (coupon stacking): P1, risk 92% → 确认资损, 222 ms.
Case #103 (carousel image ratio): P3, risk 3% → 非资损, 220 ms.
Case #105 (async reconciliation export): P2, risk 49% → 疑似资损-待复核, 282 ms.
Average 380 ms per case. Threshold-based routing keeps human review focused.
Scenario 3: Interactive UI Automation Step Decision
In Playwright-driven E2E tests, each step needs to pick a target element and an action type from the current page snapshot. Jev makes both choices in one request.
Source Code (decision request)
$request = new ClassificationRequest(
input: [
'target_step' => '输入运营管理员账号 "[email protected]"',
'current_page' => [
'url' => 'https://erp.example.com/login',
'visible_elements' => [
'btn_scan_qr' => '二维码快捷登录切换按钮',
'input_username' => '用户名/手机号/邮箱输入框 (placeholder: 请输入账号)',
'input_password' => '密码输入框 (type=password)',
'btn_submit' => '登录提交主按钮',
'link_forget_pwd' => '忘记密码超链接',
],
],
],
questions: [
'target_element' => new Choice(instructions: '根据目标用例步骤,当前页面中哪个元素是下一步必须操作或断言的目标?', options: $step['page_state']['visible_elements']),
'action_type' => new Choice('对该元素应该执行何种操作?', ['type_text'=>'输入文本','click_button'=>'点击交互','assert_state'=>'断言校验状态']),
]
);
$result = $classifier->classify($request);
$targetEl = $result->choice('target_element');
$actionType = $result->choice('action_type');Actual Output (4 steps)
Step 1: element input_username, action type_text, confidence 100%, 674 ms.
Step 2: element input_password, action type_text, confidence 100%, 218 ms.
Step 3: element btn_submit, action click_button, confidence 100%, 195 ms.
Step 4: element avatar_img, action assert_state, confidence 92%, 202 ms.
Total 1.29 s for four decisions. Merging element selection and action type into one request saves round-trips.
Scenario 4: Three-Dimensional RAG Retrieval Reranking
Vector recall (Top-10) often includes keyword-matched but business-irrelevant noise. Pipeline: vector recall → Jev three-dimensional judgment → script routing before feeding main Agent.
Judgment Dimensions
Relevance (Boolean) : "Does the case directly belong to XXX business? Core flow only; keyword mention not enough."
Topic (Choice) : "Which business segment?" Options: target_business, other_crossborder, domestic_payment, non_payment.
Quality (Score) : "Are scenario, action object, expected result complete?" Levels: missing/vague, basic but lacks detail, complete & executable.
Routing Logic
if ($relevance < 0.8 || $topic !== 'target_business') {
$rejected[] = $case; // noise, drop
} elseif ($qualityScore < 1.5) {
$review[] = $case; // incomplete, human review
} else {
$accepted[] = $case; // feed to Agent
}Actual Output (4 candidates)
Case #1 (domestic bank card payment): relevance 10%, topic domestic_payment → rejected.
Case #2 (bank exchange rate display): relevance 37%, topic non_payment → rejected.
Case #3 (complete cross-border settlement case): relevance 96%, topic target_business, quality 1.66 → accepted.
Case #4 (cross-border refund timeout): relevance 92%, topic target_business, quality 0.66 → review.
Summary: 1 accepted, 1 review, 2 rejected. Average 240 ms per case, total cost < $0.0001.
Key Takeaways
1. Dual-System Division of Labor
General LLM (System 2): open-ended generation, complex planning, deep reasoning.
Lightweight decision layer (System 1): intent routing, safety interception, content filtering, state labeling.
2. Closed Answer Sets & Mutual Exclusion
Decision models require crisp boundaries. When configuring Choice or Score, option semantics must be mutually exclusive; avoid vague overlap.
3. Retain Business-Code Final Authority
Model outputs probability distributions, not execution commands. Business code should define threshold bands for auto-accept, human-review, and auto-reject/fallback.
In today's engineering-depth AI, system usability depends not just on model size but on delivering business certainty at reasonable cost and millisecond latency.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
