← All posts 中文版

PMClite's DeepSeek Integration: Four Scenarios, Three Defenses, One Boundary

This article is not about the grand narrative of "AI empowering manufacturing." It is about one thing: where exactly DeepSeek is used in a desktop tool that PMC teams rely on every day, what verifiable improvements it delivers, and where it is deliberately kept in a cage.

Providers 8 available Default DeepSeek AI scenarios 4 Call defenses 3 layers

1. Positioning First: Why DeepSeek, and Why Not "AI Scheduling"

In PMClite's AI settings page, the provider dropdown supports 8 options (OpenAI, Azure, Anthropic, Google, DeepSeek, Qwen, local Ollama, custom), but the code default is DeepSeek:

const provider = ai.provider || 'deepseek';
const baseUrls = {
    deepseek: 'https://api.deepseek.com',
    openai: 'https://api.openai.com/v1',
    qwen: 'https://dashscope.aliyuncs.com/compatible-mode/v1',
    ...
};
const baseUrl = (ai.baseUrl || baseUrls[provider] || baseUrls.deepseek).replace(/\/$/, '');
const model = ai.model || 'deepseek-flash';

This default is a pragmatic choice: DeepSeek's API is OpenAI-compatible, cheap, reliably accessible in China, and supports JSON mode. For a tool aimed at small and medium manufacturers, AI scheduling cannot be "the boss spends extra money to try AI" — it must be "the cost per scheduling run is negligible."

Equally pragmatic is the functional positioning. PMClite hard-codes one rule in every prompt:

AI only makes "soft" judgments (priority, cause, attribution). It does not perform "hard" computation (dates, capacity, inventory). All numbers are provided in the prompt, with an explicit instruction not to regenerate them.

This division of labor runs through all four AI features. Only by understanding this can you understand all the engineering details that follow.

2. Call Layer: One Function, Three Layers of Defense

All AI calls go through a single entry point, callAIChat(messages, options). The code is not long, but it fills in several DeepSeek API pitfalls.

2.1 Retry strategy routed by error type

if (!resp.ok) {
    if ([401, 402, 403].includes(resp.status)) {
        throw new Error(errMsg);   // auth / balance issues; retry is pointless
    }
    lastError = new Error(errMsg); // 429/5xx are retryable
    continue;
}

401 (bad key), 402 (insufficient balance), and 403 (banned) are thrown immediately so the user does not waste time; 429 (rate limit) and 5xx go through backoff retry, up to 2 attempts with 800ms × attempt intervals.

2.2 Adapting to thinking mode

DeepSeek's thinking mode has a pitfall that is very easy to hit in practice: with thinking enabled, the content field may be empty, and the actual reasoning is in reasoning_content. PMClite handles it as follows:

if (options.jsonMode) {
    body.response_format = { type: 'json_object' };
} else if (provider === 'deepseek' && options.thinking) {
    body.thinking = { type: 'enabled' };
}

Thinking is forcibly disabled in JSON mode to avoid empty content; it is allowed in non-JSON mode. Even so, a fallback is in place:

let content = (msg.content || '').trim();
if (!content && msg.reasoning_content) {
    const rc = msg.reasoning_content.trim();
    const jsonMatch = rc.match(/\{[\s\S]*\}/);
    if (jsonMatch) {
        console.warn('[AI] content is empty; extracted JSON from reasoning_content');
        return jsonMatch[0];
    }
}

This is the style of "knowing what can go wrong with your dependency."

2.3 Handling finish_reason

if (!content) {
    if (finishReason === 'length') {
        lastError = new Error('AI output was truncated (insufficient tokens); reduce the number of work orders or click retry');
    } else if (finishReason === 'content_filter') {
        throw new Error('AI content was filtered for safety; adjust the prompt and retry');
    }
}

The message for length is not "AI returned an error" but specifically "reduce the number of work orders" — because the actual scenario that triggers this error is too many work orders, causing the JSON output to exceed max_tokens.

2.4 Timeout control

const controller = new AbortController();
const timeout = setTimeout(() => controller.abort(), options.timeout || 180000);

