/// DeepSeek 大模型客户端:把自然语言描述转换为可加载的 [Project]。 /// /// 架构位置:独立于 UI 与状态层的纯服务模块,仅依赖 `dart:io`(HttpClient) /// 与模型层。UI 层通过 [AiGenerateDialog] 调用,拿到 [AiResult] 后交给 /// [AppController.loadProject] 载入。 /// /// 能力: /// - **流式接收**:SSE 增量解析,实时报告「思考 / 输出」字符数; /// - **可取消**:通过 [AiCancelToken] 立即中断 HTTP 请求; /// - **超时保护**:空闲超过 `idleTimeout` 自动失败并给出可读提示; /// - **增量修改**:传入基准 [Project],让模型在现有工程上增删改而非整图重画; /// - **自动纠错**:输出无法解析为时序图时,把错误反馈给模型自动修复重试; /// - **结果清洗**:修正非法时长 / 越界角度,剔除指向不存在动作的依赖,归一化层号。 /// /// 约束:不引入任何原生插件或第三方 HTTP 包,全部使用 `dart:io` 实现。 library; import 'dart:async'; import 'dart:convert'; import 'dart:io'; import 'package:sequence_diagram/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(深度推理)。 /// /// 模型 id 必须与 DeepSeek 当前 API 保持一致(`deepseek-flash` / /// `deepseek-v4-pro`);旧 id(`deepseek-chat` / `deepseek-reasoner`) /// 已下线,继续使用会直接返回 400 Model Not Exist。 const List kAiModels = [ AiModelOption('deepseek-flash', 'Flash · 快速'), AiModelOption('deepseek-v4-pro', 'Pro · 深度推理'), ]; /// AI 调用异常(携带可读信息,便于界面直接展示)。 class AiException implements Exception { /// 构造。 AiException(this.message); /// 错误信息。 final String message; @override String toString() => message; } /// 流式生成进度:分别统计「思考」与「输出」已接收的字符数。 class AiProgress { /// 构造。 const AiProgress({ required this.reasoningChars, required this.contentChars, required this.attempt, }); /// 已接收的思考(reasoning_content)字符数;非推理模型恒为 0。 final int reasoningChars; /// 已接收的正式输出(content)字符数。 final int contentChars; /// 第几次尝试(0 起;大于 0 表示正在自动修复上一次的输出)。 final int attempt; } /// 取消令牌:界面点击「取消生成」时置位,并触发底层 HTTP 中断。 class AiCancelToken { bool _cancelled = false; void Function()? _abort; /// 是否已被取消。 bool get cancelled => _cancelled; /// 绑定底层中断动作(关闭 HTTP 客户端 / socket)。 void bindAbort(void Function() abort) => _abort = abort; /// 请求取消:先置位再触发中断,保证两侧都能观察到。 void cancel() { _cancelled = true; _abort?.call(); } } /// 生成结果:清洗后的项目 + 自动修正说明(用于状态栏提示)。 class AiResult { /// 构造。 const AiResult(this.project, this.warnings); /// 解析并清洗后的项目。 final Project project; /// 自动修正项说明;无修正时为空列表。 final List warnings; } /// 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 结构(协议 edc/1.3): { "schema": "edc/1.3", "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 开始连续编号: 同一时间段内并行执行的动作必须处于不同 layer;前后串行、时间不重叠的动作 应尽量复用同一 layer,避免层数过多(一般不超过 6 层)。 4. deps 为前置依赖数组,元素形如 { "fromId": "A1", "toId": "A2", "type": "FS", "offsetAngle": 0 }; type 取 FS(完成-启动)/ SS(起始-起始)/ FF / SF。 一个动作可以有多条 deps(多输入),也可以被多个动作引用(多输出); fromId / toId 必须引用 actions 中真实存在的动作 id,且不能指向自身。 5. 颜色从调色板循环取用:#4cc9f0, #7bd88f, #ffd166, #ff8a5c, #f472b6, #a78bfa, #38bdf8, #34d399。 6. 相位分区 phaseZones 用于标注工艺阶段,可重叠,允许结束角 > 360°。 7. 动作命名简洁(不超过 8 个汉字);不要编造不存在的工位,stationId 必须引用 stations 中已有的 id。 8. 只输出 JSON 本体,且必须是单个可直接 JSON 解析的对象。 9. 只需要输出时序图数据(name / units / cycle / stations / actions / viewState / phaseZones), 不需要也没有 `arch`、`keepEmptyLanes`、`laneSlots` 等字段;修改模式由程序负责保留原有架构图数据。 '''; /// 根据自然语言 [prompt] 生成或修改项目(流式、可取消、带自动纠错)。 /// /// - [base] 非空时进入「增量修改」模式:连同现有工程一起发送, /// 要求模型输出修改后的完整 JSON(未涉及部分保持原样); /// - [onProgress]:每收到一段增量内容回调一次(含思考 / 输出字符数与尝试次数); /// - [cancelToken]:取消后立即中断请求并抛出「已取消」; /// - 空闲超过 [idleTimeout] 无任何数据视为超时; /// - 输出无法解析 / 校验失败时,把错误反馈给模型自动修复重试(最多 [maxRepairs] 次); /// - 成功后返回 [AiResult](含结果清洗说明)。 static Future generate({ required String prompt, required AiSettings settings, Project? base, void Function(AiProgress progress)? onProgress, AiCancelToken? cancelToken, Duration idleTimeout = const Duration(seconds: 180), int maxRepairs = 2, }) async { if (settings.apiKey.trim().isEmpty) { throw AiException('请先填写 DeepSeek API Key'); } if (prompt.trim().isEmpty) { throw AiException('请输入自然语言描述'); } // 修改模式只发送时序部分:架构图 / 画布设置(arch、泳道、自动保存) // 体积大且与本次修改无关,不回传给模型,也能避免模型丢掉原有架构图。 final String baseJson = base == null ? '' : jsonEncode(base.toJson(includeArch: false)); final String firstUser = base == null ? prompt.trim() : '现有工程 JSON:\n$baseJson\n\n' '修改要求:${prompt.trim()}\n\n' '请在现有工程基础上按要求修改(增删改动作 / 相位 / 依赖等),' '未涉及的部分保持原样,输出修改后的**完整** JSON。'; String? previousOutput; String lastError = ''; for (int attempt = 0; attempt <= maxRepairs; attempt++) { if (cancelToken?.cancelled ?? false) throw AiException('已取消'); final List> messages = >[ {'role': 'system', 'content': _systemPrompt}, {'role': 'user', 'content': firstUser}, ]; if (attempt > 0) { String prev = previousOutput ?? ''; if (prev.length > 8000) prev = prev.substring(prev.length - 8000); messages.add({'role': 'assistant', 'content': prev}); messages.add({ 'role': 'user', 'content': '你上次的输出无法解析为合法的时序图:$lastError\n' '请修正后只输出完整的 JSON 本体(不要解释、不要 Markdown 代码块)。', }); } try { final String content = await _streamOnce( messages: messages, settings: settings, attempt: attempt, onProgress: onProgress, cancelToken: cancelToken, idleTimeout: idleTimeout, ); previousOutput = content; final Map decoded = jsonDecode(_extractJson(content)) as Map; final Project project = Project.fromJson(decoded); final (Project fixed, List warnings) = _sanitize(project); if (fixed.actions.isEmpty) { throw const FormatException('没有任何动作'); } // 修改模式:只采纳 AI 返回的时序内容,架构图 / 画布设置 / 泳道设置 // 一律沿用原工程,避免一次 AI 修改把架构图或用户视图状态清空。 final Project result = base == null ? fixed : base.copyWith( name: fixed.name, schema: fixed.schema, cycle: fixed.cycle, stations: fixed.stations, actions: fixed.actions, units: fixed.units, phaseZones: fixed.phaseZones, ); return AiResult(result, warnings); } on AiException { rethrow; // 网络 / 鉴权 / 超时 / 取消等错误不重试 } on FormatException catch (e) { lastError = e.message; if (attempt >= maxRepairs) { throw AiException('模型输出无法解析为时序图:${e.message}'); } } catch (e) { lastError = '$e'; if (attempt >= maxRepairs) { throw AiException('模型输出无法解析为时序图:$e'); } } } throw AiException('生成失败:$lastError'); } /// 单次流式请求:返回模型输出的完整文本内容(不含思考内容)。 static Future _streamOnce({ required List> messages, required AiSettings settings, required int attempt, void Function(AiProgress progress)? onProgress, AiCancelToken? cancelToken, required Duration idleTimeout, }) async { final HttpClient client = HttpClient()..connectionTimeout = const Duration(seconds: 20); cancelToken?.bindAbort(() => client.close(force: true)); 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': messages, 'stream': true, 'temperature': 0.2, 'max_tokens': 131072, 'response_format': {'type': 'json_object'}, // 当前 DeepSeek 模型默认开启思考,这里显式开启并按 UI 选择传推理强度。 'thinking': {'type': 'enabled'}, 'reasoning_effort': settings.effort, })); final HttpClientResponse res = await req.close(); if (res.statusCode != 200) { final String text = await res.transform(utf8.decoder).join(); throw AiException(_apiError(res.statusCode, text)); } final StringBuffer content = StringBuffer(); final StringBuffer reasoning = StringBuffer(); final Stream lines = res.transform(utf8.decoder).transform(const LineSplitter()).timeout(idleTimeout); await for (final String line in lines) { if (cancelToken?.cancelled ?? false) throw AiException('已取消'); if (!line.startsWith('data:')) continue; final String payload = line.substring(5).trim(); if (payload.isEmpty) continue; if (payload == '[DONE]') break; Map chunk; try { chunk = jsonDecode(payload) as Map; } catch (_) { continue; // 忽略无法解析的心跳 / 异常行 } final List choices = (chunk['choices'] as List?) ?? const []; if (choices.isEmpty) continue; final Map delta = ((choices.first as Map)['delta'] as Map?) ?? const {}; final String piece = (delta['content'] as String?) ?? ''; final String think = (delta['reasoning_content'] as String?) ?? ''; if (piece.isNotEmpty) content.write(piece); if (think.isNotEmpty) reasoning.write(think); if (piece.isNotEmpty || think.isNotEmpty) { onProgress?.call(AiProgress( reasoningChars: reasoning.length, contentChars: content.length, attempt: attempt, )); } } if (cancelToken?.cancelled ?? false) throw AiException('已取消'); if (content.toString().trim().isEmpty) throw AiException('模型返回为空'); return content.toString(); } on AiException { rethrow; } on TimeoutException { throw AiException('响应超时(${idleTimeout.inSeconds} 秒无数据),请检查网络后重试'); } on SocketException catch (e) { if (cancelToken?.cancelled ?? false) throw AiException('已取消'); throw AiException('网络连接失败:${e.message}'); } on HttpException catch (e) { if (cancelToken?.cancelled ?? false) throw AiException('已取消'); throw AiException('HTTP 错误:${e.message}'); } on FormatException catch (e) { throw AiException('响应格式错误:${e.message}'); } finally { client.close(force: true); } } /// 结果清洗:补齐工位、修正非法时长与越界角度、剔除指向不存在动作的 /// 依赖、归一化层号。 /// /// 返回修正后的项目与人类可读的修正说明(供状态栏提示)。 static (Project, List) _sanitize(Project p) { // 工位是动作的归属单元:模型偶发漏写 stations 或编造 stationId 时, // 直接引用会让条形视图整组动作消失,这里兜底并提示。 final List stations = p.stations.isEmpty ? const [ Station(id: 'ST1', name: '工位1', order: 0, color: 0xFF4CC9F0), ] : p.stations; final Set stationIds = {for (final Station s in stations) s.id}; final String fallbackStation = stations.first.id; int fixedStation = 0; final Set ids = {for (final Action a in p.actions) a.id}; int fixedDur = 0; int droppedDeps = 0; final List actions = []; for (final Action a in p.actions) { double start = a.startAngle; double dur = a.durationAngle; if (!start.isFinite || start < 0) start = 0; if (start > 400) start = 400; if (!dur.isFinite) dur = 0; if (dur <= 0) { dur = 5; fixedDur++; } else if (dur > 720) { dur = 720; fixedDur++; } String stationId = a.stationId; if (!stationIds.contains(stationId)) { stationId = fallbackStation; fixedStation++; } final List deps = []; for (final Dependency d in a.deps) { if (d.fromId == a.id || !ids.contains(d.fromId) || !ids.contains(d.toId)) { droppedDeps++; continue; } deps.add(d); } actions.add(a.copyWith( stationId: stationId, startAngle: start, durationAngle: dur, deps: deps, )); } // 层号归一化为连续的 0..N-1(保持相对顺序),避免稀疏层号造成空白轨道。 final List layers = {for (final Action a in actions) a.layer}.toList()..sort(); final Map remap = { for (int i = 0; i < layers.length; i++) layers[i]: i, }; final List normalized = [ for (final Action a in actions) a.copyWith(layer: remap[a.layer] ?? 0), ]; final List warnings = []; if (fixedDur > 0) warnings.add('修正 $fixedDur 处非法时长'); if (fixedStation > 0) warnings.add('修正 $fixedStation 处无效工位'); if (droppedDeps > 0) warnings.add('剔除 $droppedDeps 条无效依赖'); return (p.copyWith(stations: stations, actions: normalized), warnings); } /// 把非 200 响应转换为可读错误:优先取 DeepSeek 的 `error.message`, /// 并对常见状态码给出排查提示(模型下线 / Key 无效 / 余额不足)。 static String _apiError(int code, String raw) { String detail = _brief(raw); try { final Object? j = jsonDecode(raw); if (j is Map) { final Object? err = j['error']; if (err is Map && err['message'] is String) { detail = _brief(err['message'] as String); } else if (j['message'] is String) { detail = _brief(j['message'] as String); } } } catch (_) {} switch (code) { case 401: return 'API Key 无效或已过期(401):$detail'; case 402: return 'DeepSeek 账户余额不足(402):$detail'; case 429: return '请求过于频繁(429):$detail'; default: return '接口返回 $code:$detail'; } } /// 从模型输出中剥离 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; } }