getzero11 commited on
Commit
af868db
·
verified ·
1 Parent(s): 58a0ee6

Update src/marketResearchAgent.js

Browse files
Files changed (1) hide show
  1. src/marketResearchAgent.js +120 -185
src/marketResearchAgent.js CHANGED
@@ -10,169 +10,179 @@ export async function marketResearchAgent({ input, provider, model }) {
10
  throw new Error("keyword is required");
11
  }
12
 
13
- const keyword = normalizeKeyword(input.keyword);
14
- const normalizedTitle = `Global ${keyword} Market and Forecast 2026–2033`;
15
 
16
  /* =======================================================
17
- 1. MARKET SIZE BASELINE (light heuristic)
18
  ======================================================= */
19
 
20
- const baseMarket2023 = randomFloat(0.8, 6.0);
21
- const cagr = randomFloat(9, 23);
22
- const market2025 = round(baseMarket2023 * Math.pow(1 + cagr / 100, 2));
23
- const market2033 = round(baseMarket2023 * Math.pow(1 + cagr / 100, 10));
 
 
 
 
24
 
25
  /* =======================================================
26
- 2. SINGLE AI STRUCTURED RESEARCH CALL (CORE)
27
  ======================================================= */
28
 
29
  const researchPrompt = `
30
- You are a senior healthcare market research consultant.
31
 
32
- Market: ${keyword}
 
33
 
34
- Return STRICT JSON ONLY using the schema below.
35
- Do NOT include explanations, markdown, or extra text.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
36
 
37
  {
38
- "competitive": [
39
- { "company": "Exact Company Name", "share": number }
40
- ],
41
- "segments": [
42
  {
43
- "segment": "Segment name",
 
44
  "subSegments": [
45
- { "name": "Subsegment", "share2025": number, "cagr": number }
46
- ]
 
 
 
 
 
 
 
47
  }
48
  ],
49
- "drivers": [
50
- { "driver": "Market driver", "impact": number }
51
- ],
 
52
  "insights": {
53
  "largestSegment2025": "string",
54
  "fastestGrowingSegment": "string",
55
  "keyOpportunities": ["string"],
56
  "majorChallenges": ["string"]
57
  },
58
- "emergingTrends": ["string"],
59
- "executiveOverview": "string",
60
- "futureOutlook": "string"
 
 
 
 
 
 
 
 
 
 
61
  }
62
 
63
- RULES:
64
- - Use REAL, well-known companies only
65
- - No placeholders like Company A / Leading Player
 
66
  - Percentages as numbers only
67
- - Competitive share total 60–70
68
- - Use realistic healthcare market logic
 
69
  `;
70
 
71
- let ai = {};
72
 
73
  try {
74
  const raw = await callLLM({ provider, model, prompt: researchPrompt });
75
- const parsed = extractJsonObject(raw);
76
-
77
- validateAI(parsed);
78
- ai = parsed;
79
-
80
  } catch {
81
- ai = {};
82
  }
83
 
84
  /* =======================================================
85
- 3. DASHBOARD VIEW (AI-FIRST, SAFE FALLBACK)
86
  ======================================================= */
87
 
88
  const dashboard_view = {
89
  marketTitle: normalizedTitle,
90
 
91
  marketSummary: {
92
- past2023: baseMarket2023,
93
- current2025: market2025,
94
- forecast2033: market2033,
95
- cagr
96
  },
97
 
98
  forecast: [
99
- { year: "2023", value: baseMarket2023 },
100
- { year: "2025", value: market2025 },
101
- { year: "2033", value: market2033 }
102
  ],
103
 
104
- regional: defaultRegions(),
105
 
106
- competitive: ai.competitive ?? fallbackCompetitive(keyword),
 
 
 
107
 
108
- segments: ai.segments ?? fallbackSegments(),
109
 
110
- drivers: ai.drivers ?? fallbackDrivers(),
 
 
 
111
 
112
- insights: ai.insights ?? fallbackInsights(),
113
-
114
- citation: "iHealthcareAnalyst, Inc. AI-Assisted Market Modeling",
115
  citationUrl: "https://www.ihealthcareanalyst.com"
116
  };
117
 
118
  /* =======================================================
119
- 4. REPORT VIEW (CONSULTING-GRADE)
120
  ======================================================= */
121
 
