/// DeepSeek 大模型客户端:把自然语言描述转换为可加载的 [Project]。 /// /// 架构位置:独立于 UI 与状态层的纯服务模块,仅依赖 `dart:io`(HttpClient) /// 与模型层。UI 层通过 [AiGenerateDialog] 调用,拿到 [Project] 后交给 /// [AppController.loadProject] 载入。 /// /// 约束:不引入任何原生插件或第三方 HTTP 包,全部使用 `dart:io` 实现。 library; import 'dart:convert'; import 'dart:io'; import '../model/models.dart'; /// AI 请求参数。 class AiSettings { /// 构造参数。 const AiSettings({ required this.apiKey, required this.model, required this.effort, }); /// DeepSeek API Key(仅驻留内存,不写入工程文件)。 final String apiKey; /// 模型 id,例如 `deepseek-chat`(Flash)或 `deepseek-reasoner`(Pro)。 final String model; /// 推理强度:`high` / `max`。 final String effort; } /// 可选的模型项(id + 展示名)。 class AiModelOption { /// 构造。 const AiModelOption(this.id, this.label); /// 接口使用的模型 id。 final String id; /// 界面展示名称。 final String label; } /// 预设模型列表:Flash(快速)与 Pro(深度推理)。 const List kAiModels = [ AiModelOption('deepseek-chat', 'Flash · 快速'), AiModelOption('deepseek-reasoner', 'Pro · 深度推理'), ]; /// AI 调用异常(携带可读信息,便于界面直接展示)。 class AiException implements Exception { /// 构造。 AiException(this.message); /// 错误信息。 final String message; @override String toString() => message; } /// DeepSeek 客户端。 class AiClient { AiClient._(); /// DeepSeek 兼容 OpenAI 的对话补全端点。 static const String endpoint = 'https://api.deepseek.com/chat/completions'; /// 要求模型输出的系统提示词:严格描述 `seqdiagram/1.2` JSON 结构。 static const String _systemPrompt = ''' 你是工业节拍 / 相位角设计助手。请把用户的自然语言描述转换成严格的 JSON,且**只能输出 JSON**,不要输出解释、注释或 Markdown 代码块。 JSON 结构(协议 seqdiagram/1.2): { "schema": "seqdiagram/1.2", "project": { "name": "项目名称", "units": { "timeUnit": "s", "phaseUnit": "deg", "precision": -1, "snapAngle": 1, "snapTime": 0.1, "cycleInputPolicy": "keepAngle" }, "cycle": { "durationMs": 2400, "startAngle": 0, "direction": "cw", "origin": "twelve", "snapDeg": 1 }, "stations": [ { "id": "ST1", "name": "工位1", "order": 0, "color": "#4cc9f0" } ], "actions": [ { "id": "A1", "name": "动作1", "stationId": "ST1", "driver": "气缸 Y1", "startAngle": 0, "durationAngle": 60, "layer": 0, "color": "#4cc9f0", "deps": [] } ], "viewState": { "mode": "bar", "zoom": 1, "pan": [0, 0], "showDeps": true, "showRuler": true, "showPhaseBands": true, "showRingBg": true, "showLayerLabels": true }, "phaseZones": [ { "name": "上料相位", "startAngle": 0, "endAngle": 70 } ] } } 规则: 1. 时间只存于 cycle.durationMs(毫秒);角度为 0–360 度,0° 为 12 点钟方向、顺时针递增。 2. 每个动作 durationAngle > 0;startAngle + durationAngle 可以超过 360 表示跨循环。 3. layer 从 0 开始,每个动作独占一层(圆周视图的一个同心圆环)。 4. deps 为前置依赖数组,元素形如 { "fromId": "A1", "toId": "A2", "type": "FS", "offsetAngle": 0 }; type 取 FS(完成-启动)/ SS(起始-起始)/ FF / SF。 一个动作可以有**多条** deps(多输入),也可以被**多个**动作引用(多输出)。 5. 颜色从调色板循环取用:#4cc9f0, #7bd88f, #ffd166, #ff8a5c, #f472b6, #a78bfa, #38bdf8, #34d399。 6. 相位分区 phaseZones 用于标注工艺阶段,可重叠,允许结束角 > 360°。 7. 只输出 JSON 本体。 '''; /// 根据自然语言 [prompt] 生成项目。 /// /// 抛出 [AiException] 表示网络、鉴权或解析失败。 static Future generate({ required String prompt, required AiSettings settings, }) async { if (settings.apiKey.trim().isEmpty) { throw AiException('请先填写 DeepSeek API Key'); } if (prompt.trim().isEmpty) { throw AiException('请输入自然语言描述'); } final HttpClient client = HttpClient()..connectionTimeout = const Duration(seconds: 20); try { final HttpClientRequest req = await client.postUrl(Uri.parse(endpoint)); req.headers.set(HttpHeaders.contentTypeHeader, 'application/json'); req.headers.set(HttpHeaders.authorizationHeader, 'Bearer ${settings.apiKey.trim()}'); req.write(jsonEncode({ 'model': settings.model, 'messages': >[ {'role': 'system', 'content': _systemPrompt}, {'role': 'user', 'content': prompt.trim()}, ], 'stream': false, 'temperature': 0.2, 'response_format': {'type': 'json_object'}, // 兼容支持推理强度的接口;不支持时会被忽略。 'reasoning_effort': settings.effort, })); final HttpClientResponse res = await req.close(); final String text = await res.transform(utf8.decoder).join(); if (res.statusCode != 200) { throw AiException('接口返回 ${res.statusCode}:${_brief(text)}'); } final Map json = jsonDecode(text) as Map; final List choices = (json['choices'] as List?) ?? []; if (choices.isEmpty) throw AiException('接口未返回内容'); final Map msg = ((choices.first as Map)['message'] as Map?) ?? {}; final String content = (msg['content'] as String?) ?? ''; if (content.trim().isEmpty) throw AiException('模型返回为空'); final String cleaned = _extractJson(content); try { return Project.decode(cleaned); } catch (e) { throw AiException('模型输出无法解析为时序图:$e'); } } on AiException { rethrow; } on SocketException catch (e) { throw AiException('网络连接失败:${e.message}'); } on HttpException catch (e) { throw AiException('HTTP 错误:${e.message}'); } on FormatException catch (e) { throw AiException('响应格式错误:${e.message}'); } finally { client.close(force: true); } } /// 从模型输出中剥离 Markdown 代码围栏并截取首个 JSON 对象。 static String _extractJson(String raw) { String t = raw.trim(); if (t.startsWith('```')) { t = t.replaceFirst(RegExp(r'^```[a-zA-Z]*\s*'), ''); t = t.replaceFirst(RegExp(r'```\s*$'), ''); } final int i = t.indexOf('{'); final int j = t.lastIndexOf('}'); if (i >= 0 && j > i) t = t.substring(i, j + 1); return t.trim(); } /// 截断过长的错误信息,避免弹窗过大。 static String _brief(String s) { final String one = s.replaceAll(RegExp(r'\s+'), ' ').trim(); return one.length > 200 ? '${one.substring(0, 200)}…' : one; } }