-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstart_web.py
More file actions
303 lines (260 loc) · 9.12 KB
/
Copy pathstart_web.py
File metadata and controls
303 lines (260 loc) · 9.12 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
"""
DeepAgent Web 应用一键启动脚本
同时启动后端和前端服务
"""
import subprocess
import sys
import os
import shutil
import time
import threading
import signal
def _stream_process_output(process, prefix):
"""Forward a child process' combined output without assuming console encoding."""
try:
for line in process.stdout:
if line:
if isinstance(line, bytes):
line = line.decode("utf-8", errors="replace")
print(f"[{prefix}] {line.rstrip()}")
except Exception:
pass
def _project_executable(project_root, executable_name):
"""Resolve an executable from the active environment, project venv, or PATH."""
executable_file = executable_name + (".exe" if os.name == "nt" else "")
active_environment = os.path.join(os.path.dirname(sys.executable), executable_file)
project_environment = os.path.join(
project_root,
".venv",
"Scripts" if os.name == "nt" else "bin",
executable_file,
)
for candidate in (project_environment, active_environment, shutil.which(executable_name)):
if candidate and os.path.isfile(candidate):
return candidate
raise FileNotFoundError(
f"Required executable '{executable_name}' was not found. "
"Run 'uv sync' first, then start with 'uv run python start_web.py'."
)
def run_async_agent():
"""启动供 AsyncSubAgent 调用的本地 Agent Protocol 服务。"""
project_root = os.path.dirname(os.path.abspath(__file__))
langgraph_exe = _project_executable(project_root, "langgraph")
env = os.environ.copy()
env["PYTHONUTF8"] = "1"
env["PYTHONPATH"] = os.path.join(project_root, "src") + os.pathsep + env.get("PYTHONPATH", "")
print("[AsyncAgent] Starting Agent Protocol service at http://127.0.0.1:2024")
process = subprocess.Popen(
[langgraph_exe, "dev", "--host", "127.0.0.1", "--port", "2024",
"--no-browser", "--no-reload", "--allow-blocking"],
cwd=project_root,
env=env,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
bufsize=1,
text=True,
encoding="utf-8",
errors="replace",
)
threading.Thread(
target=_stream_process_output, args=(process, "AsyncAgent"), daemon=True
).start()
return process
def check_service_ready(url, process=None, max_wait=180, label="service"):
"""Wait for an HTTP service and fail early if its process exits."""
import urllib.request
start_time = time.time()
while time.time() - start_time < max_wait:
if process is not None and process.poll() is not None:
print(f"[ERROR] {label} exited with code {process.returncode}")
return False
try:
with urllib.request.urlopen(url, timeout=5) as response:
if 200 <= response.status < 500:
print(f"[System] {label} is ready")
return True
except Exception:
pass
time.sleep(2)
print(f"[ERROR] {label} failed to start within {max_wait} seconds")
return False
def run_backend():
"""启动后端服务"""
print("[Backend] Starting FastAPI service...")
print("[Backend] Using uvicorn at http://127.0.0.1:8090")
project_root = os.path.dirname(os.path.abspath(__file__))
src_dir = os.path.join(project_root, "src")
project_python = _project_executable(project_root, "python")
env = os.environ.copy()
env["PYTHONUTF8"] = "1"
env["PYTHONPATH"] = src_dir + os.pathsep + env.get("PYTHONPATH", "")
backend_proc = subprocess.Popen(
[project_python, "-m", "uvicorn", "api_view.web_main:app",
"--host", "127.0.0.1", "--port", "8090"],
cwd=project_root,
env=env,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
bufsize=1,
text=True,
encoding="utf-8",
errors="replace",
)
# 实时输出后端日志
def output_backend():
try:
for line in backend_proc.stdout:
if line:
print(f"[Backend] {line.rstrip()}")
except Exception:
pass
t = threading.Thread(target=output_backend, daemon=True)
t.start()
return backend_proc
def check_backend_ready(max_wait=180):
"""检查后端是否就绪"""
print("[System] Waiting for backend to be ready...")
start_time = time.time()
while time.time() - start_time < max_wait:
try:
import urllib.request
req = urllib.request.Request("http://127.0.0.1:8090/health")
response = urllib.request.urlopen(req, timeout=5)
if response.status == 200:
data = response.read().decode('utf-8')
if 'healthy' in data:
print("[System] Backend is ready!")
return True
except:
pass
time.sleep(2)
elapsed = int(time.time() - start_time)
print(f"[System] Waiting... ({elapsed}s / {max_wait}s)")
return False
def run_frontend():
"""启动前端服务"""
frontend_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)), "frontend")
# 检查 node_modules 是否存在
if not os.path.exists(os.path.join(frontend_dir, "node_modules")):
print("[Frontend] Installing dependencies...")
result = subprocess.run(
"npm install",
cwd=frontend_dir,
shell=True,
capture_output=True,
text=True
)
if result.returncode != 0:
print("[Frontend] Dependency installation failed:")
print(result.stderr)
return None
print("[Frontend] Dependencies installed")
print("[Frontend] Starting Vue dev server...")
print("[Frontend] Using Vite at http://127.0.0.1:3000")
frontend_proc = subprocess.Popen(
"npm run dev",
cwd=frontend_dir,
shell=True,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
bufsize=1,
text=True,
encoding="utf-8",
errors="replace",
)
# 实时输出前端日志
def output_frontend():
try:
for line in frontend_proc.stdout:
if line:
print(f"[Frontend] {line.rstrip()}")
except Exception:
pass
t = threading.Thread(target=output_frontend, daemon=True)
t.start()
return frontend_proc
def main():
print("=" * 60)
print(" DeepAgent Web Application Launcher")
print("=" * 60)
print()
print("NOTE: Agent initialization takes 30-60 seconds")
print(" Please wait patiently for the service to be ready")
print()
async_agent_proc = None
backend_proc = None
frontend_proc = None
def cleanup():
"""清理进程"""
print("\n\n[System] Stopping services...")
if async_agent_proc:
async_agent_proc.terminate()
try:
async_agent_proc.wait(timeout=5)
except Exception:
async_agent_proc.kill()
if backend_proc:
backend_proc.terminate()
try:
backend_proc.wait(timeout=5)
except:
backend_proc.kill()
if frontend_proc:
frontend_proc.terminate()
try:
frontend_proc.wait(timeout=5)
except:
frontend_proc.kill()
print("[System] All services stopped")
# 注册信号处理
def signal_handler(sig, frame):
cleanup()
sys.exit(0)
try:
signal.signal(signal.SIGINT, signal_handler)
signal.signal(signal.SIGTERM, signal_handler)
except:
pass # Windows 不支持某些信号
try:
# 异步分析子 Agent 必须先于 Web 后端就绪。
async_agent_proc = run_async_agent()
if not check_service_ready(
"http://127.0.0.1:2024/ok",
process=async_agent_proc,
max_wait=180,
label="Async Agent Protocol",
):
cleanup()
return
# 启动后端
backend_proc = run_backend()
# 等待后端就绪(包括 Agent 初始化)
if not check_backend_ready(max_wait=180):
print("[ERROR] Backend failed to start within 180 seconds")
print("[ERROR] Please check the logs above for errors")
cleanup()
return
# 启动前端
frontend_proc = run_frontend()
print()
print("=" * 60)
print(" All services started successfully!")
print("=" * 60)
print()
print(" Please access:")
print(" - Frontend: http://127.0.0.1:3000")
print(" - API docs: http://127.0.0.1:8090/docs")
print(" - Async Agent Protocol: http://127.0.0.1:2024/docs")
print()
print(" Press Ctrl+C to stop all services")
print("=" * 60)
# 等待
while True:
time.sleep(1)
except KeyboardInterrupt:
cleanup()
except Exception as e:
print(f"[ERROR] An error occurred: {e}")
cleanup()
if __name__ == "__main__":
main()