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

Update src/marketResearchAgent.js

Browse files
Files changed (1) hide show
  1. src/marketResearchAgent.js +166 -138
src/marketResearchAgent.js CHANGED
@@ -11,81 +11,78 @@ export async function marketResearchAgent({ input, provider, model }) {
11
  }
12
 
13
  const keyword = normalizeKeyword(input.keyword);
14
- const normalizedTitle = `Global ${keyword} Market and Forecast 2026-2033`;
15
 
16
  /* =======================================================
17
- 1. CORE MARKET ESTIMATES (heuristic baseline)
18
  ======================================================= */
19
 
20
- const baseMarket2023 = randomFloat(0.5, 5.0);
21
- const cagr = randomFloat(8, 22);
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. AI-DERIVED COMPETITIVE LANDSCAPE (STRICT)
27
  ======================================================= */
28
 
29
- const competitivePrompt = `
30
- Return ONLY a valid JSON array.
31
- Do NOT include explanations, markdown, headings, or text.
32
 
33
  Market: ${keyword}
34
 
35
- Task:
36
- List the TOP 5 REAL global companies in the ${keyword} market
37
- with estimated global market share percentages.
38
 
39
- STRICT JSON FORMAT:
40
- [
41
- { "company": "Exact Company Name", "share": number },
42
- { "company": "Exact Company Name", "share": number },
43
- { "company": "Exact Company Name", "share": number },
44
- { "company": "Exact Company Name", "share": number },
45
- { "company": "Exact Company Name", "share": number }
46
- ]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
47
 
48
  RULES:
49
  - Use REAL, well-known companies only
50
- - NO placeholders (Company A, Leading Player, etc.)
51
- - Numbers only (no % sign)
52
- - Combined share ≈ 60–70
 
53
  `;
54
 
55
- let competitive;
56
 
57
  try {
58
- const raw = await callLLM({
59
- provider,
60
- model,
61
- prompt: competitivePrompt
62
- });
63
 
64
- const parsed = extractJsonArray(raw);
65
-
66
- if (!Array.isArray(parsed) || parsed.length < 3) {
67
- throw new Error("Invalid competitive array");
68
- }
69
-
70
- parsed.forEach(c => {
71
- if (
72
- !c.company ||
73
- typeof c.share !== "number" ||
74
- /company\s?[a-z]|player|leading/i.test(c.company)
75
- ) {
76
- throw new Error("Invalid or vague company name");
77
- }
78
- });
79
-
80
- competitive = parsed;
81
 
82
  } catch {
83
- // LAST-RESORT FALLBACK (REAL COMPANIES, NOT PLACEHOLDERS)
84
- competitive = getFallbackCompanies(keyword);
85
  }
86
 
87
  /* =======================================================
88
- 3. DASHBOARD VIEW
89
  ======================================================= */
90
 
91
  const dashboard_view = {
@@ -104,39 +101,22 @@ RULES:
104
  { year: "2033", value: market2033 }
105
  ],
106
 
107
- regional: buildRegions(),
108
 
109
- competitive,
110
 
111
- segments: buildSegments(),
112
 
113
- drivers: [
114
- { driver: "Technology adoption", impact: 92 },
115
- { driver: "Rising healthcare demand", impact: 88 },
116
- { driver: "Digital transformation", impact: 85 }
117
- ],
118
 
119
- insights: {
120
- largestSegment2025: "Primary Segment",
121
- fastestGrowingSegment: "AI-Enabled Solutions",
122
- keyOpportunities: [
123
- "Emerging markets",
124
- "AI integration",
125
- "Cost-efficient platforms"
126
- ],
127
- majorChallenges: [
128
- "Regulatory approvals",
129
- "High initial investment",
130
- "Skilled workforce shortage"
131
- ]
132
- },
133
 
134
- citation: "iHealthcareAnalyst, Inc. Internal Data Analysis",
135
  citationUrl: "https://www.ihealthcareanalyst.com"
136
  };
137
 
138
  /* =======================================================
139
- 4. REPORT VIEW
140
  ======================================================= */
141
 
142
  const report_view = {
@@ -150,59 +130,53 @@ RULES:
150
  },
151
 
152
  executiveOverview:
153
- `The ${keyword} market is experiencing accelerated growth driven by technological innovation, increasing healthcare demand, and expanding adoption across developed and emerging economies.`,
154
-
155
- marketSegments: [
156
- {
157
- segmentName: "Primary Segment",
158
- subSegments: [
159
- {
160
- subSegmentName: "Core Products",
161
- segmet_marketShare_2023: 40,
162
- segment_marketShare_2025: 45,
163
- segment_marketShare_2033: 50,
164
- segmentName_cagr_Forecast: round(cagr + 2)
165
- }
166
- ]
167
- }
168
- ],
169
-
170
- marketDrivers: [
171
- "Growing demand for advanced healthcare solutions",
172
- "Increased investment in digital health",
173
- "Favorable government initiatives"
174
- ],
175
-
176
- emergingTrends: [
177
- "AI-driven diagnostics",
178
- "Cloud-based healthcare platforms",
179
- "Personalized medicine"
180
- ],
181
-
182
- competitiveLandscape: competitive.map(c => ({
183
- company: c.company,
184
- player_markerShare_2025: c.share,
185
- positioning: "Established global market participant"
186
- })),
187
 