Default is 180 seconds. The prompt for intelligent scheduling can contain a long list of work orders, so this timeout is generous; process inference and anomaly explanation do not need nearly as long, but they go through the same entry point and can override timeout as needed.

3. Four Functional Scenarios

3.1 Intelligent scheduling: AI scores, local engine schedules

This is PMClite's most core AI feature and the most easily misunderstood. Let's look at the actual flow.

Step 1: Build context (buildSchedulingContext)

Each pending work order is compressed into one line of structured data:

{
    id: w.id,
    orderNumber: w.orderNumber,
    productCode: product.code,
    quantity: w.quantity,
    priority: w.priority,
    status: w.status,
    mode: mode,                          // fixed_takt / flexible_takt / ...
    modeLabel: PRODUCTION_MODES[mode].label,
    modeParam: getModeParamSummary(product),
    estHours: calcResourceHours(product, w.quantity, w.assignedLine),  // hours computed locally
    kitStatus: 'kitted' | 'shortage(N items)' | 'no BOM',
    deliveryDate: '2026-05-15',
}

Note that estHours is computed locally, not by AI. AI receives "facts," not "raw material."

Step 2: Scoring rules in the prompt are fully transparent

## Scoring rules
1. Priority: high = base 30, medium = base 20, low = base 10
2. Delivery urgency: ≤3 days +40; ≤7 days +25; ≤14 days +15; overdue +50
3. Kit status: kitted +10; shortage -15; no BOM -30
4. In-progress work order +5
5. At the same priority, shorter hours are moderately preferred

These rules are hard-coded in the prompt rather than letting AI "decide for itself." AI's value is: it can process 20 work orders at once, take production-mode semantics into account, and provide a readable reason for each one.

The prompt also includes a dedicated "production mode explanation" so AI understands:

- fixed_takt: capacity is determined by equipment takt; adding people does not increase speed
- flexible_takt: capacity is proportional to the number of stations on the line
- batch: batching can significantly save time; prioritize merging multiple small-batch orders

This makes AI consider "the nature of this order" when scoring, rather than just doing arithmetic.

Step 3: AI outputs JSON

{
  "schedule": [
    {"woId": 1, "priorityScore": 85, "lineHint": "Line A", "reasoning": "Overdue order, prioritize"}
  ],
  "overallStrategy": "Protect overdue orders first, merge batch orders",
  "riskAlerts": ["Line A load may exceed 100% on Wednesday"]
}

Constraints are hard: output JSON only, reasoning ≤20 Chinese characters, overallStrategy ≤30 Chinese characters, riskAlerts at most 3, must include all incoming work orders, and first and last characters must be braces.

Step 4: Local engine executes scheduling (runLocalScheduler)

The priorityScore and lineHint from AI enter the local engine. Work orders are reordered by descending score, lineHint is used as the preferred line (falling back if invalid), then the same calendar-consumption logic as normal auto-scheduling is used to compute real dates.

AI does not output any dates.
The value of this design: dates are what the PMC ultimately signs off on and is responsible for; they must be recomputable, explainable, and traceable. The score from AI is just a weight input; the scheduling result itself is deterministic.

Failure fallback: when the AI call fails, the modal offers a "use local auto-schedule first (don't wait for AI)" button that jumps directly to _autoSchedule. Users are never blocked from scheduling because AI is down.

3.2 AI process inference: lowering the barrier to configuring routings

This is the most complex AI feature in the codebase and the one that best demonstrates prompt engineering.

The pain point is concrete: after a new product is created, the PMC must configure a routing — SMT placement, reflow soldering, through-hole insertion, testing, assembly, packaging. Each process requires sequence number, work center, per-unit time, setup time, and post-wait. A product with 5–8 processes means 4 fields per process, all based on experience. Veteran planners know "reflow soldering needs 30 minutes of cooling"; newcomers do not.

Input to AI inference (_collectInferContext):

