Alireza1913 commited on
Commit
3ae9623
Β·
verified Β·
1 Parent(s): e8c7792

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +76 -77
app.py CHANGED
@@ -3,125 +3,124 @@ import os
3
  import requests
4
 
5
  HF_TOKEN = os.environ.get("HF_TOKEN", "")
6
- API_URL = "https://api-inference.huggingface.co/models/mistralai/Mistral-7B-Instruct-v0.3"
7
-
8
- SYSTEM_PROMPT = """You are an expert API architect and indie hacker advisor.
9
-
10
- You know every major API deeply:
11
-
12
- PAYMENT: Stripe, Paddle, LemonSqueezy, PayPal, Razorpay
13
- AI/ML: OpenAI, Anthropic Claude, Replicate, HuggingFace Inference, AssemblyAI, ElevenLabs
14
- COMMUNICATION: Twilio (SMS/Voice), SendGrid (email), Resend, Mailgun, WhatsApp Business
15
- DATA/ENRICHMENT: Clearbit, Apollo.io, Hunter.io, Proxycurl
16
- MAPS/LOCATION: Google Maps, Mapbox, HERE, OpenStreetMap
17
- MEDIA: Cloudinary, Mux (video), Imgix, Transloadit
18
- FINANCE: Alpha Vantage, Polygon.io, CoinGecko, Plaid, Finnhub
19
- SEARCH: Algolia, Typesense, Meilisearch
20
- AUTH: Auth0, Clerk, Supabase Auth, Firebase Auth
21
- DATABASE: Supabase, Firebase, PlanetScale, Neon, Upstash
22
- SCRAPING: Apify, ScraperAPI, Browserless, Firecrawl
23
- ANALYTICS: Mixpanel, PostHog, Amplitude, Plausible"""
24
 
 
 
25
 
26
  def query_model(prompt):
 
 
 
 
 
 
 
 
27
  headers = {"Authorization": f"Bearer {HF_TOKEN}"}
28
 
29
- full_prompt = f"<s>[INST] {SYSTEM_PROMPT}\n\n{prompt} [/INST]"
30
 
31
  payload = {
32
  "inputs": full_prompt,
33
  "parameters": {
34
- "max_new_tokens": 1200,
35
  "temperature": 0.7,
36
- "return_full_text": False
 
 
37
  }
38
  }
39
 
40
- response = requests.post(API_URL, headers=headers, json=payload, timeout=60)
 
 
 
 
 
 
 
 
 
 
 
 
41
 
42
- if response.status_code == 503:
43
- return None, "⏳ Model is loading. Please wait 20 seconds and try again."
44
- if response.status_code == 401:
45
- return None, "❌ Invalid HF_TOKEN. Check Space Settings β†’ Secrets."
46
- if response.status_code == 429:
47
- return None, "❌ Rate limit hit. Wait 30 seconds and try again."
48
- if response.status_code != 200:
49
- return None, f"❌ Error {response.status_code}: {response.text[:200]}"
50
 
51
- result = response.json()
52
- if isinstance(result, list) and len(result) > 0:
53
- return result[0].get("generated_text", ""), None
54
- return None, f"❌ Unexpected response: {str(result)[:200]}"
 
 
 
 
 
55
 
56
 
57
  def get_stack(idea, budget, level, market):
58
  if not idea.strip():
59
  return "⚠️ Please describe your product idea."
60
 
61
- if not HF_TOKEN:
62
- return (
63
- "⚠️ **HF_TOKEN is not set.**\n\n"
64
- "Go to: **Space Settings β†’ Secrets β†’ New secret**\n"
65
- "- Name: `HF_TOKEN`\n"
66
- "- Value: your token from [huggingface.co/settings/tokens](https://huggingface.co/settings/tokens)\n\n"
67
- "Free token β€” no credit card needed!"
68
- )
69
 
