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f7edc0
43b2ee6
 
7a12b9e
43b2ee6
 
 
 
7a12b9e
43b2ee6
7a12b9e
 
 
43b2ee6
 
 
7a12b9e
 
0f7edc0
43b2ee6
 
 
0f7edc0
43b2ee6
 
0f7edc0
43b2ee6
 
 
 
 
0f7edc0
43b2ee6
 
 
 
 
 
 
 
 
0f7edc0
43b2ee6
 
0f7edc0
 
43b2ee6
 
 
 
 
 
 
 
 
 
 
 
 
0f7edc0
43b2ee6
 
 
 
 
 
 
 
 
 
 
 
0f7edc0
 
 
 
 
 
62f1a95
0f7edc0
43b2ee6
 
 
 
 
 
 
7a12b9e
43b2ee6
 
 
 
 
 
 
0f7edc0
43b2ee6
 
 
 
d645858
43b2ee6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d645858
43b2ee6
 
 
 
 
 
 
 
 
 
 
0f7edc0
43b2ee6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0f7edc0
43b2ee6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0f7edc0
43b2ee6
 
 
 
 
 
9e74b5e
43b2ee6
 
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
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
"""
MAKER Agent - Chat Interface
=============================
Reliable AI Agent with Web Search & File Upload
Based on: https://arxiv.org/abs/2511.09030
"""

import gradio as gr
import asyncio
import json
import re
import base64
from collections import Counter
from dataclasses import dataclass, field
from typing import Any, Callable, Optional
from pathlib import Path

# ============================================================================
# MAKER Core (Embedded)
# ============================================================================

@dataclass
class VotingConfig:
    k: int = 3
    max_samples: int = 30
    temperature_first: float = 0.0
    temperature_rest: float = 0.1
    parallel_samples: int = 3

@dataclass
class RedFlagConfig:
    max_response_chars: int = 3000
    min_response_length: int = 5
    banned_patterns: list = field(default_factory=lambda: [])


class LLMClient:
    """Universal LLM client."""
    
    def __init__(self, provider: str, api_key: str, model: str = None):
        self.provider = provider.lower()
        self.api_key = api_key
        self.model = model
        self._client = None
        self._setup_client()
    
    def _setup_client(self):
        if self.provider == "openai":
            from openai import AsyncOpenAI
            self._client = AsyncOpenAI(api_key=self.api_key)
            self.model = self.model or "gpt-4o-mini"
        elif self.provider == "anthropic":
            from anthropic import AsyncAnthropic
            self._client = AsyncAnthropic(api_key=self.api_key)
            self.model = self.model or "claude-sonnet-4-20250514"
        elif self.provider == "groq":
            from openai import AsyncOpenAI
            self._client = AsyncOpenAI(api_key=self.api_key, base_url="https://api.groq.com/openai/v1")
            self.model = self.model or "llama-3.3-70b-versatile"
        elif self.provider == "together":
            from openai import AsyncOpenAI
            self._client = AsyncOpenAI(api_key=self.api_key, base_url="https://api.together.xyz/v1")
            self.model = self.model or "meta-llama/Llama-3.3-70B-Instruct-Turbo"
        elif self.provider == "openrouter":
            from openai import AsyncOpenAI
            self._client = AsyncOpenAI(api_key=self.api_key, base_url="https://openrouter.ai/api/v1")
            self.model = self.model or "openai/gpt-4o-mini"
    
    async def generate(self, prompt: str, temperature: float = 0.0, max_tokens: int = 2000) -> str:
        if self.provider == "anthropic":
            r = await self._client.messages.create(
                model=self.model, max_tokens=max_tokens,
                messages=[{"role": "user", "content": prompt}]
            )
            return r.content[0].text
        else:
            r = await self._client.chat.completions.create(
                model=self.model,
                messages=[{"role": "user", "content": prompt}],
                temperature=temperature, max_tokens=max_tokens
            )
            return r.choices[0].message.content


class WebSearch:
    """Web search using DuckDuckGo (free)."""
    
    @staticmethod
    async def search(query: str, num_results: int = 5) -> list:
        try:
            from duckduckgo_search import DDGS
            results = []
            with DDGS() as ddgs:
                for r in ddgs.text(query, max_results=num_results):
                    results.append({
                        "title": r.get("title", ""),
                        "url": r.get("href", ""),
                        "snippet": r.get("body", "")
                    })
            return results
        except Exception as e:
            return [{"title": "Error", "url": "", "snippet": str(e)}]