122
  const report_view = {
123
- marketTitle: keyword,
 
 
 
 
 
 
 
 
124
 
125
- marketSizing: {
126
- pastYear_2023: baseMarket2023,
127
- currentYear_2025: market2025,
128
- forecastYear_2033: market2033,
129
- global_cagr_Forecast: cagr
 
 
 
 
130
  },
131
 
132
- executiveOverview:
133
- ai.executiveOverview ??
134
- `The ${keyword} market is undergoing sustained expansion driven by technological innovation, increasing healthcare demand, and broader adoption across global regions.`,
135
-
136
- marketSegments:
137
- (ai.segments ?? fallbackSegments()).map(s => ({
138
- segmentName: s.segment,
139
- subSegments: s.subSegments.map(ss => ({
140
- subSegmentName: ss.name,
141
- segmet_marketShare_2023: round(ss.share2025 - 5),
142
- segment_marketShare_2025: ss.share2025,
143
- segment_marketShare_2033: round(ss.share2025 + 5),
144
- segmentName_cagr_Forecast: ss.cagr
145
- }))
146
- })),
147
-
148
- marketDrivers:
149
- (ai.drivers ?? fallbackDrivers()).map(d => d.driver),
150
-
151
- emergingTrends:
152
- ai.emergingTrends ?? fallbackTrends(),
153
-
154
- competitiveLandscape:
155
- (ai.competitive ?? fallbackCompetitive(keyword)).map(c => ({
156
- company: c.company,
157
- player_markerShare_2025: c.share,
158
- positioning: "Established global healthcare market participant"
159
- })),
160
-
161
- regulatoryEnvironment:
162
- "The market is governed by stringent regulatory frameworks focused on patient safety, clinical validation, and data protection compliance.",
163
-
164
- geographicAnalysis:
165
- "North America currently leads market adoption, while Asia-Pacific is projected to register the fastest growth due to expanding healthcare infrastructure and investment.",
166
-
167
- futureOutlook:
168
- ai.futureOutlook ??
169
- "The market is expected to demonstrate strong growth through 2033, supported by innovation, demographic trends, and rising healthcare expenditure.",
170
-
171
- strategicRecommendations: [
172
- "Invest in advanced and AI-enabled solutions",
173
- "Expand footprint in emerging markets",
174
- "Strengthen regulatory and compliance capabilities"
175
- ]
176
  };
177
 
178
  /* =======================================================
@@ -182,7 +192,7 @@ RULES:
182
  return {
183
  meta: {
184
  job_id: input.job_id || `job_${crypto.randomUUID()}`,
185
- keyword,
186
  normalized_title: normalizedTitle,
187
  status: "completed",
188
  timestamp: new Date().toISOString(),
@@ -196,7 +206,7 @@ RULES:
196
  }
197
 
198
  /* =========================================================
199
- VALIDATION & HELPERS
200
  ========================================================= */
201
 
