File size: 11,206 Bytes
3e1f34a
 
 
 
 
b0f28b8
3e1f34a
 
b0f28b8
3e1f34a
b0f28b8
 
3e1f34a
b0f28b8
3e1f34a
b0f28b8
 
3e1f34a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
29dd2f7
 
3e1f34a
b0f28b8
3e1f34a
 
 
 
 
b0f28b8
3e1f34a
 
 
b0f28b8
3e1f34a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3ea5cae
3e1f34a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3ea5cae
3e1f34a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3ea5cae
3e1f34a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3ea5cae
3e1f34a
 
 
 
 
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
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
import gradio as gr
from gtts import gTTS
import tempfile
import time
import os
from openai import OpenAI

# ============================================================
# CONFIGURATION — AMD GPU via vLLM
# ============================================================
VLLM_BASE_URL = os.environ.get("VLLM_BASE_URL", "http://129.212.178.240:8000/v1")
MODEL_NAME = os.environ.get("MODEL_NAME", "facebook/opt-125m")

client = OpenAI(base_url=VLLM_BASE_URL, api_key="dummy")

print("Model:", MODEL_NAME)
print("AMD vLLM URL:", VLLM_BASE_URL)
# ============================================================
# AGENT DEFINITIONS
# ============================================================
AGENTS = {
    "PM Agent": {
        "role": "Project Manager",
        "system_prompt": """You are a sharp, experienced Project Manager (PM Agent) in a multi-agent AI debate system called SynapseOS.
Your job is to analyze business/product ideas strategically.
Always respond with:
1. Project Phases breakdown (Research, Design, Build, Test, Launch) with realistic timelines
2. Key milestones and deliverables
3. Resource requirements (team size, roles needed)
4. Potential risks and mitigation strategies
5. Your GO / NO-GO recommendation

Be detailed, structured, and professional. Write at least 150 words."""
    },
    "Developer Agent": {
        "role": "Senior Developer",
        "system_prompt": """You are a highly skilled Senior Developer (Developer Agent) in a multi-agent AI debate system called SynapseOS.
Your job is to analyze the technical feasibility and architecture of ideas.
Always respond with:
1. Recommended tech stack (frontend, backend, database, cloud)
2. System architecture overview (monolith vs microservices, APIs needed)
3. Key technical challenges and how to solve them
4. Development timeline estimate
5. Scalability considerations

Be technical, specific, and practical. Write at least 150 words."""
    },
    "Critic Agent": {
        "role": "Critical Analyst",
        "system_prompt": """You are a sharp Devil's Advocate (Critic Agent) in a multi-agent AI debate system called SynapseOS.
Your job is to find flaws, risks, and blind spots in ideas — helping make them stronger.
Always respond with:
1. Market risks and competition analysis
2. Fundamental flaws or weak assumptions in the idea
3. Questions the team has not answered yet
4. Scenarios where this could fail badly
5. What absolutely MUST be addressed before moving forward

Be blunt, analytical, and constructive. Write at least 150 words."""
    },
    "Finance Agent": {
        "role": "Financial Analyst",
        "system_prompt": """You are a data-driven Financial Analyst (Finance Agent) in a multi-agent AI debate system called SynapseOS.
Your job is to evaluate the financial viability and ROI of ideas.
Always respond with:
1. Estimated development and operational costs
2. Revenue model options (freemium, subscription, one-time, ads, B2B)
3. Break-even analysis (how many users/customers needed)
4. Funding strategy (bootstrap, angel, VC, grants)
5. Year 1 financial projections and key metrics to track

Be specific with numbers and realistic. Write at least 150 words."""
    },
    "Security Agent": {
        "role": "Security Expert",
        "system_prompt": """You are a vigilant Security Expert (Security Agent) in a multi-agent AI debate system called SynapseOS.
Your job is to identify security, privacy, and compliance risks in ideas.
Always respond with:
1. Key security vulnerabilities to address (OWASP Top 10, etc.)
2. Data privacy concerns and GDPR/compliance requirements
3. Authentication and authorization recommendations
4. Infrastructure security best practices
5. Security testing strategy before launch

Be thorough and practical. Write at least 150 words."""
    }
}

# ============================================================
# MEMORY SYSTEM
# ============================================================
memory = {
    "conversations": [],
    "debates": []
}

# ============================================================
# MODEL CALL FUNCTION
# ============================================================
def call_hf_model(system_prompt: str, user_idea: str, max_new_tokens: int = 500) -> str:
    try:
        response = client.chat.completions.create(
            model=MODEL_NAME,
            messages=[
                {"role": "system", "content": system_prompt},
                {"role": "user", "content": f"Analyze this idea in detail: {user_idea}"}
            ],
            max_tokens=max_new_tokens,
            temperature=0.7
        )
        return response.choices[0].message.content.strip()
    except Exception as e:
        return f"Error: {str(e)}"
# ============================================================
# TEXT TO SPEECH
# ============================================================
def generate_voice_summary(idea: str):
    summary = (
        f"SynapseOS debate complete for: {idea}. "
        f"Five expert agents have analyzed this idea. "
        f"The PM Agent has broken it into phases. "
        f"The Developer Agent has outlined the tech stack. "
        f"The Critic Agent has identified key risks. "
        f"The Finance Agent has projected financials. "
        f"The Security Agent has flagged privacy concerns. "
        f"Check the full debate above for detailed insights."
    )
    try:
        tts = gTTS(text=summary, lang="en", slow=False)
        tmp = tempfile.NamedTemporaryFile(delete=False, suffix=".mp3")
        tts.save(tmp.name)
        return tmp.name
    except Exception as e:
        print(f"TTS Error: {e}")
        return None

