Alireza1913 commited on
Commit
edf7907
Β·
verified Β·
1 Parent(s): 7fb7cdf

Delete app.py

Browse files

import gradio as gr
import os
from huggingface_hub import InferenceClient

HF_TOKEN = os.environ.get("HF_TOKEN", "")
MODEL = "mistralai/Mistral-7B-Instruct-v0.3"

SYSTEM_PROMPT = """You are an expert API architect and indie hacker advisor.

You know every major API deeply:

PAYMENT: Stripe, Paddle, LemonSqueezy, PayPal, Razorpay
AI/ML: OpenAI, Anthropic Claude, Replicate, HuggingFace Inference, AssemblyAI, ElevenLabs
COMMUNICATION: Twilio (SMS/Voice), SendGrid (email), Resend, Mailgun, WhatsApp Business
DATA/ENRICHMENT: Clearbit, Apollo.io, Hunter.io, Proxycurl
MAPS/LOCATION: Google Maps, Mapbox, HERE, OpenStreetMap
MEDIA: Cloudinary, Mux (video), Imgix, Transloadit
FINANCE: Alpha Vantage, Polygon.io, CoinGecko, Plaid, Finnhub
SEARCH: Algolia, Typesense, Meilisearch
AUTH: Auth0, Clerk, Supabase Auth, Firebase Auth
DATABASE: Supabase, Firebase, PlanetScale, Neon, Upstash
SCRAPING: Apify, ScraperAPI, Browserless, Firecrawl
ANALYTICS: Mixpanel, PostHog, Amplitude, Plausible

When a user describes their product idea, recommend the perfect API stack.

Your response MUST follow this exact format:

## 🎯 Your Idea in One Line
(restate the idea clearly)

## πŸ”§ Recommended API Stack

For each API (recommend 3-5 total):

### [API Name] β€” [Role in the product]
- **What it does for you:** (one sentence)
- **Pricing:** (free tier + paid, be specific with numbers)
- **Docs:** (exact URL)
- **Why not alternatives:** (one sentence)
- **Integration difficulty:** Easy / Medium / Hard

## πŸ’° Monthly Cost Estimate
| Users | Est. Cost |
|-------|-----------|
| 100 | $X/month |
| 1,000 | $X/month |
| 10,000| $X/month |

## ⚑ Build Order
1. First: [API] β€” because...
2. Second: [API] β€” because...
3. Third: [API] β€” because...

## 🚨 Top Mistake to Avoid
(the most common mistake with this stack)

Be specific, honest about pricing, always mention free tiers."""


def get_stack(idea, budget, level, market):
if not idea.strip():
return "⚠️ Please describe your product idea."

if not HF_TOKEN:
return (
"⚠️ **HF_TOKEN is not set.**\n\n"
"Go to: **Space Settings β†’ Secrets β†’ New secret**\n"
"- Name: `HF_TOKEN`\n"
"- Value: your token from [huggingface.co/settings/tokens](https://huggingface.co/settings/tokens)\n\n"
"Free token β€” no credit card needed!"
)

try:
client = InferenceClient(token=HF_TOKEN)

prompt = f"""Product idea: {idea}

Monthly API budget: {budget}
Technical level: {level}
Target market: {market}

Recommend the best API stack for this product."""

messages = [
{"role": "system", "content": SYSTEM_PROMPT},
{"role": "user", "content": prompt}
]

response = client.chat.completions.create(
model=MODEL,
messages=messages,
max_tokens=1500,
temperature=0.7
)
return response.choices[0].message.content

except Exception as e:
err = str(e)
if "401" in err or "auth" in err.lower():
return "❌ Invalid token. Check your HF_TOKEN in Space Settings."
if "429" in err or "rate" in err.lower():
return "❌ Rate limit hit. Wait 30 seconds and try again."
if "loading" in err.lower():
return "⏳ Model is loading (cold start). Wait 20 seconds and try again."
return f"❌ Error: {err}"