{
    product: { code, name },
    bomItems: [
        { code: 'PCB-001', name: 'Main PCB', category: 'PCB', spec: 'FR4 1.6mm', qty: 1 },
        { code: 'IC-001',  name: 'STM32F103', category: 'MCU', spec: 'Cortex-M3', qty: 1 },
        ...
    ],
    refLineName: 'SMT Line A',
    lineMode: 'fixed_takt',       // production mode of the reference line
    lines: ['SMT Line A', 'SMT Line B'],
    industry: 'Electronics',
    historyWO: 12,                 // number of completed historical work orders
    avgActualHours: 45.2,          // historical average per-unit hours
}

Unit convention is the most critical part of this prompt:

if (lineMode === 'fixed_takt') {
    unitRule = `The current line mode is [fixed takt]. For standardMinutes, enter [equipment takt, seconds/unit].`;
} else if (lineMode === 'single_station') {
    unitRule = `The current line mode is [single station]. For standardMinutes, enter [single-machine cycle time, minutes/unit].`;
} else {
    unitRule = `The current line mode is [flexible takt]. For standardMinutes, enter [time for a single worker to complete this process, minutes/unit]. Note: do not divide by the number of parallel workers; the program will automatically divide by the number of stations on the line.`;
}

These three strings solve a concrete problem: the same field name, standardMinutes, has completely different semantics under different line modes. If AI does not know that on a flexible line "single-worker 30 minutes ÷ 10 stations = effective takt 3 minutes," it will enter 3 minutes, and the local engine will divide by 10 again, yielding 0.3 minutes — the entire schedule is wrong. Writing the convention into the prompt is more reliable than doing a second correction in code.

Output schema + validation (validateInferResult):

{
  "processes": [
    {
      "sequence": 10,
      "processName": "SMT placement",
      "workCenter": "SMT Line A",
      "standardMinutes": 30,
      "setupMinutes": 30,
      "postWaitMinutes": 0,
      "confidence": 0.92,
      "evidence": "BOM contains PCB and IC"
    }
  ],
  "suggestedMode": "fixed_takt",
  "modeReason": "Contains PCB, suitable for SMT line"
}

Validation rules: processes non-empty, sequence unique and numeric, processName non-empty, standardMinutes > 0. If any one fails, the entire result is discarded and the fallback path is taken.

Rule engine fallback (ruleBasedInferProcesses)

This is the fallback when AI fails and the baseline when no API key is available. The rules are simple, based on material code prefixes and category keywords:

if (has('PCB') || has('SMT')) {
    placement(10) → reflow(20, post-wait 30 min)
}
if (has('IC') || has('MCU')) {
    testing(50)
}
if (has('enclosure') || has('hardware')) {
    assembly(60)
}
packaging(90)  // generic final process

The rule engine output goes through the same implementation workbench as AI output, only the source label differs:

🤖 AI inference
📋 Rule engine
⚠️ AI failed; rule engine fallback

Implementation workbench: confidence-driven selection

This is the most valuable interaction design in this feature. Each process carries a confidence (0–1), and the UI shows:

The user sees a candidate list, each row with "evidence" (e.g. "BOM contains PCB"), and can check rows individually, modify sequence / process name / hours / wait time, then apply all at once.

AI mode suggestion

If the AI-output suggestedMode differs from the product's current production mode, a blue banner appears:

💡 AI mode suggestion: this product may be better suited to ⚙️ single station mode. (Reason: short per-unit cycle, suitable for single-machine batch.)

Applying processes will not change the production mode. To change it, close this modal and edit it under "Product Edit."

There is a deliberate restraint here: AI suggestions are not applied automatically; they are only hints. Production mode is a structural decision; changing it incorrectly affects the scheduling logic of the entire line, so the user must click it themselves.

Traceability

On application, a record is written to _ai_impl_log in the settings table, keeping the most recent 100:

{
    ts: '2026-05-20T10:30:00Z',
    productId: 12,
    source: 'ai' | 'rules' | 'rules_fallback',
    appliedCount: 6,
    updatedCount: 4,
    insertedCount: 2,
    draft: [/* actual applied process data */],
}

Red line: AI only writes process rows in bomItems where type='process'; it never modifies BOM parent-child relationships, material primary keys, delivery dates, or costs. This rule is stated at the bottom of the implementation workbench and reflected in the code — _applyAIDraft only operates on rows where type='process'.

3.3 AI anomaly explanation: from "data" to "plain language"