class FileHandler:
    """Handle file uploads."""
    
    @staticmethod
    async def load_file(file_path: str) -> dict:
        path = Path(file_path)
        ext = path.suffix.lower()
        
        try:
            if ext in {'.txt', '.md', '.json', '.py', '.js', '.html', '.css', '.csv'}:
                content = path.read_text(encoding='utf-8', errors='replace')
                return {"type": "text", "name": path.name, "content": content[:50000]}
            
            elif ext == '.pdf':
                try:
                    import pymupdf
                    doc = pymupdf.open(str(path))
                    text = "\n\n".join([page.get_text() for page in doc])
                    doc.close()
                    return {"type": "pdf", "name": path.name, "content": text[:50000]}
                except ImportError:
                    return {"type": "error", "name": path.name, "content": "PDF requires: pip install pymupdf"}
            
            elif ext == '.docx':
                try:
                    from docx import Document
                    doc = Document(str(path))
                    text = "\n\n".join([p.text for p in doc.paragraphs])
                    return {"type": "docx", "name": path.name, "content": text[:50000]}
                except ImportError:
                    return {"type": "error", "name": path.name, "content": "DOCX requires: pip install python-docx"}
            
            elif ext in {'.png', '.jpg', '.jpeg', '.gif', '.webp'}:
                content = path.read_bytes()
                b64 = base64.b64encode(content).decode('utf-8')
                return {"type": "image", "name": path.name, "base64": b64}
            
            else:
                content = path.read_text(encoding='utf-8', errors='replace')
                return {"type": "text", "name": path.name, "content": content[:50000]}
        
        except Exception as e:
            return {"type": "error", "name": path.name, "content": str(e)}


class MAKERAgent:
    """MAKER Framework Agent."""
    
    def __init__(self, llm: LLMClient, voting: VotingConfig = None, red_flags: RedFlagConfig = None):
        self.llm = llm
        self.voting = voting or VotingConfig()
        self.red_flags = red_flags or RedFlagConfig()
        self.stats = {"samples": 0, "red_flags": 0, "tool_calls": 0}
    
    def _check_red_flags(self, response: str) -> bool:
        if len(response) > self.red_flags.max_response_chars:
            return True
        if len(response) < self.red_flags.min_response_length:
            return True
        for pattern in self.red_flags.banned_patterns:
            if re.search(pattern, response, re.IGNORECASE):
                return True
        return False
    
    def _normalize_response(self, response: str) -> str:
        """Normalize response for voting comparison."""
        return response.strip().lower()
    
    async def execute(self, prompt: str, use_search: bool = False,
                      file_context: str = None, progress_callback: Callable = None) -> dict:
        
        # Build the full prompt
        full_prompt = "You are a helpful assistant. Respond naturally and conversationally.\n\n"
        
        if file_context:
            full_prompt += f"The user has provided the following files for context:\n{file_context}\n\n"
        
        full_prompt += f"User: {prompt}\n\nAssistant:"
        
        # Handle web search if enabled
        search_results = None
        if use_search:
            if progress_callback:
                progress_callback(0.1, "Searching the web...")
            
            search_results = await WebSearch.search(prompt)
            self.stats["tool_calls"] += 1
            
            if search_results and search_results[0].get("title") != "Error":
                search_text = "\n".join([f"- {r['title']}: {r['snippet']}" for r in search_results[:5]])
                full_prompt = f"You are a helpful assistant with access to web search results.\n\n"
                if file_context:
                    full_prompt += f"Files provided:\n{file_context}\n\n"
                full_prompt += f"Web search results for '{prompt}':\n{search_text}\n\n"
                full_prompt += f"User question: {prompt}\n\nProvide a helpful response based on the search results. Assistant:"
        
        if progress_callback:
            progress_callback(0.2, "Getting response...")
        
        # Voting loop
        votes: Counter = Counter()
        responses_map = {}
        samples, flagged = 0, 0
        
        # First sample at temperature 0
        response = await self.llm.generate(full_prompt, temperature=0.0)
        samples += 1
        self.stats["samples"] += 1
        
        if not self._check_red_flags(response):
            key = self._normalize_response(response)
            votes[key] += 1
            responses_map[key] = response
        else:
            flagged += 1
            self.stats["red_flags"] += 1
        
        # Continue voting until we have a winner
        round_num = 1
        while samples < self.voting.max_samples:
            if votes:
                top = votes.most_common(2)
                top_count = top[0][1]
                second_count = top[1][1] if len(top) > 1 else 0
                if top_count - second_count >= self.voting.k:
                    break
            
            round_num += 1
            if progress_callback:
                progress_callback(0.2 + 0.7 * (samples / self.voting.max_samples), f"Voting round {round_num}...")
            
            for _ in range(self.voting.parallel_samples):
                if samples >= self.voting.max_samples:
                    break
                
                response = await self.llm.generate(full_prompt, temperature=self.voting.temperature_rest)
                samples += 1
                self.stats["samples"] += 1
                
                if not self._check_red_flags(response):
                    key = self._normalize_response(response)
                    votes[key] += 1
                    if key not in responses_map:
                        responses_map[key] = response
                else:
                    flagged += 1
                    self.stats["red_flags"] += 1
        
        if progress_callback:
            progress_callback(1.0, "Done!")
        
        if votes:
            top_key, top_count = votes.most_common(1)[0]
            return {
                "success": True,
                "response": responses_map[top_key],
                "votes": top_count,
                "total_samples": samples,
                "red_flagged": flagged,
                "search_results": search_results
            }
        
        return {
            "success": False,
            "response": "I couldn't generate a reliable response. Please try again.",
            "votes": 0,
            "total_samples": samples,
            "red_flagged": flagged,
            "search_results": search_results
        }


