-
-
Notifications
You must be signed in to change notification settings - Fork 1.1k
Expand file tree
/
Copy pathsecondary-market-research-api.py
More file actions
619 lines (526 loc) Β· 23.8 KB
/
secondary-market-research-api.py
File metadata and controls
619 lines (526 loc) Β· 23.8 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
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
"""
Secondary Market Research FastAPI Application
This FastAPI application provides a REST API for generating customized
secondary market research reports. Users can specify company, geography,
industry, and research sections to generate tailored reports.
Features:
- RESTful API endpoints for market research
- Customizable research parameters
- Async report generation
- JSON and PDF report formats
- Real-time progress tracking
- Report history and caching
Usage:
uvicorn secondary-market-research-api:app --reload --port 8000
Then visit: http://localhost:8000/docs for API documentation
"""
from fastapi import FastAPI, HTTPException, BackgroundTasks, Depends
from fastapi.responses import JSONResponse, FileResponse
from fastapi.middleware.cors import CORSMiddleware
from pydantic import BaseModel, Field
from typing import List, Optional, Dict, Any
import asyncio
import json
import uuid
from datetime import datetime
import os
from pathlib import Path
# Import our market research system
from praisonaiagents import Agent, Task, AgentTeam, Tools
# Create FastAPI app
app = FastAPI(
title="Secondary Market Research API",
description="Generate customized secondary market research reports",
version="1.0.0",
docs_url="/docs",
redoc_url="/redoc"
)
# Add CORS middleware with secure configuration
cors_origins = os.getenv("API_CORS_ORIGINS", "").split(",")
cors_origins = [origin.strip() for origin in cors_origins if origin.strip() and origin.strip() != "*"]
# Default secure origins if none specified
if not cors_origins:
# Secure defaults for different environments
if os.getenv("ENVIRONMENT") == "production":
# In production, require explicit configuration
cors_origins = []
else:
# Development defaults - restrict to local origins
cors_origins = [
"http://localhost:3000", # Development frontend
"http://localhost:8000", # Local development
"http://127.0.0.1:3000", # Local development
"http://127.0.0.1:8000", # Local development
]
# Only add CORS middleware if origins are specified
if cors_origins:
app.add_middleware(
CORSMiddleware,
allow_origins=cors_origins,
allow_credentials=True,
allow_methods=["GET", "POST", "PUT", "DELETE", "OPTIONS"],
allow_headers=["Authorization", "Content-Type", "Origin", "Accept"],
)
# Create directories for storing reports
REPORTS_DIR = Path("generated_reports")
REPORTS_DIR.mkdir(exist_ok=True)
# In-memory storage for job status (in production, use Redis or database)
job_status = {}
# Pydantic models for request/response
class MarketResearchRequest(BaseModel):
"""Request model for market research generation"""
company: str = Field(..., description="Company name to research", example="Tesla")
geography: str = Field(..., description="Geographic region", example="North America")
industry: str = Field(..., description="Industry sector", example="Electric Vehicles")
sections: Optional[List[str]] = Field(
default=["market_overview", "competitive_analysis", "financial_performance", "growth_opportunities", "risk_assessment"],
description="Research sections to include",
example=["market_overview", "competitive_analysis", "financial_performance"]
)
format: Optional[str] = Field(default="json", description="Output format: json or pdf", example="json")
email: Optional[str] = Field(None, description="Email for notification when complete", example="user@company.com")
class MarketResearchResponse(BaseModel):
"""Response model for market research request"""
job_id: str = Field(..., description="Unique job identifier")
status: str = Field(..., description="Job status: pending, running, completed, failed")
message: str = Field(..., description="Status message")
estimated_completion: Optional[str] = Field(None, description="Estimated completion time")
class JobStatusResponse(BaseModel):
"""Response model for job status check"""
job_id: str
status: str
progress: int = Field(..., description="Progress percentage (0-100)")
message: str
created_at: str
updated_at: str
result_url: Optional[str] = None
error: Optional[str] = None
class MarketResearchConfig:
"""Configuration class for market research parameters"""
def __init__(self, company: str, geography: str, industry: str, sections: List[str]):
self.company = company
self.geography = geography
self.industry = industry
self.sections = sections
self.timestamp = datetime.now().isoformat()
def create_market_research_agents(config: MarketResearchConfig):
"""Create specialized market research agents"""
agents = {}
if "market_overview" in config.sections:
agents["market_overview"] = Agent(
name="Market Overview Specialist",
role="Market Analysis Expert",
goal=f"Analyze the {config.industry} market in {config.geography}",
instructions=f"""
Analyze market size, trends, growth drivers, and overall market dynamics for
{config.industry} in {config.geography}. Provide quantitative data and cite sources.
""",
tools=[Tools.internet_search], output="minimal"
)
if "competitive_analysis" in config.sections:
agents["competitive"] = Agent(
name="Competitive Intelligence Analyst",
role="Competition Research Expert",
goal=f"Analyze {config.company}'s competitive landscape",
instructions=f"""
Analyze {config.company}'s competitive position in {config.industry} within {config.geography}.
Identify key competitors, market share, and competitive advantages.
""",
tools=[Tools.internet_search], output="minimal"
)
if "financial_performance" in config.sections:
agents["financial"] = Agent(
name="Financial Performance Analyst",
role="Financial Research Expert",
goal=f"Analyze {config.company}'s financial performance",
instructions=f"""
Research {config.company}'s financial performance, revenue trends, profitability,
and compare with industry benchmarks.
""",
tools=[Tools.internet_search], output="minimal"
)
if "growth_opportunities" in config.sections:
agents["growth"] = Agent(
name="Growth Opportunities Researcher",
role="Strategic Growth Expert",
goal=f"Identify growth opportunities for {config.company}",
instructions=f"""
Identify emerging opportunities, market gaps, expansion possibilities for {config.company}
in {config.industry} within {config.geography}.
""",
tools=[Tools.internet_search], output="minimal"
)
if "risk_assessment" in config.sections:
agents["risk"] = Agent(
name="Risk Assessment Specialist",
role="Risk Analysis Expert",
goal=f"Assess risks for {config.company}",
instructions=f"""
Identify and analyze potential risks, challenges, and threats facing {config.company}
in {config.geography}. Consider regulatory, competitive, and market risks.
""",
tools=[Tools.internet_search], output="minimal"
)
# Always include synthesizer
agents["synthesizer"] = Agent(
name="Research Report Synthesizer",
role="Report Writing Expert",
goal="Synthesize research into comprehensive report",
instructions=f"""
Create a professional secondary market research report for {config.company}
in {config.industry} with clear structure, insights, and recommendations.
""", output="minimal"
)
return agents
def create_research_tasks(agents: Dict[str, Agent], config: MarketResearchConfig):
"""Create research tasks for the agents"""
tasks = []
# Create tasks based on available sections
if "market_overview" in config.sections and "market_overview" in agents:
market_task = Task(
name="market_overview_research",
description=f"Research {config.industry} market overview in {config.geography}",
expected_output="Market overview analysis with key metrics and trends",
agent=agents["market_overview"]
)
tasks.append(market_task)
if "competitive_analysis" in config.sections and "competitive" in agents:
competitive_task = Task(
name="competitive_analysis",
description=f"Analyze competitive landscape for {config.company}",
expected_output="Competitive analysis with key competitors and positioning",
agent=agents["competitive"]
)
tasks.append(competitive_task)
if "financial_performance" in config.sections and "financial" in agents:
financial_task = Task(
name="financial_analysis",
description=f"Analyze {config.company}'s financial performance",
expected_output="Financial performance analysis with key metrics",
agent=agents["financial"]
)
tasks.append(financial_task)
if "growth_opportunities" in config.sections and "growth" in agents:
growth_task = Task(
name="growth_opportunities",
description=f"Identify growth opportunities for {config.company}",
expected_output="Growth opportunities analysis with strategic recommendations",
agent=agents["growth"]
)
tasks.append(growth_task)
if "risk_assessment" in config.sections and "risk" in agents:
risk_task = Task(
name="risk_assessment",
description=f"Assess risks for {config.company}",
expected_output="Risk assessment with mitigation strategies",
agent=agents["risk"]
)
tasks.append(risk_task)
# Synthesis task
synthesis_task = Task(
name="synthesis",
description=f"Synthesize all findings into comprehensive report",
expected_output="Complete secondary market research report",
agent=agents["synthesizer"],
context=tasks
)
tasks.append(synthesis_task)
return tasks
async def generate_market_research_report(job_id: str, config: MarketResearchConfig):
"""Background task to generate market research report"""
try:
# Update job status
job_status[job_id]["status"] = "running"
job_status[job_id]["progress"] = 10
job_status[job_id]["message"] = "Creating research agents..."
job_status[job_id]["updated_at"] = datetime.now().isoformat()
# Create agents and tasks
agents = create_market_research_agents(config)
tasks = create_research_tasks(agents, config)
job_status[job_id]["progress"] = 20
job_status[job_id]["message"] = "Setting up research workflow..."
# Create workflow
workflow = AgentTeam(
agents=list(agents.values()),
tasks=tasks,
process="sequential", output="minimal"
)
job_status[job_id]["progress"] = 30
job_status[job_id]["message"] = "Executing research workflow..."
# Execute research
results = await workflow.astart()
job_status[job_id]["progress"] = 90
job_status[job_id]["message"] = "Generating final report..."
# Prepare final report
report_data = {
"metadata": {
"job_id": job_id,
"company": config.company,
"geography": config.geography,
"industry": config.industry,
"sections": config.sections,
"generated_at": datetime.now().isoformat()
},
"executive_summary": "Executive summary would be generated here...",
"research_findings": {}
}
# Extract results from each task with comprehensive logging
print(f"DEBUG: Raw results type: {type(results)}")
print(f"DEBUG: Raw results content: {results}")
if isinstance(results, str):
# Sequential process returns a string result directly
print("DEBUG: Sequential process returned string result")
report_data["research_findings"]["synthesis_report"] = {
"content": results,
"agent": "Research Report Synthesizer",
"section": "Complete Market Research Report"
}
print(f"DEBUG: Added synthesis_report with content length: {len(results)}")
elif isinstance(results, dict):
print(f"DEBUG: Results is dict with keys: {list(results.keys())}")
if "task_results" in results:
print(f"DEBUG: Found task_results: {results['task_results']}")
print(f"DEBUG: task_results type: {type(results['task_results'])}")
for task_name, result in results["task_results"].items():
print(f"DEBUG: Processing task '{task_name}', result type: {type(result)}")
print(f"DEBUG: Result content: {result}")
if result:
# Try multiple ways to extract content
content = None
agent_name = "Unknown"
if hasattr(result, 'raw'):
content = result.raw
print(f"DEBUG: Extracted content from result.raw")
elif hasattr(result, 'content'):
content = result.content
print(f"DEBUG: Extracted content from result.content")
elif isinstance(result, str):
content = result
print(f"DEBUG: Result is string, using directly")
else:
content = str(result)
print(f"DEBUG: Converting result to string")
if hasattr(result, 'agent'):
agent_name = result.agent
elif hasattr(result, 'agent_name'):
agent_name = result.agent_name
if content:
report_data["research_findings"][task_name] = {
"content": content,
"agent": agent_name,
"section": f"Task {task_name}"
}
print(f"DEBUG: Added task '{task_name}' with content length: {len(str(content))}")
else:
print(f"DEBUG: No content found for task '{task_name}'")
else:
print(f"DEBUG: Task '{task_name}' result is None or empty")
else:
print("DEBUG: No 'task_results' found in results dict")
# Try to use the whole results as content
report_data["research_findings"]["workflow_output"] = {
"content": str(results),
"agent": "PraisonAI Workflow",
"section": "Complete Workflow Output"
}
print("DEBUG: Added entire results as workflow_output")
else:
print(f"DEBUG: Unexpected results type: {type(results)}")
report_data["research_findings"]["raw_output"] = {
"content": str(results),
"agent": "Unknown",
"section": "Raw Output"
}
print(f"DEBUG: Final research_findings keys: {list(report_data['research_findings'].keys())}")
print(f"DEBUG: Final research_findings count: {len(report_data['research_findings'])}")
# Generate executive summary from synthesis if available
if "synthesis_report" in report_data["research_findings"]:
content = report_data["research_findings"]["synthesis_report"]["content"]
# Extract first few sentences as executive summary
sentences = content.split('. ')[:3]
report_data["executive_summary"] = '. '.join(sentences) + '.' if sentences else "Market research analysis completed."
print("DEBUG: Generated executive summary from synthesis report")
# Save report to file
report_filename = f"market_research_{job_id}.json"
report_path = REPORTS_DIR / report_filename
with open(report_path, "w") as f:
json.dump(report_data, f, indent=2, default=str)
# Update job status to completed
job_status[job_id]["status"] = "completed"
job_status[job_id]["progress"] = 100
job_status[job_id]["message"] = "Report generation completed successfully"
job_status[job_id]["result_url"] = f"/reports/{job_id}"
job_status[job_id]["updated_at"] = datetime.now().isoformat()
except Exception as e:
# Update job status to failed
job_status[job_id]["status"] = "failed"
job_status[job_id]["error"] = str(e)
job_status[job_id]["message"] = f"Report generation failed: {str(e)}"
job_status[job_id]["updated_at"] = datetime.now().isoformat()
# API Endpoints
@app.get("/", summary="API Health Check")
async def root():
"""Health check endpoint"""
return {
"service": "Secondary Market Research API",
"status": "active",
"version": "1.0.0",
"timestamp": datetime.now().isoformat()
}
@app.post("/research/generate", response_model=MarketResearchResponse, summary="Generate Market Research Report")
async def generate_research(
request: MarketResearchRequest,
background_tasks: BackgroundTasks
):
"""
Generate a secondary market research report with customizable parameters.
This endpoint starts an async job to generate a comprehensive market research
report based on the provided parameters. The report generation runs in the
background and can be tracked using the returned job_id.
"""
# Generate unique job ID
job_id = str(uuid.uuid4())
# Initialize job status
job_status[job_id] = {
"job_id": job_id,
"status": "pending",
"progress": 0,
"message": "Report generation queued",
"created_at": datetime.now().isoformat(),
"updated_at": datetime.now().isoformat(),
"config": request.model_dump()
}
# Create config object
config = MarketResearchConfig(
company=request.company,
geography=request.geography,
industry=request.industry,
sections=request.sections
)
# Start background task
background_tasks.add_task(generate_market_research_report, job_id, config)
return MarketResearchResponse(
job_id=job_id,
status="pending",
message="Market research report generation started",
estimated_completion=datetime.now().isoformat()
)
@app.get("/research/status/{job_id}", response_model=JobStatusResponse, summary="Check Job Status")
async def check_job_status(job_id: str):
"""
Check the status of a market research report generation job.
Returns the current status, progress percentage, and any results or errors.
"""
if job_id not in job_status:
raise HTTPException(status_code=404, detail="Job ID not found")
return JobStatusResponse(**job_status[job_id])
@app.get("/research/reports/{job_id}", summary="Download Research Report")
async def download_report(job_id: str):
"""
Download the generated market research report.
Returns the complete report in JSON format once generation is complete.
"""
if job_id not in job_status:
raise HTTPException(status_code=404, detail="Job ID not found")
if job_status[job_id]["status"] != "completed":
raise HTTPException(status_code=400, detail="Report not ready. Check job status first.")
report_path = REPORTS_DIR / f"market_research_{job_id}.json"
if not report_path.exists():
raise HTTPException(status_code=404, detail="Report file not found")
return FileResponse(
path=report_path,
media_type="application/json",
filename=f"market_research_{job_id}.json"
)
@app.get("/research/jobs", summary="List All Jobs")
async def list_jobs():
"""
List all market research jobs and their current status.
Useful for monitoring and administrative purposes.
"""
return {
"total_jobs": len(job_status),
"jobs": [
{
"job_id": job_id,
"status": status["status"],
"progress": status["progress"],
"created_at": status["created_at"],
"company": status["config"]["company"] if "config" in status else "Unknown"
}
for job_id, status in job_status.items()
]
}
@app.delete("/research/jobs/{job_id}", summary="Cancel Job")
async def cancel_job(job_id: str):
"""
Cancel a pending or running market research job.
"""
if job_id not in job_status:
raise HTTPException(status_code=404, detail="Job ID not found")
if job_status[job_id]["status"] in ["completed", "failed"]:
raise HTTPException(status_code=400, detail="Cannot cancel completed or failed job")
job_status[job_id]["status"] = "cancelled"
job_status[job_id]["message"] = "Job cancelled by user"
job_status[job_id]["updated_at"] = datetime.now().isoformat()
return {"message": "Job cancelled successfully", "job_id": job_id}
@app.get("/research/templates", summary="Get Research Templates")
async def get_research_templates():
"""
Get predefined research templates for common use cases.
"""
templates = {
"technology_company": {
"sections": ["market_overview", "competitive_analysis", "financial_performance", "growth_opportunities"],
"example": {
"company": "Tesla",
"geography": "North America",
"industry": "Electric Vehicles"
}
},
"financial_services": {
"sections": ["market_overview", "competitive_analysis", "risk_assessment", "financial_performance"],
"example": {
"company": "Goldman Sachs",
"geography": "Global",
"industry": "Investment Banking"
}
},
"healthcare": {
"sections": ["market_overview", "competitive_analysis", "growth_opportunities", "risk_assessment"],
"example": {
"company": "Johnson & Johnson",
"geography": "North America",
"industry": "Pharmaceuticals"
}
},
"retail": {
"sections": ["market_overview", "competitive_analysis", "financial_performance", "growth_opportunities"],
"example": {
"company": "Amazon",
"geography": "Global",
"industry": "E-commerce"
}
}
}
return {
"templates": templates,
"available_sections": [
"market_overview",
"competitive_analysis",
"financial_performance",
"growth_opportunities",
"risk_assessment"
]
}
if __name__ == "__main__":
import uvicorn
print("π Starting Secondary Market Research API...")
print("π API Documentation: http://localhost:8000/docs")
print("π ReDoc Documentation: http://localhost:8000/redoc")
uvicorn.run(
"secondary-market-research-api:app",
host="0.0.0.0",
port=8000,
reload=True
)