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,945 @@
1
+ """
2
+ mcp_bridge.py - MolForge 大语言模型桥接(OpenAI 兼容端点 + 真实 function calling)
3
+ =================================================================================
4
+ 让外部 LLM(任意 OpenAI 兼容端点:本地 vLLM/Ollama/DeepSeek/OpenAI 等)能:
5
+ 1. 读取当前画布分子(原子/键/元素/坐标/公式)
6
+ 2. 通过命令总线真实编辑结构(加/删原子、加/删键、修改内坐标,可撤销)
7
+ 3. 调用本地分析与量子化学工具(平面性、CalChem SCF/Opt、超算 Slurm 脚本生成)
8
+
9
+ 不引入 openai 第三方依赖,直接用标准库 urllib 调 /chat/completions;
10
+ 所有结构修改必须经 CommandBus(带撤销),LLM 不能直接写文档。
11
+ 配置从 QSettings("MolForge", "LLM") 读取:base_url / api_key / model。
12
+ """
13
+ from __future__ import annotations
14
+
15
+ import json
16
+ import urllib.request
17
+ import urllib.error
18
+ from typing import Any, Optional
19
+
20
+ try:
21
+ from PyQt6.QtCore import QSettings
22
+ except ImportError:
23
+ QSettings = None
24
+
25
+ from ..application.builtin_commands import AddAtomCommand, DeleteAtomCommand, AddBondCommand
26
+
27
+
28
+ from pathlib import Path
29
+
30
+
31
+ def _config_file() -> Path:
32
+ try:
33
+ from ..runtime import data_dir
34
+ d = data_dir() / "settings"
35
+ except Exception:
36
+ d = Path(__file__).resolve().parents[2] / "user_data" / "settings"
37
+ d.mkdir(parents=True, exist_ok=True)
38
+ return d / "llm_config.json"
39
+
40
+
41
+ def _settings() -> Optional[Any]:
42
+ if QSettings is None:
43
+ return None
44
+ try:
45
+ from ..runtime import configure_runtime
46
+ configure_runtime()
47
+ return QSettings("MolForge", "LLM")
48
+ except Exception:
49
+ return None
50
+
51
+
52
+ _CONFIG_CACHE: dict[str, Any] = {}
53
+
54
+
55
+ def fetch_remote_models(base_url: str, api_key: str) -> list[str]:
56
+ """通过 OpenAI 兼容的 /models 端点拉取服务器当前所有可用模型。"""
57
+ url = str(base_url).strip().rstrip("/")
58
+ if not url.endswith("/v1"):
59
+ if not url.endswith("/models"):
60
+ models_url = url + "/v1/models"
61
+ else:
62
+ models_url = url
63
+ else:
64
+ models_url = url + "/models"
65
+ headers = {}
66
+ if api_key and api_key != "EMPTY":
67
+ headers["Authorization"] = f"Bearer {api_key.strip()}"
68
+ req = urllib.request.Request(models_url, headers=headers)
69
+ with urllib.request.urlopen(req, timeout=6) as resp:
70
+ data = json.loads(resp.read().decode("utf-8"))
71
+ models = [m["id"] for m in data.get("data", []) if isinstance(m, dict) and "id" in m]
72
+ return models
73
+
74
+
75
+ def get_llm_config() -> dict[str, Any]:
76
+ global _CONFIG_CACHE
77
+ if _CONFIG_CACHE:
78
+ return dict(_CONFIG_CACHE)
79
+ """读取全局统一的大模型配置(打通右侧面板 AI_Config、独立弹窗 LLM 与 JSON 持久化存储,彻底杜绝割裂二次配置)。"""
80
+ base_url = "http://127.0.0.1:8045/v1"
81
+ api_key = ""
82
+ model = "gemini-3.8-flash"
83
+ temperature = 0.3
84
+ max_tokens = 4096
85
+ reasoning_effort = "none"
86
+
87
+
88
+ # 1. 优先读取磁盘配置文件 (Single Source of Truth)
89
+ cfg_file = _config_file()
90
+ if cfg_file.exists():
91
+ try:
92
+ with open(cfg_file, "r", encoding="utf-8") as f:
93
+ disk_data = json.load(f)
94
+ if isinstance(disk_data, dict):
95
+ if disk_data.get("base_url"):
96
+ base_url = str(disk_data["base_url"]).strip()
97
+ if disk_data.get("api_key"):
98
+ api_key = str(disk_data["api_key"]).strip()
99
+ if disk_data.get("model"):
100
+ m_str = str(disk_data["model"]).strip()
101
+ if m_str and m_str not in ("default-model", "antigravity"):
102
+ model = m_str
103
+ else:
104
+ model = "gemini-3.8-flash"
105
+ if "temperature" in disk_data:
106
+ temperature = float(disk_data["temperature"])
107
+ if "max_tokens" in disk_data:
108
+ max_tokens = int(disk_data["max_tokens"])
109
+ if "reasoning_effort" in disk_data:
110
+ reasoning_effort = str(disk_data["reasoning_effort"])
111
+ return {
112
+ "base_url": base_url or "http://127.0.0.1:8045/v1",
113
+ "api_key": api_key if api_key else "EMPTY",
114
+ "model": model or "gemini-3.8-flash",
115
+ "temperature": temperature,
116
+ "max_tokens": max_tokens,
117
+ "reasoning_effort": reasoning_effort,
118
+ }
119
+ except Exception:
120
+ pass
121
+
122
+ # 2. 读取 QSettings("MolForge", "LLM")
123
+ s_llm = _settings()
124
+ if s_llm is not None:
125
+ try:
126
+ v_url = s_llm.value("base_url", "", str)
127
+ v_key = s_llm.value("api_key", "", str)
128
+ v_model = s_llm.value("model", "", str)
129
+ if v_url: base_url = v_url.strip()
130
+ if v_key: api_key = v_key.strip()
131
+ if v_model:
132
+ v_model = v_model.strip()
133
+ if v_model and v_model not in ("default-model", "antigravity"):
134
+ model = v_model
135
+ else:
136
+ model = "gemini-3.8-flash"
137
+ v_temp = s_llm.value("temperature", None)
138
+ if v_temp is not None: temperature = float(v_temp)
139
+ v_mt = s_llm.value("max_tokens", None)
140
+ if v_mt is not None: max_tokens = int(v_mt)
141
+ v_re = s_llm.value("reasoning_effort", "", str)
142
+ if v_re: reasoning_effort = v_re
143
+ except Exception:
144
+ pass
145
+
146
+ # 3. 读取 QSettings("MolForge", "AI_Config")
147
+ if QSettings is not None:
148
+ try:
149
+ s_ai = QSettings("MolForge", "AI_Config")
150
+ ai_url = s_ai.value("llm_base_url", "", str)
151
+ ai_key = s_ai.value("deepseek_api_key", "", str)
152
+ ai_model = s_ai.value("llm_model_name", "", str)
153
+ if ai_url: base_url = ai_url.strip()
154
+ if ai_key: api_key = ai_key.strip()
155
+ if ai_model:
156
+ ai_model = ai_model.strip()
157
+ if ai_model and ai_model not in ("default-model", "antigravity"):
158
+ model = ai_model
159
+ else:
160
+ model = "gemini-3.8-flash"
161
+ except Exception:
162
+ pass
163
+
164
+ return {
165
+ "base_url": base_url or "http://127.0.0.1:8045/v1",
166
+ "api_key": api_key or "EMPTY",
167
+ "model": model or "gemini-3.8-flash",
168
+ "temperature": temperature,
169
+ "max_tokens": max_tokens,
170
+ "reasoning_effort": reasoning_effort,
171
+ }
172
+
173
+
174
+
175
+ def set_llm_config(
176
+ base_url: str,
177
+ api_key: str,
178
+ model: str,
179
+ temperature: float = 0.3,
180
+ max_tokens: int = 4096,
181
+ reasoning_effort: str = "none",
182
+ ) -> None:
183
+ global _CONFIG_CACHE
184
+ base_url = str(base_url).strip() or "http://127.0.0.1:8045/v1"
185
+ key_str = str(api_key).strip()
186
+ api_key = key_str if key_str else "EMPTY"
187
+ m_val = str(model).strip()
188
+ if not m_val or m_val in ("default-model", "antigravity"):
189
+ model = "gemini-3.8-flash"
190
+ else:
191
+ model = m_val
192
+ temperature = float(temperature)
193
+ max_tokens = int(max_tokens)
194
+ reasoning_effort = str(reasoning_effort)
195
+
196
+ _CONFIG_CACHE = {
197
+ "base_url": base_url,
198
+ "api_key": api_key,
199
+ "model": model,
200
+ "temperature": temperature,
201
+ "max_tokens": max_tokens,
202
+ "reasoning_effort": reasoning_effort,
203
+ }
204
+ """持久化保存大模型配置,同步写入 MolForge/LLM、MolForge/AI_Config 与本地 JSON 文件,保持 100% 同步。"""
205
+ # 1. 写入磁盘 JSON 文件 (单点真理)
206
+ try:
207
+ cfg_file = _config_file()
208
+ with open(cfg_file, "w", encoding="utf-8") as f:
209
+ json.dump({
210
+ "base_url": base_url,
211
+ "api_key": api_key,
212
+ "model": model,
213
+ "temperature": temperature,
214
+ "max_tokens": max_tokens,
215
+ "reasoning_effort": reasoning_effort,
216
+ }, f, indent=2, ensure_ascii=False)
217
+ except Exception:
218
+ pass
219
+
220
+ # 2. 写入 QSettings("MolForge", "LLM")
221
+ s_llm = _settings()
222
+ if s_llm is not None:
223
+ try:
224
+ s_llm.setValue("base_url", base_url)
225
+ s_llm.setValue("api_key", api_key)
226
+ s_llm.setValue("model", model)
227
+ s_llm.setValue("temperature", temperature)
228
+ s_llm.setValue("max_tokens", max_tokens)
229
+ s_llm.setValue("reasoning_effort", reasoning_effort)
230
+ s_llm.sync()
231
+ except Exception:
232
+ pass
233
+
234
+ # 3. 写入 QSettings("MolForge", "AI_Config")
235
+ if QSettings is not None:
236
+ try:
237
+ s_ai = QSettings("MolForge", "AI_Config")
238
+ s_ai.setValue("llm_base_url", base_url)
239
+ s_ai.setValue("deepseek_api_key", api_key)
240
+ s_ai.setValue("llm_model_name", model)
241
+ s_ai.setValue("temperature", temperature)
242
+ s_ai.setValue("max_tokens", max_tokens)
243
+ s_ai.setValue("reasoning_effort", reasoning_effort)
244
+ s_ai.sync()
245
+ except Exception:
246
+ pass
247
+
248
+
249
+ class MolForgeMCPBridge:
250
+ """把当前 MoleculeDocument + CommandBus 暴露给 LLM 的 function-calling 桥。"""
251
+
252
+ def __init__(self, document=None, command_bus=None):
253
+ self.document = document
254
+ self.command_bus = command_bus
255
+ self.history: list[dict] = []
256
+ self.config = get_llm_config()
257
+
258
+ # ---------- 工具定义(OpenAI function calling 格式) ----------
259
+ def tool_definitions(self) -> list[dict]:
260
+ return [
261
+ {
262
+ "type": "function",
263
+ "function": {
264
+ "name": "describe_structure",
265
+ "description": "返回当前画布分子的摘要:名称、公式、原子数、键数、元素统计、是否有3D坐标。",
266
+ "parameters": {"type": "object", "properties": {}},
267
+ },
268
+ },
269
+ {
270
+ "type": "function",
271
+ "function": {
272
+ "name": "list_atoms",
273
+ "description": "列出当前分子所有原子(视口稳定编号(AtomId+1,删除后可能不连续)、元素符号、3D 坐标)。",
274
+ "parameters": {"type": "object", "properties": {}},
275
+ },
276
+ },
277
+ {
278
+ "type": "function",
279
+ "function": {
280
+ "name": "add_atom",
281
+ "description": "在指定已有原子附近添加一个新原子(元素由 atomic_num 指定)。需要命令总线。",
282
+ "parameters": {
283
+ "type": "object",
284
+ "properties": {
285
+ "near_atom": {"type": "integer", "description": "参考原子的视口稳定编号(AtomId+1,删除后可能不连续)", "minimum": 1},
286
+ "atomic_num": {"type": "integer", "description": "新原子的原子序数,如 6=C, 7=N, 8=O, 1=H", "minimum": 1},
287
+ },
288
+ "required": ["near_atom", "atomic_num"],
289
+ },
290
+ },
291
+ },
292
+ {
293
+ "type": "function",
294
+ "function": {
295
+ "name": "delete_atom",
296
+ "description": "删除指定视口稳定编号(AtomId+1,删除后可能不连续)的原子(连带其键)。需要命令总线。",
297
+ "parameters": {
298
+ "type": "object",
299
+ "properties": {
300
+ "atom_index": {"type": "integer", "description": "要删除原子的视口稳定编号(AtomId+1,删除后可能不连续)", "minimum": 1},
301
+ },
302
+ "required": ["atom_index"],
303
+ },
304
+ },
305
+ },
306
+ {
307
+ "type": "function",
308
+ "function": {
309
+ "name": "add_bond",
310
+ "description": "在两个视口稳定编号(AtomId+1,删除后可能不连续)的原子之间添加单键。需要命令总线。",
311
+ "parameters": {
312
+ "type": "object",
313
+ "properties": {
314
+ "atom_a": {"type": "integer", "description": "第一个原子视口稳定编号(AtomId+1,删除后可能不连续)", "minimum": 1},
315
+ "atom_b": {"type": "integer", "description": "第二个原子视口稳定编号(AtomId+1,删除后可能不连续)", "minimum": 1},
316
+ },
317
+ "required": ["atom_a", "atom_b"],
318
+ },
319
+ },
320
+ },
321
+ {
322
+ "type": "function",
323
+ "function": {
324
+ "name": "modify_internal_coordinate",
325
+ "description": "精确修改分子的内坐标(键长/键角/二面角),自动联动旋转连通子图刚体几何,保持其他键长不变(可撤销)。",
326
+ "parameters": {
327
+ "type": "object",
328
+ "properties": {
329
+ "coord_type": {
330
+ "type": "string",
331
+ "enum": ["bond_length", "bond_angle", "dihedral"],
332
+ "description": "内坐标类型",
333
+ },
334
+ "atoms": {
335
+ "type": "array",
336
+ "items": {"type": "integer"},
337
+ "description": "原子编号列表 (1-based序号)。键长需2个,键角需3个(中间为顶点),二面角需4个。",
338
+ },
339
+ "target_value": {
340
+ "type": "number",
341
+ "description": "目标数值(键长单位为 Å,键角/二面角单位为度 °)",
342
+ },
343
+ },
344
+ "required": ["coord_type", "atoms", "target_value"],
345
+ },
346
+ },
347
+ },
348
+ {
349
+ "type": "function",
350
+ "function": {
351
+ "name": "run_calchem_scf",
352
+ "description": "调用 CalChem 纯 Rust 内核秒级执行从头算 RHF 自洽场计算,获取精确总能量、HOMO/LUMO 能级、能隙与偶极矩。",
353
+ "parameters": {
354
+ "type": "object",
355
+ "properties": {
356
+ "basis": {
357
+ "type": "string",
358
+ "enum": ["sto-3g", "6-31g", "6-31g(d)", "6-31g(d,p)", "lanl2dz"],
359
+ "description": "量化计算基组",
360
+ },
361
+ },
362
+ },
363
+ },
364
+ },
365
+ {
366
+ "type": "function",
367
+ "function": {
368
+ "name": "run_calchem_opt",
369
+ "description": "调用 CalChem 纯 Rust BFGS 算法执行高精度 3D 几何构象优化,并自动通过命令总线回填更新视口(支持可撤销)。",
370
+ "parameters": {
371
+ "type": "object",
372
+ "properties": {
373
+ "basis": {"type": "string", "description": "量化计算基组"},
374
+ "max_steps": {"type": "integer", "description": "最大优化步数", "minimum": 1},
375
+ },
376
+ },
377
+ },
378
+ },
379
+ {
380
+ "type": "function",
381
+ "function": {
382
+ "name": "generate_hpc_slurm_script",
383
+ "description": "为当前分子生成可直接提交至远程 Linux 超算集群运行的 Slurm 批处理计算脚本 (Gaussian/ORCA/GROMACS/CalChem)。",
384
+ "parameters": {
385
+ "type": "object",
386
+ "properties": {
387
+ "engine": {"type": "string", "enum": ["g16", "orca", "gromacs", "xtb", "calchem"], "description": "计算软件"},
388
+ "job_name": {"type": "string", "description": "作业名称"},
389
+ "n_cores": {"type": "integer", "description": "CPU核心数", "minimum": 1},
390
+ "memory_mb": {"type": "integer", "description": "内存限额 (MB)", "minimum": 100},
391
+ "walltime": {"type": "string", "description": "运行时长限制"},
392
+ },
393
+ "required": ["engine"],
394
+ },
395
+ },
396
+ },
397
+ {
398
+ "type": "function",
399
+ "function": {
400
+ "name": "run_planarity",
401
+ "description": "对当前分子计算重原子最佳拟合平面的平面度 RMSD(MPP)。",
402
+ "parameters": {"type": "object", "properties": {}},
403
+ },
404
+ },
405
+ {
406
+ "type": "function",
407
+ "function": {
408
+ "name": "run_rest_scf",
409
+ "description": "在 WSL2 环境中调用复旦大学 REST (Rust-based Electronic Structure Toolkit) 原生执行真实 DFT/双杂化 SCF 计算,获取总能量、Mulliken 电荷与轨道能隙。",
410
+ "parameters": {
411
+ "type": "object",
412
+ "properties": {
413
+ "xc": {
414
+ "type": "string",
415
+ "enum": ["b3lyp", "hf", "pbe0", "wb97xd", "cam-b3lyp", "xyg3", "xygjos", "r-xdh7"],
416
+ "description": "交换相关泛函或双杂化方法",
417
+ },
418
+ "basis": {
419
+ "type": "string",
420
+ "enum": ["STO-3G", "def2-SVP", "def2-TZVP", "6-31G*", "cc-pVDZ"],
421
+ "description": "基组名称",
422
+ },
423
+ },
424
+ },
425
+ },
426
+ },
427
+ {
428
+ "type": "function",
429
+ "function": {
430
+ "name": "build_from_smiles",
431
+ "description": "根据 SMILES 字符串一键生成带 3D 构象的分子或片段并追加到当前画布(支持撤销)。",
432
+ "parameters": {
433
+ "type": "object",
434
+ "properties": {
435
+ "smiles": {"type": "string", "description": "有效 SMILES,如 c1ccccc1、CC(=O)O、O"},
436
+ "name": {"type": "string", "description": "可选分子名称"},
437
+ },
438
+ "required": ["smiles"],
439
+ },
440
+ },
441
+ },
442
+ {
443
+ "type": "function",
444
+ "function": {
445
+ "name": "add_ring",
446
+ "description": "在画布中添加环系(如苯环、环己烷),可选接枝到已有原子(支持撤销)。",
447
+ "parameters": {
448
+ "type": "object",
449
+ "properties": {
450
+ "size": {"type": "integer", "minimum": 3, "maximum": 12},
451
+ "aromatic": {"type": "boolean"},
452
+ "attach_to": {"type": "integer", "minimum": 1},
453
+ },
454
+ },
455
+ },
456
+ },
457
+ {
458
+ "type": "function",
459
+ "function": {
460
+ "name": "change_element",
461
+ "description": "将指定原子替换为新元素(如将 C 替换为 N/O/S/F 等,支持撤销)。",
462
+ "parameters": {
463
+ "type": "object",
464
+ "properties": {
465
+ "atom_index": {"type": "integer", "minimum": 1},
466
+ "new_atomic_num": {"type": "integer", "minimum": 1, "maximum": 118},
467
+ },
468
+ "required": ["atom_index", "new_atomic_num"],
469
+ },
470
+ },
471
+ },
472
+ {
473
+ "type": "function",
474
+ "function": {
475
+ "name": "change_bond_order",
476
+ "description": "修改两个原子之间的键级(1=单键, 2=双键, 3=三键, 4=芳香键),若尚未成键则新建(支持撤销)。",
477
+ "parameters": {
478
+ "type": "object",
479
+ "properties": {
480
+ "atom_a": {"type": "integer", "minimum": 1},
481
+ "atom_b": {"type": "integer", "minimum": 1},
482
+ "order": {"type": "integer", "enum": [1, 2, 3, 4]},
483
+ },
484
+ "required": ["atom_a", "atom_b", "order"],
485
+ },
486
+ },
487
+ },
488
+ {
489
+ "type": "function",
490
+ "function": {
491
+ "name": "clean_geometry_3d",
492
+ "description": "执行 3D 分子力场几何弛豫优化 (MMFF94/UFF)(支持撤销)。",
493
+ "parameters": {"type": "object", "properties": {}},
494
+ },
495
+ },
496
+ {
497
+ "type": "function",
498
+ "function": {
499
+ "name": "set_atom_charge",
500
+ "description": "设置指定原子的形式电荷(支持撤销)。",
501
+ "parameters": {
502
+ "type": "object",
503
+ "properties": {
504
+ "atom_index": {"type": "integer", "minimum": 1},
505
+ "formal_charge": {"type": "integer", "minimum": -4, "maximum": 4},
506
+ },
507
+ "required": ["atom_index", "formal_charge"],
508
+ },
509
+ },
510
+ },
511
+ {
512
+ "type": "function",
513
+ "function": {
514
+ "name": "undo_last",
515
+ "description": "撤销上一步分子编辑操作。",
516
+ "parameters": {"type": "object", "properties": {}},
517
+ },
518
+ },
519
+ {
520
+ "type": "function",
521
+ "function": {
522
+ "name": "redo_last",
523
+ "description": "重做上一步被撤销的分子编辑操作。",
524
+ "parameters": {"type": "object", "properties": {}},
525
+ },
526
+ },
527
+ ]
528
+
529
+ # ---------- 工具实现 ----------
530
+ def _elem_symbol(self, z: int) -> str:
531
+ from ..domain.elements import get_element
532
+ el = get_element(z)
533
+ return el.symbol if el else "C"
534
+
535
+ def _aid_at_1based(self, idx: int):
536
+ if not self.document:
537
+ return None
538
+ atoms = list(self.document.topology.atom_ids)
539
+ return next((aid for aid in atoms if aid.value + 1 == idx), None)
540
+
541
+ def _tool_describe(self) -> dict:
542
+ d = self.document
543
+ from collections import Counter
544
+ cnt = Counter(self.document.topology.get_atom(a).atomic_num for a in d.topology.atom_ids)
545
+ elems = {self._elem_symbol(z): c for z, c in cnt.items()}
546
+ return {
547
+ "name": d.name,
548
+ "num_atoms": d.num_atoms,
549
+ "num_bonds": d.topology.num_bonds,
550
+ "elements": elems,
551
+ "has_3d": bool(d.has_3d and d.coordinates.current is not None),
552
+ }
553
+
554
+ def _tool_list_atoms(self) -> dict:
555
+ d = self.document
556
+ rows = []
557
+ coords = d.coordinates.current.coords if (d.has_3d and d.coordinates.current is not None) else None
558
+ for i, aid in enumerate(d.topology.atom_ids, start=1):
559
+ z = d.topology.get_atom(aid).atomic_num
560
+ c = coords[i - 1].tolist() if coords is not None and i - 1 < len(coords) else None
561
+ rows.append({"index": aid.value + 1, "element": self._elem_symbol(z), "coord_3d": c})
562
+ return {"atoms": rows}
563
+
564
+ def _tool_add_atom(self, near_atom: int, atomic_num: int) -> dict:
565
+ aid = self._aid_at_1based(near_atom)
566
+ if aid is None or self.command_bus is None:
567
+ return {"ok": False, "error": "参考原子越界或未连接命令总线"}
568
+ res = self.command_bus.execute(AddAtomCommand(atomic_num=atomic_num, bond_to=aid))
569
+ return {"ok": getattr(res, "success", True), "message": getattr(res, "message", ""), "num_atoms": self.document.num_atoms}
570
+
571
+ def _tool_delete_atom(self, atom_index: int) -> dict:
572
+ aid = self._aid_at_1based(atom_index)
573
+ if aid is None or self.command_bus is None:
574
+ return {"ok": False, "error": "原子越界或未连接命令总线"}
575
+ res = self.command_bus.execute(DeleteAtomCommand(aid))
576
+ return {"ok": getattr(res, "success", True), "message": getattr(res, "message", ""), "num_atoms": self.document.num_atoms}
577
+
578
+ def _tool_add_bond(self, atom_a: int, atom_b: int) -> dict:
579
+ a, b = self._aid_at_1based(atom_a), self._aid_at_1based(atom_b)
580
+ if a is None or b is None or self.command_bus is None:
581
+ return {"ok": False, "error": "原子越界或未连接命令总线"}
582
+ res = self.command_bus.execute(AddBondCommand(a, b, order=1))
583
+ return {"ok": getattr(res, "success", True), "message": getattr(res, "message", ""), "num_bonds": self.document.topology.num_bonds}
584
+
585
+ def _tool_modify_internal_coordinate(self, coord_type: str, atoms: list[int], target_value: float) -> dict:
586
+ if self.document is None:
587
+ return {"ok": False, "error": "没有打开的分子"}
588
+ from ..domain.ids import AtomId
589
+ val = float(target_value)
590
+ atom_ids = [self._aid_at_1based(x) for x in atoms]
591
+ if any(a is None for a in atom_ids):
592
+ return {"ok": False, "error": f"指定的原子序号越界: {atoms}"}
593
+
594
+ if coord_type == "bond_length" and len(atom_ids) == 2:
595
+ from ..application.builtin_commands import ModifyBondLength3DCommand
596
+ bid = self.document.topology.bond_between(atom_ids[0], atom_ids[1])
597
+ if bid is None:
598
+ return {"ok": False, "error": f"原子 #{atoms[0]} 与 #{atoms[1]} 之间不存在化学键"}
599
+ cmd = ModifyBondLength3DCommand(bid, val)
600
+ elif coord_type == "bond_angle" and len(atom_ids) == 3:
601
+ from ..application.internal_coordinates import ModifyAngle3DCommand
602
+ cmd = ModifyAngle3DCommand(atom_ids[0], atom_ids[1], atom_ids[2], val)
603
+ elif coord_type == "dihedral" and len(atom_ids) == 4:
604
+ from ..application.internal_coordinates import ModifyDihedral3DCommand
605
+ cmd = ModifyDihedral3DCommand(atom_ids[0], atom_ids[1], atom_ids[2], atom_ids[3], val)
606
+ else:
607
+ return {"ok": False, "error": f"不合法的内坐标修改参数 (coord_type={coord_type}, atoms={atoms})"}
608
+
609
+ bus = self.command_bus
610
+ if bus is None:
611
+ from ..application.command_bus import CommandBus
612
+ bus = CommandBus(self.document)
613
+ r = bus.execute(cmd)
614
+ return {"ok": r.success, "message": r.message}
615
+
616
+ def _tool_run_calchem_scf(self, basis: str = "sto-3g") -> dict:
617
+ if self.document is None:
618
+ return {"ok": False, "error": "没有打开的分子"}
619
+ from ..io.calchem_bridge import run_calchem_single_point
620
+ res = run_calchem_single_point(self.document, basis=basis)
621
+ if not res.get("success"):
622
+ return {"ok": False, "error": res.get("error", "计算失败")}
623
+ return {
624
+ "ok": True,
625
+ "converged": res.get("converged"),
626
+ "total_energy_hartree": res.get("total_energy_hartree"),
627
+ "homo_energy_hartree": res.get("homo_energy_hartree"),
628
+ "lumo_energy_hartree": res.get("lumo_energy_hartree"),
629
+ "gap_ev": res.get("gap_ev"),
630
+ "dipole_debye": res.get("dipole_debye"),
631
+ }
632
+
633
+ def _tool_run_calchem_opt(self, basis: str = "sto-3g", max_steps: int = 50) -> dict:
634
+ if self.document is None:
635
+ return {"ok": False, "error": "没有打开的分子"}
636
+ from ..io.calchem_bridge import run_calchem_optimization
637
+ res = run_calchem_optimization(self.document, basis=basis, max_steps=max_steps)
638
+ if not res.get("success"):
639
+ return {"ok": False, "error": res.get("error", "优化失败")}
640
+ if self.command_bus and "command" in res:
641
+ self.command_bus.execute(res["command"])
642
+ return {
643
+ "ok": True,
644
+ "converged": res.get("converged"),
645
+ "steps": res.get("steps"),
646
+ "final_energy_hartree": res.get("energy_hartree"),
647
+ "applied_to_viewport": bool(self.command_bus),
648
+ }
649
+
650
+ def _tool_generate_hpc_slurm_script(
651
+ self,
652
+ engine: str,
653
+ job_name: str = "chem_job",
654
+ n_cores: int = 16,
655
+ memory_mb: int = 32000,
656
+ walltime: str = "24:00:00",
657
+ ) -> dict:
658
+ from ..infrastructure.hpc.slurm_generator import SlurmScriptGenerator, JobSpec
659
+ from ..infrastructure.hpc.cluster_config import ClusterProfile
660
+ job = JobSpec(
661
+ job_name=job_name,
662
+ engine=engine,
663
+ input_file=f"{job_name}.{'gjf' if engine == 'g16' else 'inp'}",
664
+ output_file=f"{job_name}.{'log' if engine == 'g16' else 'out'}",
665
+ n_cores=n_cores,
666
+ memory_mb=memory_mb,
667
+ walltime=walltime,
668
+ )
669
+ script = SlurmScriptGenerator.generate(job, ClusterProfile())
670
+ return {"ok": True, "engine": engine, "slurm_script": script}
671
+
672
+ def _tool_planarity(self) -> dict:
673
+ from ..application.calculators.qc_input_generator import export_document_to_xyz
674
+ from ..workflows.planarity_analysis import run_planarity_workflow
675
+ import tempfile, os
676
+ tmp = os.path.join(tempfile.gettempdir(), "molforge_mcp_plane.xyz")
677
+ export_document_to_xyz(self.document, tmp)
678
+ out = run_planarity_workflow(tmp, tempfile.gettempdir())
679
+ summary_path = os.path.join(str(out), "planarity.json")
680
+ with open(summary_path, encoding="utf-8") as fh:
681
+ return json.load(fh)
682
+
683
+ def _tool_run_rest_scf(self, xc: str = "b3lyp", basis: str = "def2-SVP") -> dict:
684
+ if self.document is None:
685
+ return {"ok": False, "error": "没有打开的分子"}
686
+ from ..application.calculators.rest_engine import RestEngine
687
+ engine = RestEngine()
688
+ if not engine.probe():
689
+ return {"ok": False, "error": "未检测到本地 WSL2 REST 虚拟环境 (/home/administrator/miniforge3/envs/rest-py311/bin/rest)"}
690
+ return engine.run_calculation(self.document, xc=xc, basis=basis)
691
+
692
+ def _tool_build_from_smiles(self, smiles: str, name: str = "") -> dict:
693
+ if self.command_bus is None:
694
+ return {"ok": False, "error": "未连接命令总线"}
695
+ from ..io.rdkit_adapter import create_molecule_from_smiles
696
+ from ..application.builtin_commands import AppendMoleculeCommand
697
+ sub_doc = create_molecule_from_smiles(smiles.strip(), name=name or smiles.strip())
698
+ res = self.command_bus.execute(AppendMoleculeCommand(sub_doc))
699
+ return {"ok": getattr(res, "success", True), "message": getattr(res, "message", ""), "num_atoms": self.document.num_atoms, "num_bonds": self.document.topology.num_bonds}
700
+
701
+ def _tool_add_ring(self, size: int = 6, aromatic: bool = True, attach_to: int | None = None) -> dict:
702
+ if self.command_bus is None:
703
+ return {"ok": False, "error": "未连接命令总线"}
704
+ from ..application.builtin_commands import AddRingCommand
705
+ attach_aid = self._aid_at_1based(attach_to) if attach_to else None
706
+ if attach_to and attach_aid is None:
707
+ return {"ok": False, "error": f"接枝原子 #{attach_to} 越界"}
708
+ res = self.command_bus.execute(AddRingCommand(size=int(size), aromatic=bool(aromatic), attach_to=attach_aid))
709
+ return {"ok": getattr(res, "success", True), "message": getattr(res, "message", ""), "num_atoms": self.document.num_atoms}
710
+
711
+ def _tool_change_element(self, atom_index: int, new_atomic_num: int) -> dict:
712
+ if self.command_bus is None:
713
+ return {"ok": False, "error": "未连接命令总线"}
714
+ from ..application.builtin_commands import ChangeElementCommand
715
+ aid = self._aid_at_1based(atom_index)
716
+ if aid is None:
717
+ return {"ok": False, "error": f"原子 #{atom_index} 越界"}
718
+ res = self.command_bus.execute(ChangeElementCommand(aid, int(new_atomic_num)))
719
+ return {"ok": getattr(res, "success", True), "message": getattr(res, "message", "")}
720
+
721
+ def _tool_change_bond_order(self, atom_a: int, atom_b: int, order: int = 2) -> dict:
722
+ if self.command_bus is None:
723
+ return {"ok": False, "error": "未连接命令总线"}
724
+ from ..application.builtin_commands import ChangeBondOrderCommand
725
+ a, b = self._aid_at_1based(atom_a), self._aid_at_1based(atom_b)
726
+ if a is None or b is None:
727
+ return {"ok": False, "error": "原子编号越界"}
728
+ bid = self.document.topology.bond_between(a, b)
729
+ cmd = ChangeBondOrderCommand(bid, int(order)) if bid is not None else AddBondCommand(a, b, order=int(order))
730
+ res = self.command_bus.execute(cmd)
731
+ return {"ok": getattr(res, "success", True), "message": getattr(res, "message", "")}
732
+
733
+ def _tool_clean_geometry_3d(self) -> dict:
734
+ if self.command_bus is None:
735
+ return {"ok": False, "error": "未连接命令总线"}
736
+ from ..application.builtin_commands import CleanGeometry3DCommand
737
+ res = self.command_bus.execute(CleanGeometry3DCommand())
738
+ return {"ok": getattr(res, "success", True), "message": getattr(res, "message", "")}
739
+
740
+ def _tool_set_atom_charge(self, atom_index: int, formal_charge: int) -> dict:
741
+ if self.command_bus is None:
742
+ return {"ok": False, "error": "未连接命令总线"}
743
+ from ..application.builtin_commands import ChangeAtomStyleCommand
744
+ aid = self._aid_at_1based(atom_index)
745
+ if aid is None:
746
+ return {"ok": False, "error": f"原子 #{atom_index} 越界"}
747
+ res = self.command_bus.execute(ChangeAtomStyleCommand([aid], formal_charge=int(formal_charge)))
748
+ return {"ok": getattr(res, "success", True), "message": getattr(res, "message", "")}
749
+
750
+ def _tool_undo_last(self) -> dict:
751
+ if self.command_bus is None:
752
+ return {"ok": False, "error": "未连接命令总线"}
753
+ res = self.command_bus.undo()
754
+ return {"ok": getattr(res, "success", True), "message": getattr(res, "message", ""), "num_atoms": self.document.num_atoms}
755
+
756
+ def _tool_redo_last(self) -> dict:
757
+ if self.command_bus is None:
758
+ return {"ok": False, "error": "未连接命令总线"}
759
+ res = self.command_bus.redo()
760
+ return {"ok": getattr(res, "success", True), "message": getattr(res, "message", ""), "num_atoms": self.document.num_atoms}
761
+
762
+ def dispatch(self, name: str, arguments: dict[str, Any]) -> Any:
763
+ try:
764
+ if self.document is None:
765
+ return {"ok": False, "error": "没有打开的分子"}
766
+ spec = next((d["function"]["parameters"] for d in self.tool_definitions() if d["function"]["name"] == name), None)
767
+ if spec is None or not isinstance(arguments, dict):
768
+ raise ValueError(f"未知工具 '{name}' 或参数必须是对象")
769
+ props = spec.get("properties", {})
770
+ required_keys = set(spec.get("required", []))
771
+
772
+ # 1. 检查必需参数
773
+ missing = required_keys - set(arguments.keys())
774
+ if missing:
775
+ raise ValueError(f"缺少必需参数: {sorted(missing)}")
776
+
777
+ # 2. 检查未知参数
778
+ extra = set(arguments.keys()) - set(props.keys())
779
+ if extra:
780
+ raise ValueError(f"包含未知参数: {sorted(extra)}")
781
+
782
+ # 3. 按 schema 动态进行类型校验
783
+ for key, value in arguments.items():
784
+ pinfo = props.get(key, {})
785
+ ptype = pinfo.get("type")
786
+ if ptype == "integer":
787
+ if not isinstance(value, int) or isinstance(value, bool):
788
+ raise ValueError(f"{key} 必须是整数")
789
+ min_val = pinfo.get("minimum", 1 if key in ("near_atom", "atom_index", "atom_a", "atom_b") else None)
790
+ if min_val is not None and value < min_val:
791
+ raise ValueError(f"{key} 必须 >= {min_val}")
792
+ if key == "atomic_num" and not (1 <= value <= 118):
793
+ raise ValueError("atomic_num 超出元素范围1–118")
794
+ elif ptype == "number":
795
+ if not isinstance(value, (int, float)) or isinstance(value, bool):
796
+ raise ValueError(f"{key} 必须是数值")
797
+ elif ptype == "string":
798
+ if not isinstance(value, str):
799
+ raise ValueError(f"{key} 必须是字符串")
800
+ if "enum" in pinfo and value not in pinfo["enum"]:
801
+ raise ValueError(f"{key} 的值 '{value}' 不在允许的枚举范围 {pinfo['enum']} 内")
802
+ elif ptype == "array":
803
+ if not isinstance(value, list):
804
+ raise ValueError(f"{key} 必须是列表")
805
+ item_type = pinfo.get("items", {}).get("type")
806
+ if item_type == "integer":
807
+ if not all(isinstance(x, int) and not isinstance(x, bool) and x >= 1 for x in value):
808
+ raise ValueError(f"{key} 中的元素必须是 >= 1 的整数")
809
+
810
+ return self._dispatch_validated(name, arguments)
811
+ except Exception as exc:
812
+ return {"ok": False, "error": str(exc)}
813
+
814
+ def _dispatch_validated(self, name: str, arguments: dict[str, Any]) -> Any:
815
+ if name == "describe_structure":
816
+ return self._tool_describe()
817
+ if name == "list_atoms":
818
+ return self._tool_list_atoms()
819
+ if name == "add_atom":
820
+ return self._tool_add_atom(**arguments)
821
+ if name == "delete_atom":
822
+ return self._tool_delete_atom(**arguments)
823
+ if name == "add_bond":
824
+ return self._tool_add_bond(**arguments)
825
+ if name == "modify_internal_coordinate":
826
+ return self._tool_modify_internal_coordinate(**arguments)
827
+ if name == "run_calchem_scf":
828
+ return self._tool_run_calchem_scf(**arguments)
829
+ if name == "run_calchem_opt":
830
+ return self._tool_run_calchem_opt(**arguments)
831
+ if name == "generate_hpc_slurm_script":
832
+ return self._tool_generate_hpc_slurm_script(**arguments)
833
+ if name == "run_planarity":
834
+ return self._tool_planarity()
835
+ if name == "run_rest_scf":
836
+ return self._tool_run_rest_scf(**arguments)
837
+ if name == "build_from_smiles":
838
+ return self._tool_build_from_smiles(**arguments)
839
+ if name == "add_ring":
840
+ return self._tool_add_ring(**arguments)
841
+ if name == "change_element":
842
+ return self._tool_change_element(**arguments)
843
+ if name == "change_bond_order":
844
+ return self._tool_change_bond_order(**arguments)
845
+ if name == "clean_geometry_3d":
846
+ return self._tool_clean_geometry_3d()
847
+ if name == "set_atom_charge":
848
+ return self._tool_set_atom_charge(**arguments)
849
+ if name == "undo_last":
850
+ return self._tool_undo_last()
851
+ if name == "redo_last":
852
+ return self._tool_redo_last()
853
+ return {"error": f"未知工具: {name}"}
854
+
855
+ # ---------- 对话循环(OpenAI 兼容) ----------
856
+ def chat(self, user_message: str, max_tool_rounds: int = 6, tool_executor=None) -> str:
857
+ """发送一轮消息,自动执行 LLM 请求的工具调用,返回最终文本答复。"""
858
+ cfg = self.config if getattr(self, 'config', None) else get_llm_config()
859
+ from urllib.parse import urlsplit
860
+ if urlsplit(cfg["base_url"]).scheme not in ("http", "https"):
861
+ return "LLM端点必须是http/https地址"
862
+ if self.document is not None:
863
+ turn_start_len = len(self.history)
864
+ self.history.append({"role": "user", "content": user_message})
865
+ else:
866
+ return "当前没有打开的分子文档,LLM 无可读取的结构。"
867
+
868
+ for _ in range(max_tool_rounds):
869
+ payload = {
870
+ "model": cfg["model"],
871
+ "messages": self.history,
872
+ "tools": self.tool_definitions(),
873
+ "tool_choice": "auto",
874
+ "temperature": float(cfg.get("temperature", 0.3)),
875
+ "max_tokens": int(cfg.get("max_tokens", 4096)),
876
+ }
877
+ if cfg.get("reasoning_effort") and cfg["reasoning_effort"] not in ("none", "关闭"):
878
+ payload["reasoning_effort"] = cfg["reasoning_effort"]
879
+
880
+ url = cfg["base_url"].rstrip("/") + "/chat/completions"
881
+ req = urllib.request.Request(
882
+ url,
883
+ data=json.dumps(payload).encode("utf-8"),
884
+ headers={
885
+ "Content-Type": "application/json",
886
+ "Authorization": f"Bearer {cfg['api_key']}",
887
+ },
888
+ method="POST",
889
+ )
890
+ try:
891
+ with urllib.request.urlopen(req, timeout=120) as resp:
892
+ data = json.loads(resp.read().decode("utf-8"))
893
+ except urllib.error.HTTPError as exc:
894
+ del self.history[turn_start_len:]
895
+ err_body = exc.read().decode("utf-8", errors="ignore")
896
+ detail = ""
897
+ try:
898
+ err_json = json.loads(err_body)
899
+ detail = (
900
+ err_json.get("error", {}).get("readable_summary")
901
+ or err_json.get("error", {}).get("message")
902
+ or err_json.get("message")
903
+ or str(exc)
904
+ )
905
+ except Exception:
906
+ detail = err_body[:240] if err_body else str(exc)
907
+ return f"LLM 服务返回错误 (HTTP {exc.code}):{detail}\n💡 诊断建议:若提示模型不存在,请在上方配置区点击「🔄 获取可用模型」并从下拉菜单中选中可用模型(如 gemini-3.8-flash)。"
908
+ except (urllib.error.URLError, TimeoutError, ValueError, OSError) as exc:
909
+ del self.history[turn_start_len:]
910
+ return f"无法连接 LLM 端点 ({cfg['base_url']}):{exc}"
911
+
912
+ try:
913
+ msg = data["choices"][0]["message"]
914
+ if not isinstance(msg, dict):
915
+ raise ValueError("message不是对象")
916
+ except (KeyError, IndexError, TypeError, ValueError) as exc:
917
+ del self.history[turn_start_len:]
918
+ return f"LLM响应格式错误:{exc}"
919
+ tool_calls = msg.get("tool_calls") or []
920
+ if not isinstance(tool_calls, list):
921
+ del self.history[turn_start_len:]
922
+ return "LLM响应格式错误:tool_calls必须是数组"
923
+ if not tool_calls:
924
+ reply = msg.get("content", "")
925
+ self.history.append(msg)
926
+ return reply
927
+
928
+ self.history.append(msg)
929
+ for call in tool_calls:
930
+ if not isinstance(call, dict) or not isinstance(call.get("function"), dict) or not call.get("id") or not isinstance(call["function"].get("name"), str):
931
+ del self.history[turn_start_len:]
932
+ return "LLM响应格式错误:工具调用缺少id/function/name"
933
+ fname = call["function"]["name"]
934
+ try:
935
+ fargs = json.loads(call["function"].get("arguments") or "{}")
936
+ except json.JSONDecodeError:
937
+ fargs = {}
938
+ result = (tool_executor or self.dispatch)(fname, fargs)
939
+ self.history.append({
940
+ "role": "tool",
941
+ "tool_call_id": call["id"],
942
+ "name": fname,
943
+ "content": json.dumps(result, ensure_ascii=False),
944
+ })
945
+ return "达到最大工具调用轮数,已停止。"