202
  function extractJsonObject(text) {
@@ -213,19 +223,10 @@ function extractJsonObject(text) {
213
 
214
  function validateAI(obj) {
215
  if (!obj || typeof obj !== "object") {
216
- throw new Error("Invalid AI response");
217
  }
218
-
219
- if (obj.competitive) {
220
- obj.competitive.forEach(c => {
221
- if (
222
- !c.company ||
223
- typeof c.share !== "number" ||
224
- /company\s?[a-z]|player|leading/i.test(c.company)
225
- ) {
226
- throw new Error("Invalid competitive data");
227
- }
228
- });
229
  }
230
  }
231
 
@@ -241,72 +242,6 @@ function randomFloat(min, max) {
241
  return round(min + Math.random() * (max - min));
242
  }
243
 
244
- /* =========================================================
245
- FALLBACKS (SAFE, NEVER BREAK)
246
- ========================================================= */
247
-
248
- function fallbackCompetitive() {
249
- return [
250
- { company: "Johnson & Johnson", share: 18 },
251
- { company: "Abbott Laboratories", share: 15 },
252
- { company: "Medtronic", share: 12 },
253
- { company: "Becton Dickinson", share: 10 },
254
- { company: "Stryker Corporation", share: 8 }
255
- ];
256
- }
257
-
258
- function fallbackSegments() {
259
- return [
260
- {
261
- segment: "Core Products",
262
- subSegments: [
263
- { name: "Implants & Devices", share2025: 45, cagr: 17.2 },
264
- { name: "Digital & AI Solutions", share2025: 35, cagr: 20.1 },
265
- { name: "Associated Services", share2025: 20, cagr: 13.4 }
266
- ]
267
- }
268
- ];
269
- }
270
-
271
- function fallbackDrivers() {
272
- return [
273
- { driver: "Rising chronic disease prevalence", impact: 90 },
274
- { driver: "Technological innovation", impact: 88 },
275
- { driver: "Expanding healthcare access", impact: 85 }
276
- ];
277
- }
278
-
279
- function fallbackInsights() {
280
- return {
281
- largestSegment2025: "Core Products",
282
- fastestGrowingSegment: "Digital & AI Solutions",
283
- keyOpportunities: [
284
- "Emerging markets",
285
- "AI-driven diagnostics",
286
- "Cost-efficient care delivery"
287
- ],
288
- majorChallenges: [
289
- "Regulatory complexity",
290
- "High capital investment",
291
- "Talent shortages"
292
- ]
293
- };
294
- }
295
-
296
- function fallbackTrends() {
297
- return [
298
- "AI-assisted diagnostics",
299
- "Minimally invasive procedures",
300
- "Personalized and precision medicine"
301
- ];
302
- }
303
-
304
- function defaultRegions() {
305
- return [
306
- { region: "North America", share: 42, cagr: 14.2 },
307
- { region: "Europe", share: 28, cagr: 12.8 },
308
- { region: "Asia Pacific", share: 22, cagr: 18.6 },
309
- { region: "Latin America", share: 5, cagr: 11.3 },
310
- { region: "Middle East & Africa", share: 3, cagr: 10.9 }
311
- ];
312
  }
 
10
  throw new Error("keyword is required");
11
  }
12
 
13
+ const marketTitle = normalizeKeyword(input.keyword);
14
+ const normalizedTitle = `Global ${marketTitle} Market and Forecast 2026–2033`;
15
 
16
  /* =======================================================
17
+ 1. MARKET SIZE BASELINE (numeric anchor)
18
  ======================================================= */
19
 
20
+ const pastYear_2023 = randomFloat(0.8, 8.5);
21
+ const global_cagr_Forecast = randomFloat(6.5, 18.5);
22
+ const currentYear_2025 = round(
23
+ pastYear_2023 * Math.pow(1 + global_cagr_Forecast / 100, 2)
24
+ );
25
+ const forecastYear_2033 = round(
26
+ pastYear_2023 * Math.pow(1 + global_cagr_Forecast / 100, 10)
27
+ );
28
 
29
  /* =======================================================
30
+ 2. SINGLE AI RESEARCH PROMPT (MULTI-AXIS)
31
  ======================================================= */
32
 
33
  const researchPrompt = `
34
+ You are a senior healthcare market research analyst.
35
 
36
+ Analyze the GLOBAL market for:
37
+ "${marketTitle}"
38
 
39
+ Your task is to generate a comprehensive market research analysis
40
+ segmented by ALL RELEVANT AXES applicable to this market.
41
+
42
+ You MUST decide which of the following segment categories apply:
43
+ - Products
44
+ - Diseases / Conditions
45
+ - Treatments
46
+ - Technologies
47
+ - Applications
48
+ - End Users
49
+ - Services
50
+ - Geography
51
+
52
+ Use ONLY the categories that are relevant to this market.
53
+ Each selected category becomes a segment group.
54
+
55
+ Return STRICT JSON ONLY in the following structure:
56
 
57
  {
58
+ "executiveOverview": "string",
59
+
60
+ "marketSegments": [
 
61
  {
62
+ "segmentCategory": "Products | Diseases | Treatments | Technologies | Applications | End Users | Services | Geography",
63
+ "segmentName": "Segment name",
64
  "subSegments": [
65
+ {
66
+ "subSegmentName": "Sub-segment name",
67
+ "segmet_marketShare_2023": number,
68
+ "segment_marketShare_2025": number,
69
+ "segment_marketShare_2033": number,
70
+ "sub-segmentName_cagr_Forecast": number
71
+ }
72
+ ],
73
+ "segmentName_cagr_Forecast": number
74
  }
75
  ],
76
+
77
+ "marketDrivers": ["string"],
78
+ "emergingTrends": ["string"],
79
+
80
  "insights": {
81
  "largestSegment2025": "string",
82
  "fastestGrowingSegment": "string",
83
  "keyOpportunities": ["string"],
84
  "majorChallenges": ["string"]
85
  },
86
+
87
+ "competitiveLandscape": [
88
+ {
89
+ "company": "Exact Company Name",
90
+ "player_markerShare_2025": number,
91
+ "positioning": "string"
92
+ }
93
+ ],
94
+
95
+ "regulatoryEnvironment": "string",
96
+ "geographicAnalysis": "string",
97
+ "futureOutlook": "string",
98
+ "strategicRecommendations": ["string"]
99
  }
100
 
101
+ MANDATORY RULES:
102
+ - Use REAL healthcare terminology
103
+ - Segments must reflect clinical, product, or operational reality
104
+ - Do NOT use generic placeholders (e.g. Core Products)
105
  - Percentages as numbers only
106
+ - Competitive players must be real companies
107
+ - Market shares must be realistic and internally consistent
108
+ - No markdown, no explanations, JSON only
109
  `;
110
 
111
+ let ai;
112
 
113
  try {
114
  const raw = await callLLM({ provider, model, prompt: researchPrompt });
115
+ ai = extractJsonObject(raw);
116
+ validateAI(ai);
 
 
 
117
  } catch {
118
+ ai = null;
119
  }
120
 
121
  /* =======================================================
122
+ 3. DASHBOARD VIEW (INFOGRAPHIC-READY)
123
  ======================================================= */
124
 
125
  const dashboard_view = {
126
  marketTitle: normalizedTitle,
127
 
128
  marketSummary: {
129
+ past2023: pastYear_2023,
130
+ current2025: currentYear_2025,
131
+ forecast2033: forecastYear_2033,
132
+ cagr: global_cagr_Forecast
133
  },
134
 
135
  forecast: [
136
+ { year: "2023", value: pastYear_2023 },
137
+ { year: "2025", value: currentYear_2025 },
138
+ { year: "2033", value: forecastYear_2033 }
139
  ],
140
 
141
+ marketSegments: ai?.marketSegments ?? [],
142
 
143
+ drivers: (ai?.marketDrivers ?? []).map(d => ({
144
+ driver: d,
145
+ impact: randomInt(70, 95)
146
+ })),
147
 
148
+ insights: ai?.insights ?? {},
149
 
150
+ competitive: (ai?.competitiveLandscape ?? []).map(c => ({
151
+ company: c.company,
152
+ share: c.player_markerShare_2025
153
+ })),
154
 
155
+ citation: "AI-Assisted Healthcare Market Analysis",
 
 
156
  citationUrl: "https://www.ihealthcareanalyst.com"
157
  };
158
 
159
  /* =======================================================
160
+ 4. REPORT VIEW (PDF-READY)
161
  ======================================================= */
162
 
163
  const report_view = {
164
+ marketTitle,
165
+
166
+ marketOverview: {
167
+ executiveOverview: ai?.executiveOverview ?? "",
168
+ pastYear_2023,
169
+ currentYear_2025,
170
+ forecastYear_2033,
171
+ global_cagr_Forecast
172
+ },
173
 
174
+ marketSegments: ai?.marketSegments ?? [],
175
+
176
+ marketDynamics: {
177
+ marketDrivers: ai?.marketDrivers ?? [],
178
+ emergingTrends: ai?.emergingTrends ?? [],
179
+ regulatoryEnvironment: ai?.regulatoryEnvironment ?? "",
180
+ geographicAnalysis: ai?.geographicAnalysis ?? "",
181
+ futureOutlook: ai?.futureOutlook ?? "",
182
+ strategicRecommendations: ai?.strategicRecommendations ?? []
183
  },
184
 
185
+ competitiveLandscape: ai?.competitiveLandscape ?? []
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
186
  };
187
 
188
  /* =======================================================
 
192
  return {
193
  meta: {
194
  job_id: input.job_id || `job_${crypto.randomUUID()}`,
195
+ keyword: marketTitle,
196
  normalized_title: normalizedTitle,
197
  status: "completed",
198
  timestamp: new Date().toISOString(),
 
206
  }
207
 
208
  /* =========================================================
209
+ HELPERS & VALIDATION
210
  ========================================================= */
211
 
212
  function extractJsonObject(text) {
 
223
 
224
  function validateAI(obj) {
225
  if (!obj || typeof obj !== "object") {
226
+ throw new Error("Invalid AI output");
227
  }
228
+ if (!Array.isArray(obj.marketSegments)) {
229
+ throw new Error("marketSegments missing");
 
 
 
 
 
 
 
 
 
230
  }
231
  }
232
 
 
242
  return round(min + Math.random() * (max - min));
243
  }
244
 
245
+ function randomInt(min, max) {
246
+ return Math.floor(min + Math.random() * (max - min + 1));
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
247
  }