molforge-studio 7.4.3__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (219) hide show
  1. main.py +71 -0
  2. molforge/__init__.py +19 -0
  3. molforge/ai/__init__.py +15 -0
  4. molforge/ai/deepseek_harness.py +185 -0
  5. molforge/ai/mcp/desktop_client.py +38 -0
  6. molforge/ai/mcp/desktop_service.py +121 -0
  7. molforge/ai/mcp/mcp_server.py +780 -0
  8. molforge/ai/mcp_bridge.py +945 -0
  9. molforge/ai/observation.py +152 -0
  10. molforge/ai/tools.py +455 -0
  11. molforge/application/__init__.py +22 -0
  12. molforge/application/ai/__init__.py +1 -0
  13. molforge/application/ai/deepseek_client.py +293 -0
  14. molforge/application/ai/observation.py +161 -0
  15. molforge/application/ai/tools.py +200 -0
  16. molforge/application/ai_proposals.py +166 -0
  17. molforge/application/bio_selection.py +143 -0
  18. molforge/application/builtin_commands.py +1445 -0
  19. molforge/application/calculators/__init__.py +10 -0
  20. molforge/application/calculators/base.py +143 -0
  21. molforge/application/calculators/calchem_engine.py +67 -0
  22. molforge/application/calculators/calchem_subprocess_worker.py +109 -0
  23. molforge/application/calculators/gaussian_engine.py +59 -0
  24. molforge/application/calculators/gaussian_job_spec.py +240 -0
  25. molforge/application/calculators/orca_engine.py +92 -0
  26. molforge/application/calculators/qc_input_generator.py +300 -0
  27. molforge/application/calculators/registry.py +29 -0
  28. molforge/application/calculators/rest_engine.py +262 -0
  29. molforge/application/command_bus.py +139 -0
  30. molforge/application/commands.py +55 -0
  31. molforge/application/conformers.py +143 -0
  32. molforge/application/document_session.py +156 -0
  33. molforge/application/events.py +74 -0
  34. molforge/application/fragment_catalog.py +422 -0
  35. molforge/application/fragment_commands.py +268 -0
  36. molforge/application/geometry_commands.py +84 -0
  37. molforge/application/history.py +105 -0
  38. molforge/application/internal_coordinates.py +293 -0
  39. molforge/application/invalidation.py +1174 -0
  40. molforge/application/jobs.py +185 -0
  41. molforge/application/measurement.py +167 -0
  42. molforge/application/measurement_targets.py +264 -0
  43. molforge/application/modeling_commands.py +61 -0
  44. molforge/application/plugins.py +197 -0
  45. molforge/application/ports/editor2d.py +85 -0
  46. molforge/application/reaction.py +75 -0
  47. molforge/application/selection.py +164 -0
  48. molforge/application/selection_commands.py +31 -0
  49. molforge/application/trajectory.py +120 -0
  50. molforge/application/trajectory_analysis.py +231 -0
  51. molforge/application/workspace_registry.py +226 -0
  52. molforge/core/__init__.py +12 -0
  53. molforge/core/conformer.py +45 -0
  54. molforge/core/molecule.py +150 -0
  55. molforge/core/orbital.py +33 -0
  56. molforge/core/properties.py +43 -0
  57. molforge/domain/__init__.py +12 -0
  58. molforge/domain/biomolecule.py +99 -0
  59. molforge/domain/chemical_summary.py +129 -0
  60. molforge/domain/chemistry.py +13 -0
  61. molforge/domain/coordinate_store.py +164 -0
  62. molforge/domain/coordination.py +133 -0
  63. molforge/domain/custom_fragments.py +255 -0
  64. molforge/domain/document.py +469 -0
  65. molforge/domain/element_reference.json +598 -0
  66. molforge/domain/elements.py +188 -0
  67. molforge/domain/ids.py +58 -0
  68. molforge/domain/massive_system.py +246 -0
  69. molforge/domain/periodic.py +116 -0
  70. molforge/domain/provenance.py +115 -0
  71. molforge/domain/topology.py +364 -0
  72. molforge/infrastructure/__init__.py +23 -0
  73. molforge/infrastructure/hpc/cluster_config.py +122 -0
  74. molforge/infrastructure/hpc/remote_executor.py +212 -0
  75. molforge/infrastructure/hpc/slurm_generator.py +93 -0
  76. molforge/io/__init__.py +35 -0
  77. molforge/io/calchem_bridge.py +407 -0
  78. molforge/io/calculators.py +893 -0
  79. molforge/io/cclib_adapter.py +422 -0
  80. molforge/io/conformers.py +183 -0
  81. molforge/io/cube_reader.py +215 -0
  82. molforge/io/custom_fragments.py +79 -0
  83. molforge/io/format_matrix.py +157 -0
  84. molforge/io/gemmi_adapter.py +150 -0
  85. molforge/io/history_skill.py +46 -0
  86. molforge/io/mdanalysis_adapter.py +155 -0
  87. molforge/io/mforge_storage.py +261 -0
  88. molforge/io/multiwfn_driver.py +614 -0
  89. molforge/io/openbabel_adapter.py +265 -0
  90. molforge/io/openbabel_handler.py +33 -0
  91. molforge/io/rdkit_adapter.py +1865 -0
  92. molforge/io/readers/__init__.py +10 -0
  93. molforge/io/readers/cube_reader.py +71 -0
  94. molforge/io/readers/gjf_reader.py +110 -0
  95. molforge/io/readers/glog_reader.py +45 -0
  96. molforge/io/readers/mol2_reader.py +36 -0
  97. molforge/io/readers/mol_reader.py +56 -0
  98. molforge/io/readers/pdb_reader.py +39 -0
  99. molforge/io/readers/smi_reader.py +40 -0
  100. molforge/io/readers/xyz_reader.py +47 -0
  101. molforge/io/registry.py +128 -0
  102. molforge/io/writers/__init__.py +7 -0
  103. molforge/io/writers/gjf_writer.py +68 -0
  104. molforge/io/writers/pdb_writer.py +37 -0
  105. molforge/io/writers/png_writer.py +31 -0
  106. molforge/io/writers/svg_writer.py +111 -0
  107. molforge/io/writers/xyz_writer.py +39 -0
  108. molforge/rendering/__init__.py +21 -0
  109. molforge/rendering/benchmark.py +121 -0
  110. molforge/rendering/bridge.py +60 -0
  111. molforge/rendering/contracts.py +119 -0
  112. molforge/rendering/glyph_scene.py +279 -0
  113. molforge/rendering/ketcher_bridge.py +131 -0
  114. molforge/rendering/ketcher_id_mapping.py +110 -0
  115. molforge/rendering/materials.py +127 -0
  116. molforge/rendering/molstar_backend.py +245 -0
  117. molforge/rendering/native_labels.py +134 -0
  118. molforge/rendering/orbitals.py +139 -0
  119. molforge/rendering/vtk_backend.py +2294 -0
  120. molforge/runtime.py +29 -0
  121. molforge/server/__init__.py +1 -0
  122. molforge/server/api_bridge.py +947 -0
  123. molforge/ui/__init__.py +1 -0
  124. molforge/ui/assets/caffeine_2d.svg +150 -0
  125. molforge/ui/assets/caffeine_3d_preview.svg +209 -0
  126. molforge/ui/assets/caffeine_preview.json +302 -0
  127. molforge/ui/assets/icons/atom.svg +1 -0
  128. molforge/ui/assets/icons/bond.svg +1 -0
  129. molforge/ui/assets/icons/cleanup.svg +1 -0
  130. molforge/ui/assets/icons/export.svg +1 -0
  131. molforge/ui/assets/icons/fragments.svg +1 -0
  132. molforge/ui/assets/icons/history.svg +1 -0
  133. molforge/ui/assets/icons/jobs.svg +1 -0
  134. molforge/ui/assets/icons/measure.svg +1 -0
  135. molforge/ui/assets/icons/molecules.svg +1 -0
  136. molforge/ui/assets/icons/overview.svg +1 -0
  137. molforge/ui/assets/icons/ring.svg +1 -0
  138. molforge/ui/assets/icons/search.svg +1 -0
  139. molforge/ui/assets/icons/select.svg +1 -0
  140. molforge/ui/assets/icons/settings.svg +1 -0
  141. molforge/ui/assets/icons/templates.svg +1 -0
  142. molforge/ui/assets/molforge_logo.ico +0 -0
  143. molforge/ui/assets/molforge_logo.png +0 -0
  144. molforge/ui/atom_labels.py +92 -0
  145. molforge/ui/bio_structure_dialog.py +57 -0
  146. molforge/ui/conformer_dialog.py +151 -0
  147. molforge/ui/dialogs/__init__.py +2 -0
  148. molforge/ui/dialogs/aim_qtaim_dialog.py +533 -0
  149. molforge/ui/dialogs/calchem_orbitals_dialog.py +287 -0
  150. molforge/ui/dialogs/element_fragments.py +130 -0
  151. molforge/ui/dialogs/gaussian_calculation_setup.py +308 -0
  152. molforge/ui/dialogs/hpc_job_dialog.py +427 -0
  153. molforge/ui/dialogs/vibrational_spectrum_dialog.py +381 -0
  154. molforge/ui/editor2d_widget.py +1803 -0
  155. molforge/ui/element_picker.py +218 -0
  156. molforge/ui/gmv_window_manager.py +65 -0
  157. molforge/ui/gromacs_job_dialog.py +47 -0
  158. molforge/ui/hotkeys.py +107 -0
  159. molforge/ui/i18n.py +237 -0
  160. molforge/ui/live_llm_dialog.py +135 -0
  161. molforge/ui/llm_config_dialog.py +103 -0
  162. molforge/ui/modeling_actions.py +176 -0
  163. molforge/ui/molstar_widget.py +98 -0
  164. molforge/ui/molstar_window.py +85 -0
  165. molforge/ui/panels.py +2966 -0
  166. molforge/ui/qc_result_dialog.py +1924 -0
  167. molforge/ui/render3d_widget.py +1579 -0
  168. molforge/ui/scrolling.py +52 -0
  169. molforge/ui/settings_panel.py +330 -0
  170. molforge/ui/shells/__init__.py +4 -0
  171. molforge/ui/shells/base_shell.py +72 -0
  172. molforge/ui/shells/document_tabs.py +715 -0
  173. molforge/ui/shells/studio_2d.py +339 -0
  174. molforge/ui/shells/studio_3d.py +401 -0
  175. molforge/ui/shells/studio_split.py +370 -0
  176. molforge/ui/shells/workflow_inputs.py +698 -0
  177. molforge/ui/theme.py +719 -0
  178. molforge/ui/trajectory_window.py +333 -0
  179. molforge/ui/views.py +892 -0
  180. molforge/ui/vtk_multiview_widget.py +141 -0
  181. molforge/ui/welcome_window.py +223 -0
  182. molforge/ui/window.py +3320 -0
  183. molforge/workflows/__init__.py +25 -0
  184. molforge/workflows/assets/OSC_MD_workflows/templates/01-MD/delete_solvent.py +216 -0
  185. molforge/workflows/assets/OSC_MD_workflows/templates/02-RDF/extract_atoms.py +60 -0
  186. molforge/workflows/assets/OSC_MD_workflows/templates/02-RDF/extract_atoms_example.py +22 -0
  187. molforge/workflows/assets/OSC_MD_workflows/templates/03-/342/225/244/320/225/342/225/250/342/226/221/342/225/250/320/246/342/225/244/320/227/342/225/250/342/225/226/342/225/250/342/224/220/342/225/244/320/225/342/225/250/320/247/342/225/250/342/226/221/342/225/244/320/224/321/202/320/245/320/254/342/225/250/320/265/analysis_mol.py +244 -0
  188. molforge/workflows/assets/OSC_MD_workflows/templates/04-/342/225/244/320/224/321/202/320/245/320/241/342/225/250/320/254/342/225/244/320/227/321/202/320/245/320/247/321/202/320/244/320/264/342/225/244/320/225/342/225/250/342/224/220/342/225/250/320/246/342/225/244/320/225/321/202/320/245/320/241/342/225/250/342/225/242/rms_roughness.py +33 -0
  189. molforge/workflows/assets/OSC_MD_workflows/templates/04-/342/225/244/320/224/321/202/320/245/320/241/342/225/250/320/254/342/225/244/320/227/321/202/320/245/320/247/321/202/320/244/320/264/342/225/244/320/225/342/225/250/342/224/220/342/225/250/320/246/342/225/244/320/225/321/202/320/245/320/241/342/225/250/342/225/242/xpm_2.py +117 -0
  190. molforge/workflows/assets/OSC_MD_workflows/templates/09-/342/225/244/320/231/342/225/250/320/240/342/225/250/320/277/342/225/244/320/227/342/225/250/320/256/342/225/250/320/247/marcus_rate.py +60 -0
  191. molforge/workflows/assets/esp-surface-analysis/scripts/compute_descriptors.py +134 -0
  192. molforge/workflows/assets/esp-surface-analysis/scripts/parse_surfanalysis.py +58 -0
  193. molforge/workflows/assets/esp-surface-analysis/scripts/plot_esp_hist.py +115 -0
  194. molforge/workflows/assets/homo-lumo-plot/extract_orb_energy.py +57 -0
  195. molforge/workflows/assets/homo-lumo-plot/make_level_plot.py +76 -0
  196. molforge/workflows/assets/homo-lumo-plot/run_pipeline.py +84 -0
  197. molforge/workflows/assets/osc-energy-level-diagram/scripts/extract_levels.py +60 -0
  198. molforge/workflows/assets/osc-energy-level-diagram/scripts/make_editable_pptx.py +122 -0
  199. molforge/workflows/assets/osc-energy-level-diagram/scripts/make_energy_table.py +66 -0
  200. molforge/workflows/assets/osc-energy-level-diagram/scripts/make_level_lines_diagram.py +148 -0
  201. molforge/workflows/assets/osc-energy-level-diagram/scripts/make_rectangle_diagram.py +148 -0
  202. molforge/workflows/assets/osc-energy-level-diagram/scripts/verify_from_log.py +45 -0
  203. molforge/workflows/dipole_analysis.py +32 -0
  204. molforge/workflows/esp_surface.py +36 -0
  205. molforge/workflows/gromacs_submit.py +167 -0
  206. molforge/workflows/homo_lumo_plot.py +59 -0
  207. molforge/workflows/igmh_interaction.py +111 -0
  208. molforge/workflows/md_rdf_analysis.py +134 -0
  209. molforge/workflows/md_studio.py +255 -0
  210. molforge/workflows/osc_energy_diagram.py +24 -0
  211. molforge/workflows/planarity_analysis.py +66 -0
  212. molforge/workflows/reorganization_energy.py +166 -0
  213. molforge/workflows/scientific_workflows.py +650 -0
  214. molforge_studio-7.4.3.dist-info/METADATA +215 -0
  215. molforge_studio-7.4.3.dist-info/RECORD +219 -0
  216. molforge_studio-7.4.3.dist-info/WHEEL +5 -0
  217. molforge_studio-7.4.3.dist-info/entry_points.txt +3 -0
  218. molforge_studio-7.4.3.dist-info/licenses/LICENSE +93 -0
  219. molforge_studio-7.4.3.dist-info/top_level.txt +2 -0
