femo-plugin 1.0.0

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 (166) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +627 -0
  3. package/femo2host/__init__.py +4 -0
  4. package/femo2host/femoToolcall/chronica.py +156 -0
  5. package/femo2host/femoToolcall/femo-chat.mjs +69 -0
  6. package/femo2host/femoToolcall/femo_debugger.py +1515 -0
  7. package/femo2host/femo_api.py +437 -0
  8. package/femo2host/femo_gen_api.jsx +77 -0
  9. package/femoBridges/ContextExample.py +555 -0
  10. package/femoBridges/MemoryExample.py +163 -0
  11. package/femoBridges/__init__.py +1 -0
  12. package/femoBridges/getDir/get_dir.py +56 -0
  13. package/femoBridges/getDir//344/275/240/345/217/257/344/273/245/350/256/276/345/256/232/344/273/273/346/204/217/346/226/207/344/273/266/345/244/271/344/270/272/347/224/250/346/210/267/346/225/260/346/215/256/346/226/207/344/273/266/345/244/271.txt +10 -0
  14. package/femoBridges/llmBridge.py +247 -0
  15. package/femoBridges/llmProviders.py +308 -0
  16. package/femoCompiler/FEMO_CLIrenderer.py +198 -0
  17. package/femoCompiler/FEMO_config.py +35 -0
  18. package/femoCompiler/FEMO_errors.py +278 -0
  19. package/femoCompiler/FEMO_interpreter.py +163 -0
  20. package/femoCompiler/FEMO_normalizer.py +396 -0
  21. package/femoCompiler/FEMO_parser.py +2468 -0
  22. package/femoCompiler/FEMO_runtime.py +3630 -0
  23. package/femoCompiler/FEMO_scope_resolver.py +209 -0
  24. package/femoCompiler/__init__.py +1 -0
  25. package/femoCompiler/actor_resolver.py +86 -0
  26. package/femoCompiler/block_collector.py +441 -0
  27. package/femoCompiler/db_utils.py +485 -0
  28. package/femoCompiler/femoAsync.py +401 -0
  29. package/femoCompiler/host_manifest.py +68 -0
  30. package/femoCompiler/job_manager.py +767 -0
  31. package/femoCompiler/protocol.py +126 -0
  32. package/femoCompiler/save_dialog.py +402 -0
  33. package/femoCompiler/task_world.py +544 -0
  34. package/femoCompiler/vars/__init__.py +19 -0
  35. package/femoCompiler/vars/checkpoint.py +113 -0
  36. package/femoCompiler/vars/env.py +686 -0
  37. package/femoCompiler/vars/evaluator.py +567 -0
  38. package/femoCompiler/vars/join.py +303 -0
  39. package/femoCompiler/vars/merge.py +157 -0
  40. package/femoCompiler/vars/model.py +245 -0
  41. package/femoExamples/AI/345/211/252/350/247/206/351/242/221/AI/345/211/252/350/247/206/351/242/221.femo +192 -0
  42. package/femoExamples/AI/350/201/212/345/244/251/345/256/244/group-chat.femo +42 -0
  43. package/femoExamples/AI/350/201/212/345/244/251/345/256/244/random_wait_time.py +10 -0
  44. package/femoExamples/LuxFiat/luxfiat.femo +38 -0
  45. package/femoExamples/LuxFiat/wait.py +29 -0
  46. package/femoExamples/debug/347/245/236/345/231/250/debug/347/245/236/345/231/250.femo +222 -0
  47. package/femoExamples/discussion.femo +70 -0
  48. package/femoExamples/goal-mode.femo +23 -0
  49. package/femoExamples//345/270/270/347/224/250/345/267/245/345/205/267python/wait.py +29 -0
  50. package/femoExamples//347/213/274/344/272/272/346/235/200/werewolf_utils.py +205 -0
  51. package/femoExamples//347/213/274/344/272/272/346/235/200/werewolf_utils2.py +324 -0
  52. package/femoExamples//347/213/274/344/272/272/346/235/200//347/213/274/344/272/272/346/235/200-/350/255/246/351/225/277/347/211/210.femo +544 -0
  53. package/femoExamples//347/213/274/344/272/272/346/235/200//347/213/274/344/272/272/346/235/200.femo +331 -0
  54. package/femoExamples//350/260/201/346/230/257/345/215/247/345/272/225/undercover_utils.py +683 -0
  55. package/femoExamples//350/260/201/346/230/257/345/215/247/345/272/225//350/260/201/346/230/257/345/215/247/345/272/225-/350/217/234/345/270/202/345/234/272/345/261/200.femo +348 -0
  56. package/femoExamples//350/260/201/346/230/257/345/215/247/345/272/225//350/260/201/346/230/257/345/215/247/345/272/225.femo +392 -0
  57. package/femoGen/document_ch.html +2352 -0
  58. package/femoGen/document_en.html +2279 -0
  59. package/femoGen/index.html +19 -0
  60. package/femoGen/intro_ch.html +942 -0
  61. package/femoGen/intro_en.html +932 -0
  62. package/femoGen/package-lock.json +1698 -0
  63. package/femoGen/package.json +19 -0
  64. package/femoGen/public/character_need.ttf +0 -0
  65. package/femoGen/public/favicon.ico +0 -0
  66. package/femoGen/public/femo-logo-slogan.svg +83 -0
  67. package/femoGen/public/femo-logo.svg +55 -0
  68. package/femoGen/public/logo-fullsize.ico +0 -0
  69. package/femoGen/src/FemoWorAuto.jsx +5444 -0
  70. package/femoGen/src/actionModal.jsx +358 -0
  71. package/femoGen/src/bubbleOverlay.jsx +701 -0
  72. package/femoGen/src/canvasNodes.jsx +608 -0
  73. package/femoGen/src/common.jsx +715 -0
  74. package/femoGen/src/debugPanel.jsx +530 -0
  75. package/femoGen/src/faIcons.jsx +84 -0
  76. package/femoGen/src/femoDiagnostics.js +122 -0
  77. package/femoGen/src/femoFileList.jsx +357 -0
  78. package/femoGen/src/femoGenerator.jsx +1198 -0
  79. package/femoGen/src/femoLog.js +107 -0
  80. package/femoGen/src/femoParser.jsx +2255 -0
  81. package/femoGen/src/femoPreview.jsx +297 -0
  82. package/femoGen/src/graphBuilder.jsx +358 -0
  83. package/femoGen/src/libPanel.jsx +519 -0
  84. package/femoGen/src/main.jsx +22 -0
  85. package/femoGen/src/mobileView.jsx +2796 -0
  86. package/femoGen/src/projectPanel.jsx +529 -0
  87. package/femoGen/src/soulModal.jsx +162 -0
  88. package/femoGen/src/styles/font.css +10 -0
  89. package/femoGen/src/themes.js +465 -0
  90. package/femoGen/src/useCanvasInteraction.jsx +319 -0
  91. package/femoGen/vite.config.js +28 -0
  92. package/femoGen//347/222/207/345/255/230/346/247/221.txt +15 -0
  93. package/hostAdapter/dshAdapter/README.md +68 -0
  94. package/hostAdapter/dshAdapter/build.mjs +75 -0
  95. package/hostAdapter/dshAdapter/client/client-ui/chat-node.tsx +339 -0
  96. package/hostAdapter/dshAdapter/client/client-ui/composer.tsx +997 -0
  97. package/hostAdapter/dshAdapter/client/client-ui/editor-page.tsx +726 -0
  98. package/hostAdapter/dshAdapter/client/client-ui/editor-view.tsx +88 -0
  99. package/hostAdapter/dshAdapter/client/client-ui/femo-stream-live.tsx +264 -0
  100. package/hostAdapter/dshAdapter/client/client-ui/proj2/frame-router.ts +282 -0
  101. package/hostAdapter/dshAdapter/client/client-ui/proj2/index.ts +44 -0
  102. package/hostAdapter/dshAdapter/client/client-ui/proj2/ledger.ts +329 -0
  103. package/hostAdapter/dshAdapter/client/client-ui/proj2/turn-view.tsx +211 -0
  104. package/hostAdapter/dshAdapter/client/client-ui/proj2/window-id.ts +28 -0
  105. package/hostAdapter/dshAdapter/client/client-ui/stream-store.ts +550 -0
  106. package/hostAdapter/dshAdapter/client/client-ui/styles.ts +144 -0
  107. package/hostAdapter/dshAdapter/client/client-ui/view-button.tsx +572 -0
  108. package/hostAdapter/dshAdapter/client/client-ui/view-state.ts +61 -0
  109. package/hostAdapter/dshAdapter/client/client.tsx +518 -0
  110. package/hostAdapter/dshAdapter/client/fa-icons.tsx +112 -0
  111. package/hostAdapter/dshAdapter/client/femo-reasoning-row.tsx +103 -0
  112. package/hostAdapter/dshAdapter/client/lineage-fork-native.jsx +624 -0
  113. package/hostAdapter/dshAdapter/client/lineage-fork.jsx +585 -0
  114. package/hostAdapter/dshAdapter/cordis.patch.yml +8 -0
  115. package/hostAdapter/dshAdapter/dshPatch/DSH-0.1.2-fork/344/277/256/346/224/271/351/234/200/346/261/202.md +184 -0
  116. package/hostAdapter/dshAdapter/dshPatch/MEOW_MODIFICATIONS.md +3105 -0
  117. package/hostAdapter/dshAdapter/dshPatch/patch-dsh-0.1.2-alpha.1.py +313 -0
  118. package/hostAdapter/dshAdapter/host/api-retry.ts +141 -0
  119. package/hostAdapter/dshAdapter/host/bridge.ts +224 -0
  120. package/hostAdapter/dshAdapter/host/config.ts +124 -0
  121. package/hostAdapter/dshAdapter/host/debug-log.ts +29 -0
  122. package/hostAdapter/dshAdapter/host/debug-run.ts +793 -0
  123. package/hostAdapter/dshAdapter/host/diag-feed.ts +56 -0
  124. package/hostAdapter/dshAdapter/host/engine-events.ts +891 -0
  125. package/hostAdapter/dshAdapter/host/engine-transcript.ts +122 -0
  126. package/hostAdapter/dshAdapter/host/femo-files.ts +210 -0
  127. package/hostAdapter/dshAdapter/host/god-mirror.ts +234 -0
  128. package/hostAdapter/dshAdapter/host/host-log.ts +101 -0
  129. package/hostAdapter/dshAdapter/host/http.ts +66 -0
  130. package/hostAdapter/dshAdapter/host/index.ts +633 -0
  131. package/hostAdapter/dshAdapter/host/list-cache.ts +183 -0
  132. package/hostAdapter/dshAdapter/host/main-actor.ts +853 -0
  133. package/hostAdapter/dshAdapter/host/main-delivery-queue.ts +115 -0
  134. package/hostAdapter/dshAdapter/host/native-state.ts +21 -0
  135. package/hostAdapter/dshAdapter/host/node-retry.ts +246 -0
  136. package/hostAdapter/dshAdapter/host/persona.ts +146 -0
  137. package/hostAdapter/dshAdapter/host/pre-step-gate.ts +95 -0
  138. package/hostAdapter/dshAdapter/host/proj-trace.ts +49 -0
  139. package/hostAdapter/dshAdapter/host/projection-input.ts +238 -0
  140. package/hostAdapter/dshAdapter/host/projection.ts +742 -0
  141. package/hostAdapter/dshAdapter/host/routes.ts +1196 -0
  142. package/hostAdapter/dshAdapter/host/run-control.ts +641 -0
  143. package/hostAdapter/dshAdapter/host/safe-steer.ts +33 -0
  144. package/hostAdapter/dshAdapter/host/section-gate.ts +108 -0
  145. package/hostAdapter/dshAdapter/host/session-events.ts +45 -0
  146. package/hostAdapter/dshAdapter/host/state-files.ts +301 -0
  147. package/hostAdapter/dshAdapter/host/stream-frames.ts +229 -0
  148. package/hostAdapter/dshAdapter/host/subagent-native.ts +997 -0
  149. package/hostAdapter/dshAdapter/host/subagent.ts +1205 -0
  150. package/hostAdapter/dshAdapter/host/tools.ts +486 -0
  151. package/hostAdapter/dshAdapter/host/windowing-native.ts +294 -0
  152. package/hostAdapter/dshAdapter/host.manifest.json +6 -0
  153. package/hostAdapter/dshAdapter/lib/client.js +19161 -0
  154. package/hostAdapter/dshAdapter/lib/client.js.map +7 -0
  155. package/hostAdapter/dshAdapter/lib/index.js +8173 -0
  156. package/hostAdapter/dshAdapter/lib/index.js.map +7 -0
  157. package/hostAdapter/dshAdapter/package-lock.json +500 -0
  158. package/hostAdapter/dshAdapter/package.json +55 -0
  159. package/hostAdapter/dshAdapter/pnpm-lock.yaml +596 -0
  160. package/hostAdapter/dshAdapter/pnpm-workspace.yaml +2 -0
  161. package/hostAdapter/dshAdapter/python/dev-bridge-test.py +43 -0
  162. package/hostAdapter/dshAdapter/python/femo_bridge.py +533 -0
  163. package/hostAdapter/dshAdapter/tsconfig.host.json +9 -0
  164. package/hostAdapter/dshAdapter/tsconfig.json +21 -0
  165. package/package.json +40 -0
  166. package//350/257/255/346/263/225/346/226/207/346/241/243.md +1136 -0
