Turbiling's picture
Update app.py
2ca5b44 verified
Raw
History Blame Contribute Delete
18.6 kB
"""
Startup Ideation Assistant - From Idea to Maturity
Developed by Najaf Ali Sharqi
"""
import gradio as gr
from groq import Groq
import os
import json
from datetime import datetime
# Initialize Groq client
client = Groq(api_key=os.environ.get("GROQ_API_KEY"))
# Session state management
class IdeationSession:
def __init__(self):
self.ideas = []
self.current_idea = None
session = IdeationSession()
# System prompts
DISCOVERY_PROMPT = """You are a startup ideation expert. Help users discover innovative startup ideas using these four sources:
1. **Problems**: Identify real problems (agricultural waste, infrastructure issues, import dependency)
2. **Intersections**: Combine fields (Transportation + Mobile = Uber, Hospitality + Internet = Airbnb)
3. **Future Trends**: Emerging technologies (AI, drones, IoT, renewable energy)
4. **Edges of Knowledge**: Cutting-edge breakthroughs (new materials, gene editing, quantum computing)
Be specific, provide concrete examples, and encourage bold thinking."""
EVALUATION_PROMPT = """Evaluate startup ideas using the 4-question framework:
**Q1: Is it a good problem?** Market size, pain level, financial loss, customer recognition
**Q2: Can I fix it?** Skills, realistic assessment, learning curve
**Q3: Is solution robust?** Easy to use, addresses pain, provides benefits, easy decision
**Q4: Do I have resources?** MVP capability, customer access, scaling potential, minimum funding
Rate honestly (1-10 for each criterion) and provide constructive feedback."""
REFINEMENT_PROMPT = """Help refine ideas based on evaluation:
- Strong ideas: Develop MVP strategy, customer discovery plan, next steps
- Weak areas: Suggest specific improvements and potential pivots
- Focus on: Customer interviews (not surveys), building with own resources, minimal MVP, quick testing, finding mentors"""
ACTION_PLANNING_PROMPT = """Create concrete action plans:
1. Immediate actions (this week): 3-5 specific validation tasks
2. Short-term goals (1 month): Customer discovery targets, MVP specs
3. Resources needed: Skills, team, tools, initial budget
4. Milestones: Success metrics, decision points, timeline
Be specific and actionable for beginners."""
def chat_with_groq(message, system_prompt, history=None):
"""Send message to Groq API"""
try:
messages = [{"role": "system", "content": system_prompt}]
if history:
messages.extend(history)
messages.append({"role": "user", "content": message})
response = client.chat.completions.create(
model="llama-3.3-70b-versatile",
messages=messages,
temperature=0.7,
max_tokens=2000,
)
return response.choices[0].message.content
except Exception as e:
return f"Error: {str(e)}. Please check your GROQ_API_KEY environment variable."
def format_for_chatbot(history):
"""Format chat history for Gradio Chatbot - handles both tuple and dict formats"""
# Gradio 6.x uses dict format with role/content
formatted = []
for msg in history:
formatted.append({
"role": msg["role"],
"content": msg["content"]
})
return formatted
def discover_ideas(source_type, user_input, context, history):
"""Help discover ideas"""
if not user_input or not context:
return history, history
prompt = f"""Using the {source_type} approach:
My Background: {context}
My Observation: {user_input}
Please help me explore innovative startup ideas. Provide:
1. Specific idea suggestions based on my observation
2. Real-world examples of similar successful solutions
3. Probing questions to help me think deeper
4. Potential opportunities I might be missing
Focus on ideas that are innovative, address real needs, and have potential for scale."""
history.append({"role": "user", "content": prompt})
response = chat_with_groq(prompt, DISCOVERY_PROMPT, history)
history.append({"role": "assistant", "content": response})
return format_for_chatbot(history), history
def evaluate_idea(idea_desc, target_market, problem_stmt, solution, history):
"""Evaluate using 4-question framework"""
if not idea_desc or not problem_stmt:
return history, history, "Please fill in at least Idea Description and Problem Statement"
prompt = f"""Evaluate this startup idea using the 4-question framework:
**Idea Description:** {idea_desc}
**Target Market:** {target_market}
**Problem Statement:** {problem_stmt}
**Solution Approach:** {solution}
Please provide:
1. Detailed evaluation for each of the 4 questions
2. Scores (1-10) for each major criterion
3. Overall assessment
4. Specific areas that need improvement
5. Red flags or concerns (if any)
6. Strengths to leverage
Be honest and constructive. This is for a beginner entrepreneur."""
history.append({"role": "user", "content": prompt})
response = chat_with_groq(prompt, EVALUATION_PROMPT, history)
history.append({"role": "assistant", "content": response})
session.current_idea = {
"description": idea_desc,
"target_market": target_market,
"problem": problem_stmt,
"solution": solution,
"evaluation": response,
"timestamp": datetime.now().isoformat()
}
session.ideas.append(session.current_idea)
return format_for_chatbot(history), history, f"✅ Idea #{len(session.ideas)} evaluated and saved!"
def refine_idea(refinement_input, history):
"""Refine and improve idea"""
if not session.current_idea:
error_msg = [{"role": "assistant", "content": "⚠️ Please evaluate an idea first in the 'Evaluate Ideas' tab before seeking refinement advice."}]
return format_for_chatbot(error_msg), history, ""
if not refinement_input:
return format_for_chatbot(history), history, ""
prompt = f"""Based on the evaluation of my current idea, I need help with:
{refinement_input}
**Current Idea Summary:**
- Problem: {session.current_idea['problem']}
- Solution: {session.current_idea['solution']}
- Target Market: {session.current_idea['target_market']}
Please provide specific, actionable advice to improve this idea."""
history.append({"role": "user", "content": prompt})
# Include previous evaluation for context
context_messages = [
{"role": "assistant", "content": f"Previous Evaluation:\n{session.current_idea['evaluation']}"},
{"role": "user", "content": prompt}
]
response = chat_with_groq(prompt, REFINEMENT_PROMPT, context_messages)
history.append({"role": "assistant", "content": response})
return format_for_chatbot(history), history, "💡 Refinement suggestions provided"
def create_action_plan(goals, timeline, resources, history):
"""Create action plan"""
if not session.current_idea:
error_msg = [{"role": "assistant", "content": "⚠️ Please evaluate an idea first before creating an action plan."}]
return format_for_chatbot(error_msg), history, ""
if not goals or not timeline:
return format_for_chatbot(history), history, "Please fill in at least Goals and Timeline"
prompt = f"""Create a detailed action plan for my startup idea:
**Idea:** {session.current_idea['description']}
**Problem:** {session.current_idea['problem']}
**Solution:** {session.current_idea['solution']}
**Target Market:** {session.current_idea['target_market']}
**My Goals:** {goals}
**Timeline:** {timeline}
**Available Resources:** {resources}
Please create a comprehensive action plan with:
1. Immediate next steps (this week)
2. Short-term milestones (1 month)
3. Medium-term objectives (3 months)
4. Resource requirements (skills, team, tools, budget)
5. Key metrics to track
6. Potential obstacles and how to overcome them
Make it specific and actionable for an absolute beginner."""
history.append({"role": "user", "content": prompt})
response = chat_with_groq(prompt, ACTION_PLANNING_PROMPT, history)
history.append({"role": "assistant", "content": response})
session.current_idea['action_plan'] = response
session.current_idea['updated'] = datetime.now().isoformat()
return format_for_chatbot(history), history, "📋 Action plan created and saved!"
def export_session():
"""Export all ideas"""
if not session.ideas:
return "No ideas to export yet. Start by discovering and evaluating ideas!", ""
report = f"""# STARTUP IDEATION SESSION REPORT
Generated: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}
Total Ideas Explored: {len(session.ideas)}
{'='*80}
"""
for i, idea in enumerate(session.ideas, 1):
report += f"""
## IDEA {i}: {idea['description'][:100]}{'...' if len(idea['description']) > 100 else ''}
**Target Market:** {idea['target_market']}
**Problem Statement:**
{idea['problem']}
**Solution Approach:**
{idea['solution']}
**Evaluation:**
{idea['evaluation']}
"""
if 'action_plan' in idea:
report += f"""
**Action Plan:**
{idea['action_plan']}
"""
report += f"\n{'='*80}\n"
json_data = json.dumps({
"export_date": datetime.now().isoformat(),
"total_ideas": len(session.ideas),
"ideas": session.ideas
}, indent=2)
return report, json_data
def clear_session():
"""Reset session"""
global session
session = IdeationSession()
return "✅ Session cleared! You can start fresh.", [], []
# Build Gradio Interface
with gr.Blocks(title="Startup Ideation Assistant") as app:
gr.HTML("""
<div style='background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
padding: 2rem; border-radius: 10px; color: white; margin-bottom: 2rem; text-align: center;'>
<h1 style='margin: 0 0 0.5rem 0;'>🚀 Startup Ideation Assistant</h1>
<p style='margin: 0; font-size: 1.1rem;'>AI-Powered Idea Discovery, Evaluation & Planning</p>
</div>
""")
gr.Markdown("""
## Welcome to Your Startup Journey!
This tool guides you through 4 stages:
1. **Discover Ideas** - Generate innovative ideas from 4 proven sources
2. **Evaluate Ideas** - Test viability with critical questions
3. **Refine Ideas** - Strengthen weak areas
4. **Create Action Plan** - Build concrete execution roadmap
""")
discovery_history = gr.State([])
evaluation_history = gr.State([])
refinement_history = gr.State([])
planning_history = gr.State([])
with gr.Tabs():
# TAB 1: IDEA DISCOVERY
with gr.Tab("1️⃣ Discover Ideas"):
gr.Markdown("### Four Sources of Innovative Ideas")
with gr.Row():
with gr.Column(scale=2):
source_selector = gr.Radio(
choices=[
"🔴 Problems",
"🔄 Intersections",
"🔮 Future Trends",
"🧬 Edges of Knowledge"
],
label="Select Idea Source",
value="🔴 Problems"
)
user_context = gr.TextArea(
label="Your Background & Interests",
placeholder="Example: I'm a software developer interested in solving agricultural problems in Pakistan...",
lines=3
)
user_input = gr.TextArea(
label="Your Observation or Question",
placeholder="Example: I noticed farmers waste tons of crop residue after harvest. This could be valuable...",
lines=4
)
discover_btn = gr.Button("💡 Discover Ideas", variant="primary", size="lg")
with gr.Column(scale=3):
discovery_chat = gr.Chatbot(
label="AI Idea Discovery Assistant",
height=500
)
discover_btn.click(
fn=discover_ideas,
inputs=[source_selector, user_input, user_context, discovery_history],
outputs=[discovery_chat, discovery_history]
)
# TAB 2: IDEA EVALUATION
with gr.Tab("2️⃣ Evaluate Ideas"):
gr.Markdown("### The 4-Question Evaluation Framework")
with gr.Row():
with gr.Column():
idea_desc = gr.TextArea(
label="📝 Idea Description",
placeholder="Describe your startup idea in detail...",
lines=3
)
target_market = gr.TextArea(
label="🎯 Target Market",
placeholder="Who are your customers? How many potential users?",
lines=2
)
problem_statement = gr.TextArea(
label="❓ Problem Statement",
placeholder="What problem does this solve? Why is it important?",
lines=3
)
solution_approach = gr.TextArea(
label="💡 Your Solution",
placeholder="How will you solve this problem?",
lines=3
)
evaluate_btn = gr.Button("🔍 Evaluate Idea", variant="primary", size="lg")
eval_status = gr.Textbox(label="Status", interactive=False)
with gr.Row():
evaluation_chat = gr.Chatbot(
label="AI Evaluation Results",
height=500
)
evaluate_btn.click(
fn=evaluate_idea,
inputs=[idea_desc, target_market, problem_statement, solution_approach, evaluation_history],
outputs=[evaluation_chat, evaluation_history, eval_status]
)
# TAB 3: IDEA REFINEMENT
with gr.Tab("3️⃣ Refine Ideas"):
gr.Markdown("### Improve and Strengthen Your Idea")
with gr.Row():
with gr.Column(scale=1):
refinement_input = gr.TextArea(
label="What would you like to improve?",
placeholder="Example: How can I reduce costs? How do I find early customers? What if people don't recognize this problem?",
lines=5
)
refine_btn = gr.Button("✨ Get Refinement Advice", variant="primary", size="lg")
refine_status = gr.Textbox(label="Status", interactive=False)
with gr.Column(scale=2):
refinement_chat = gr.Chatbot(
label="AI Refinement Advisor",
height=600
)
refine_btn.click(
fn=refine_idea,
inputs=[refinement_input, refinement_history],
outputs=[refinement_chat, refinement_history, refine_status]
)
# TAB 4: ACTION PLANNING
with gr.Tab("4️⃣ Create Action Plan"):
gr.Markdown("### From Idea to Execution")
with gr.Row():
with gr.Column():
goals_input = gr.TextArea(
label="🎯 Your Goals",
placeholder="Example: Validate idea with 20 customers, build MVP, find co-founder...",
lines=3
)
timeline_input = gr.TextArea(
label="⏰ Timeline",
placeholder="Example: 3 months, 6 months, 1 year...",
lines=2
)
resources_input = gr.TextArea(
label="💰 Available Resources",
placeholder="Example: Skills (Python, marketing), Time (20hrs/week), Money ($5000), Team (solo)...",
lines=3
)
plan_btn = gr.Button("📋 Create Action Plan", variant="primary", size="lg")
plan_status = gr.Textbox(label="Status", interactive=False)
with gr.Row():
planning_chat = gr.Chatbot(
label="AI Action Plan",
height=500
)
plan_btn.click(
fn=create_action_plan,
inputs=[goals_input, timeline_input, resources_input, planning_history],
outputs=[planning_chat, planning_history, plan_status]
)
# TAB 5: EXPORT & SUMMARY
with gr.Tab("5️⃣ Export & Summary"):
gr.Markdown("### 📊 Your Ideation Journey Summary")
with gr.Row():
export_btn = gr.Button("📥 Generate Report", variant="primary", size="lg")
clear_btn = gr.Button("🗑️ Clear Session", variant="secondary")
with gr.Row():
with gr.Column():
report_output = gr.TextArea(
label="Formatted Report",
lines=20
)
with gr.Column():
json_output = gr.TextArea(
label="JSON Data (for portability)",
lines=20
)
clear_status = gr.Textbox(label="Status", interactive=False)
export_btn.click(fn=export_session, outputs=[report_output, json_output])
clear_btn.click(fn=clear_session, outputs=[clear_status, discovery_history, evaluation_history])
gr.Markdown("""
---
### 👨‍💻 Developed by Najaf Ali Sharqi
*AI-powered startup ideation platform for aspiring entrepreneurs*
""")
if __name__ == "__main__":
app.launch()