@@ -0,0 +1,293 @@
1
+ """
2
+ application/ai/deepseek_client.py - DeepSeek AI 化学助手客户端与本地智能引擎
3
+ =============================================================================
4
+ 特性:
5
+ - 原生对接 DeepSeek API (https://api.deepseek.com/v1/chat/completions),支持
6
+ deepseek-chat (DeepSeek-V3) 与 deepseek-reasoner (DeepSeek-R1)
7
+ - 零第三方网络库依赖(使用标准库 urllib.request + ssl,开箱即用)
8
+ - 自动注入当前分子的化学上下文(分子式、原子/键数、选中原子几何测量、3D 构象状态)
9
+ - 支持结构修改指令、Gaussian (.gjf) 与复旦 REST (ctrl.in) 输入卡自动生成
10
+ - 当未配置 API Key 时,内置离线化学专家规则引擎,保证任何时候提问都有真实科学响应与工具调用!
11
+ """
12
+ from __future__ import annotations
13
+
14
+ import json
15
+ import os
16
+ import urllib.request
17
+ import urllib.error
18
+ from dataclasses import dataclass, field
19
+ from typing import Any, Callable
20
+
21
+ from ...domain.document import MoleculeDocument
22
+ from ...domain.elements import get_element
23
+ from ..selection import SelectionService
24
+ from ..calculators.qc_input_generator import generate_gaussian_gjf, generate_rest_ctrl_in
25
+
26
+
27
+ DEEPSEEK_API_URL = "https://api.deepseek.com/v1/chat/completions"
28
+
29
+ SYSTEM_PROMPT = """你是 MolForge 内置的 AI 计算化学与有机光伏 (OSC) 科研助手。
30
+ 你精通:
31
+ 1. 有机太阳能电池给体/受体分子设计(如 PM6、D18、Y6、ITIC、BTP-eC9 等 A-D-A / D-A 体系的推拉电子效应、氟代/氯代/氰基修饰对 HOMO/LUMO 能级与结晶堆积的影响)。
32
+ 2. Gaussian 16 量子化学计算(基态 B3LYP-D3(BJ)/6-31G(d) 优化、wB97XD/def2SVP、CAM-B3LYP TD-DFT 激发态紫外吸收光谱、ESP 静电势分析)。
33
+ 3. 复旦大学张颖/徐昕教授团队开发的 REST (Rust-based Electronic Structure Toolkit) 程序输入卡 (`ctrl.in` TOML 格式,含 `[ctrl]` 和 `[geom]` 区块,支持 B3LYP/PBE0 及第五阶双杂化泛函 XYG3、XYGJOS、R-xDH7-SCC15、scsRPA)。
34
+ 4. VMD / PyMOL / Multiwfn 后处理脚本编写。
35
+
36
+ 请用简洁、专业、直接的科研同行口吻回答问题。如果用户请求修改当前分子或生成输入卡,你也可以在回复末尾附上一段 JSON 动作指令(用 ```molforge_action ... ``` 包裹),格式示例:
37
+ ```molforge_action
38
+ {"action": "add_ring", "size": 5, "aromatic": true, "hetero": {"0": 16}}
39
+ ```
40
+ 可用 action 包括:
41
+ - `{"action": "add_ring", "size": 6, "aromatic": true, "hetero": {}}` (如苯环、噻吩 `{"0": 16}`、吡啶 `{"0": 7}`)
42
+ - `{"action": "add_group", "group": "-CN" | "-F" | "-Cl" | "-OH" | "-COOH" | "-NH2" | "-OCH3"}`
43
+ - `{"action": "clean_3d"}`
44
+ - `{"action": "open_qc_dialog", "tab": "gaussian" | "rest" | "energy"}`
45
+ """
46
+
47
+
48
+ @dataclass
49
+ class AssistantResponse:
50
+ reply_text: str
51
+ executed_actions: list[str] = field(default_factory=list)
52
+ generated_code: str = ""
53
+ used_online_api: bool = False
54
+
55
+
56
+ class DeepSeekChemistryAssistant:
57
+ """
58
+ DeepSeek AI 化学助手(支持在线 DeepSeek-V3/R1 API 与离线本地科学引擎无缝切换)。
59
+ """
60
+
61
+ def __init__(
62
+ self,
63
+ api_key: str = "",
64
+ model: str = "deepseek-chat",
65
+ base_url: str = DEEPSEEK_API_URL,
66
+ ) -> None:
67
+ self.api_key = api_key or os.environ.get("DEEPSEEK_API_KEY", "")
68
+ self.model = model
69
+ self.base_url = base_url
70
+
71
+ def build_molecule_context(
72
+ self,
73
+ doc: MoleculeDocument | None,
74
+ selection: SelectionService | None = None,
75
+ ) -> str:
76
+ """提取当前分子的真实拓扑、元素组成与选中原子几何信息作为 Prompt 上下文。"""
77
+ if doc is None or doc.num_atoms == 0:
78
+ return "当前工作区为空分子。"
79
+
80
+ counts: dict[str, int] = {}
81
+ for aid in doc.topology.atom_ids:
82
+ z = doc.topology.get_atom(aid).atomic_num
83
+ el = get_element(z)
84
+ sym = el.symbol if el else f"Z{z}"
85
+ counts[sym] = counts.get(sym, 0) + 1
86
+ comp = " ".join(f"{k}:{v}" for k, v in sorted(counts.items()))
87
+
88
+ sel_info = "无选中原子"
89
+ if selection is not None and not selection.is_empty:
90
+ sel_aids = list(selection.selected_atoms)
91
+ sel_info = f"已选中 {len(sel_aids)} 个原子 {[a.value for a in sel_aids[:8]]}"
92
+
93
+ return (
94
+ f"当前分子名称:{doc.name}\n"
95
+ f"原子总数:{doc.num_atoms},化学键总数:{doc.num_bonds}\n"
96
+ f"元素组成:{comp}\n"
97
+ f"3D 坐标状态:{'已具备 3D 构象' if doc.has_3d else '仅 2D'}\n"
98
+ f"选择状态:{sel_info}"
99
+ )
100
+
101
+ def ask(
102
+ self,
103
+ question: str,
104
+ doc: MoleculeDocument | None,
105
+ selection: SelectionService | None = None,
106
+ action_executor: Callable[[dict[str, Any]], str | None] | None = None,
107
+ ) -> AssistantResponse:
108
+ """
109
+ 向助手提问:
110
+ - 若已配置 DeepSeek API Key,调用在线 DeepSeek 模型并解析返回的 molforge_action
111
+ - 若未配置 API Key 或网络受限,自动使用内置计算化学规则引擎执行指令并给出专业答复
112
+ """
113
+ q = question.strip()
114
+ if not q:
115
+ return AssistantResponse("请输入关于分子结构、官能团修饰、Gaussian 或 REST 计算的问题。")
116
+
117
+ context_str = self.build_molecule_context(doc, selection)
118
+
119
+ if self.api_key.strip():
120
+ try:
121
+ reply = self._call_deepseek_api(q, context_str)
122
+ actions_done = self._extract_and_run_actions(reply, action_executor)
123
+ clean_reply = self._strip_action_block(reply)
124
+ return AssistantResponse(
125
+ reply_text=clean_reply,
126
+ executed_actions=actions_done,
127
+ used_online_api=True,
128
+ )
129
+ except Exception as e:
130
+ fallback = self._local_chemistry_engine(q, doc, selection, action_executor)
131
+ fallback.reply_text = f"[DeepSeek API 调用提示: {e},已切换本地化学引擎响应]\n\n" + fallback.reply_text
132
+ return fallback
133
+
134
+ return self._local_chemistry_engine(q, doc, selection, action_executor)
135
+
136
+ def _call_deepseek_api(self, question: str, context_str: str) -> str:
137
+ payload = {
138
+ "model": self.model,
139
+ "messages": [
140
+ {"role": "system", "content": SYSTEM_PROMPT + "\n\n【当前工作区分子状态】\n" + context_str},
141
+ {"role": "user", "content": question},
142
+ ],
143
+ "temperature": 0.3,
144
+ "max_tokens": 1200,
145
+ }
146
+ data = json.dumps(payload).encode("utf-8")
147
+ url = self.base_url.strip()
148
+ if not url.endswith("/chat/completions"):
149
+ url = url.rstrip("/") + "/chat/completions"
150
+ headers = {
151
+ "Content-Type": "application/json",
152
+ }
153
+ if self.api_key.strip():
154
+ headers["Authorization"] = f"Bearer {self.api_key.strip()}"
155
+ req = urllib.request.Request(
156
+ url,
157
+ data=data,
158
+ headers=headers,
159
+ method="POST",
160
+ )
161
+ try:
162
+ with urllib.request.urlopen(req, timeout=30) as resp:
163
+ body = json.loads(resp.read().decode("utf-8"))
164
+ return body["choices"][0]["message"]["content"]
165
+ except urllib.error.HTTPError as exc:
166
+ err_body = exc.read().decode("utf-8", errors="ignore")
167
+ detail = ""
168
+ try:
169
+ err_json = json.loads(err_body)
170
+ detail = err_json.get("error", {}).get("readable_summary") or err_json.get("error", {}).get("message") or err_json.get("message") or str(exc)
171
+ except Exception:
172
+ detail = err_body[:240] if err_body else str(exc)
173
+ return f"❌ 接口请求失败 (HTTP {exc.code}):{detail}\n💡 建议:请点击「获取可用模型」下拉选择正确的可用模型(如 gemini-3.8-flash)。"
174
+
175
+ def _extract_and_run_actions(
176
+ self,
177
+ text: str,
178
+ action_executor: Callable[[dict[str, Any]], str | None] | None,
179
+ ) -> list[str]:
180
+ import re
181
+ if action_executor is None:
182
+ return []
183
+ executed = []
184
+ for m in re.finditer(r"```molforge_action\s*(\{.*?\})\s*```", text, flags=re.DOTALL):
185
+ try:
186
+ act = json.loads(m.group(1))
187
+ msg = action_executor(act)
188
+ if msg:
189
+ executed.append(msg)
190
+ except Exception:
191
+ pass
192
+ return executed
193
+
194
+ @staticmethod
195
+ def _strip_action_block(text: str) -> str:
196
+ import re
197
+ return re.sub(r"```molforge_action\s*\{.*?\}\s*```", "", text, flags=re.DOTALL).strip()
198
+
199
+ def _local_chemistry_engine(
200
+ self,
201
+ q: str,
202
+ doc: MoleculeDocument | None,
203
+ selection: SelectionService | None,
204
+ action_executor: Callable[[dict[str, Any]], str | None] | None,
205
+ ) -> AssistantResponse:
206
+ """离线计算化学与 OSC 专家引擎:识别结构编辑、REST/Gaussian 输入卡生成与能级分析指令。"""
207
+ ql = q.lower()
208
+ executed: list[str] = []
209
+
210
+ # 1. 识别 REST 输入卡请求
211
+ if "rest" in ql or "ctrl.in" in ql or "xyg3" in ql or "xygjos" in ql or "r-xdh7" in ql:
212
+ xc = "xyg3" if "xyg3" in ql else ("r-xdh7" if "xdh7" in ql else ("pbe0" if "pbe0" in ql else "b3lyp"))
213
+ basis = "def2-QZVPP" if xc in ("xyg3", "r-xdh7") else "def2-TZVPP"
214
+ job_type = "opt" if ("优化" in ql or "opt" in ql) else "energy"
215
+ ctrl_txt = generate_rest_ctrl_in(
216
+ doc or MoleculeDocument("OSC_Mol"),
217
+ xc=xc,
218
+ basis=basis,
219
+ job_type=job_type,
220
+ post_ai_correction=("scc15" if xc == "r-xdh7" else ""),
221
+ )
222
+ if action_executor:
223
+ msg = action_executor({"action": "preview_rest", "content": ctrl_txt})
224
+ if msg:
225
+ executed.append(msg)
226
+ reply = (
227
+ f"已为当前分子 **{doc.name if doc else '未命名'}** 生成符合复旦大学张颖/徐昕团队规范的 **REST (`ctrl.in`)** 输入卡(方法:`xc = \"{xc}\"`,基组:`{basis}`):\n\n"
228
+ f"```toml\n{ctrl_txt.strip()}\n```\n\n"
229
+ "提示:点击下方 **「准备 DFT / REST 计算」** 按钮可直接保存 `ctrl.in` 或切换 XYG3 / R-xDH7-SCC15 / scsRPA 等方法。"
230
+ )
231
+ return AssistantResponse(reply_text=reply, executed_actions=executed, generated_code=ctrl_txt)
232
+
233
+ # 2. 识别 Gaussian / TD-DFT / gjf 请求
234
+ if any(k in ql for k in ("gaussian", "gjf", "td-dft", "tddft", "激发态", "wb97xd", "cam-b3lyp", "b3lyp")):
235
+ if "td" in ql or "激发" in ql or "吸收" in ql or "cam" in ql:
236
+ route = "#p CAM-B3LYP/6-311+G(d,p) TD=(NStates=10) SCRF=(PCM,Solvent=Chloroform) pop=full"
237
+ elif "wb97" in ql:
238
+ route = "#p wB97XD/def2SVP opt pop=full"
239
+ else:
240
+ route = "#p B3LYP/6-31G(d) EmpiricalDispersion=GD3BJ opt freq"
241
+ gjf_txt = generate_gaussian_gjf(doc or MoleculeDocument("OSC_Mol"), route=route)
242
+ reply = (
243
+ f"已为 **{doc.name if doc else '当前分子'}** 生成 Gaussian 输入卡 (`.gjf`):\n\n"
244
+ f"```text\n{gjf_txt.strip()}\n```\n\n"
245
+ "在有机光伏 (OSC) 体系中,建议先用 `B3LYP-D3(BJ)/6-31G(d)` 完成基态构型优化,再用 `CAM-B3LYP` 或 `wB97XD` 配合氯仿 (`Chloroform`) 溶剂模型计算 TD-DFT 吸收光谱。"
246
+ )
247
+ return AssistantResponse(reply_text=reply, executed_actions=executed, generated_code=gjf_txt)
248
+
249
+ # 3. 识别结构编辑请求(加噻吩、苯环、吸电子基团 -F / -CN / -Cl 等)
250
+ if action_executor is not None:
251
+ if "噻吩" in ql or "thiophene" in ql:
252
+ msg = action_executor({"action": "add_ring", "size": 5, "aromatic": True, "hetero": {"0": 16}})
253
+ if msg:
254
+ executed.append(msg)
255
+ return AssistantResponse(
256
+ "已在当前结构中添加 **噻吩环 (Thiophene)** 并自动同步 3D 几何(可按 `Ctrl+Z` 撤销)。噻吩作为富电子共轭单元,常用于提升给体材料的共面性与载流子迁移率。",
257
+ executed_actions=executed,
258
+ )
259
+ if "苯" in ql or "benzene" in ql:
260
+ msg = action_executor({"action": "add_ring", "size": 6, "aromatic": True, "hetero": {}})
261
+ if msg:
262
+ executed.append(msg)
263
+ return AssistantResponse("已在当前结构中添加 **苯环** 并同步更新 2D/3D 视图。", executed_actions=executed)
264
+ for key, grp, desc in (
265
+ ("氰基", "-CN", "强吸电子氰基 (-CN),能显著下移 LUMO 能级并增强分子内电荷转移 (ICT)"),
266
+ ("-cn", "-CN", "强吸电子氰基 (-CN)"),
267
+ ("氟", "-F", "氟原子 (-F),通过诱导效应同时下移 HOMO/LUMO 并借助 F···S 非共价锁增强平面度"),
268
+ ("氯", "-Cl", "氯原子 (-Cl),比氟具有更强的空 d 轨道离域能力,适合微调开路电压 Voc"),
269
+ ("羧基", "-COOH", "羧基 (-COOH)"),
270
+ ("羟基", "-OH", "羟基 (-OH)"),
271
+ ("氨基", "-NH2", "给电子氨基 (-NH₂)"),
272
+ ):
273
+ if key in ql:
274
+ msg = action_executor({"action": "add_group", "group": grp})
275
+ if msg:
276
+ executed.append(msg)
277
+ return AssistantResponse(f"已向当前分子引入 **{desc}**,并同步更新了 3D 构象。", executed_actions=executed)
278
+ if "优化" in ql or "清理" in ql or "clean" in ql:
279
+ msg = action_executor({"action": "clean_3d"})
280
+ if msg:
281
+ executed.append(msg)
282
+ return AssistantResponse("已对当前分子执行 MMFF94/UFF 3D 力场几何弛豫。", executed_actions=executed)
283
+
284
+ # 4. 默认返回针对当前分子的 OSC 结构与电子性质专业分析
285
+ ctx = self.build_molecule_context(doc, selection)
286
+ reply = (
287
+ f"### 当前分子结构与 OSC 计算建议\n"
288
+ f"{ctx}\n\n"
289
+ "- **快速建模指令**:可直接输入“加一个噻吩环”、“引入氟原子”、“引入氰基 -CN”或“3D 结构优化”,我会直接调用 `CommandBus` 修改结构。\n"
290
+ "- **量化输入生成**:输入“生成 Gaussian TD-DFT 输入”或“生成 REST XYG3 输入卡”,即可一键生成 `.gjf` 或复旦 REST 的 `ctrl.in`。\n"
291
+ "- **接入在线 DeepSeek-V3/R1**:点击本面板右上角 **「配置 API Key」** 填入你的 DeepSeek Key,即可开启完整大模型自由问答。"
292
+ )
293
+ return AssistantResponse(reply_text=reply, executed_actions=executed)
@@ -0,0 +1,161 @@
1
+ """
2
+ application/ai/observation.py - AI 结构/几何/工件观察工具
3
+ ========================================================
4
+ 给 AI 提供一个**只读、限量、带单位、可判断过期**的观察窗口:
5
+ - observe_selection 已选 AtomID / BondID(含元素、坐标、键级)
6
+ - observe_conformer 当前构象/帧状态(不倾倒全部坐标)
7
+ - observe_artifacts 工件元数据(只给路径与类型,不自动传文件)
8
+
9
+ 每个结果都带:
10
+ units 单位(坐标 Å、能量 eV/Hartree、时间 ps)
11
+ stale 与观察时记录的 revision 比对,判断是否过期
12
+ data_complete 是否为真实数据(无数据时显式 False,绝不虚构)
13
+ """
14
+ from __future__ import annotations
15
+
16
+ from dataclasses import dataclass, field
17
+ from typing import Any, Callable
18
+
19
+ from ...domain.document import MoleculeDocument
20
+ from ..selection import SelectionService
21
+
22
+
23
+ @dataclass
24
+ class Observation:
25
+ kind: str
26
+ data: dict[str, Any]
27
+ units: dict[str, str]
28
+ observed_revision: int
29
+ data_complete: bool = True
30
+ note: str = ""
31
+
32
+ def is_stale(self, document: MoleculeDocument) -> bool:
33
+ """数据是否已过期(文档 revision 已变化)。"""
34
+ return document.revision != self.observed_revision
35
+
36
+
37
+ class ObservationTool:
38
+ """AI 只读观察工具。"""
39
+
40
+ # 一次观察最多返回的坐标数(限制数据量,防止上下文爆炸)
41
+ MAX_COORDS = 50
42
+
43
+ def __init__(
44
+ self,
45
+ document: MoleculeDocument,
46
+ selection: SelectionService | None = None,
47
+ artifact_provider: Callable[[], list[dict]] | None = None,
48
+ ) -> None:
49
+ self.document = document
50
+ self.selection = selection
51
+ self.artifact_provider = artifact_provider
52
+
53
+ @property
54
+ def _units(self) -> dict[str, str]:
55
+ return dict(self.document.units)
56
+
57
+ # ---------- 选择 ----------
58
+
59
+ def observe_selection(self) -> Observation:
60
+ if self.selection is None or self.selection.is_empty:
61
+ return Observation(
62
+ kind="selection", data={"selected_atoms": [], "selected_bonds": []},
63
+ units=self._units, observed_revision=self.document.revision,
64
+ data_complete=False, note="当前没有选中任何对象")
65
+
66
+ atoms = []
67
+ for aid in sorted(self.selection.selected_atoms):
68
+ atom = self.document.topology.get_atom(aid)
69
+ from ...domain.elements import get_element
70
+ symbol = get_element(atom.atomic_num).symbol
71
+ entry: dict[str, Any] = {"atom_id": aid, "element": symbol,
72
+ "formal_charge": atom.formal_charge}
73
+ coord = self._safe_coord(aid)
74
+ if coord is not None:
75
+ entry["coord_angstrom"] = coord
76
+ atoms.append(entry)
77
+
78
+ bonds = []
79
+ for bid in sorted(self.selection.selected_bonds):
80
+ bond = self.document.topology.get_bond(bid)
81
+ bonds.append({"bond_id": bid, "begin": bond.begin,
82
+ "end": bond.end, "order": bond.order})
83
+
84
+ return Observation(
85
+ kind="selection",
86
+ data={"selected_atoms": atoms, "selected_bonds": bonds,
87
+ "count": len(atoms) + len(bonds)},
88
+ units=self._units, observed_revision=self.document.revision,
89
+ note=(f"共 {len(atoms)} 个原子、{len(bonds)} 个键"
90
+ + ("(坐标已限量,仅显示选中项)" if len(atoms) > self.MAX_COORDS
91
+ else "")))
92
+
93
+ # ---------- 构象 ----------
94
+
95
+ def observe_conformer(self) -> Observation:
96
+ has_3d = self.document.has_3d
97
+ if not has_3d:
98
+ return Observation(
99
+ kind="conformer",
100
+ data={"has_3d": False, "num_frames": 0},
101
+ units=self._units, observed_revision=self.document.revision,
102
+ data_complete=False, note="当前分子没有 3D 构象/坐标")
103
+
104
+ store = self.document.coordinates
105
+ cur = store.current
106
+ # 只返回当前帧的少量坐标(限量),不倾倒全部
107
+ sample = []
108
+ if cur is not None:
109
+ n = min(len(cur.coords), self.MAX_COORDS)
110
+ for i in range(n):
111
+ sample.append([round(float(x), 4) for x in cur.coords[i]])
112
+ return Observation(
113
+ kind="conformer",
114
+ data={"has_3d": True, "num_frames": store.num_frames,
115
+ "current_frame": store.current_index,
116
+ "num_atoms": self.document.num_atoms,
117
+ "sample_coords_angstrom": sample,
118
+ "sample_truncated": len(cur.coords) > self.MAX_COORDS if cur else False},
119
+ units=self._units, observed_revision=self.document.revision,
120
+ note="坐标仅为当前帧前若干个样本,完整数据需用读取工具")
121
+
122
+ # ---------- 工件 ----------
123
+
124
+ def observe_artifacts(self) -> Observation:
125
+ if self.artifact_provider is None:
126
+ artifacts = []
127
+ note = "没有注册工件来源"
128
+ else:
129
+ artifacts = self.artifact_provider()
130
+ note = f"共 {len(artifacts)} 个工件"
131
+ # 只返回元数据(名称/类型/路径/大小),绝不自动读取或上传文件
132
+ safe = []
133
+ for a in artifacts:
134
+ safe.append({k: a.get(k) for k in
135
+ ("name", "type", "path", "size", "source") if k in a})
136
+ return Observation(
137
+ kind="artifacts", data={"artifacts": safe, "count": len(safe)},
138
+ units=self._units, observed_revision=self.document.revision,
139
+ data_complete=bool(safe), note=note)
140
+
141
+ # ---------- 工具 ----------
142
+
143
+ def _safe_coord(self, aid) -> list[float] | None:
144
+ """取原子当前坐标;无坐标或索引越界返回 None(不虚构)。"""
145
+ if not self.document.has_3d:
146
+ return None
147
+ try:
148
+ store = self.document.coordinates
149
+ cur = store.current
150
+ if cur is None:
151
+ return None
152
+ # 坐标按拓扑 atom_ids 顺序排列
153
+ ordered = list(self.document.topology.atom_ids)
154
+ if aid not in ordered:
155
+ return None
156
+ idx = ordered.index(aid)
157
+ if idx >= len(cur.coords):
158
+ return None
159
+ return [round(float(x), 4) for x in cur.coords[idx]]
160
+ except Exception:
161
+ return None
@@ -0,0 +1,200 @@
1
+ """
2
+ application/ai/tools.py - AI Tool Registry
3
+ ==========================================
4
+ LLM 只能调用注册表里的工具,不能执行任意 Python:
5
+ - 权限分级 Read / View / Edit / Execute / Export
6
+ - 每个工具带输入 JSON Schema,调用前强制校验(内置轻量校验器,无外部依赖)
7
+ - 调用次数 / 计算预算限制
8
+ - Edit/Execute/Export 必须显式批准,否则拒绝(不产生副作用)
9
+ - 每次调用生成带追溯信息的收据并落日志
10
+ - 无 shell / eval
11
+ """
12
+ from __future__ import annotations
13
+
14
+ import time
15
+ import uuid
16
+ from dataclasses import dataclass, field
17
+ from enum import Enum
18
+ from typing import Any, Callable
19
+
20
+ from .observation import ObservationTool
21
+
22
+
23
+ class ToolPermission(Enum):
24
+ READ = "read"
25
+ VIEW = "view"
26
+ EDIT = "edit"
27
+ EXECUTE = "execute"
28
+ EXPORT = "export"
29
+
30
+
31
+ # 需要批准的权限级别
32
+ _NEEDS_APPROVAL = {ToolPermission.EDIT, ToolPermission.EXECUTE,
33
+ ToolPermission.EXPORT}
34
+
35
+
36
+ @dataclass
37
+ class ToolReceipt:
38
+ receipt_id: str
39
+ tool_name: str
40
+ arguments: dict[str, Any]
41
+ permission: str
42
+ success: bool
43
+ approved: bool
44
+ result: Any = None
45
+ error: str = ""
46
+ started_at: float = 0.0
47
+ finished_at: float = 0.0
48
+ duration_ms: float = 0.0
49
+
50
+ def trace(self) -> dict:
51
+ """可追溯信息。"""
52
+ return {
53
+ "receipt_id": self.receipt_id, "tool": self.tool_name,
54
+ "permission": self.permission, "success": self.success,
55
+ "approved": self.approved, "error": self.error,
56
+ "duration_ms": round(self.duration_ms, 2),
57
+ "started_at": self.started_at,
58
+ }
59
+
60
+
61
+ # ---------- 轻量 JSON Schema 校验 ----------
62
+
63
+ _TYPE_MAP = {
64
+ "string": str, "integer": int, "number": (int, float),
65
+ "boolean": bool, "object": dict, "array": list,
66
+ }
67
+
68
+
69
+ def validate_schema(value: Any, schema: dict, path: str = "$") -> list[str]:
70
+ """返回错误列表(空表示通过)。支持 type/required/enum/properties/range。"""
71
+ errs: list[str] = []
72
+ if "enum" in schema and value not in schema["enum"]:
73
+ errs.append(f"{path}: 值 {value!r} 不在允许范围 {schema['enum']}")
74
+
75
+ t = schema.get("type")
76
+ if t:
77
+ py = _TYPE_MAP.get(t)
78
+ ok = isinstance(value, py) if py else True
79
+ if t == "integer" and isinstance(value, bool):
80
+ ok = False
81
+ if not ok:
82
+ errs.append(f"{path}: 期望 {t},得到 {type(value).__name__}")
83
+ return errs
84
+
85
+ if t == "object":
86
+ for r in schema.get("required", []):
87
+ if r not in value:
88
+ errs.append(f"{path}: 缺少必填字段 '{r}'")
89
+ for k, sub in schema.get("properties", {}).items():
90
+ if k in value:
91
+ errs.extend(validate_schema(value[k], sub, f"{path}.{k}"))
92
+
93
+ if t in ("integer", "number"):
94
+ if "minimum" in schema and value < schema["minimum"]:
95
+ errs.append(f"{path}: {value} 小于最小值 {schema['minimum']}")
96
+ if "maximum" in schema and value > schema["maximum"]:
97
+ errs.append(f"{path}: {value} 大于最大值 {schema['maximum']}")
98
+
99
+ if t == "array" and "items" in schema:
100
+ for i, item in enumerate(value):
101
+ errs.extend(validate_schema(item, schema["items"], f"{path}[{i}]"))
102
+ return errs
103
+
104
+
105
+ # ---------- Registry ----------
106
+
107
+ class ToolRegistry:
108
+ def __init__(self, max_calls: int = 50, budget_seconds: float = 300.0) -> None:
109
+ self._tools: dict[str, dict] = {}
110
+ self._log: list[ToolReceipt] = []
111
+ self._call_count = 0
112
+ self.max_calls = max_calls
113
+ self.budget_seconds = budget_seconds
114
+ self._used_seconds = 0.0
115
+
116
+ def register(self, name: str, description: str, schema: dict,
117
+ handler: Callable[..., Any],
118
+ permission: ToolPermission = ToolPermission.READ,
119
+ cost_seconds: float = 0.0) -> None:
120
+ self._tools[name] = {
121
+ "name": name, "description": description, "schema": schema,
122
+ "handler": handler, "permission": permission,
123
+ "cost_seconds": cost_seconds}
124
+
125
+ def definitions(self) -> list[dict]:
126
+ """OpenAI function calling 格式。"""
127
+ return [
128
+ {"type": "function", "function": {
129
+ "name": t["name"], "description": t["description"],
130
+ "parameters": t["schema"]}}
131
+ for t in self._tools.values()]
132
+
133
+ def needs_approval(self, name: str) -> bool:
134
+ return self._tools[name]["permission"] in _NEEDS_APPROVAL
135
+
136
+ def call(self, name: str, arguments: dict[str, Any],
137
+ approved: bool = False) -> ToolReceipt:
138
+ rid = uuid.uuid4().hex[:12]
139
+ start = time.time()
140
+
141
+ def fail(msg):
142
+ r = ToolReceipt(
143
+ rid, name, arguments,
144
+ self._tools.get(name, {}).get("permission",
145
+ ToolPermission.READ).value if name in self._tools else "?",
146
+ False, approved, error=msg, started_at=start,
147
+ finished_at=time.time())
148
+ self._log.append(r)
149
+ return r
150
+
151
+ # 未知工具
152
+ if name not in self._tools:
153
+ return fail(f"未知工具: {name}")
154
+ tool = self._tools[name]
155
+
156
+ # 调用次数
157
+ if self._call_count >= self.max_calls:
158
+ return fail(f"超过调用次数限制({self.max_calls})")
159
+
160
+ # 预算
161
+ if self._used_seconds + tool["cost_seconds"] > self.budget_seconds:
162
+ return fail(
163
+ f"计算预算不足(已用 {self._used_seconds:.1f}s / "
164
+ f"上限 {self.budget_seconds:.1f}s)")
165
+
166
+ # 参数校验
167
+ if not isinstance(arguments, dict):
168
+ return fail("参数必须是对象")
169
+ verrs = validate_schema(arguments, tool["schema"])
170
+ if verrs:
171
+ return fail("参数非法: " + "; ".join(verrs))
172
+
173
+ # 批准门:未批准的副作用操作直接拒绝
174
+ if self.needs_approval(name) and not approved:
175
+ return fail(f"工具 {name} 属于 {tool['permission'].value} 级,"
176
+ "未获批准,已拒绝执行")
177
+
178
+ # 执行
179
+ self._call_count += 1
180
+ try:
181
+ result = tool["handler"](**arguments)
182
+ ok, err = True, ""
183
+ except Exception as e:
184
+ result, ok, err = None, False, str(e)
185
+ end = time.time()
186
+ self._used_seconds += tool["cost_seconds"]
187
+
188
+ receipt = ToolReceipt(
189
+ rid, name, arguments, tool["permission"].value, ok, approved,
190
+ result=result, error=err, started_at=start, finished_at=end,
191
+ duration_ms=(end - start) * 1000)
192
+ self._log.append(receipt)
193
+ return receipt
194
+
195
+ def log(self) -> list[ToolReceipt]:
196
+ return list(self._log)
197
+
198
+ @property
199
+ def used_seconds(self) -> float:
200
+ return self._used_seconds