Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -8,20 +8,36 @@ import time
|
|
| 8 |
from typing import List, Dict, Generator, Tuple, Optional, Union
|
| 9 |
import logging
|
| 10 |
import warnings
|
| 11 |
-
from dataclasses import dataclass
|
| 12 |
import gc
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 13 |
|
| 14 |
# Set up logging
|
| 15 |
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
|
| 16 |
logger = logging.getLogger(__name__)
|
| 17 |
-
|
| 18 |
warnings.filterwarnings("ignore", message="torch.utils.checkpoint: please pass in use_reentrant=True or use_reentrant=False explicitly")
|
| 19 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 20 |
@dataclass
|
| 21 |
class ModelInfo:
|
| 22 |
id: str
|
| 23 |
name: str
|
| 24 |
required_memory: str # Estimated VRAM requirement
|
|
|
|
|
|
|
| 25 |
|
| 26 |
@dataclass
|
| 27 |
class Persona:
|
|
@@ -31,11 +47,103 @@ class Persona:
|
|
| 31 |
style: str
|
| 32 |
emoji: str
|
| 33 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 34 |
MODELS = [
|
| 35 |
-
ModelInfo(
|
| 36 |
-
|
| 37 |
-
|
| 38 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 39 |
]
|
| 40 |
|
| 41 |
PERSONAS = [
|
|
@@ -69,9 +177,12 @@ PERSONAS = [
|
|
| 69 |
)
|
| 70 |
]
|
| 71 |
|
|
|
|
| 72 |
model_cache = {}
|
| 73 |
current_device = None
|
|
|
|
| 74 |
|
|
|
|
| 75 |
def get_device() -> str:
|
| 76 |
global current_device
|
| 77 |
if current_device:
|
|
@@ -102,32 +213,39 @@ def load_model(model_info: ModelInfo) -> Tuple[pipeline, AutoTokenizer]:
|
|
| 102 |
if model_info.id in model_cache:
|
| 103 |
logger.info(f"Using cached model: {model_info.name}")
|
| 104 |
return model_cache[model_info.id]
|
|
|
|
| 105 |
device = get_device()
|
|
|
|
|
|
|
| 106 |
if device == "cuda":
|
| 107 |
gpu_mem = torch.cuda.get_device_properties(0).total_memory / (1024**3)
|
| 108 |
required_mem = float(model_info.required_memory.replace("GB", ""))
|
| 109 |
-
if gpu_mem < required_mem:
|
| 110 |
logger.warning(f"Insufficient GPU memory for {model_info.name} (needs {required_mem}GB, has {gpu_mem:.1f}GB)")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 111 |
logger.info(f"Loading {model_info.name} on {device}")
|
| 112 |
try:
|
| 113 |
start_time = time.time()
|
| 114 |
tokenizer = AutoTokenizer.from_pretrained(model_info.id)
|
| 115 |
-
|
| 116 |
-
|
| 117 |
-
|
| 118 |
-
|
| 119 |
-
|
| 120 |
-
|
| 121 |
-
|
| 122 |
-
model
|
| 123 |
-
|
| 124 |
-
|
| 125 |
-
|
| 126 |
-
|
| 127 |
-
model=model,
|
| 128 |
-
tokenizer=tokenizer,
|
| 129 |
-
device=model.device
|
| 130 |
-
)
|
| 131 |
model_cache[model_info.id] = (pipe, tokenizer)
|
| 132 |
load_time = time.time() - start_time
|
| 133 |
logger.info(f"Loaded {model_info.name} in {load_time:.1f}s")
|
|
@@ -139,14 +257,15 @@ def load_model(model_info: ModelInfo) -> Tuple[pipeline, AutoTokenizer]:
|
|
| 139 |
def create_debate_prompt(
|
| 140 |
user_prompt: str,
|
| 141 |
persona: Persona,
|
| 142 |
-
debate_style:
|
| 143 |
previous_responses: Optional[List[str]] = None
|
| 144 |
) -> str:
|
| 145 |
style_guidance = {
|
| 146 |
-
|
| 147 |
-
|
| 148 |
-
|
| 149 |
}.get(debate_style, "Present your authentic perspective.")
|
|
|
|
| 150 |
base_prompt = f"""You are {persona.name}, {persona.description}
|
| 151 |
Your communication style: {persona.style}
|
| 152 |
Traits: {persona.traits}
|
|
@@ -155,6 +274,7 @@ You're in a council debating: "{user_prompt}"
|
|
| 155 |
|
| 156 |
{style_guidance}
|
| 157 |
Respond naturally in 3-4 paragraphs."""
|
|
|
|
| 158 |
if previous_responses:
|
| 159 |
debate_history = "\n\n".join(previous_responses)
|
| 160 |
return f"""{base_prompt}
|
|
@@ -164,6 +284,7 @@ Current discussion:
|
|
| 164 |
|
| 165 |
Now respond thoughtfully to the ongoing debate:
|
| 166 |
{persona.name}:"""
|
|
|
|
| 167 |
return f"""{base_prompt}
|
| 168 |
|
| 169 |
Begin your response:
|
|
@@ -193,9 +314,13 @@ def stream_response(
|
|
| 193 |
temperature: float = 0.7,
|
| 194 |
max_tokens: int = 512
|
| 195 |
) -> Generator[str, None, None]:
|
|
|
|
|
|
|
|
|
|
| 196 |
try:
|
| 197 |
streamer = TextIteratorStreamer(tokenizer, skip_prompt=True, skip_special_tokens=True)
|
| 198 |
input_ids = tokenizer(prompt, return_tensors="pt").input_ids.to(pipe.model.device)
|
|
|
|
| 199 |
generation_kwargs = dict(
|
| 200 |
input_ids=input_ids,
|
| 201 |
streamer=streamer,
|
|
@@ -206,22 +331,36 @@ def stream_response(
|
|
| 206 |
repetition_penalty=1.1,
|
| 207 |
eos_token_id=tokenizer.eos_token_id,
|
| 208 |
)
|
|
|
|
| 209 |
thread = threading.Thread(target=pipe.model.generate, kwargs=generation_kwargs)
|
| 210 |
thread.start()
|
|
|
|
| 211 |
buffer = ""
|
| 212 |
for new_text in streamer:
|
| 213 |
buffer += new_text
|
|
|
|
| 214 |
if new_text and new_text[-1] in " .,;!?\n":
|
| 215 |
if speaker_name:
|
| 216 |
yield f"**{speaker_name}:** {buffer.strip()}"
|
| 217 |
else:
|
| 218 |
yield buffer.strip()
|
|
|
|
|
|
|
| 219 |
thread.join()
|
|
|
|
| 220 |
if buffer.strip():
|
| 221 |
if speaker_name:
|
| 222 |
yield f"**{speaker_name}:** {buffer.strip()}"
|
| 223 |
else:
|
| 224 |
yield buffer.strip()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 225 |
except Exception as e:
|
| 226 |
logger.error(f"Streaming error: {str(e)}")
|
| 227 |
error_msg = f"[Error: {str(e)}]"
|
|
@@ -230,21 +369,32 @@ def stream_response(
|
|
| 230 |
def council_chat_stream(
|
| 231 |
user_prompt: str,
|
| 232 |
num_members: int = 3,
|
| 233 |
-
debate_style: str =
|
| 234 |
temperature: float = 0.7,
|
| 235 |
selected_models: Optional[List[str]] = None,
|
| 236 |
continue_debate: bool = False,
|
| 237 |
-
history: Optional[List[str]] = None
|
|
|
|
| 238 |
) -> Generator[str, None, None]:
|
| 239 |
if not user_prompt.strip():
|
| 240 |
yield "Please enter a topic for debate."
|
| 241 |
return
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 242 |
num_members = max(2, min(num_members, len(PERSONAS)))
|
| 243 |
temperature = max(0.1, min(temperature, 1.0))
|
|
|
|
| 244 |
start_time = time.time()
|
| 245 |
selected_personas = random.sample(PERSONAS, num_members)
|
| 246 |
model_pool = selected_models if selected_models else [model.id for model in MODELS]
|
| 247 |
selected_model_infos = random.sample([m for m in MODELS if m.id in model_pool], num_members)
|
|
|
|
| 248 |
loaded_models = []
|
| 249 |
for model_info in selected_model_infos:
|
| 250 |
try:
|
|
@@ -256,41 +406,56 @@ def council_chat_stream(
|
|
| 256 |
logger.error(f"Skipping {model_info.name}: {str(e)}")
|
| 257 |
yield f"⚠️ Couldn't load {model_info.name}, skipping..."
|
| 258 |
continue
|
|
|
|
| 259 |
if not loaded_models:
|
| 260 |
yield "❌ No models could be loaded. Please try again later."
|
| 261 |
return
|
|
|
|
| 262 |
responses = []
|
| 263 |
formatted_responses = []
|
| 264 |
persona_responses = []
|
|
|
|
|
|
|
| 265 |
if continue_debate and history:
|
| 266 |
formatted_responses.extend(history)
|
| 267 |
persona_responses.extend([r.split("**:")[-1].strip() for r in history if "**:" in r])
|
|
|
|
| 268 |
for i, (persona, (pipe, tokenizer, model_info)) in enumerate(zip(selected_personas, loaded_models)):
|
| 269 |
display_name = f"{persona.emoji} {persona.name} ({model_info.name})"
|
|
|
|
|
|
|
| 270 |
thinking_msg = f"**{display_name}** is thinking..."
|
| 271 |
current_output = "\n\n".join([f"**User:** {user_prompt}"] + formatted_responses + [thinking_msg])
|
| 272 |
yield current_output
|
|
|
|
| 273 |
prompt = create_debate_prompt(
|
| 274 |
user_prompt,
|
| 275 |
persona,
|
| 276 |
debate_style,
|
| 277 |
persona_responses if i > 0 else None
|
| 278 |
)
|
|
|
|
| 279 |
full_response = ""
|
| 280 |
for chunk in stream_response(pipe, tokenizer, prompt, display_name, temperature):
|
| 281 |
full_response = chunk
|
| 282 |
current_output = "\n\n".join([f"**User:** {user_prompt}"] + formatted_responses + [chunk])
|
| 283 |
yield current_output
|
|
|
|
| 284 |
persona_responses.append(f"{persona.name}: {full_response.split('**:')[-1].strip()}")
|
| 285 |
formatted_responses.append(full_response)
|
|
|
|
|
|
|
| 286 |
synth_pipe, synth_tokenizer, _ = random.choice(loaded_models)
|
| 287 |
synth_prompt = create_synthesis_prompt(user_prompt, persona_responses)
|
|
|
|
| 288 |
yield "\n\n".join([f"**User:** {user_prompt}"] + formatted_responses + ["✨ **Facilitator** is synthesizing..."])
|
|
|
|
| 289 |
synthesis = ""
|
| 290 |
for chunk in stream_response(synth_pipe, synth_tokenizer, synth_prompt, "✨ Facilitator", temperature):
|
| 291 |
synthesis = chunk
|
| 292 |
current_output = "\n\n".join([f"**User:** {user_prompt}"] + formatted_responses + [chunk])
|
| 293 |
yield current_output
|
|
|
|
| 294 |
elapsed_time = time.time() - start_time
|
| 295 |
transcript = (
|
| 296 |
f"**User:** {user_prompt}\n\n" +
|
|
@@ -298,153 +463,119 @@ def council_chat_stream(
|
|
| 298 |
f"\n\n{synthesis}\n\n" +
|
| 299 |
f"---\n*Debate completed in {elapsed_time:.1f} seconds*"
|
| 300 |
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 301 |
yield transcript
|
| 302 |
|
| 303 |
def council_chat_stream_chatbot(
|
| 304 |
user_prompt: str,
|
| 305 |
num_members: int = 3,
|
| 306 |
-
debate_style: str =
|
| 307 |
temperature: float = 0.7,
|
| 308 |
selected_models: Optional[List[str]] = None,
|
| 309 |
continue_debate: bool = False,
|
| 310 |
-
history: Optional[List[str]] = None
|
|
|
|
| 311 |
) -> Generator[list, None, None]:
|
| 312 |
chat_history = []
|
| 313 |
for output in council_chat_stream(
|
| 314 |
-
user_prompt, num_members, debate_style, temperature,
|
|
|
|
| 315 |
):
|
| 316 |
chat_history.append((None, output))
|
| 317 |
yield chat_history
|
| 318 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 319 |
def build_gradio_interface():
|
| 320 |
custom_css = """
|
| 321 |
.gradio-container { font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; }
|
| 322 |
-
|
| 323 |
-
|
| 324 |
-
|
| 325 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 326 |
"""
|
|
|
|
| 327 |
with gr.Blocks(theme=gr.themes.Soft(), css=custom_css) as demo:
|
| 328 |
current_debate = gr.State([])
|
|
|
|
|
|
|
| 329 |
gr.Markdown("# 🏛️ AI Council Debate\n*Get diverse AI perspectives on any topic*")
|
|
|
|
| 330 |
with gr.Row():
|
| 331 |
with gr.Column(scale=2):
|
| 332 |
-
|
| 333 |
-
|
| 334 |
-
|
| 335 |
-
|
| 336 |
-
|
| 337 |
-
|
| 338 |
-
|
| 339 |
-
with gr.Row():
|
| 340 |
-
num_members = gr.Slider(
|
| 341 |
-
minimum=2,
|
| 342 |
-
maximum=len(PERSONAS),
|
| 343 |
-
value=3,
|
| 344 |
-
step=1,
|
| 345 |
-
label="Number of Council Members"
|
| 346 |
-
)
|
| 347 |
-
debate_style = gr.Radio(
|
| 348 |
-
["Collaborative", "Adversarial", "Balanced"],
|
| 349 |
-
value="Balanced",
|
| 350 |
-
label="Debate Style"
|
| 351 |
-
)
|
| 352 |
-
with gr.Row():
|
| 353 |
-
temperature = gr.Slider(
|
| 354 |
-
minimum=0.1,
|
| 355 |
-
maximum=1.0,
|
| 356 |
-
value=0.7,
|
| 357 |
-
step=0.1,
|
| 358 |
-
label="Creativity (Temperature)"
|
| 359 |
-
)
|
| 360 |
-
model_selection = gr.CheckboxGroup(
|
| 361 |
-
choices=[model.name for model in MODELS],
|
| 362 |
-
value=[model.name for model in MODELS],
|
| 363 |
-
label="Models to Use"
|
| 364 |
-
)
|
| 365 |
-
with gr.Row():
|
| 366 |
-
continue_btn = gr.Checkbox(
|
| 367 |
-
label="Continue Previous Debate",
|
| 368 |
-
value=False
|
| 369 |
-
)
|
| 370 |
-
clear_cache_btn = gr.Button(
|
| 371 |
-
"Clear Model Cache",
|
| 372 |
-
variant="secondary"
|
| 373 |
-
)
|
| 374 |
-
with gr.Row():
|
| 375 |
-
output_style = gr.Radio(
|
| 376 |
-
["Transcript (Markdown)", "Chatbot (Chat History)"],
|
| 377 |
-
value="Transcript (Markdown)",
|
| 378 |
-
label="Output Style"
|
| 379 |
-
)
|
| 380 |
-
submit_btn = gr.Button(
|
| 381 |
-
"Start Debate",
|
| 382 |
-
variant="primary"
|
| 383 |
)
|
| 384 |
-
|
| 385 |
-
|
| 386 |
-
|
| 387 |
-
|
| 388 |
-
|
| 389 |
-
|
| 390 |
-
|
| 391 |
-
|
| 392 |
-
|
| 393 |
-
|
| 394 |
-
|
| 395 |
-
|
| 396 |
-
|
| 397 |
-
|
| 398 |
-
|
| 399 |
-
|
| 400 |
-
|
| 401 |
-
gr.Markdown(f"""
|
| 402 |
-
- **Device:** {'GPU' if torch.cuda.is_available() else 'CPU'}
|
| 403 |
-
- **Available Models:** {len(MODELS)}
|
| 404 |
-
- **Council Members:** {len(PERSONAS)}
|
| 405 |
-
- **Note:** First run may take time to download models
|
| 406 |
-
""")
|
| 407 |
-
def route_debate(user_prompt, num_members, debate_style, temperature, model_selection, continue_btn, current_debate, output_style):
|
| 408 |
-
selected_model_ids = [m.id for m in MODELS if m.name in model_selection]
|
| 409 |
-
if output_style == "Transcript (Markdown)":
|
| 410 |
-
for out in council_chat_stream(
|
| 411 |
-
user_prompt, num_members, debate_style, temperature, selected_model_ids, continue_btn, current_debate
|
| 412 |
-
):
|
| 413 |
-
yield gr.update(visible=True, value=out), gr.update(visible=False)
|
| 414 |
-
else:
|
| 415 |
-
for out in council_chat_stream_chatbot(
|
| 416 |
-
user_prompt, num_members, debate_style, temperature, selected_model_ids, continue_btn, current_debate
|
| 417 |
-
):
|
| 418 |
-
yield gr.update(visible=False), gr.update(visible=True, value=out)
|
| 419 |
-
submit_btn.click(
|
| 420 |
-
route_debate,
|
| 421 |
-
[user_prompt, num_members, debate_style, temperature, model_selection, continue_btn, current_debate, output_style],
|
| 422 |
-
[transcript_out, chatbot_out],
|
| 423 |
-
queue=True
|
| 424 |
-
)
|
| 425 |
-
stop_btn.click(
|
| 426 |
-
fn=None, inputs=None, outputs=None, cancels=[submit_btn]
|
| 427 |
-
)
|
| 428 |
-
clear_cache_btn.click(
|
| 429 |
-
fn=clear_model_cache, inputs=None, outputs=None
|
| 430 |
-
)
|
| 431 |
-
def update_history(history: List[str], new_output: str) -> List[str]:
|
| 432 |
-
if "✨ Facilitator" in new_output:
|
| 433 |
-
return []
|
| 434 |
-
return history + [new_output] if history else [new_output]
|
| 435 |
-
transcript_out.change(
|
| 436 |
-
fn=update_history,
|
| 437 |
-
inputs=[current_debate, transcript_out],
|
| 438 |
-
outputs=current_debate
|
| 439 |
-
)
|
| 440 |
-
return demo
|
| 441 |
-
|
| 442 |
-
if __name__ == "__main__":
|
| 443 |
-
device = get_device()
|
| 444 |
-
if device == "cuda":
|
| 445 |
-
gpu_info = torch.cuda.get_device_properties(0)
|
| 446 |
-
logger.info(f"Using GPU: {gpu_info.name} ({gpu_info.total_memory / (1024**3):.1f}GB)")
|
| 447 |
-
else:
|
| 448 |
-
logger.info("Using CPU")
|
| 449 |
-
demo = build_gradio_interface()
|
| 450 |
-
demo.launch()
|
|
|
|
| 8 |
from typing import List, Dict, Generator, Tuple, Optional, Union
|
| 9 |
import logging
|
| 10 |
import warnings
|
| 11 |
+
from dataclasses import dataclass, field
|
| 12 |
import gc
|
| 13 |
+
from enum import Enum
|
| 14 |
+
import json
|
| 15 |
+
from pathlib import Path
|
| 16 |
+
import uuid
|
| 17 |
+
from datetime import datetime
|
| 18 |
|
| 19 |
# Set up logging
|
| 20 |
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
|
| 21 |
logger = logging.getLogger(__name__)
|
|
|
|
| 22 |
warnings.filterwarnings("ignore", message="torch.utils.checkpoint: please pass in use_reentrant=True or use_reentrant=False explicitly")
|
| 23 |
|
| 24 |
+
# Enums and Data Classes
|
| 25 |
+
class DebateStyle(str, Enum):
|
| 26 |
+
COLLABORATIVE = "Collaborative"
|
| 27 |
+
ADVERSARIAL = "Adversarial"
|
| 28 |
+
BALANCED = "Balanced"
|
| 29 |
+
|
| 30 |
+
class OutputStyle(str, Enum):
|
| 31 |
+
TRANSCRIPT = "Transcript (Markdown)"
|
| 32 |
+
CHATBOT = "Chatbot (Chat History)"
|
| 33 |
+
|
| 34 |
@dataclass
|
| 35 |
class ModelInfo:
|
| 36 |
id: str
|
| 37 |
name: str
|
| 38 |
required_memory: str # Estimated VRAM requirement
|
| 39 |
+
supports_quantization: bool = False
|
| 40 |
+
quantization_config: Optional[Dict] = field(default_factory=dict)
|
| 41 |
|
| 42 |
@dataclass
|
| 43 |
class Persona:
|
|
|
|
| 47 |
style: str
|
| 48 |
emoji: str
|
| 49 |
|
| 50 |
+
@dataclass
|
| 51 |
+
class DebateHistoryItem:
|
| 52 |
+
id: str
|
| 53 |
+
timestamp: float
|
| 54 |
+
topic: str
|
| 55 |
+
transcript: str
|
| 56 |
+
participants: List[str]
|
| 57 |
+
debate_style: str
|
| 58 |
+
|
| 59 |
+
class ModelPerformance:
|
| 60 |
+
def __init__(self):
|
| 61 |
+
self.times = {}
|
| 62 |
+
self.token_counts = {}
|
| 63 |
+
|
| 64 |
+
def record_generation(self, model_id: str, time_taken: float, tokens_generated: int):
|
| 65 |
+
if model_id not in self.times:
|
| 66 |
+
self.times[model_id] = []
|
| 67 |
+
self.token_counts[model_id] = []
|
| 68 |
+
self.times[model_id].append(time_taken)
|
| 69 |
+
self.token_counts[model_id].append(tokens_generated)
|
| 70 |
+
|
| 71 |
+
def get_stats(self, model_id: str) -> Dict:
|
| 72 |
+
times = self.times.get(model_id, [])
|
| 73 |
+
tokens = self.token_counts.get(model_id, [])
|
| 74 |
+
return {
|
| 75 |
+
"avg_time": sum(times) / max(1, len(times)),
|
| 76 |
+
"avg_tokens": sum(tokens) / max(1, len(tokens)),
|
| 77 |
+
"total_calls": len(times),
|
| 78 |
+
"tokens_per_second": sum(tokens) / max(1, sum(times)) if times else 0
|
| 79 |
+
}
|
| 80 |
+
|
| 81 |
+
class DebateHistoryManager:
|
| 82 |
+
HISTORY_FILE = "debate_history.json"
|
| 83 |
+
|
| 84 |
+
@classmethod
|
| 85 |
+
def save_history(cls, item: DebateHistoryItem):
|
| 86 |
+
history = cls.load_history()
|
| 87 |
+
history.append({
|
| 88 |
+
"id": item.id,
|
| 89 |
+
"timestamp": item.timestamp,
|
| 90 |
+
"topic": item.topic,
|
| 91 |
+
"transcript": item.transcript,
|
| 92 |
+
"participants": item.participants,
|
| 93 |
+
"debate_style": item.debate_style
|
| 94 |
+
})
|
| 95 |
+
with open(cls.HISTORY_FILE, "w") as f:
|
| 96 |
+
json.dump(history, f, indent=2)
|
| 97 |
+
|
| 98 |
+
@classmethod
|
| 99 |
+
def load_history(cls) -> List[Dict]:
|
| 100 |
+
path = Path(cls.HISTORY_FILE)
|
| 101 |
+
if not path.exists():
|
| 102 |
+
return []
|
| 103 |
+
try:
|
| 104 |
+
with open(path, "r") as f:
|
| 105 |
+
return json.load(f)
|
| 106 |
+
except Exception as e:
|
| 107 |
+
logger.error(f"Error loading history: {str(e)}")
|
| 108 |
+
return []
|
| 109 |
+
|
| 110 |
+
@classmethod
|
| 111 |
+
def get_history_item(cls, item_id: str) -> Optional[Dict]:
|
| 112 |
+
history = cls.load_history()
|
| 113 |
+
for item in history:
|
| 114 |
+
if item["id"] == item_id:
|
| 115 |
+
return item
|
| 116 |
+
return None
|
| 117 |
+
|
| 118 |
+
# Constants
|
| 119 |
MODELS = [
|
| 120 |
+
ModelInfo(
|
| 121 |
+
"meta-llama/Meta-Llama-3-8B-Instruct",
|
| 122 |
+
"Llama 3 8B Instruct",
|
| 123 |
+
"16GB",
|
| 124 |
+
True,
|
| 125 |
+
{"load_in_4bit": True, "bnb_4bit_compute_dtype": torch.float16}
|
| 126 |
+
),
|
| 127 |
+
ModelInfo(
|
| 128 |
+
"Qwen/Qwen1.5-7B-Chat",
|
| 129 |
+
"Qwen1.5 7B Chat",
|
| 130 |
+
"14GB",
|
| 131 |
+
True,
|
| 132 |
+
{"load_in_4bit": True, "bnb_4bit_compute_dtype": torch.float16}
|
| 133 |
+
),
|
| 134 |
+
ModelInfo(
|
| 135 |
+
"HuggingFaceH4/zephyr-7b-beta",
|
| 136 |
+
"Zephyr 7B Beta",
|
| 137 |
+
"14GB",
|
| 138 |
+
False
|
| 139 |
+
),
|
| 140 |
+
ModelInfo(
|
| 141 |
+
"mistralai/Mistral-7B-Instruct-v0.2",
|
| 142 |
+
"Mistral 7B Instruct",
|
| 143 |
+
"14GB",
|
| 144 |
+
True,
|
| 145 |
+
{"load_in_4bit": True, "bnb_4bit_compute_dtype": torch.float16}
|
| 146 |
+
),
|
| 147 |
]
|
| 148 |
|
| 149 |
PERSONAS = [
|
|
|
|
| 177 |
)
|
| 178 |
]
|
| 179 |
|
| 180 |
+
# Global State
|
| 181 |
model_cache = {}
|
| 182 |
current_device = None
|
| 183 |
+
performance_monitor = ModelPerformance()
|
| 184 |
|
| 185 |
+
# Core Functions
|
| 186 |
def get_device() -> str:
|
| 187 |
global current_device
|
| 188 |
if current_device:
|
|
|
|
| 213 |
if model_info.id in model_cache:
|
| 214 |
logger.info(f"Using cached model: {model_info.name}")
|
| 215 |
return model_cache[model_info.id]
|
| 216 |
+
|
| 217 |
device = get_device()
|
| 218 |
+
kwargs = {"trust_remote_code": True}
|
| 219 |
+
|
| 220 |
if device == "cuda":
|
| 221 |
gpu_mem = torch.cuda.get_device_properties(0).total_memory / (1024**3)
|
| 222 |
required_mem = float(model_info.required_memory.replace("GB", ""))
|
| 223 |
+
if gpu_mem < required_mem and not model_info.supports_quantization:
|
| 224 |
logger.warning(f"Insufficient GPU memory for {model_info.name} (needs {required_mem}GB, has {gpu_mem:.1f}GB)")
|
| 225 |
+
|
| 226 |
+
# Handle quantization if supported and on CUDA
|
| 227 |
+
if device == "cuda" and model_info.supports_quantization:
|
| 228 |
+
kwargs.update(model_info.quantization_config)
|
| 229 |
+
kwargs["device_map"] = "auto"
|
| 230 |
+
else:
|
| 231 |
+
kwargs["torch_dtype"] = torch.float16 if device == "cuda" else torch.float32
|
| 232 |
+
|
| 233 |
logger.info(f"Loading {model_info.name} on {device}")
|
| 234 |
try:
|
| 235 |
start_time = time.time()
|
| 236 |
tokenizer = AutoTokenizer.from_pretrained(model_info.id)
|
| 237 |
+
model = AutoModelForCausalLM.from_pretrained(model_info.id, **kwargs)
|
| 238 |
+
|
| 239 |
+
if device == "cuda" and not model_info.supports_quantization:
|
| 240 |
+
model = model.to(device)
|
| 241 |
+
|
| 242 |
+
pipe = pipeline(
|
| 243 |
+
"text-generation",
|
| 244 |
+
model=model,
|
| 245 |
+
tokenizer=tokenizer,
|
| 246 |
+
device=model.device
|
| 247 |
+
)
|
| 248 |
+
|
|
|
|
|
|
|
|
|
|
|
|
|
| 249 |
model_cache[model_info.id] = (pipe, tokenizer)
|
| 250 |
load_time = time.time() - start_time
|
| 251 |
logger.info(f"Loaded {model_info.name} in {load_time:.1f}s")
|
|
|
|
| 257 |
def create_debate_prompt(
|
| 258 |
user_prompt: str,
|
| 259 |
persona: Persona,
|
| 260 |
+
debate_style: DebateStyle = DebateStyle.BALANCED,
|
| 261 |
previous_responses: Optional[List[str]] = None
|
| 262 |
) -> str:
|
| 263 |
style_guidance = {
|
| 264 |
+
DebateStyle.COLLABORATIVE: "Focus on building upon ideas and finding common ground.",
|
| 265 |
+
DebateStyle.ADVERSARIAL: "Challenge assumptions and present strong contrasting views.",
|
| 266 |
+
DebateStyle.BALANCED: "Present your perspective while respecting others."
|
| 267 |
}.get(debate_style, "Present your authentic perspective.")
|
| 268 |
+
|
| 269 |
base_prompt = f"""You are {persona.name}, {persona.description}
|
| 270 |
Your communication style: {persona.style}
|
| 271 |
Traits: {persona.traits}
|
|
|
|
| 274 |
|
| 275 |
{style_guidance}
|
| 276 |
Respond naturally in 3-4 paragraphs."""
|
| 277 |
+
|
| 278 |
if previous_responses:
|
| 279 |
debate_history = "\n\n".join(previous_responses)
|
| 280 |
return f"""{base_prompt}
|
|
|
|
| 284 |
|
| 285 |
Now respond thoughtfully to the ongoing debate:
|
| 286 |
{persona.name}:"""
|
| 287 |
+
|
| 288 |
return f"""{base_prompt}
|
| 289 |
|
| 290 |
Begin your response:
|
|
|
|
| 314 |
temperature: float = 0.7,
|
| 315 |
max_tokens: int = 512
|
| 316 |
) -> Generator[str, None, None]:
|
| 317 |
+
start_time = time.time()
|
| 318 |
+
tokens_generated = 0
|
| 319 |
+
|
| 320 |
try:
|
| 321 |
streamer = TextIteratorStreamer(tokenizer, skip_prompt=True, skip_special_tokens=True)
|
| 322 |
input_ids = tokenizer(prompt, return_tensors="pt").input_ids.to(pipe.model.device)
|
| 323 |
+
|
| 324 |
generation_kwargs = dict(
|
| 325 |
input_ids=input_ids,
|
| 326 |
streamer=streamer,
|
|
|
|
| 331 |
repetition_penalty=1.1,
|
| 332 |
eos_token_id=tokenizer.eos_token_id,
|
| 333 |
)
|
| 334 |
+
|
| 335 |
thread = threading.Thread(target=pipe.model.generate, kwargs=generation_kwargs)
|
| 336 |
thread.start()
|
| 337 |
+
|
| 338 |
buffer = ""
|
| 339 |
for new_text in streamer:
|
| 340 |
buffer += new_text
|
| 341 |
+
tokens_generated += len(tokenizer.encode(new_text))
|
| 342 |
if new_text and new_text[-1] in " .,;!?\n":
|
| 343 |
if speaker_name:
|
| 344 |
yield f"**{speaker_name}:** {buffer.strip()}"
|
| 345 |
else:
|
| 346 |
yield buffer.strip()
|
| 347 |
+
buffer = ""
|
| 348 |
+
|
| 349 |
thread.join()
|
| 350 |
+
|
| 351 |
if buffer.strip():
|
| 352 |
if speaker_name:
|
| 353 |
yield f"**{speaker_name}:** {buffer.strip()}"
|
| 354 |
else:
|
| 355 |
yield buffer.strip()
|
| 356 |
+
|
| 357 |
+
# Record performance metrics
|
| 358 |
+
performance_monitor.record_generation(
|
| 359 |
+
pipe.model.config._name_or_path,
|
| 360 |
+
time.time() - start_time,
|
| 361 |
+
tokens_generated
|
| 362 |
+
)
|
| 363 |
+
|
| 364 |
except Exception as e:
|
| 365 |
logger.error(f"Streaming error: {str(e)}")
|
| 366 |
error_msg = f"[Error: {str(e)}]"
|
|
|
|
| 369 |
def council_chat_stream(
|
| 370 |
user_prompt: str,
|
| 371 |
num_members: int = 3,
|
| 372 |
+
debate_style: Union[DebateStyle, str] = DebateStyle.BALANCED,
|
| 373 |
temperature: float = 0.7,
|
| 374 |
selected_models: Optional[List[str]] = None,
|
| 375 |
continue_debate: bool = False,
|
| 376 |
+
history: Optional[List[str]] = None,
|
| 377 |
+
save_history: bool = True
|
| 378 |
) -> Generator[str, None, None]:
|
| 379 |
if not user_prompt.strip():
|
| 380 |
yield "Please enter a topic for debate."
|
| 381 |
return
|
| 382 |
+
|
| 383 |
+
# Convert string style to Enum if needed
|
| 384 |
+
if isinstance(debate_style, str):
|
| 385 |
+
try:
|
| 386 |
+
debate_style = DebateStyle(debate_style)
|
| 387 |
+
except ValueError:
|
| 388 |
+
debate_style = DebateStyle.BALANCED
|
| 389 |
+
|
| 390 |
num_members = max(2, min(num_members, len(PERSONAS)))
|
| 391 |
temperature = max(0.1, min(temperature, 1.0))
|
| 392 |
+
|
| 393 |
start_time = time.time()
|
| 394 |
selected_personas = random.sample(PERSONAS, num_members)
|
| 395 |
model_pool = selected_models if selected_models else [model.id for model in MODELS]
|
| 396 |
selected_model_infos = random.sample([m for m in MODELS if m.id in model_pool], num_members)
|
| 397 |
+
|
| 398 |
loaded_models = []
|
| 399 |
for model_info in selected_model_infos:
|
| 400 |
try:
|
|
|
|
| 406 |
logger.error(f"Skipping {model_info.name}: {str(e)}")
|
| 407 |
yield f"⚠️ Couldn't load {model_info.name}, skipping..."
|
| 408 |
continue
|
| 409 |
+
|
| 410 |
if not loaded_models:
|
| 411 |
yield "❌ No models could be loaded. Please try again later."
|
| 412 |
return
|
| 413 |
+
|
| 414 |
responses = []
|
| 415 |
formatted_responses = []
|
| 416 |
persona_responses = []
|
| 417 |
+
participant_names = []
|
| 418 |
+
|
| 419 |
if continue_debate and history:
|
| 420 |
formatted_responses.extend(history)
|
| 421 |
persona_responses.extend([r.split("**:")[-1].strip() for r in history if "**:" in r])
|
| 422 |
+
|
| 423 |
for i, (persona, (pipe, tokenizer, model_info)) in enumerate(zip(selected_personas, loaded_models)):
|
| 424 |
display_name = f"{persona.emoji} {persona.name} ({model_info.name})"
|
| 425 |
+
participant_names.append(display_name)
|
| 426 |
+
|
| 427 |
thinking_msg = f"**{display_name}** is thinking..."
|
| 428 |
current_output = "\n\n".join([f"**User:** {user_prompt}"] + formatted_responses + [thinking_msg])
|
| 429 |
yield current_output
|
| 430 |
+
|
| 431 |
prompt = create_debate_prompt(
|
| 432 |
user_prompt,
|
| 433 |
persona,
|
| 434 |
debate_style,
|
| 435 |
persona_responses if i > 0 else None
|
| 436 |
)
|
| 437 |
+
|
| 438 |
full_response = ""
|
| 439 |
for chunk in stream_response(pipe, tokenizer, prompt, display_name, temperature):
|
| 440 |
full_response = chunk
|
| 441 |
current_output = "\n\n".join([f"**User:** {user_prompt}"] + formatted_responses + [chunk])
|
| 442 |
yield current_output
|
| 443 |
+
|
| 444 |
persona_responses.append(f"{persona.name}: {full_response.split('**:')[-1].strip()}")
|
| 445 |
formatted_responses.append(full_response)
|
| 446 |
+
|
| 447 |
+
# Generate synthesis
|
| 448 |
synth_pipe, synth_tokenizer, _ = random.choice(loaded_models)
|
| 449 |
synth_prompt = create_synthesis_prompt(user_prompt, persona_responses)
|
| 450 |
+
|
| 451 |
yield "\n\n".join([f"**User:** {user_prompt}"] + formatted_responses + ["✨ **Facilitator** is synthesizing..."])
|
| 452 |
+
|
| 453 |
synthesis = ""
|
| 454 |
for chunk in stream_response(synth_pipe, synth_tokenizer, synth_prompt, "✨ Facilitator", temperature):
|
| 455 |
synthesis = chunk
|
| 456 |
current_output = "\n\n".join([f"**User:** {user_prompt}"] + formatted_responses + [chunk])
|
| 457 |
yield current_output
|
| 458 |
+
|
| 459 |
elapsed_time = time.time() - start_time
|
| 460 |
transcript = (
|
| 461 |
f"**User:** {user_prompt}\n\n" +
|
|
|
|
| 463 |
f"\n\n{synthesis}\n\n" +
|
| 464 |
f"---\n*Debate completed in {elapsed_time:.1f} seconds*"
|
| 465 |
)
|
| 466 |
+
|
| 467 |
+
# Save to history
|
| 468 |
+
if save_history:
|
| 469 |
+
history_item = DebateHistoryItem(
|
| 470 |
+
id=str(uuid.uuid4()),
|
| 471 |
+
timestamp=time.time(),
|
| 472 |
+
topic=user_prompt,
|
| 473 |
+
transcript=transcript,
|
| 474 |
+
participants=participant_names,
|
| 475 |
+
debate_style=debate_style.value
|
| 476 |
+
)
|
| 477 |
+
DebateHistoryManager.save_history(history_item)
|
| 478 |
+
|
| 479 |
yield transcript
|
| 480 |
|
| 481 |
def council_chat_stream_chatbot(
|
| 482 |
user_prompt: str,
|
| 483 |
num_members: int = 3,
|
| 484 |
+
debate_style: Union[DebateStyle, str] = DebateStyle.BALANCED,
|
| 485 |
temperature: float = 0.7,
|
| 486 |
selected_models: Optional[List[str]] = None,
|
| 487 |
continue_debate: bool = False,
|
| 488 |
+
history: Optional[List[str]] = None,
|
| 489 |
+
save_history: bool = True
|
| 490 |
) -> Generator[list, None, None]:
|
| 491 |
chat_history = []
|
| 492 |
for output in council_chat_stream(
|
| 493 |
+
user_prompt, num_members, debate_style, temperature,
|
| 494 |
+
selected_models, continue_debate, history, save_history
|
| 495 |
):
|
| 496 |
chat_history.append((None, output))
|
| 497 |
yield chat_history
|
| 498 |
|
| 499 |
+
# UI Components
|
| 500 |
+
def build_persona_card(persona: Persona) -> gr.Box:
|
| 501 |
+
with gr.Box(elem_classes="member-card") as card:
|
| 502 |
+
gr.Markdown(f"""
|
| 503 |
+
<h3>{persona.emoji} {persona.name}</h3>
|
| 504 |
+
<p><strong>Description:</strong> {persona.description}</p>
|
| 505 |
+
<p><strong>Traits:</strong> {persona.traits}</p>
|
| 506 |
+
<p><strong>Style:</strong> {persona.style}</p>
|
| 507 |
+
""")
|
| 508 |
+
return card
|
| 509 |
+
|
| 510 |
+
def build_model_info_card(model: ModelInfo) -> gr.Box:
|
| 511 |
+
with gr.Box(elem_classes="model-card") as card:
|
| 512 |
+
gr.Markdown(f"""
|
| 513 |
+
<h3>{model.name}</h3>
|
| 514 |
+
<p><strong>ID:</strong> {model.id}</p>
|
| 515 |
+
<p><strong>Memory Requirement:</strong> {model.required_memory}</p>
|
| 516 |
+
<p><strong>Quantization:</strong> {'Supported' if model.supports_quantization else 'Not Supported'}</p>
|
| 517 |
+
""")
|
| 518 |
+
return card
|
| 519 |
+
|
| 520 |
+
def build_history_item_ui(history_item: Dict) -> gr.Box:
|
| 521 |
+
with gr.Box(elem_classes="history-item") as item:
|
| 522 |
+
with gr.Row():
|
| 523 |
+
with gr.Column(scale=3):
|
| 524 |
+
gr.Markdown(f"**{history_item['topic']}**")
|
| 525 |
+
gr.Markdown(f"*{datetime.fromtimestamp(history_item['timestamp']).strftime('%Y-%m-%d %H:%M:%S')}*")
|
| 526 |
+
with gr.Column(scale=1):
|
| 527 |
+
view_btn = gr.Button("View", size="sm")
|
| 528 |
+
load_btn = gr.Button("Load", size="sm")
|
| 529 |
+
return item, view_btn, load_btn
|
| 530 |
+
|
| 531 |
+
# Gradio Interface
|
| 532 |
def build_gradio_interface():
|
| 533 |
custom_css = """
|
| 534 |
.gradio-container { font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; }
|
| 535 |
+
.member-card, .model-card, .history-item {
|
| 536 |
+
border: 1px solid #e0e0e0;
|
| 537 |
+
border-radius: 8px;
|
| 538 |
+
padding: 15px;
|
| 539 |
+
margin-bottom: 15px;
|
| 540 |
+
background: #f9f9f9;
|
| 541 |
+
}
|
| 542 |
+
.member-card h3, .model-card h3 { margin-top: 0; color: #333; }
|
| 543 |
+
#transcript-container { position: relative; max-height: 600px; overflow-y: auto; }
|
| 544 |
+
#chatbot-container { max-height: 600px; }
|
| 545 |
+
.stats-table { width: 100%; border-collapse: collapse; }
|
| 546 |
+
.stats-table th, .stats-table td { padding: 8px; text-align: left; border-bottom: 1px solid #ddd; }
|
| 547 |
"""
|
| 548 |
+
|
| 549 |
with gr.Blocks(theme=gr.themes.Soft(), css=custom_css) as demo:
|
| 550 |
current_debate = gr.State([])
|
| 551 |
+
current_history_id = gr.State(None)
|
| 552 |
+
|
| 553 |
gr.Markdown("# 🏛️ AI Council Debate\n*Get diverse AI perspectives on any topic*")
|
| 554 |
+
|
| 555 |
with gr.Row():
|
| 556 |
with gr.Column(scale=2):
|
| 557 |
+
# Debate Input Section
|
| 558 |
+
with gr.Group():
|
| 559 |
+
user_prompt = gr.Textbox(
|
| 560 |
+
label="Debate Topic",
|
| 561 |
+
placeholder="Enter your question or topic for debate...",
|
| 562 |
+
lines=4,
|
| 563 |
+
max_lines=6
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 564 |
)
|
| 565 |
+
|
| 566 |
+
with gr.Accordion("⚙️ Debate Settings", open=False):
|
| 567 |
+
with gr.Row():
|
| 568 |
+
num_members = gr.Slider(
|
| 569 |
+
minimum=2,
|
| 570 |
+
maximum=len(PERSONAS),
|
| 571 |
+
value=3,
|
| 572 |
+
step=1,
|
| 573 |
+
label="Number of Council Members"
|
| 574 |
+
)
|
| 575 |
+
debate_style = gr.Radio(
|
| 576 |
+
list(DebateStyle),
|
| 577 |
+
value=DebateStyle.BALANCED,
|
| 578 |
+
label="Debate Style"
|
| 579 |
+
)
|
| 580 |
+
|
| 581 |
+
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|