70
- prompt = f"""Product idea: {idea}
71
- Monthly API budget: {budget}
72
- Technical level: {level}
73
- Target market: {market}
74
 
75
- Recommend the best API stack. Use this format:
 
76
 
77
- ## 🎯 Your Idea in One Line
78
- (restate clearly)
79
 
80
- ## πŸ”§ Recommended API Stack
81
- For each API (3-5 total):
82
- ### [API Name] β€” [Role]
83
- - What it does for you: (one sentence)
84
- - Pricing: (free tier + paid with numbers)
85
- - Docs: (exact URL)
86
- - Integration difficulty: Easy / Medium / Hard
87
 
88
  ## πŸ’° Monthly Cost Estimate
89
- | Users | Est. Cost |
90
- |-------|-----------|
91
- | 100 | $X/month |
92
- | 1,000 | $X/month |
93
- | 10,000 | $X/month |
94
 
95
  ## ⚑ Build Order
96
- 1. First: [API] β€” because...
97
- 2. Second: [API] β€” because...
 
98
 
99
- ## 🚨 Top Mistake to Avoid
100
- (most common mistake)"""
101
 
102
  result, error = query_model(prompt)
103
  if error:
104
  return error
105
- return result
106
 
107
 
108
  def ask_followup(question, prev):
109
  if not question.strip():
110
  return ""
111
  if not prev or prev.startswith("⚠️") or prev.startswith("❌"):
112
- return "⚠️ Please generate a stack recommendation first."
113
-
114
- prompt = f"""Previous recommendation:
115
- {prev[:500]}
116
 
117
- Follow-up question: {question}
 
118
 
119
- Answer concisely and helpfully."""
 
120
 
121
  result, error = query_model(prompt)
122
  if error:
123
  return error
124
- return result
125
 
126
 