@@ -0,0 +1,308 @@
1
+ """
2
+ femoCompiler/llmProviders.py —— 统一 LLM 调用模块
3
+ ========================================
4
+ 支持从 .env 自动检测已配置的 API Key,
5
+ 并通过 OpenAI 兼容接口实现流式聊天。
6
+
7
+ 代码原则:所有代码不许写try静默兜底不报错,有错必须报错。
8
+
9
+ 支持的供应商:
10
+ deepseek, glm, kimi, minimax, claude, gemini,
11
+ mimo, baidu, qianwen, hunyuan, spark, openai
12
+ """
13
+
14
+ import os
15
+ import json
16
+ import requests
17
+ from typing import Generator, Optional, Dict, Any
18
+
19
+ # ── 供应商配置表 ──
20
+ PROVIDER_CONFIG = {
21
+ "deepseek": {
22
+ "env_prefix": "DEEPSEEK",
23
+ "default_url": "https://api.deepseek.com/v1/chat/completions",
24
+ "default_model": "deepseek-v4-flash",
25
+ "headers_extra": {},
26
+ },
27
+ "glm": {
28
+ "env_prefix": "GLM",
29
+ "default_url": "https://open.bigmodel.cn/api/paas/v4/chat/completions",
30
+ "default_model": "glm-5.1",
31
+ "headers_extra": {},
32
+ },
33
+ "kimi": {
34
+ "env_prefix": "KIMI",
35
+ "default_url": "https://api.moonshot.cn/v1/chat/completions",
36
+ "default_model": "kimi-k2.5",
37
+ "headers_extra": {},
38
+ },
39
+ "minimax": {
40
+ "env_prefix": "MINIMAX",
41
+ "default_url": "https://api.minimax.io/v1/chat/completions",
42
+ "default_model": "MiniMax-M2.7",
43
+ "headers_extra": {},
44
+ },
45
+ "claude": {
46
+ "env_prefix": "CLAUDE",
47
+ # Anthropic 兼容 OpenAI 接口需要设置 header x-api-key
48
+ "default_url": "https://api.anthropic.com/v1/chat/completions",
49
+ "default_model": "claude-opus-4-8",
50
+ "headers_extra": {
51
+ "x-api-key": "${API_KEY}", # 占位符,运行时替换
52
+ },
53
+ },
54
+ "gemini": {
55
+ "env_prefix": "GEMINI",
56
+ "default_url": "https://generativelanguage.googleapis.com/v1beta/chat/completions",
57
+ "default_model": "gemini-3.5-flash",
58
+ "headers_extra": {},
59
+ },
60
+ "mimo": {
61
+ "env_prefix": "MIMO",
62
+ "default_url": "https://token-plan-cn.xiaomimimo.com/v1/chat/completions",
63
+ "default_model": "mimo-v2.5-pro",
64
+ "headers_extra": {},
65
+ },
66
+ "baidu": {
67
+ "env_prefix": "BAIDU",
68
+ "default_url": "", # 百度的鉴权方式不同,后续特殊处理
69
+ "default_model": "ernie-5.1",
70
+ "headers_extra": {},
71
+ },
72
+ "qianwen": {
73
+ "env_prefix": "QIANWEN",
74
+ "default_url": "https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions",
75
+ "default_model": "qwen3.7-max",
76
+ "headers_extra": {},
77
+ },
78
+ "hunyuan": {
79
+ "env_prefix": "HUNYUAN",
80
+ "default_url": "https://api.hunyuan.cloud.tencent.com/v1/chat/completions",
81
+ "default_model": "hy3-preview",
82
+ "headers_extra": {},
83
+ },
84
+ "spark": {
85
+ "env_prefix": "SPARK",
86
+ "default_url": "", # 讯飞使用 WebSocket,单独处理
87
+ "default_model": "spark-x",
88
+ "headers_extra": {},
89
+ },
90
+ "openai": {
91
+ "env_prefix": "OPENAI",
92
+ "default_url": "https://api.openai.com/v1/chat/completions",
93
+ "default_model": "gpt-5",
94
+ "headers_extra": {},
95
+ },
96
+ }
97
+
98
+
99
+ def detect_provider() -> Optional[str]:
100
+ """自动检测第一个已配置 API Key 的供应商"""
101
+ for name, cfg in PROVIDER_CONFIG.items():
102
+ env_key = f"{cfg['env_prefix']}_API_KEY"
103
+ if os.getenv(env_key):
104
+ return name
105
+ return None
106
+
107
+
108
+ def get_provider_config(provider: str) -> Dict[str, Any]:
109
+ """获取指定供应商的配置,并从环境变量读取实际值"""
110
+ cfg = PROVIDER_CONFIG.get(provider)
111
+ if not cfg:
112
+ raise ValueError(f"不支持的供应商: {provider}")
113
+
114
+ env_prefix = cfg["env_prefix"]
115
+ api_key = os.getenv(f"{env_prefix}_API_KEY")
116
+ if not api_key:
117
+ raise ValueError(f"环境变量 {env_prefix}_API_KEY 未设置")
118
+
119
+ api_url = os.getenv(f"{env_prefix}_API_URL") or cfg["default_url"]
120
+ model = os.getenv(f"{env_prefix}_API_MODEL") or cfg["default_model"]
121
+
122
+ # 构建请求头
123
+ headers = {"Content-Type": "application/json"}
124
+
125
+ # 大多数供应商使用 Bearer Token,放在 Authorization 头中
126
+ use_bearer = True
127
+ for k, v in cfg.get("headers_extra", {}).items():
128
+ headers[k] = v.replace("${API_KEY}", api_key)
129
+ # 如果已经设置了 Authorization 或 x-api-key,则说明使用自定义认证方式
130
+ if k.lower() in ("authorization", "x-api-key"):
131
+ use_bearer = False
132
+
133
+ # 对于未指定特殊认证方式的供应商,统一添加 Bearer Token
134
+ if use_bearer and "Authorization" not in headers:
135
+ headers["Authorization"] = f"Bearer {api_key}"
136
+
137
+ return {
138
+ "api_key": api_key,
139
+ "api_url": api_url,
140
+ "model": model,
141
+ "headers": headers,
142
+ }
143
+
144
+
145
+ def stream_chat(
146
+ provider: str,
147
+ messages: list,
148
+ system_prompt: str = "",
149
+ deep_think: bool = False,
150
+ sampling_params: dict = None,
151
+ stop_event=None,
152
+ api_key: str = None,
153
+ api_url: str = None,
154
+ model: str = None,
155
+ ) -> Generator[str, None, None]:
156
+ """
157
+ 统一的流式聊天接口
158
+ provider: 供应商名称,如 'deepseek'
159
+ messages: 已组装的消息列表 [{"role":"system","content":"..."}, ...]
160
+ model: 用户传入的模型名,优先于环境变量或默认模型
161
+ 返回一个生成器,逐块产生回答文本(str)
162
+ """
163
+ # 如果传入了 api_key,直接构建配置,不检查环境变量
164
+ if api_key:
165
+ cfg_base = PROVIDER_CONFIG.get(provider)
166
+ if not cfg_base:
167
+ raise ValueError(f"不支持的供应商: {provider}")
168
+ env_prefix = cfg_base["env_prefix"]
169
+ final_url = api_url or os.getenv(f"{env_prefix}_API_URL") or cfg_base["default_url"]
170
+ final_model = model or os.getenv(f"{env_prefix}_API_MODEL") or cfg_base["default_model"]
171
+ # 构建 headers
172
+ headers = {"Content-Type": "application/json"}
173
+ use_bearer = True
174
+ for k, v in cfg_base.get("headers_extra", {}).items():
175
+ headers[k] = v.replace("${API_KEY}", api_key)
176
+ if k.lower() in ("authorization", "x-api-key"):
177
+ use_bearer = False
178
+ if use_bearer and "Authorization" not in headers:
179
+ headers["Authorization"] = f"Bearer {api_key}"
180
+ cfg = {
181
+ "api_key": api_key,
182
+ "api_url": final_url,
183
+ "model": final_model,
184
+ "headers": headers,
185
+ }
186
+ else:
187
+ # llmBridge 应该在调用前就确保传入了 api_key,这里不负责查找
188
+ raise ValueError("stream_chat 需要 api_key 参数,但未收到")
189
+
190
+ api_url = cfg["api_url"]
191
+ headers = cfg["headers"]
192
+ model = cfg["model"]
193
+
194
+ # 构建请求体
195
+ body = {
196
+ "model": model,
197
+ "messages": messages,
198
+ "stream": True,
199
+ }
200
+
201
+ # 添加额外的采样参数
202
+ if sampling_params:
203
+ body.update(sampling_params)
204
+
205
+ # 针对某些供应商的特殊参数(如深度思考)
206
+ if provider == "deepseek" and deep_think:
207
+ body["deep_think"] = True
208
+
209
+ # 百度文心一言:使用 Access Token 鉴权,需要特殊处理
210
+ if provider == "baidu":
211
+ return _baidu_stream_chat(cfg, messages, stop_event)
212
+
213
+ # 讯飞星火:使用 WebSocket 协议,暂不实现流式,返回空
214
+ if provider == "spark":
215
+ raise NotImplementedError("讯飞星火暂不支持自动流式调用")
216
+
217
+ # 发送请求
218
+ try:
219
+ resp = requests.post(
220
+ api_url,
221
+ headers=headers,
222
+ json=body,
223
+ stream=True,
224
+ timeout=30,
225
+ )
226
+ resp.raise_for_status()
227
+
228
+ # 解析 SSE 流,手动处理字节以强制 UTF-8 编码
229
+ for line in resp.iter_lines():
230
+ if stop_event and stop_event.is_set():
231
+ break
232
+ if not line:
233
+ continue
234
+
235
+ # 强制 UTF-8 解码,避免服务器响应头错误编码导致中文乱码
236
+ try:
237
+ decoded_line = line.decode('utf-8')
238
+ except UnicodeDecodeError:
239
+ continue
240
+
241
+ if decoded_line.startswith(":"):
242
+ continue
243
+ if decoded_line.startswith("data: "):
244
+ data_str = decoded_line[6:]
245
+ if data_str.strip() == "[DONE]":
246
+ break
247
+ try:
248
+ data = json.loads(data_str)
249
+ delta = data.get("choices", [{}])[0].get("delta", {})
250
+ content = delta.get("content", "")
251
+ if content:
252
+ yield content
253
+ except (json.JSONDecodeError, KeyError, IndexError):
254
+ continue
255
+
256
+ except requests.exceptions.RequestException as e:
257
+ raise RuntimeError(f"API 请求失败: {e}") from e
258
+
259
+
260
+ def _baidu_stream_chat(cfg: dict, messages: list, stop_event=None) -> Generator[str, None, None]:
261
+ """百度文心一言的特殊流式调用 (需要先获取 access_token)"""
262
+ # 百度 API Key 和 Secret Key 需从环境变量中获取
263
+ api_key = cfg["api_key"] # 这其实是 API Key
264
+ secret_key = os.getenv("BAIDU_SECRET_KEY")
265
+ if not secret_key:
266
+ raise ValueError("百度 API 需要同时设置 BAIDU_API_KEY 和 BAIDU_SECRET_KEY")
267
+
268
+ # 获取 access_token
269
+ token_url = "https://aip.baidubce.com/oauth/2.0/token"
270
+ params = {
271
+ "grant_type": "client_credentials",
272
+ "client_id": api_key,
273
+ "client_secret": secret_key,
274
+ }
275
+ r = requests.get(token_url, params=params)
276
+ r.raise_for_status()
277
+ access_token = r.json().get("access_token")
278
+ if not access_token:
279
+ raise ValueError("获取百度 access_token 失败")
280
+
281
+ # 实际的聊天接口 URL
282
+ api_url = cfg.get("api_url") or f"https://aip.baidubce.com/rpc/2.0/ai_custom/v1/wenxinworkshop/chat/completions?access_token={access_token}"
283
+ headers = {"Content-Type": "application/json"}
284
+ body = {
285
+ "messages": messages,
286
+ "stream": True,
287
+ }
288
+ # 模型由 URL 或参数指定,此处简化,使用默认 URL 中已包含模型路径
289
+ # 如果用户指定了 BAIDU_API_URL,则直接使用
290
+
291
+ resp = requests.post(api_url, headers=headers, json=body, stream=True, timeout=30)
292
+ resp.raise_for_status()
293
+
294
+ for line in resp.iter_lines(decode_unicode=True):
295
+ if stop_event and stop_event.is_set():
296
+ break
297
+ if not line or line.startswith(":"):
298
+ continue
299
+ if line.startswith("data: "):
300
+ data_str = line[6:]
301
+ try:
302
+ data = json.loads(data_str)
303
+ # 百度返回格式可能不同,需要适配
304
+ result = data.get("result", "")
305
+ if result:
306
+ yield result
307
+ except json.JSONDecodeError:
308
+ continue
@@ -0,0 +1,198 @@
1
+ """
2
+ femoCompiler/FEMO_CLIrenderer.py — 终端美化输出模块
3
+ ===================================
4
+ 为 FEMO 运行时提供统一的命令行打印接口。
5
+ 通过事件回调机制集成,与运行时核心逻辑解耦。
6
+ """
7
+
8
+ import os
9
+ import sys
10
+ import time
11
+ from typing import Any, Dict, Optional
12
+
13
+
14
+ class CLIRenderer:
15
+ """命令行渲染器,负责所有终端输出的格式和时机"""
16
+
17
+ def __init__(self, verbose: bool = False):
18
+ self.verbose = verbose
19
+ self._streaming = False # 是否正在流式输出 AI 回答
20
+ self._current_node_name = "" # 当前节点名,用于流式输出前缀
21
+ self._context_shown = False # 标记是否已经展示过首次上下文
22
+
23
+ # ── 事件分发入口 ──
24
+ def handle_event(self, event_type: str, data: Dict[str, Any]):
25
+ """FEMORunner 通过 event_callback 调用此方法"""
26
+ method = getattr(self, f"on_{event_type}", None)
27
+ if method:
28
+ try:
29
+ method(data)
30
+ except Exception as e:
31
+ print(f"\n[CLI_renderer] ⚠️ 渲染事件 '{event_type}' 时出错: {e}")
32
+
33
+ # ── 具体事件处理 ──
34
+ def on_flow_start(self, data: dict):
35
+ entry = data.get("entry", "?")
36
+ max_steps = data.get("max_steps", 0)
37
+ print()
38
+ print("=" * 60)
39
+ print("🚀 开始执行 Flow")
40
+ print(f" 入口: {entry}")
41
+ if max_steps:
42
+ print(f" 最大步数: {max_steps}")
43
+ print("=" * 60)
44
+ self._context_shown = False # 每次新流程开始时重置上下文显示标记
45
+
46
+ def on_step(self, data: dict):
47
+ step_no = data.get("step", 0)
48
+ prev = data.get("prev_node", "?")
49
+ current = data.get("current_node", "?")
50
+ kind = data.get("kind", "?")
51
+ print(f"\n📍 Step {step_no}: [{prev}] → [{current}] ({kind})")
52
+
53
+ def on_node_start(self, data: dict):
54
+ node_name = data.get("node_name", "")
55
+ node_type = data.get("node_type", "")
56
+ prompt = data.get("prompt", "")
57
+ self._current_node_name = node_name
58
+
59
+ print(f"{'─' * 40}")
60
+ if node_type == "ai":
61
+ print(f"🤖 AI 节点: {node_name}")
62
+ if prompt and self.verbose:
63
+ print(f" Prompt: {prompt[:100]}{'...' if len(prompt)>100 else ''}")
64
+ elif node_type == "human":
65
+ print(f"👤 人类节点: {node_name}")
66
+ elif node_type == "func":
67
+ print(f"🔧 函数节点: {node_name}")
68
+ elif node_type == "assign":
69
+ print(f"📝 赋值节点: {node_name}")
70
+ else:
71
+ print(f"⚡ 节点: {node_name} ({node_type})")
72
+
73
+ def on_context_ready(self, data: dict):
74
+ length = data.get("length", 0)
75
+ if self.verbose:
76
+ print(f" 📖 上下文: {length} 条记录")
77
+
78
+ def on_memory_ready(self, data: dict):
79
+ length = data.get("length", 0)
80
+ if self.verbose:
81
+ print(f" 🧠 记忆: {length} 条记录")
82
+
83
+ def on_ai_token(self, data: dict):
84
+ token = data.get("token", "")
85
+ if not self._streaming:
86
+ print()
87
+ if self._current_node_name:
88
+ print(f"[{self._current_node_name}]:")
89
+ self._streaming = True
90
+ # 处理可能存在的转义换行,使其真正换行
91
+ token = token.replace('\\n', '\n')
92
+ sys.stdout.write(token)
93
+ sys.stdout.flush()
94
+
95
+ def on_ai_response(self, data: dict):
96
+ """非流式时的完整回复(备用)"""
97
+ response = data.get("output", "")
98
+ if not self._streaming:
99
+ print()
100
+ if self._current_node_name:
101
+ print(f"[{self._current_node_name}]:")
102
+ print(response)
103
+ else:
104
+ # 流式已经在 on_ai_token 输出完毕,这里只收尾
105
+ print() # 结束换行
106
+ self._streaming = False
107
+
108
+ def on_human_wait(self, data: dict):
109
+ prompt = data.get("prompt", "")
110
+ context = data.get("context", "")
111
+
112
+ # 只在第一次遇到人类节点时展示完整上下文
113
+ if not self._context_shown and context:
114
+ print()
115
+ print("=" * 60)
116
+ print("📖 首次进入 — 当前对话上下文:")
117
+ print(context)
118
+ print("=" * 60)
119
+ self._context_shown = True
120
+
121
+ if prompt:
122
+ print(f"\n💬 {prompt}")
123
+
124
+ def on_func_result(self, data: dict):
125
+ if self.verbose:
126
+ print(f" ✅ 函数完成: {data.get('node_name', '')}")
127
+ output = data.get('output', '')
128
+ if output:
129
+ print(f" 结果: {output}")
130
+
131
+ def on_assign_result(self, data: dict):
132
+ if self.verbose:
133
+ print(f" ✅ 赋值完成: {data.get('node_name', '')}")
134
+ output = data.get('output', '')
135
+ if output:
136
+ print(f" 结果: {output}")
137
+
138
+ def on_flow_done(self, data: dict):
139
+ total_steps = data.get("total_steps", 0)
140
+ duration = data.get("duration", 0)
141
+ print()
142
+ print("=" * 60)
143
+ print("🏁 Flow 执行结束")
144
+ if total_steps:
145
+ print(f" 共执行 {total_steps} 个节点")
146
+ if duration:
147
+ print(f" 耗时 {duration:.1f} 秒")
148
+ print("=" * 60)
149
+
150
+ def on_flow_error(self, data: dict):
151
+ error = data.get("error", "未知错误")
152
+ print(f"\n❌ 运行错误: {error}")
153
+
154
+ def on_error(self, data: dict):
155
+ print(f"\n❌ 错误: {data.get('message', '')}")
156
+
157
+ # ── 特殊交互:清屏并显示上下文(用于 /godview 和 /@actor) ──
158
+ def clear_and_show_context(self, title: str, context: str):
159
+ """清屏,打印标题和完整上下文,然后恢复输入区域"""
160
+ os.system('clear' if os.name != 'nt' else 'cls')
161
+ print(f"\n{'=' * 60}")
162
+ print(f"👁️ {title}")
163
+ print(f"{'=' * 60}")
164
+ if context:
165
+ print(context)
166
+ else:
167
+ print("(暂无可见对话记录)")
168
+ print(f"{'=' * 60}")
169
+ print("(继续输入内容,或输入 /end 结束)")
170
+ self._context_shown = True # 手动切换视角后视为已展示上下文,避免紧接着的人类节点再重复显示
171
+
172
+ # ── 流式输出结束后的收尾 ──
173
+ def finish_stream(self):
174
+ if self._streaming:
175
+ print()
176
+ self._streaming = False
177
+
178
+
179
+ # ── 辅助函数:将旧的 print 迁移到事件 ──
180
+ def emit_step(runner, step_no, prev_node, current_node, kind):
181
+ """在 _execute_flow 的循环中调用,替代原来的 print"""
182
+ if runner._event_callback:
183
+ runner._event_callback('step', {
184
+ 'step': step_no,
185
+ 'prev_node': prev_node,
186
+ 'current_node': current_node,
187
+ 'kind': kind,
188
+ })
189
+
190
+
191
+ def emit_context_ready(runner, length):
192
+ if runner._event_callback:
193
+ runner._event_callback('context_ready', {'length': length})
194
+
195
+
196
+ def emit_memory_ready(runner, length):
197
+ if runner._event_callback:
198
+ runner._event_callback('memory_ready', {'length': length})
@@ -0,0 +1,35 @@
1
+ """
2
+ FEMO_config.py — 全局运行时配置(单例)
3
+ =====================================
4
+ 统一管理数据库路径等配置。
5
+ 由 FEMO 解释器在解析 meta 后调用 set_db_path() 设置,
6
+ 其他模块调用 get_db_path() 读取。
7
+
8
+ 代码原则:所有代码不许写try静默兜底不报错,有错必须报错。
9
+ """
10
+
11
+ import os
12
+
13
+ _db_path: str = ""
14
+
15
+
16
+ def set_db_path(path: str):
17
+ """设置数据库文件路径(通常由解释器调用)"""
18
+ global _db_path
19
+ _db_path = path
20
+ print(f"[config] 📁 数据库路径已设置为: {_db_path}")
21
+
22
+
23
+ def get_db_path() -> str:
24
+ """获取数据库文件路径,未设置时返回默认值"""
25
+ global _db_path
26
+ if not _db_path:
27
+ from femoBridges.getDir.get_dir import get_user_dir
28
+ user_dir = get_user_dir()
29
+ _db_path = os.path.join(user_dir, "user_data", "memory", "Chronica.wor")
30
+ print(f"[config] ⚠️ 未设置数据库路径,使用默认值: {_db_path}")
31
+ # 如果是相对路径,基于 user_dir 解析
32
+ if not os.path.isabs(_db_path):
33
+ from femoBridges.getDir.get_dir import get_user_dir
34
+ _db_path = os.path.join(get_user_dir(), _db_path)
35
+ return _db_path