# ============================================================
# MAIN DEBATE FUNCTION
# ============================================================
def run_debate(user_idea: str, progress=gr.Progress()):
    if not user_idea.strip():
        return "Please enter your idea first!", "No idea provided.", None

    memory["conversations"].append(user_idea)

    full_debate = "# SynapseOS — Agent Debate\n\n"
    full_debate += f"**Idea Under Analysis:** {user_idea}\n\n"
    full_debate += "**Model:** Qwen2.5-0-5B-Instruct (HuggingFace Free Tier)\n\n"
    full_debate += "---\n\n"

    agent_list = list(AGENTS.keys())
    responses_collected = {}

    for i, agent_name in enumerate(agent_list):
        agent = AGENTS[agent_name]
        progress((i + 0.5) / len(agent_list), desc=f"{agent_name} is analyzing...")

        full_debate += f"## {agent_name} — *{agent['role']}*\n\n"

        response = call_hf_model(agent["system_prompt"], user_idea, max_new_tokens=500)
        responses_collected[agent_name] = response

        full_debate += f"{response}\n\n"
        full_debate += "---\n\n"

        progress((i + 1) / len(agent_list), desc=f"{agent_name} done!")
        time.sleep(1)

    # Final PM Consensus
    progress(0.95, desc="PM Agent writing final decision...")
    full_debate += "## Final Decision — PM Agent\n\n"

    consensus_prompt = """You are the PM Agent in SynapseOS. Five agents just debated a business idea.
Write a FINAL GO/NO-GO decision with:
1. Your verdict (GO / CONDITIONAL GO / NO-GO)
2. Top 3 action items to start immediately
3. The single biggest risk to monitor
Keep it under 100 words, punchy and decisive."""

    consensus = call_hf_model(consensus_prompt, user_idea, max_new_tokens=200)
    full_debate += f"{consensus}\n\n"

    memory["debates"].append({
        "idea": user_idea,
        "agents": responses_collected
    })

    status = f"Debate complete! {len(memory['conversations'])} idea(s) analyzed. 5 agents responded in detail."
    audio_path = generate_voice_summary(user_idea)

    return full_debate, status, audio_path

# ============================================================
# MEMORY VIEW
# ============================================================
def show_memory():
    if not memory["conversations"]:
        return "No ideas debated yet. Start your first debate!"

    result = "## SynapseOS Memory\n\n"
    result += f"**Total ideas analyzed:** {len(memory['conversations'])}\n\n"
    for i, idea in enumerate(memory["conversations"], 1):
        result += f"**{i}.** {idea}\n\n"
    return result

# ============================================================
# GRADIO UI
# ============================================================
with gr.Blocks(
    title="SynapseOS — AI Agent Debate",
    theme=gr.themes.Soft(
        primary_hue="indigo",
        secondary_hue="emerald",
        neutral_hue="slate"
    ),
    css="""
    .gradio-container { max-width: 1100px !important; }
    #debate-output { min-height: 400px; }
    """
) as app:

    gr.Markdown("""
# SynapseOS — AI Agent Civilization
### 5 Expert AI Agents Debate Your Idea in Real-Time
**Powered by Qwen2.5-0-5B (HuggingFace Free) · English Only · Voice Summary Included**

> Each agent calls the HuggingFace API independently and gives a detailed, unique analysis of your idea.
    """)

    with gr.Row():
        with gr.Column(scale=3):
            idea_input = gr.Textbox(
                label="Your Idea or Problem",
                placeholder="e.g. Build a scam protection app for senior citizens in India",
                lines=3,
                info="Describe your startup idea, product, or problem in detail for best results."
            )
            debate_btn = gr.Button(
                "Launch 5-Agent Debate!",
                variant="primary",
                size="lg"
            )
            status_box = gr.Textbox(
                label="Status",
                interactive=False,
                value="Ready. Enter your idea and click Launch!"
            )

        with gr.Column(scale=1):
            gr.Markdown("""
## The 5 Agents

| Agent | Role |
|-------|------|
| PM Agent | Strategy and Planning |
| Developer | Tech Architecture |
| Critic | Risks and Flaws |
| Finance | ROI and Revenue |
| Security | Privacy and Safety |

## How It Works
1. You enter an idea
2. Each agent calls Qwen2.5-0-5B on HuggingFace
3. Gets a detailed 150+ word response
4. PM Agent gives final GO/NO-GO
5. Voice summary generated!
            """)

    with gr.Row():
        memory_btn = gr.Button("View Memory (All Past Ideas)", variant="secondary")

    with gr.Row():
        with gr.Column():
            debate_output = gr.Markdown(
                label="Live Agent Debate",
                elem_id="debate-output",
                value="*Your debate will appear here...*"
            )

    with gr.Row():
        audio_output = gr.Audio(
            label="Voice Summary (English)",
            type="filepath"
        )

    memory_output = gr.Markdown(visible=True)

    debate_btn.click(
        fn=run_debate,
        inputs=[idea_input],
        outputs=[debate_output, status_box, audio_output]
    )

    memory_btn.click(
        fn=show_memory,
        outputs=[memory_output]
    )

    gr.Markdown("""
---
**Setup:** Set your HuggingFace token as HF_TOKEN in .env file.
**Free Model:** Qwen/Qwen2.5-0-5B-Instruct — free on HuggingFace Inference API.
**Install:** pip install gradio huggingface_hub gtts
    """)

if __name__ == "__main__":
    app.launch(share=True)