Files
EasyDesignCollection/lib/ai/ai_client.dart
T
呆头鹅 6cfa79507c feat: V1.0.0 发布(呆头鹅)
- 默认浅色白底主题;字体整数化 + Microsoft YaHei UI 提升清晰度
- 相位分区:圆周/条形显示、沿弧排列、拖拽边界(虚线参考+弱吸附)、增删改(对话框/右键/双击)
- 动作:Ctrl 多选批量对齐;上下拖拽自由换行;左右端拖拽改起止(虚线+弱吸附+左右箭头光标)
- 动作编辑支持角度与时间双向换算
- 圆周顺时针箭头移至刻度环外;条形左侧标题列收窄
- 侧栏可隐藏/钉住;适应视图按内容自适应;节拍统计改为按钮弹窗
- AI 生成时序图(DeepSeek,Flash/Pro,推理强度),基于 dart:io 无插件
- 窗口标题显示文件名/未命名文件;关于信息(设计人/版本/版权)
- 全量中文注释、docs/ARCHITECTURE.md、docs/HELP.md(按任务组织)
- 构建脚本输出到 dist/,并附带 dist 生成物
2026-09-18 16:50:12 +08:00

186 lines
7.1 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] 调用,拿到 [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<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;
}
/// 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<Project> 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(<String, dynamic>{
'model': settings.model,
'messages': <Map<String, String>>[
<String, String>{'role': 'system', 'content': _systemPrompt},
<String, String>{'role': 'user', 'content': prompt.trim()},
],
'stream': false,
'temperature': 0.2,
'response_format': <String, String>{'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<String, dynamic> json = jsonDecode(text) as Map<String, dynamic>;
final List<dynamic> choices = (json['choices'] as List<dynamic>?) ?? <dynamic>[];
if (choices.isEmpty) throw AiException('接口未返回内容');
final Map<String, dynamic> msg =
((choices.first as Map<String, dynamic>)['message'] as Map<String, dynamic>?) ?? <String, dynamic>{};
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;
}
}