Skip to content
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -180,6 +180,7 @@ These use the latest TinyFish SDK and are deployed with live demos you can try r
| [competitor-scout-cli](./competitor-scout-cli) | Natural-language CLI for researching competitor feature decisions |
| [logistics-sentry](./logistics-sentry) | Port congestion and carrier-risk tracking |
| [tenders-finder](./tenders-finder) | Singapore government tender discovery across multiple portals |
| [monai](./monai) | Vietnam F&B trend intelligence — menu gaps, forecasts, regional compare, supplier discovery ([live demo](https://mon-ai-alpha.vercel.app/)) |

### Education & Discovery

Expand Down
13 changes: 13 additions & 0 deletions monai/.env.example
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
TINYFISH_API_KEY=
# Optional overrides (defaults are official TinyFish endpoints)
# TINYFISH_SEARCH_URL=https://api.search.tinyfish.ai
# TINYFISH_FETCH_URL=https://api.fetch.tinyfish.ai
# TINYFISH_SEARCH_LOCATION=VN
# TINYFISH_SEARCH_LANGUAGE=vi

# Optional — richer AI synthesis when set; otherwise routes use live TinyFish search/fetch data
OPENAI_API_KEY=

ALLOWED_ORIGINS=http://localhost:5173,http://127.0.0.1:5173
# Production example (comma-separated, no trailing slashes):
# ALLOWED_ORIGINS=https://mon-ai-alpha.vercel.app
13 changes: 13 additions & 0 deletions monai/.env.template
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
TINYFISH_API_KEY=
# Optional overrides (defaults are official TinyFish endpoints)
# TINYFISH_SEARCH_URL=https://api.search.tinyfish.ai
# TINYFISH_FETCH_URL=https://api.fetch.tinyfish.ai
# TINYFISH_SEARCH_LOCATION=VN
# TINYFISH_SEARCH_LANGUAGE=vi

# Optional — richer AI synthesis when set; otherwise routes use live TinyFish search/fetch data
OPENAI_API_KEY=

ALLOWED_ORIGINS=http://localhost:5173,http://127.0.0.1:5173
# Production example (comma-separated, no trailing slashes):
# ALLOWED_ORIGINS=https://mon-ai-alpha.vercel.app
13 changes: 13 additions & 0 deletions monai/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
.env
.env.*
!.env.example
!.env.template
__pycache__/
*.py[cod]
*.egg-info/
.venv/
venv/
node_modules/
dist/
.pytest_cache/
.mypy_cache/
1 change: 1 addition & 0 deletions monai/.python-version
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
3.12.8
151 changes: 151 additions & 0 deletions monai/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,151 @@
# MonAI

**Live demo: [mon-ai-alpha.vercel.app](https://mon-ai-alpha.vercel.app)**

**Vietnam food-trend intelligence for F&B brands — menu gaps, forecasts, regional compare, supplier discovery, and RFQ outreach.**

MonAI uses **TinyFish Search** (`api.search.tinyfish.ai`) to scan live Vietnamese web signals (social, delivery apps, operator menus) and **TinyFish Fetch** (`api.fetch.tinyfish.ai`) to extract competitor menu pages as clean markdown. A FastAPI backend structures results into executive-ready reports; a React dashboard lets product teams run analyses without writing prompts.

## Demo

**[Try the live app →](https://mon-ai-alpha.vercel.app)** — open **Dashboard**, run Menu Gap or Forecast, and view formatted intelligence reports.

> Screen recording: use the live demo above for the full walkthrough (landing page → trend board → analysis console).

## TinyFish API usage

Search powers emerging trends, forecasts, menu-gap signals, regional comparisons, and supplier discovery. Fetch reads competitor menu URLs when provided.

```python
# app/services/tinyfish_client.py

async def search_tinyfish(query: str, max_results: int = 10, *, location: str | None = None, ...) -> dict:
params = {
"query": query,
"location": location or "VN",
"language": language or "vi",
}
async with httpx.AsyncClient(timeout=30.0) as client:
response = await client.get("https://api.search.tinyfish.ai", params=params, headers=_headers())
response.raise_for_status()
return response.json()

async def fetch_tinyfish(url: str, *, format: str = "markdown") -> dict:
payload = {"urls": [url], "format": format}
async with httpx.AsyncClient(timeout=60.0) as client:
response = await client.post(
"https://api.fetch.tinyfish.ai",
json=payload,
headers={**_headers(), "Content-Type": "application/json"},
)
response.raise_for_status()
return response.json()
```

Example search query from the trends route:

```python
data = await search_tinyfish(
f"emerging food beverage trends {location} {category} Vietnam 2025",
max_results=10,
location="VN",
language="vi",
)
```

## How to run

### Prerequisites

- Python 3.12+
- Node.js 20+
- [TinyFish API key](https://agent.tinyfish.ai/) (Search + Fetch are free)

### Backend

```bash
cd monai
cp .env.template .env
# Set TINYFISH_API_KEY and ALLOWED_ORIGINS in .env

pip install -r requirements.txt
uvicorn main:app --reload --port 8000
```

### Frontend

```bash
cd monai/frontend
cp .env.example .env
# VITE_API_BASE_URL=http://localhost:8000

npm install
npm run dev
```

Open [http://localhost:5173](http://localhost:5173).

### Environment variables

| Variable | Required | Description |
|----------|----------|-------------|
| `TINYFISH_API_KEY` | Yes | TinyFish API key |
| `ALLOWED_ORIGINS` | Yes | Comma-separated CORS origins (e.g. `http://localhost:5173`) |
| `OPENAI_API_KEY` | No | Optional richer synthesis; core flows work with TinyFish only |
| `VITE_API_BASE_URL` | Yes (frontend) | Backend URL (e.g. `http://localhost:8000` or your Render URL) |

## Architecture

```mermaid
flowchart LR
subgraph Client
UI[React dashboard<br/>Vercel]
end

subgraph Backend["FastAPI — Render"]
API[REST routes]
TF[TinyFish client]
SA[Search analysis + reports]
end

subgraph TinyFish
SEARCH[Search API<br/>api.search.tinyfish.ai]
FETCH[Fetch API<br/>api.fetch.tinyfish.ai]
end

UI -->|HTTPS JSON| API
API --> TF
TF --> SEARCH
TF --> FETCH
API --> SA
SA -->|IntelligenceReport| UI
```

### Analysis flows

| Feature | TinyFish endpoint | What it does |
|---------|-------------------|--------------|
| Emerging trends | Search | Rank live F&B signals for a city/category |
| Trend forecast | Search | Estimate adoption timeline from web evidence |
| Menu gap | Search + Fetch | Benchmark menu vs trends; fetch competitor URLs |
| Regional compare | Search | Side-by-side city intelligence |
| Supplier discovery | Search | Rank wholesale/supplier candidates |
| RFQ outreach | — | Bilingual templates (optional OpenAI polish) |

## Deployment

- **Frontend:** Vercel — root `frontend/`, set `VITE_API_BASE_URL`
- **Backend:** Render — `render.yaml` included, set `TINYFISH_API_KEY` + `ALLOWED_ORIGINS`

## Project structure

```
monai/
├── app/
│ ├── routes/ # trends, analysis, suppliers
│ └── services/ # tinyfish_client, search_analysis, report_builder
├── frontend/ # React 19 + TanStack Router + shadcn/ui
├── main.py
├── requirements.txt
└── render.yaml
```
1 change: 1 addition & 0 deletions monai/app/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
# __init__.py
13 changes: 13 additions & 0 deletions monai/app/http_errors.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
import logging

from fastapi import HTTPException

logger = logging.getLogger(__name__)


def raise_internal_error(exc: Exception, *, context: str = "request") -> None:
logger.exception("%s failed", context, exc_info=exc)
raise HTTPException(
status_code=500,
detail="An internal error occurred. Please try again later.",
) from exc
1 change: 1 addition & 0 deletions monai/app/routes/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
# __init__.py
92 changes: 92 additions & 0 deletions monai/app/routes/analysis.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,92 @@
from fastapi import APIRouter
from pydantic import BaseModel

from app.http_errors import raise_internal_error
from app.services.ai_client import analyze_data, has_openai
from app.services.report_builder import build_menu_gap_report
from app.services.response_parser import normalize_payload, parse_llm_json
from app.services.search_analysis import as_json_text, menu_gap_from_search
from app.services.tinyfish_client import fetch_tinyfish, search_tinyfish

router = APIRouter(prefix="/api/analysis", tags=["Analysis"])

SYSTEM_JSON = (
"You are a senior Vietnam F&B menu strategist. Output ONLY valid JSON. "
"Write recommendations as actionable, specific prose."
)


class MenuGapRequest(BaseModel):
current_menu_items: list[str]
location: str
competitor_urls: list[str] = []


@router.post("/menu-gap")
async def analyze_menu_gap(request: MenuGapRequest):
"""Compares current menu with competitors and emerging trends to find gaps."""
try:
trends_query = f"fastest growing beverage and food trends in {request.location} Vietnam"
trends_results = await search_tinyfish(
trends_query,
purpose=f"Find menu gap opportunities in {request.location}",
)

competitor_menus = []
for url in request.competitor_urls[:2]:
try:
fetched = await fetch_tinyfish(url)
page = (fetched.get("results") or [{}])[0]
competitor_menus.append(
{
"url": url,
"title": page.get("title"),
"text": (page.get("text") or "")[:4000],
}
)
except Exception as fetch_err:
print(f"Failed to fetch {url}: {fetch_err}")

if has_openai():
prompt = f"""
Menu gap analysis for {request.location}.

Current menu: {request.current_menu_items}
Trend signals: {as_json_text(trends_results)}
Competitor pages: {as_json_text(competitor_menus)}

Return JSON with keys:
location, current_menu_items, executive_summary (2 sentences),
missing_opportunities (array max 5). Each opportunity needs:
trend, priority (High/Medium/Low), evidence (1-2 sentences),
competitor_adoption (1 sentence), recommendation (actionable 1-2 sentences).
"""
ai_response = await analyze_data(prompt, SYSTEM_JSON)
analysis = parse_llm_json(ai_response)
if not isinstance(analysis, dict):
analysis = menu_gap_from_search(
request.current_menu_items,
request.location,
trends_results,
competitor_menus,
)
else:
analysis.setdefault("trend_signals", [
{"title": r.get("title"), "snippet": r.get("snippet"), "url": r.get("url")}
for r in trends_results.get("results", [])[:8]
])
else:
analysis = menu_gap_from_search(
request.current_menu_items,
request.location,
trends_results,
competitor_menus,
)

analysis = normalize_payload(analysis)
return {
"menu_gap_analysis": analysis,
"report": build_menu_gap_report(analysis if isinstance(analysis, dict) else {}),
}
except Exception as e:
raise_internal_error(e, context="menu gap analysis")
Loading