188
  regulatoryEnvironment:
189
- "The market is regulated by stringent healthcare and data protection regulations, with increasing emphasis on patient safety and clinical validation.",
190
 
191
  geographicAnalysis:
192
- "North America leads the market due to early adoption, while Asia-Pacific is expected to witness the fastest growth driven by expanding healthcare infrastructure.",
193
 
194
  futureOutlook:
195
- "The market is projected to grow steadily through 2033, supported by innovation, demographic trends, and increased healthcare spending.",
 
196
 
197
  strategicRecommendations: [
198
- "Invest in AI-enabled platforms",
199
- "Expand presence in emerging markets",
200
- "Strengthen regulatory compliance capabilities"
201
  ]
202
  };
203
 
204
  /* =======================================================
205
- 5. FINAL RETURN
206
  ======================================================= */
207
 
208
  return {
@@ -214,7 +188,7 @@ RULES:
214
  timestamp: new Date().toISOString(),
215
  provider_used: provider || "auto",
216
  model_used: model || "auto",
217
- confidence: "medium"
218
  },
219
  dashboard_view,
220
  report_view
@@ -222,13 +196,13 @@ RULES:
222
  }
223
 
224
  /* =========================================================
225
- HELPERS
226
  ========================================================= */
227
 
228
- function extractJsonArray(text) {
229
  if (!text) return null;
230
- const start = text.indexOf("[");
231
- const end = text.lastIndexOf("]");
232
  if (start === -1 || end === -1 || end <= start) return null;
233
  try {
234
  return JSON.parse(text.slice(start, end + 1));
@@ -237,15 +211,22 @@ function extractJsonArray(text) {
237
  }
238
  }
239
 
240
- function getFallbackCompanies(keyword) {
241
- // Healthcare-safe defaults
242
- return [
243
- { company: "Johnson & Johnson", share: 18 },
244
- { company: "Abbott Laboratories", share: 15 },
245
- { company: "Medtronic", share: 12 },
246
- { company: "Becton Dickinson", share: 10 },
247
- { company: "Stryker Corporation", share: 8 }
248
- ];
 
 
 
 
 
 
 
249
  }
250
 
251
  function normalizeKeyword(k) {
@@ -260,25 +241,72 @@ function randomFloat(min, max) {
260
  return round(min + Math.random() * (max - min));
261
  }
262
 
263
- function buildRegions() {
 
 
 
 
264
  return [
265
- { region: "North America", share: 42, cagr: 14.2 },
266
- { region: "Europe", share: 28, cagr: 12.8 },
267
- { region: "Asia Pacific", share: 22, cagr: 18.6 },
268
- { region: "Latin America", share: 5, cagr: 11.3 },
269
- { region: "Middle East & Africa", share: 3, cagr: 10.9 }
270
  ];
271
  }
272
 
273
- function buildSegments() {
274
  return [
275
  {
276
- segment: "Primary Segment",
277
  subSegments: [
278
- { name: "Core Products", share2025: 45, cagr: 16.5 },
279
- { name: "AI Solutions", share2025: 35, cagr: 19.2 },
280
- { name: "Services", share2025: 20, cagr: 13.1 }
281
  ]
282
  }
283
  ];
284
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
11
  }
12
 
13
  const keyword = normalizeKeyword(input.keyword);
14
+ const normalizedTitle = `Global ${keyword} Market and Forecast 20262033`;
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 = {
 
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 = {
 
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
  /* =======================================================
179
+ 5. FINAL RESPONSE
180
  ======================================================= */
181
 
182
  return {
 
188
  timestamp: new Date().toISOString(),
189
  provider_used: provider || "auto",
190
  model_used: model || "auto",
191
+ confidence: "high"
192
  },
193
  dashboard_view,
194
  report_view
 
196
  }
197
 
198
  /* =========================================================
199
+ VALIDATION & HELPERS
200
  ========================================================= */
201
 
202
+ function extractJsonObject(text) {
203
  if (!text) return null;
204
+ const start = text.indexOf("{");
205
+ const end = text.lastIndexOf("}");
206
  if (start === -1 || end === -1 || end <= start) return null;
207
  try {
208
  return JSON.parse(text.slice(start, end + 1));
 
211
  }
212
  }
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
 
232
  function normalizeKeyword(k) {
 
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
+ }