# ============================================================================
# Global State
# ============================================================================

current_agent = None
loaded_files = {}

# ============================================================================
# Functions
# ============================================================================

def setup_agent(provider, api_key, model, k_votes):
    global current_agent
    if not api_key:
        return "❌ Please enter your API key", gr.update(interactive=False)
    try:
        llm = LLMClient(provider, api_key, model if model else None)
        current_agent = MAKERAgent(llm, VotingConfig(k=k_votes))
        return f"βœ… Connected to {provider} ({llm.model})", gr.update(interactive=True)
    except Exception as e:
        return f"❌ Error: {e}", gr.update(interactive=False)


def process_files(files):
    global loaded_files
    loaded_files = {}
    
    if not files:
        return "No files attached"
    
    names = []
    for f in files:
        info = asyncio.run(FileHandler.load_file(f.name))
        loaded_files[info['name']] = info
        names.append(info['name'])
    
    return f"πŸ“Ž {', '.join(names)}"


async def chat_async(message, history, use_search, files, progress=gr.Progress()):
    global current_agent, loaded_files
    
    if not current_agent:
        return history + [[message, "⚠️ Please set up your API key first in the Settings tab."]]
    
    # Process any new files
    if files:
        for f in files:
            info = await FileHandler.load_file(f.name)
            loaded_files[info['name']] = info
    
    # Build file context
    file_context = None
    if loaded_files:
        parts = []
        for name, info in loaded_files.items():
            if info["type"] != "image" and info["type"] != "error":
                parts.append(f"=== {name} ===\n{info.get('content', '')[:10000]}")
        if parts:
            file_context = "\n\n".join(parts)
    
    def update_progress(pct, msg):
        progress(pct, desc=msg)
    
    try:
        result = await current_agent.execute(
            message, 
            use_search=use_search,
            file_context=file_context,
            progress_callback=update_progress
        )
        
        response = result["response"]
        
        # Add subtle stats footer
        stats = f"\n\n---\n*{result['votes']} votes, {result['total_samples']} samples*"
        
        return history + [[message, response + stats]]
    
    except Exception as e:
        return history + [[message, f"❌ Error: {str(e)}"]]


def chat(message, history, use_search, files):
    return asyncio.run(chat_async(message, history, use_search, files))


def clear_chat():
    global loaded_files
    loaded_files = {}
    return [], None, "No files attached"


# ============================================================================
# UI
# ============================================================================

