getzero11 commited on
Commit
31d651e
·
verified ·
1 Parent(s): 52b8088

Update server.js

Browse files
Files changed (1) hide show
  1. server.js +80 -79
server.js CHANGED
@@ -1,24 +1,32 @@
1
  import express from "express";
2
- import { spawn } from "child_process";
3
  import dotenv from "dotenv";
4
 
5
  console.log('OpenClaw HF Space: Starting server...');
6
 
7
- try {
8
- dotenv.config();
9
- console.log('Environment loaded');
10
- } catch (err) {
11
- console.error('Failed to load environment:', err.message);
12
- }
13
 
14
  const app = express();
15
  app.use(express.json());
16
 
17
- // Simple health check
 
 
 
 
 
 
 
 
 
18
  app.get("/", (req, res) => {
19
  res.json({
20
  status: "OpenClaw HF Space Running",
21
- endpoint: "POST /api/market-research",
 
 
 
22
  timestamp: new Date().toISOString()
23
  });
24
  });
@@ -31,14 +39,11 @@ app.get("/health", (req, res) => {
31
  });
32
  });
33
 
34
- // Market research endpoint
35
- app.post("/api/market-research", async (req, res) => {
36
- console.log('Market research request:', {
37
- keyword: req.body.keyword,
38
- timestamp: new Date().toISOString()
39
- });
40
 
41
- const { keyword, api_key, provider = "deepseek" } = req.body;
42
 
43
  if (!keyword) {
44
  return res.status(400).json({ error: "keyword is required" });
@@ -51,75 +56,71 @@ app.post("/api/market-research", async (req, res) => {
51
  });
52
  }
53
 
54
- const env = {
55
- ...process.env,
56
- OPENCLAW_PROVIDER: provider,
57
- OPENCLAW_API_KEY: api_key,
58
- OPENCLAW_TASK: "market_research",
59
- OPENCLAW_TIMEOUT: "180000"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
60
  };
61
 
62
- try {
63
- console.log(`Calling OpenClaw agent with provider: ${provider}`);
64
- const result = await runOpenClaw(env, { keyword });
65
- console.log('OpenClaw agent succeeded');
66
- return res.json(result);
67
- } catch (err) {
68
- console.error('OpenClaw agent failed:', err.message);
69
- return res.status(500).json({
70
- error: "OpenClaw agent failed",
71
- details: err.message,
72
- keyword: keyword,
73
- timestamp: new Date().toISOString()
74
- });
75
- }
76
  });
77
 
78
- function runOpenClaw(env, payload) {
79
- return new Promise((resolve, reject) => {
80
- const proc = spawn(process.execPath, ["src/index.js"], {
81
- cwd: process.cwd(),
82
- env
83
- });
84
-
85
- let stdout = "";
86
- let stderr = "";
87
-
88
- proc.on("error", err => {
89
- console.error('Spawn error:', err);
90
- reject(err);
91
- });
92
-
93
- proc.stdout.on("data", data => {
94
- stdout += data.toString();
95
- });
96
 
97
- proc.stderr.on("data", data => {
98
- stderr += data.toString();
99
- });
100
 
101
- proc.on("close", code => {
102
- if (code !== 0) {
103
- console.error('Agent exited with code:', code, 'stderr:', stderr);
104
- return reject(new Error(`Agent failed: ${stderr || code}`));
105
- }
106
 
107
- try {
108
- const json = JSON.parse(stdout);
109
- resolve(json);
110
- } catch (err) {
111
- console.error('JSON parse error:', err.message);
112
- console.error('Raw output (first 500 chars):', stdout.substring(0, 500));
113
- reject(new Error("Invalid JSON from agent"));
114
- }
115
- });
116
 
117
- proc.stdin.write(JSON.stringify(payload));
118
- proc.stdin.end();
 
 
 
119
  });
120
- }
121
-
122
- const PORT = process.env.PORT || 7860;
123
- app.listen(PORT, "0.0.0.0", () => {
124
- console.log(`🚀 Server running on port ${PORT}`);
125
- });
 
1
  import express from "express";
 
