File size: 6,127 Bytes
0f06ab1 | 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 | """FastAPI server for KG-based report generation."""
import json
import logging
import os
from contextlib import asynccontextmanager
from enum import Enum
from fastapi import FastAPI, HTTPException
from fastapi.middleware.cors import CORSMiddleware
from pydantic import BaseModel, Field
from api.kg_routes import get_companies_list, get_company_stats, run_kg_generation
from config.rules import (
COMPANY_PRODUCT_RULE,
FOUNDERS_TEAM_RULE,
KEY_DEBATES_RULE,
MARKET_CUSTOMER_SIGNALS_RULE,
TAM_MARKET_RULE,
)
from services.kg import KGClient
from services.llm import GeminiLLM, LlmProvider, OpenAiLLM
logger = logging.getLogger(__name__)
# Section name to rule mapping
SECTION_RULES = {
"tam": TAM_MARKET_RULE,
"product": COMPANY_PRODUCT_RULE,
"customer_signals": MARKET_CUSTOMER_SIGNALS_RULE,
"team": FOUNDERS_TEAM_RULE,
"key_debates": KEY_DEBATES_RULE,
}
class SectionName(str, Enum):
tam = "tam"
product = "product"
customer_signals = "customer_signals"
team = "team"
key_debates = "key_debates"
class RetrievalMode(str, Enum):
chunks = "chunks"
full_documents = "full_documents"
hybrid = "hybrid"
class ModelProvider(str, Enum):
gemini_flash = "gemini-2.0-flash"
gemini_flash_lite = "gemini-2.0-flash-lite"
gemini_pro = "gemini-2.5-pro-preview-05-06"
gpt_4o = "gpt-4o"
gpt_4o_mini = "gpt-4o-mini"
# Request/Response models
class GenerateReportRequest(BaseModel):
company_id: str = Field(..., description="Company ID from the knowledge graph")
section: SectionName = Field(..., description="Report section to generate")
model: ModelProvider = Field(
default=ModelProvider.gemini_flash_lite, description="LLM model to use"
)
retrieval_mode: RetrievalMode = Field(
default=RetrievalMode.hybrid, description="How to retrieve context from KG"
)
extra_queries: list[str] | None = Field(
default=None, description="Additional queries for retrieval"
)
top_k: int = Field(default=40, ge=1, le=100, description="Number of chunks to retrieve")
class CompanyResponse(BaseModel):
id: str
name: str
class CompanyStatsResponse(BaseModel):
doc_count: int
chunk_count: int
class GenerateReportResponse(BaseModel):
success: bool
section: str
data: dict | None = None
error: str | None = None
# Global KG client (initialized on startup)
_kg_client: KGClient | None = None
def get_kg_client() -> KGClient:
global _kg_client
if _kg_client is None:
supabase_url = os.environ.get("SUPABASE_URL")
supabase_key = os.environ.get("SUPABASE_KEY")
if not supabase_url or not supabase_key:
raise HTTPException(status_code=500, detail="SUPABASE_URL and SUPABASE_KEY must be set")
_kg_client = KGClient(supabase_url, supabase_key)
return _kg_client
def get_llm_provider(model: ModelProvider) -> LlmProvider:
model_name = model.value
if model_name.startswith("gemini"):
api_key = os.environ.get("GEMINI_API_KEY")
if not api_key:
raise HTTPException(status_code=500, detail="GEMINI_API_KEY must be set")
return GeminiLLM(api_key=api_key, model_name=model_name)
else:
api_key = os.environ.get("OPENAI_API_KEY")
if not api_key:
raise HTTPException(status_code=500, detail="OPENAI_API_KEY must be set")
return OpenAiLLM(api_key=api_key, model_name=model_name)
@asynccontextmanager
async def lifespan(app: FastAPI):
# Startup: initialize KG client
logger.info("Starting up API server...")
yield
# Shutdown
logger.info("Shutting down API server...")
app = FastAPI(
title="Day1 Report Generation API",
description="API for generating due diligence reports from knowledge graph",
version="0.1.0",
lifespan=lifespan,
)
# CORS middleware - configure for your frontend origin
app.add_middleware(
CORSMiddleware,
allow_origins=["*"], # Update with your frontend URL in production
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
@app.get("/health")
async def health_check():
return {"status": "ok"}
@app.get("/companies", response_model=list[CompanyResponse])
async def list_companies():
"""Get all companies available in the knowledge graph."""
kg_client = get_kg_client()
companies = get_companies_list(kg_client)
return companies
@app.get("/companies/{company_id}/stats", response_model=CompanyStatsResponse)
async def get_stats(company_id: str):
"""Get document and chunk counts for a company."""
kg_client = get_kg_client()
stats = get_company_stats(kg_client, company_id)
return stats
@app.post("/reports/generate", response_model=GenerateReportResponse)
async def generate_report(request: GenerateReportRequest):
"""Generate a report section for a company using KG data."""
kg_client = get_kg_client()
llm_provider = get_llm_provider(request.model)
rule = SECTION_RULES.get(request.section.value)
if not rule:
raise HTTPException(status_code=400, detail=f"Unknown section: {request.section}")
result = run_kg_generation(
rule=rule,
llm_provider=llm_provider,
kg_client=kg_client,
company_id=request.company_id,
extra_queries=request.extra_queries,
retrieval_mode=request.retrieval_mode.value,
top_k=request.top_k,
)
if result is None:
return GenerateReportResponse(
success=False,
section=request.section.value,
error="Generation failed - check logs for details",
)
try:
data = json.loads(result)
except json.JSONDecodeError:
return GenerateReportResponse(
success=False,
section=request.section.value,
error="Failed to parse LLM response as JSON",
)
return GenerateReportResponse(
success=True,
section=request.section.value,
data=data,
)
if __name__ == "__main__":
import uvicorn
uvicorn.run(app, host="0.0.0.0", port=8000)
|