def ask_followup(question, prev):
if not question.strip():
return ""
if not prev or prev.startswith("⚠️") or prev.startswith("❌"):
return "⚠️ Please generate a stack recommendation first."

try:
client = InferenceClient(token=HF_TOKEN)
messages = [
{"role": "system", "content": SYSTEM_PROMPT},
{
"role": "user",
"content": (
f"Previous recommendation:\n{prev}\n\n"
f"Follow-up question: {question}\n\n"
f"Answer concisely and helpfully."
)
}
]
response = client.chat.completions.create(
model=MODEL,
messages=messages,
max_tokens=800,
temperature=0.7
)
return response.choices[0].message.content

except Exception as e:
return f"❌ Error: {str(e)}"


EXAMPLES = [
["A Notion-like notes app with AI summarization", "$50/month", "Intermediate", "Students"],
["SMS marketing platform for small restaurants", "$30/month", "Beginner", "Restaurant owners"],
["Job board that auto-matches candidates with AI", "$100/month", "Advanced", "Tech recruiters"],
["Podcast transcription and highlight tool", "$20/month", "Beginner", "Podcasters"],
["Crypto portfolio tracker with price alerts", "$0 (free only)", "Intermediate", "Retail investors"],
]

css = """
.gradio-container { max-width: 900px !important; margin: auto; }
footer { display: none !important; }
"""

with gr.Blocks(css=css, title="API Stack Finder") as demo:
gr.Markdown("""
# πŸ”§ API Stack Finder
**Describe your product idea β†’ Get the perfect API stack, pricing, and build order**

Powered by **Mistral-7B-Instruct** via HuggingFace Inference API β€” 100% Free.
""")

with gr.Row():
with gr.Column(scale=3):
idea_input = gr.Textbox(
label="Describe your product idea",
placeholder="e.g. A platform where freelancers can sell services and get paid instantly...",
lines=4
)
with gr.Column(scale=1):
budget_input = gr.Dropdown(
choices=[
"$0 (free only)",
"$10/month",
"$30/month",
"$50/month",
"$100/month",
"$500/month",
"Unlimited"
],
value="$30/month",
label="Monthly API budget"
)
level_input = gr.Dropdown(
choices=["Beginner", "Intermediate", "Advanced"],
value="Intermediate",
label="Technical level"
)
market_input = gr.Textbox(
label="Target market",
placeholder="e.g. Small business owners",
value="General consumers"
)

gr.Markdown("**Try an example:**")
with gr.Row():
for ex in EXAMPLES:
gr.Button(ex[0][:32] + "...", size="sm").click(
lambda e=ex: (e[0], e[1], e[2], e[3]),
outputs=[idea_input, budget_input, level_input, market_input]
)

submit_btn = gr.Button("πŸ” Find My API Stack", variant="primary", size="lg")
output = gr.Markdown("*Your API stack will appear here...*")

gr.Markdown("---")
gr.Markdown("### πŸ’¬ Ask a follow-up")

with gr.Row():
followup_input = gr.Textbox(
label="Follow-up question",
placeholder="e.g. Is there a free alternative to Stripe? / How do I add auth cheaply?",
scale=4
)
followup_btn = gr.Button("Ask", scale=1, variant="secondary")

followup_output = gr.Markdown()

submit_btn.click(
get_stack,
inputs=[idea_input, budget_input, level_input, market_input],
outputs=output
)
followup_btn.click(
ask_followup,
inputs=[followup_input, output],
outputs=followup_output
)

gr.Markdown("""
---
πŸ€– Model: `Mistral-7B-Instruct-v0.3` Β· πŸ†“ Free via HuggingFace Inference API
πŸ”‘ Get your free token: [huggingface.co/settings/tokens](https://huggingface.co/settings/tokens)
""")

if __name__ == "__main__":
demo.launch()

1 file changed -235
app.pyDeleted-235