2
  import dotenv from "dotenv";
3
 
4
  console.log('OpenClaw HF Space: Starting server...');
5
 
6
+ // Load environment
7
+ dotenv.config();
8
+ console.log('Environment loaded, PORT:', process.env.PORT);
 
 
 
9
 
10
  const app = express();
11
  app.use(express.json());
12
 
13
+ // Handle JSON parsing errors
14
+ app.use((err, req, res, next) => {
15
+ if (err instanceof SyntaxError && err.status === 400 && 'body' in err) {
16
+ console.error('JSON parsing error:', err.message);
17
+ return res.status(400).json({ error: "Invalid JSON" });
18
+ }
19
+ next();
20
+ });
21
+
22
+ // Simple endpoints
23
  app.get("/", (req, res) => {
24
  res.json({
25
  status: "OpenClaw HF Space Running",
26
+ endpoints: {
27
+ health: "GET /health",
28
+ market_research: "POST /api/market-research"
29
+ },
30
  timestamp: new Date().toISOString()
31
  });
32
  });
 
39
  });
40
  });
41
 
42
+ // Market research endpoint - SIMPLIFIED
43
+ app.post("/api/market-research", (req, res) => {
44
+ console.log('Received market research request');
 
 
 
45
 
46
+ const { keyword, api_key } = req.body || {};
47
 
48
  if (!keyword) {
49
  return res.status(400).json({ error: "keyword is required" });
 
56
  });
57
  }
58
 
59
+ console.log('Processing keyword:', keyword, 'with API key (first 10 chars):', api_key.substring(0, 10));
60
+
61
+ // Return mock response for testing
62
+ const mockResponse = {
63
+ marketTitle: `Global ${keyword} Market Analysis`,
64
+ marketOverview: {
65
+ pastYear_2023: 10.5,
66
+ currentYear_2025: 15.2,
67
+ forecastYear_2033: 28.7,
68
+ global_cagr_Forecast: 12.5
69
+ },
70
+ marketSegments: [
71
+ {
72
+ segment: "Primary Segment",
73
+ segment_marketShare_2023: "35%",
74
+ segment_marketShare_2025: "38%",
75
+ segment_marketShare_2033: "42%",
76
+ segment_cagr: "12%"
77
+ }
78
+ ],
79
+ competitiveLandscape: [
80
+ {
81
+ company: "Leading Company",
82
+ player_marketShare_2025: 25
83
+ }
84
+ ],
85
+ status: "success",
86
+ message: "Mock data for testing - OpenClaw agent is running!"
87
  };
88
 
89
+ console.log('Returning mock response');
90
+ res.json(mockResponse);
 
 
 
 
 
 
 
 
 
 
 
 
91
  });
92
 
93
+ // Error handling middleware
94
+ app.use((err, req, res, next) => {
95
+ console.error('Server error:', err.message);
96
+ res.status(500).json({
97
+ error: "Internal server error",
98
+ message: err.message
99
+ });
100
+ });
 
 
 
 
 
 
 
 
 
 
101
 
102
+ // Start server
103
+ const PORT = process.env.PORT || 7860;
104
+ console.log('Starting server on port:', PORT);
105
 
106
+ // Global error handlers to prevent crashes
107
+ process.on('uncaughtException', (error) => {
108
+ console.error('Uncaught Exception:', error.message);
109
+ console.error('Stack:', error.stack);
110
+ });
111
 
112
+ process.on('unhandledRejection', (reason, promise) => {
113
+ console.error('Unhandled Rejection at:', promise);
114
+ console.error('Reason:', reason);
115
+ });
 
 
 
 
 
116
 
117
+ try {
118
+ app.listen(PORT, "0.0.0.0", () => {
119
+ console.log(`✅ Server successfully running on port ${PORT}`);
120
+ console.log(`✅ Health endpoint: GET /health`);
121
+ console.log(`✅ API endpoint: POST /api/market-research`);
122
  });
123
+ } catch (error) {
124
+ console.error('❌ Failed to start server:', error.message);
125
+ process.exit(1);
126
+ }