127
  EXAMPLES = [
@@ -142,14 +141,14 @@ with gr.Blocks(css=css, title="API Stack Finder") as demo:
142
  # πŸ”§ API Stack Finder
143
  **Describe your product idea β†’ Get the perfect API stack, pricing, and build order**
144
 
145
- Powered by **Mistral-7B** via HuggingFace Inference API β€” 100% Free.
146
  """)
147
 
148
  with gr.Row():
149
  with gr.Column(scale=3):
150
  idea_input = gr.Textbox(
151
  label="Describe your product idea",
152
- placeholder="e.g. A platform where freelancers can sell services and get paid instantly...",
153
  lines=4
154
  )
155
  with gr.Column(scale=1):
@@ -209,8 +208,8 @@ Powered by **Mistral-7B** via HuggingFace Inference API β€” 100% Free.
209
 
210
  gr.Markdown("""
211
  ---
212
- πŸ€– Model: `Mistral-7B-Instruct-v0.3` Β· πŸ†“ Free via HuggingFace
213
- πŸ”‘ Token: [huggingface.co/settings/tokens](https://huggingface.co/settings/tokens)
214
  """)
215
 
216
  if __name__ == "__main__":
 
3
  import requests
4
 
5
  HF_TOKEN = os.environ.get("HF_TOKEN", "")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6
 
7
+ # Using a reliable free model on HuggingFace
8
+ API_URL = "https://api-inference.huggingface.co/models/HuggingFaceH4/zephyr-7b-beta"
9
 
10
  def query_model(prompt):
11
+ if not HF_TOKEN:
12
+ return None, (
13
+ "⚠️ **HF_TOKEN is not set.**\n\n"
14
+ "Space Settings β†’ Secrets β†’ New secret\n"
15
+ "- Name: `HF_TOKEN`\n"
16
+ "- Value: your token from huggingface.co/settings/tokens"
17
+ )
18
+
19
  headers = {"Authorization": f"Bearer {HF_TOKEN}"}
20
 
21
+ full_prompt = f"<|system|>\nYou are an expert API architect and startup advisor.\n</s>\n<|user|>\n{prompt}\n</s>\n<|assistant|>\n"
22
 
23
  payload = {
24
  "inputs": full_prompt,
25
  "parameters": {
26
+ "max_new_tokens": 1000,
27
  "temperature": 0.7,
28
+ "do_sample": True,
29
+ "return_full_text": False,
30
+ "stop": ["<|user|>", "</s>"]
31
  }
32
  }
33
 
34
+ try:
35
+ response = requests.post(API_URL, headers=headers, json=payload, timeout=60)
36
+
37
+ if response.status_code == 503:
38
+ return None, "⏳ Model is loading (cold start). Wait 30 seconds and try again."
39
+ if response.status_code == 401:
40
+ return None, "❌ Invalid HF_TOKEN. Go to Space Settings and check your token."
41
+ if response.status_code == 429:
42
+ return None, "❌ Rate limit. Wait 1 minute and try again."
43
+ if response.status_code != 200:
44
+ return None, f"❌ API Error {response.status_code}: {response.text[:300]}"
45
+
46
+ data = response.json()
47
 
48
+ if isinstance(data, list) and len(data) > 0:
49
+ text = data[0].get("generated_text", "").strip()
50
+ if text:
51
+ return text, None
 
 
 
 
52
 
53
+ if isinstance(data, dict) and "error" in data:
54
+ return None, f"❌ Model error: {data['error']}"
55
+
56
+ return None, f"❌ Empty response from model. Try again."
57
+
58
+ except requests.exceptions.Timeout:
59
+ return None, "⏳ Request timed out. The model may be loading. Try again in 30 seconds."
60
+ except Exception as e:
61
+ return None, f"❌ Error: {str(e)}"
62
 
63
 
64
  def get_stack(idea, budget, level, market):
65
  if not idea.strip():
66
  return "⚠️ Please describe your product idea."
67
 
68
+ prompt = f"""I want to build: {idea}
69
+
70
+ My monthly API budget: {budget}
71
+ My technical level: {level}
72
+ My target market: {market}
 
 
 
73
 
74
+ Please recommend the best API stack for my product using this format:
 
 
 
75
 
76
+ ## 🎯 My Idea
77
+ (one sentence summary)
78
 
79
+ ## πŸ”§ Recommended APIs
 
80
 
81
+ ### [API Name] β€” [what it does in my product]
82
+ - What it does: (one sentence)
83
+ - Pricing: (free tier details + paid pricing)
84
+ - Docs: (URL)
85
+ - Difficulty: Easy / Medium / Hard
86
+
87
+ (repeat for 3-5 APIs)
88
 
89
  ## πŸ’° Monthly Cost Estimate
90
+ - 100 users: $X/month
91
+ - 1,000 users: $X/month
92
+ - 10,000 users: $X/month
 
 
93
 
94
  ## ⚑ Build Order
95
+ 1. Start with [API] because...
96
+ 2. Then add [API] because...
97
+ 3. Finally [API] because...
98
 
99
+ ## 🚨 Biggest Mistake to Avoid
100
+ (one paragraph)"""
101
 
102
  result, error = query_model(prompt)
103
  if error:
104
  return error
105
+ return result if result else "❌ No response received. Please try again."
106
 
107
 
108
  def ask_followup(question, prev):
109
  if not question.strip():
110
  return ""
111
  if not prev or prev.startswith("⚠️") or prev.startswith("❌"):
112
+ return "⚠️ Generate a stack recommendation first, then ask follow-up questions."
 
 
 
113
 
114
+ prompt = f"""Based on this API stack recommendation:
115
+ {prev[:600]}
116
 
117
+ Answer this follow-up question clearly and concisely:
118
+ {question}"""
119
 
120
  result, error = query_model(prompt)
121
  if error:
122
  return error
123
+ return result if result else "❌ No response. Please try again."
124
 
125
 
126
  EXAMPLES = [
 
141
  # πŸ”§ API Stack Finder
142
  **Describe your product idea β†’ Get the perfect API stack, pricing, and build order**
143
 
144
+ Powered by **Zephyr-7B** via HuggingFace Inference API β€” 100% Free.
145
  """)
146
 
147
  with gr.Row():
148
  with gr.Column(scale=3):
149
  idea_input = gr.Textbox(
150
  label="Describe your product idea",
151
+ placeholder="e.g. A platform where freelancers sell services and get paid instantly...",
152
  lines=4
153
  )
154
  with gr.Column(scale=1):
 
208
 
209
  gr.Markdown("""
210
  ---
211
+ πŸ€– Model: `Zephyr-7B-Beta` Β· πŸ†“ Free via HuggingFace
212
+ πŸ”‘ Get token: [huggingface.co/settings/tokens](https://huggingface.co/settings/tokens)
213
  """)
214
 
215
  if __name__ == "__main__":