Every event on the decision desk (shortage, delivery, capacity, rush order, report confirmation) has a "🤖 Explain" button.

The pain point: the event title says "3 material shortages, affecting start," but what the PMC needs to know is: what is short, is there any in-transit purchase, when will it arrive, will it affect delivery, and what should be done now. This information is scattered across work order, BOM, inventory, purchasing, and sales tables; manually checking takes minutes.

Data collection is deterministic (collectExplainContext), dispatched by event type:

Prompt constraints are very hard:

Output format (strictly follow):
Sentence 1: Cause (why this is happening)
Sentence 2: Impact (what is affected and by how much)
Sentence 3: Recommendation (what the PMC should do specifically)

No headings, no numbering, no repeating numbers already present in the data. Output only these three sentences.

The system prompt also states:

Strict requirements: (1) do not fabricate any numbers; all numbers are already in the input data; (2) do not use vague words like "possibly" or "maybe"; (3) output directly, no prefix formatting; (4) keep total length under 100 Chinese characters.

Three-layer degradation is the core design of this code:

  1. AI available → call DeepSeek, output three-sentence analysis
  2. AI not enabled (no API key or enabled=false) → show only structured data, with a top hint "AI intelligent explanation is not currently enabled. Below is a structured analysis generated by the system based on real-time data; all numbers can be verified."
  3. AI call failed → show structured data, with a yellow banner "⚠️ AI explanation failed (specific error). Below is a structured analysis generated by the system based on real-time data."

Regardless of the layer, the structured data block always renders (_renderShortageData / _renderDelayData / _renderCapacityData / _renderInsertData / _renderReportData). This means: no matter how well AI explains, the user can immediately verify against the data below; if AI is down, the feature still works, just without the summarizing sentence.

The AI block also has a disclaimer at the bottom:

⚠️ AI only summarizes and analyzes; it does not generate new numbers. All numbers are subject to the "Data basis" below and can be verified independently.

This line is not a legal disclaimer; it is product design: telling the user what to trust and what not to trust.

3.4 AI labor deviation attribution: from "number deviation" to "cause judgment"

The labor calibration wizard (_openLaborCalibrationWizard) is the core of the scheduling quality loop. The flow is: collect the most recent 20 completed work orders → compute overall deviation and standard deviation → attribute → compute suggested value → impact preview.

Rule-based attribution comes first (_attributeLaborDeviation):

AI attribution supplements rule attribution (_aiExplainLaborDeviation):

Input is the rule attribution result + key statistics + detail of the most recent 5 orders. The prompt requires:

Based on the following labor deviation facts, give an attribution judgment in one sentence (no more than 50 Chinese characters). Do not fabricate numbers; only summarize causes.

- Output one sentence directly; no headings, no numbering
- Focus on "the most likely cause" and "whether calibration is recommended"
- If samples are few or variance is high, remind "calibration is not recommended for now"

The AI output is rendered in a blue box labeled "🤖 AI attribution," displayed alongside the rule attribution above.

The design trade-off here: labor attribution is the scenario where AI is least confident — there may be only 3 samples, variance may be high, and AI easily produces a judgment that sounds reasonable but has no basis. Therefore:

AI does not participate in computing the suggested value (_computeCalibratedValue is pure arithmetic: weighted average, newer samples weighted higher). AI is only responsible for "explaining why it deviated," not "what to change it to." This is yet another boundary: soft judgment to AI, hard computation to code.

4. Real Value: Three Verifiable Improvements

Setting aside marketing language, the actual improvements visible from the code and interaction design are these three.

4.1 The "trust cost" of scheduling is lower

The dilemma of traditional scheduling tools: the algorithm produces a result, the PMC cannot understand why it is scheduled that way, does not dare to use it, and ends up manually adjusting. Or conversely, the PMC schedules by experience and cannot review afterward when problems arise.

PMClite's AI scheduling gives: a 0–100 score for each work order + a ≤20-character reason + a suggested line, and then the local engine schedules dates by score. What the PMC sees is:

WO-001  85  🔴High  Overdue order, prioritize        → SMT Line A  05-10 → 05-12
WO-002  52  🟡Medium  Batch mergeable, reduce changeover  → SMT Line B  05-13 → 05-14
WO-003  20  🟢Low   Loose delivery, no shortage        → SMT Line A  05-15 → 05-15

This result is readable, question-able, and modifiable. If the PMC disagrees that "WO-002 should be scored 70," they can manually adjust the date or change the priority and rerun. AI's value is not producing "the correct schedule," but producing "a discussable schedule."

4.2 The time cost of routing configuration drops dramatically

This is the most quantifiable improvement. A typical routing for an electronics product: placement, reflow, insertion, wave soldering, testing, assembly, packaging — 7 processes, each requiring sequence, process name, work center, per-unit time, setup time, and post-wait: 6 fields × 7 rows = 42 inputs.

The key is not "AI configures more accurately than humans," but "AI turns starting from zero into starting from candidates."
Reviewing is much faster than creating, especially for newcomers. Confidence-tiered checking (>85% checked by default, 60–85% requiring confirmation, <60% unchecked by default) lets users know "which ones can be trusted directly, which ones need careful review," rather than facing a 7-row list and doubting every row.

4.3 "Information-gathering time" for anomaly handling is compressed

The PMC spends a lot of time every day on "looking things up": why is this order short on materials? Is there in-transit stock? When will it arrive? Will it affect delivery? Answering this chain requires switching back and forth among the work order table, BOM tree, inventory table, purchase orders, and sales orders.

AI explanation compresses this process into three sentences:

3 materials are short; the core is IC-001 with a 150-unit gap, because the supplier lead time extended from 5 to 12 days.
This affects WO-008, planned to start on 05-12, linked to SO-2026-0031 with a commitment of 05-18, posing a 2-day overdue risk.
Recommend contacting the supplier to expedite immediately, or evaluating a transfer from SMT Line B's reserve stock.

The structured data block below expands simultaneously: shortage detail, in-transit purchases, and linked orders are all verifiable.

3 s
read 5 tables, compute gap, link to delivery
3 sentences
cause / impact / recommendation, fixed structure
0
new numbers generated by AI

The value of this feature is not that "AI is smarter than humans," but that "AI is faster than humans" — it can read 5 tables, compute the gap, and link it to delivery in 3 seconds, then summarize in plain language. The PMC's job shifts from "gathering information" to "judging and deciding."

5. Engineering Restraint: Where AI Is Kept in a Cage

The previous sections covered what AI does. This section covers what AI cannot do. These constraints are deliberate and are the most instructive part of this integration.

5.1 Every AI feature has a non-AI fallback

AI featureFallback pathTrigger condition
Intelligent scheduling_autoSchedule local auto-scheduleAI not enabled / call failed / user choice
Process inferenceruleBasedInferProcesses rule engineAI not enabled / schema validation failed / call failed
Anomaly explanationStructured data renderingAI not enabled / call failed
Labor attribution_attributeLaborDeviation rule attributionAI not enabled / call failed

Fallback is not "making do when something goes wrong"; it is two parallel paths by design. The rule engine and AI go through the same implementation workbench, only the source label differs; structured data and AI explanation are arranged vertically in the same modal. Users do not lose functionality because AI is down.

5.2 AI output always goes through validation

5.3 Never regenerate numbers: a hard prompt constraint

All prompts contain a similar line:

All numbers are already in the input data; (2) do not fabricate any numbers

This is not politeness. LLMs have a typical failure mode in "summarization" scenarios: misremembering numbers from the input, computing them incorrectly, or "helpfully" adding one. PMClite's approach: list all numbers AI needs clearly in the prompt, explicitly instruct "do not regenerate," and then show the original data in the UI for comparison.

5.4 API keys do not go through regular data sync

await window.__TAURI__.core.invoke('save_ai_settings', {
    settings: db.aiSettings
});

AI settings have a separate save command and do not go through saveDBSync. The reason: saveDBSync serializes db to disk, which would put the API key into the JSON backup file. The separate command routes it through encrypted storage, so it does not leak during backup.

5.5 AI application is traceable