with gr.Blocks(title="MAKER Agent") as demo:
    
    # Header
    gr.HTML("""
        <div style="text-align: center; padding: 20px 0 10px 0;">
            <h1 style="font-size: 2rem; margin: 0;">πŸ”§ MAKER Agent</h1>
            <p style="color: #666; margin: 5px 0;">Reliable AI with Voting β€’ <a href="https://arxiv.org/abs/2511.09030" target="_blank">Paper</a></p>
        </div>
    """)
    
    with gr.Tabs():
        
        # Chat Tab
        with gr.Tab("πŸ’¬ Chat"):
            
            chatbot = gr.Chatbot(
                height=450,
            )
            
            with gr.Row():
                with gr.Column(scale=12):
                    msg = gr.Textbox(
                        placeholder="Ask anything...",
                        show_label=False,
                        lines=2,
                    )
                
                with gr.Column(scale=1, min_width=80):
                    send_btn = gr.Button("Send", variant="primary", interactive=False)
            
            with gr.Row():
                with gr.Column(scale=4):
                    file_upload = gr.File(
                        label="",
                        file_count="multiple",
                        file_types=[".pdf", ".docx", ".txt", ".md", ".json", ".csv"],
                        show_label=False,
                    )
                
                with gr.Column(scale=2):
                    file_status = gr.Markdown("No files attached")
                
                with gr.Column(scale=2):
                    use_search = gr.Checkbox(
                        label="πŸ” Web Search",
                        value=False,
                        info="Search DuckDuckGo"
                    )
                
                with gr.Column(scale=1):
                    clear_btn = gr.Button("πŸ—‘οΈ Clear")
            
            # Event handlers
            file_upload.change(process_files, file_upload, file_status)
            
            msg.submit(chat, [msg, chatbot, use_search, file_upload], chatbot).then(
                lambda: "", None, msg
            )
            send_btn.click(chat, [msg, chatbot, use_search, file_upload], chatbot).then(
                lambda: "", None, msg
            )
            clear_btn.click(clear_chat, None, [chatbot, file_upload, file_status])
        
        # Settings Tab
        with gr.Tab("βš™οΈ Settings"):
            
            gr.Markdown("### Connect to an LLM Provider")
            
            with gr.Row():
                with gr.Column():
                    provider = gr.Dropdown(
                        ["groq", "openai", "anthropic", "together", "openrouter"],
                        value="groq",
                        label="Provider",
                        info="Groq is free & fast!"
                    )
                    api_key = gr.Textbox(
                        label="API Key",
                        type="password",
                        placeholder="Paste your API key here..."
                    )
                    model = gr.Textbox(
                        label="Model (optional)",
                        placeholder="Leave blank for default"
                    )
                
                with gr.Column():
                    k_votes = gr.Slider(
                        1, 7, value=3, step=1,
                        label="Reliability (K votes)",
                        info="Higher = more reliable, slower"
                    )
                    
                    gr.Markdown("""
                    ### Get API Keys
                    
                    **Groq** (recommended - free & fast):
                    [console.groq.com](https://console.groq.com)
                    
                    **OpenAI**: [platform.openai.com/api-keys](https://platform.openai.com/api-keys)
                    
                    **Anthropic**: [console.anthropic.com](https://console.anthropic.com)
                    """)
            
            connect_btn = gr.Button("πŸ”Œ Connect", variant="primary")
            status = gr.Markdown("πŸ‘† Enter your API key and click Connect")
            
            connect_btn.click(
                setup_agent,
                [provider, api_key, model, k_votes],
                [status, send_btn]
            )
        
        # About Tab
        with gr.Tab("ℹ️ About"):
            gr.Markdown("""
## How MAKER Works

This agent uses the **MAKER Framework** to achieve reliable AI responses:

1. **Multiple Samples** - Generates several responses for each question
2. **Voting** - Responses "vote" and the winner needs K votes ahead
3. **Red-Flagging** - Suspicious outputs are automatically discarded

### Why This Matters

Instead of hoping the AI gets it right, MAKER uses statistics to ensure reliability. The paper achieved **1 million steps with zero errors** using this approach.

### Features

- πŸ” **Web Search** - Free DuckDuckGo search (no API key needed)
- πŸ“Ž **File Upload** - PDF, DOCX, TXT, MD, JSON, CSV
- ⚑ **Multiple Providers** - Groq, OpenAI, Anthropic, and more

### Links

- πŸ“„ [Research Paper](https://arxiv.org/abs/2511.09030)
- πŸŽ₯ [Video Explanation](https://youtube.com/watch?v=TJ-vWGCosdQ)
""")
    
    # Footer
    gr.HTML("""
        <div style="text-align: center; color: #888; padding: 15px; font-size: 0.85rem;">
            MAKER Framework β€’ <a href="https://arxiv.org/abs/2511.09030" style="color: #888;">arxiv.org/abs/2511.09030</a>
        </div>
    """)

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