Files
EasyDesignCollection/lib/ai/ai_client.dart
T
admin 91c6132ef9 feat(ai): AI 生成强化——流式进度、可取消、超时、增量修改、自动纠错与结果清洗
- 流式接收(SSE):实时显示已用时 / 思考字符数 / 输出字符数,可随时取消
- 空闲 180 秒无数据自动超时并给出可读提示(此前可能无限等待)
- 新增「修改当前工程」模式:在现有工程上增删改,不再只能整图替换
- 解析/校验失败时自动把错误反馈给模型修复(最多 2 次重试)
- 结果清洗:修正非法时长与越界角度、剔除无效依赖、层号归一化,并提示修正项
- 提示词优化:layer 按并行资源分配(避免层数爆炸)、命名与 id 引用约束
- 版本号 1.1.0+11
2026-10-08 15:44:37 +08:00

399 lines
16 KiB
Dart
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
/// 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 '../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<AiModelOption> kAiModels = <AiModelOption>[
AiModelOption('deepseek-chat', 'Flash · 快速'),
AiModelOption('deepseek-reasoner', '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<String> 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 结构(协议 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 开始连续编号:
同一时间段内并行执行的动作必须处于不同 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 解析的对象。
''';
/// 根据自然语言 [prompt] 生成或修改项目(流式、可取消、带自动纠错)。
///
/// - [base] 非空时进入「增量修改」模式:连同现有工程一起发送,
/// 要求模型输出修改后的完整 JSON(未涉及部分保持原样);
/// - [onProgress]:每收到一段增量内容回调一次(含思考 / 输出字符数与尝试次数);
/// - [cancelToken]:取消后立即中断请求并抛出「已取消」;
/// - 空闲超过 [idleTimeout] 无任何数据视为超时;
/// - 输出无法解析 / 校验失败时,把错误反馈给模型自动修复重试(最多 [maxRepairs] 次);
/// - 成功后返回 [AiResult](含结果清洗说明)。
static Future<AiResult> 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('请输入自然语言描述');
}
final String baseJson = base == null ? '' : jsonEncode(base.toJson());
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<Map<String, String>> messages = <Map<String, String>>[
<String, String>{'role': 'system', 'content': _systemPrompt},
<String, String>{'role': 'user', 'content': firstUser},
];
if (attempt > 0) {
String prev = previousOutput ?? '';
if (prev.length > 8000) prev = prev.substring(prev.length - 8000);
messages.add(<String, String>{'role': 'assistant', 'content': prev});
messages.add(<String, String>{
'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<String, dynamic> decoded =
jsonDecode(_extractJson(content)) as Map<String, dynamic>;
final Project project = Project.fromJson(decoded);
final (Project fixed, List<String> warnings) = _sanitize(project);
if (fixed.actions.isEmpty) {
throw const FormatException('没有任何动作');
}
return AiResult(fixed, 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<String> _streamOnce({
required List<Map<String, String>> 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(<String, dynamic>{
'model': settings.model,
'messages': messages,
'stream': true,
'temperature': 0.2,
'response_format': <String, String>{'type': 'json_object'},
// 兼容支持推理强度的接口;不支持时会被忽略。
'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('接口返回 ${res.statusCode}:${_brief(text)}');
}
final StringBuffer content = StringBuffer();
final StringBuffer reasoning = StringBuffer();
final Stream<String> 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<String, dynamic> chunk;
try {
chunk = jsonDecode(payload) as Map<String, dynamic>;
} catch (_) {
continue; // 忽略无法解析的心跳 / 异常行
}
final List<dynamic> choices = (chunk['choices'] as List<dynamic>?) ?? const <dynamic>[];
if (choices.isEmpty) continue;
final Map<String, dynamic> delta =
((choices.first as Map<String, dynamic>)['delta'] as Map<String, dynamic>?) ??
const <String, dynamic>{};
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<String>) _sanitize(Project p) {
final Set<String> ids = <String>{for (final Action a in p.actions) a.id};
int fixedDur = 0;
int droppedDeps = 0;
final List<Action> actions = <Action>[];
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++;
}
final List<Dependency> deps = <Dependency>[];
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(startAngle: start, durationAngle: dur, deps: deps));
}
// 层号归一化为连续的 0..N-1(保持相对顺序),避免稀疏层号造成空白轨道。
final List<int> layers = <int>{for (final Action a in actions) a.layer}.toList()..sort();
final Map<int, int> remap = <int, int>{
for (int i = 0; i < layers.length; i++) layers[i]: i,
};
final List<Action> normalized = <Action>[
for (final Action a in actions) a.copyWith(layer: remap[a.layer] ?? 0),
];
final List<String> warnings = <String>[];
if (fixedDur > 0) warnings.add('修正 $fixedDur 处非法时长');
if (droppedDeps > 0) warnings.add('剔除 $droppedDeps 条无效依赖');
return (p.copyWith(actions: normalized), warnings);
}
/// 从模型输出中剥离 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;
}
}