Process inference application records are written to _ai_impl_log, keeping the most recent 100, including time, product, source (ai/rules/rules_fallback), applied count, updated/inserted count, and the full draft. When problems arise, you can trace "when was this product's routing configured, from what source, and based on what input."

6. What's Next: Extension Points Visible from the Code

No vague statements like "we will do multimodal and Agents in the future." Only directions where hooks are already in the code but not fully expanded.

6.1 Editable prompts

The code already contains executeSchedulingWithPrompt(userPrompt) and _updatePromptStats(), indicating that a UI for "user-defined scheduling prompts" has existed; the default path just uses buildPMCPrompt. The next reasonable step: let advanced users tweak scoring rules and add industry-specific constraints in the settings page without changing code.

6.2 Per-feature model selection

Currently db.aiSettings is a single global configuration. But the four features have very different model requirements:

The next step could be "feature-level model configuration," letting cost-sensitive scenarios use lightweight models and complex reasoning use heavier models.

6.3 Streaming output

Currently stream: false, so anomaly explanation takes 3–5 seconds to produce results. Explanation scenarios are naturally suited to streaming — users see words pop out one by one, reducing perceived wait. Process inference could also stream "analyzing BOM… generating processes…" alongside the existing progress bar.

6.4 Measuring AI adoption rate

There is traceability now, but no statistics. A natural evolution: count how many AI-inferred processes are ultimately adopted, modified, or deleted. This data can feed back into prompt optimization — if a certain industry's process inference always has "packaging" deleted, the rules or prompt need adjustment.

6.5 Multi-turn conversational sandbox

The current sandbox simulation is "fill parameters → see result," one-shot. The next step could be conversational:

User: Can this order move forward by two days?
AI: (calls sandbox tool) Moving forward by two days displaces WO-012, adding +2 days of delivery risk, but still within the commitment window. Recommend moving it forward.
User: What about a different line?
AI: (calls sandbox tool, changes line) SMT Line B is idle in the same period, no displacement, no delivery risk. Recommend changing line.

The key to this direction is tool calling — AI does not compute directly; it calls existing deterministic functions like calcScheduleImpact / _calcL25SandboxConflicts and explains the result in plain language. It is the same idea as the current anomaly explanation, just going from "one-shot" to "multi-turn."

6.6 Local model routing

The code already supports local (Ollama/LLaMA). For data-sensitive enterprises (e.g. defense, medical), API calls are a red line. The next step could be "intelligent routing": simple tasks (anomaly explanation, labor attribution) use local small models; complex tasks (scheduling, process inference) use the cloud; users can configure which data does not leave the intranet.

7. Conclusion: What Role Should AI Play in a PMC Tool?

The answer from PMClite's DeepSeek integration can be condensed into three sentences:

First, AI does the "soft" judgments that PMC is unwilling or unable to do well — scoring, attribution, summarization, recommendations. The common thread: input is structured, output is natural language, and if it is wrong, humans can see it.

Second, AI does not do the "hard" computation that PMC must be responsible for — dates, capacity, inventory, cost. The common thread: results must be signed off, audited, and traced back; they must be deterministic and recomputable.

Third, AI is always optional, never mandatory. Every AI feature has a non-AI fallback, every AI output has validation and disclaimers, every AI application is traceable. If AI is down, the tool still works; if AI is wrong, the user can spot it; if AI is misused, it can be investigated afterward.

This boundary is not a technical limitation; it is a product judgment.
In a scenario where the PMC signs off every day, carries delivery commitments, and is asked by the boss "why was this order late," explainability, intervenability, and traceability matter far more than "intelligence."

DeepSeek's role in this system is not a "thinking brain" but an assistant that "reads data, speaks plain language, and computes weights correctly." It frees the PMC from "gathering information" to do the judgment that truly requires a human — this positioning is more honest and far more practical than "AI replacing scheduling."

Want AI to be a co-pilot in your PMC workflow?

On-premise · One-time purchase · Live in 1–3 days · 30-day full-feature trial

Explore PMClite →

Algorithms and implementation details referenced in this article reflect our public demo builds; the shipped product takes precedence. PMClite is an independent product and has no commercial relationship with any third-party vendor mentioned in this article.