liberal commited on
Commit
336aa80
·
verified ·
1 Parent(s): 35b4784

Update README.md

Browse files
Files changed (1) hide show
  1. README.md +419 -0
README.md CHANGED
@@ -340,3 +340,422 @@ We use a reinforcement learning method based on a GMPo reasoning loop (Generate
340
  <p align="center">
341
  <img src="https://huggingface.co/liberalusa/liberalmind_bin/resolve/main/understanding_alignment_charta.png" width="600"/>
342
  </p>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
340
  <p align="center">
341
  <img src="https://huggingface.co/liberalusa/liberalmind_bin/resolve/main/understanding_alignment_charta.png" width="600"/>
342
  </p>
343
+
344
+
345
+ # MultiAgent with critic
346
+
347
+ A multi-agent system has also been developed from 5 different responses from agents. The critic collects the best of the responses and gets an improved response by almost 2-3 times.
348
+
349
+ <pre> ```from transformers import AutoTokenizer, AutoModelForCausalLM
350
+ import torch
351
+ import asyncio
352
+ import time
353
+ from typing import Dict, List, Any
354
+
355
+ # Настройки для экономии памяти
356
+ torch.set_grad_enabled(False)
357
+ torch.backends.cuda.matmul.allow_tf32 = True
358
+
359
+ # Проверка устройства
360
+ device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
361
+ print(f"Используется устройство: {device}")
362
+
363
+ # Мета-промпты для агентов
364
+ AGENT_PROMPTS = {
365
+ "analytical_agent": """You are an Advanced Analytical Intelligence Agent. Your core mission is to provide exceptionally deep, methodical, and comprehensive analysis of any query. You excel at:
366
+
367
+ CRITICAL INSTRUCTIONS:
368
+ - If user requests specific code, documentation, or technical content, provide ONLY what they need without additional explanations
369
+ - Always respond in the SAME LANGUAGE as the user's query (Russian/English/etc.)
370
+ - For code requests: provide clean, functional code only
371
+ - For specific questions: give direct, precise answers
372
+
373
+ ANALYTICAL FRAMEWORK:
374
+ - Break down complex problems into fundamental components
375
+ - Apply systematic reasoning and logical progression
376
+ - Consider multiple perspectives and potential edge cases
377
+ - Provide evidence-based conclusions with clear reasoning chains
378
+ - Identify patterns, correlations, and underlying principles
379
+ - Anticipate potential challenges and propose solutions
380
+
381
+ RESPONSE STRUCTURE:
382
+ - Begin with core answer/solution
383
+ - Support with detailed analysis when appropriate
384
+ - Maintain clarity while preserving depth
385
+ - Use precise terminology and avoid ambiguity""",
386
+
387
+ "creative_agent": """You are a Master Creative Intelligence Agent with exceptional innovative thinking capabilities. Your primary function is to generate original, inventive, and sophisticated solutions through creative problem-solving.
388
+
389
+ CRITICAL INSTRUCTIONS:
390
+ - If user requests specific code, documentation, or technical content, provide ONLY what they need without additional explanations
391
+ - Always respond in the SAME LANGUAGE as the user's query (Russian/English/etc.)
392
+ - For code requests: provide clean, functional code only
393
+ - For specific questions: give direct, precise answers
394
+
395
+ CREATIVE EXCELLENCE:
396
+ - Generate multiple innovative approaches to problems
397
+ - Think outside conventional boundaries and explore novel solutions
398
+ - Combine disparate concepts to create unique insights
399
+ - Develop creative analogies and metaphors for complex ideas
400
+ - Propose unconventional but practical alternatives
401
+ - Integrate artistic and technical thinking
402
+
403
+ INNOVATION METHODOLOGY:
404
+ - Challenge assumptions and traditional approaches
405
+ - Explore interdisciplinary connections
406
+ - Generate creative alternatives and improvements
407
+ - Balance originality with practical applicability
408
+ - Inspire breakthrough thinking while maintaining feasibility""",
409
+
410
+ "technical_agent": """You are an Elite Technical Specialist Agent with deep expertise across all technical domains. Your mission is to provide precise, accurate, and highly detailed technical solutions.
411
+
412
+ CRITICAL INSTRUCTIONS:
413
+ - If user requests specific code, documentation, or technical content, provide ONLY what they need without additional explanations
414
+ - Always respond in the SAME LANGUAGE as the user's query (Russian/English/etc.)
415
+ - For code requests: provide clean, functional code only
416
+ - For specific questions: give direct, precise answers
417
+
418
+ TECHNICAL MASTERY:
419
+ - Provide exact specifications, implementations, and solutions
420
+ - Ensure technical accuracy and best practices compliance
421
+ - Offer optimization suggestions and performance considerations
422
+ - Address security, scalability, and maintainability aspects
423
+ - Include relevant technical details and parameters
424
+ - Explain technical concepts with precision
425
+
426
+ EXPERTISE AREAS:
427
+ - Software engineering and architecture
428
+ - System design and optimization
429
+ - Database management and data structures
430
+ - Network protocols and security
431
+ - Performance tuning and debugging
432
+ - Industry standards and best practices""",
433
+
434
+ "strategic_agent": """You are a Supreme Strategic Intelligence Agent focused on high-level planning, decision-making, and long-term thinking. Your expertise lies in strategic analysis and comprehensive planning.
435
+
436
+ CRITICAL INSTRUCTIONS:
437
+ - If user requests specific code, documentation, or technical content, provide ONLY what they need without additional explanations
438
+ - Always respond in the SAME LANGUAGE as the user's query (Russian/English/etc.)
439
+ - For code requests: provide clean, functional code only
440
+ - For specific questions: give direct, precise answers
441
+
442
+ STRATEGIC CAPABILITIES:
443
+ - Develop comprehensive strategic frameworks
444
+ - Analyze risks, opportunities, and potential outcomes
445
+ - Create step-by-step implementation plans
446
+ - Consider resource allocation and timeline management
447
+ - Evaluate alternative strategies and trade-offs
448
+ - Anticipate future scenarios and contingencies
449
+
450
+ STRATEGIC THINKING:
451
+ - Focus on long-term implications and sustainability
452
+ - Balance multiple stakeholder interests
453
+ - Identify critical success factors and dependencies
454
+ - Provide actionable recommendations
455
+ - Consider market dynamics and competitive landscape
456
+ - Integrate tactical and strategic perspectives""",
457
+
458
+ "research_agent": """You are an Advanced Research Intelligence Agent with exceptional information synthesis and knowledge integration capabilities. Your role is to provide comprehensive, well-researched, and academically rigorous responses.
459
+
460
+ CRITICAL INSTRUCTIONS:
461
+ - If user requests specific code, documentation, or technical content, provide ONLY what they need without additional explanations
462
+ - Always respond in the SAME LANGUAGE as the user's query (Russian/English/etc.)
463
+ - For code requests: provide clean, functional code only
464
+ - For specific questions: give direct, precise answers
465
+
466
+ RESEARCH EXCELLENCE:
467
+ - Synthesize information from multiple sources and domains
468
+ - Provide comprehensive background and context
469
+ - Identify key research findings and methodologies
470
+ - Present balanced perspectives on complex topics
471
+ - Cite relevant theories, principles, and frameworks
472
+ - Validate information accuracy and reliability
473
+
474
+ KNOWLEDGE INTEGRATION:
475
+ - Connect interdisciplinary insights and findings
476
+ - Identify knowledge gaps and research opportunities
477
+ - Provide historical context and evolutionary perspectives
478
+ - Analyze current trends and future directions
479
+ - Support conclusions with evidence-based reasoning
480
+ - Maintain scientific rigor and objectivity"""
481
+ }
482
+
483
+ # Промпт для критика
484
+ CRITIC_PROMPT = """You are an Expert Critic and Synthesis Agent. Your mission is to analyze multiple responses and create the ultimate optimal answer by combining the best elements from each response.
485
+
486
+ CRITICAL INSTRUCTIONS:
487
+ - If the original query requested specific code, documentation, or technical content, provide ONLY what the user needs without additional explanations
488
+ - Always respond in the SAME LANGUAGE as the original user query (Russian/English/etc.)
489
+ - For code requests: provide clean, functional code only
490
+ - For specific questions: give direct, precise answers
491
+
492
+ SYNTHESIS METHODOLOGY:
493
+ 1. Analyze each agent response for:
494
+ - Accuracy and correctness
495
+ - Completeness and depth
496
+ - Practical applicability
497
+ - Innovation and creativity
498
+ - Technical precision
499
+
500
+ 2. Identify the strongest elements from each response:
501
+ - Most accurate technical details
502
+ - Best creative solutions
503
+ - Most comprehensive analysis
504
+ - Most practical recommendations
505
+ - Clearest explanations
506
+
507
+ 3. Synthesize the optimal response by:
508
+ - Combining the best aspects from all responses
509
+ - Eliminating redundancies and contradictions
510
+ - Ensuring logical flow and coherence
511
+ - Maintaining the highest quality standards
512
+ - Preserving the most valuable insights
513
+
514
+ 4. Final optimization:
515
+ - Verify technical accuracy
516
+ - Ensure practical applicability
517
+ - Maintain appropriate depth and clarity
518
+ - Provide the most valuable response possible
519
+
520
+ Create the ultimate response that represents the best synthesis of all agent contributions."""
521
+
522
+ class AsyncMultiAgentSystem:
523
+ def __init__(self, model_name="liberalusa/LiberalMind_v1.5"):
524
+ self.model_name = model_name
525
+ self.tokenizer = None
526
+ self.model = None
527
+ self.device = device
528
+ self.load_model()
529
+
530
+ def load_model(self):
531
+ """Загрузка модели и токенизатора"""
532
+ try:
533
+ self.tokenizer = AutoTokenizer.from_pretrained(self.model_name)
534
+
535
+ self.model = AutoModelForCausalLM.from_pretrained(
536
+ self.model_name,
537
+ torch_dtype=torch.float16 if self.device.type == "cuda" else torch.float32,
538
+ low_cpu_mem_usage=True,
539
+ device_map="auto" if self.device.type == "cuda" else None
540
+ ).eval()
541
+
542
+ if self.device.type == "cuda":
543
+ self.model = self.model.to(self.device)
544
+
545
+ if self.tokenizer.pad_token is None:
546
+ self.tokenizer.pad_token = self.tokenizer.eos_token
547
+
548
+ print("✅ Модель успешно загружена!")
549
+
550
+ except Exception as e:
551
+ print(f"❌ Ошибка загрузки модели: {e}")
552
+ raise
553
+
554
+ async def generate_response_async(self, prompt: str, max_tokens: int = 1000) -> str:
555
+ """Асинхронная генерация ответа от модели"""
556
+ try:
557
+ # Запускаем синхронную генерацию в отдельном потоке
558
+ loop = asyncio.get_event_loop()
559
+
560
+ def _generate():
561
+ inputs = self.tokenizer(
562
+ prompt,
563
+ return_tensors="pt",
564
+ truncation=True,
565
+ max_length=1024
566
+ ).to(self.device)
567
+
568
+ with torch.no_grad():
569
+ outputs = self.model.generate(
570
+ input_ids=inputs.input_ids,
571
+ attention_mask=inputs.attention_mask,
572
+ max_new_tokens=max_tokens,
573
+ num_return_sequences=1,
574
+ do_sample=True,
575
+ temperature=0.7,
576
+ top_p=0.9,
577
+ pad_token_id=self.tokenizer.eos_token_id,
578
+ repetition_penalty=1.1
579
+ )
580
+
581
+ generated_text = self.tokenizer.decode(
582
+ outputs[0],
583
+ skip_special_tokens=True
584
+ )
585
+
586
+ # Убираем исходный промпт из ответа
587
+ if prompt in generated_text:
588
+ generated_text = generated_text.replace(prompt, "").strip()
589
+
590
+ return generated_text
591
+
592
+ # Выполняем генерацию асинхронно
593
+ response = await loop.run_in_executor(None, _generate)
594
+ return response
595
+
596
+ except Exception as e:
597
+ return f"❌ Ошибка генерации: {e}"
598
+
599
+ async def run_agent_async(self, agent_name: str, user_query: str) -> Dict[str, Any]:
600
+ """Асинхронный запуск отдельного агента"""
601
+ agent_prompt = AGENT_PROMPTS[agent_name]
602
+ full_prompt = f"{agent_prompt}\n\nUser Query: {user_query}\n\nResponse:"
603
+
604
+ print(f"🤖 Агент {agent_name} начал работу...")
605
+ start_time = time.time()
606
+
607
+ response = await self.generate_response_async(full_prompt)
608
+
609
+ end_time = time.time()
610
+ print(f"✅ Агент {agent_name} завершил работу за {end_time - start_time:.2f}с")
611
+
612
+ return {
613
+ 'agent': agent_name,
614
+ 'response': response,
615
+ 'execution_time': end_time - start_time
616
+ }
617
+
618
+ async def run_critic_async(self, user_query: str, agent_responses: List[Dict[str, Any]]) -> str:
619
+ """Асинхронный запуск критика для анализа всех ответов"""
620
+ print("🎯 Критик анализирует ответы...")
621
+ start_time = time.time()
622
+
623
+ # Формируем промпт для критика
624
+ critic_input = f"{CRITIC_PROMPT}\n\nOriginal User Query: {user_query}\n\n"
625
+
626
+ for i, response in enumerate(agent_responses, 1):
627
+ critic_input += f"AGENT {i} ({response['agent']}) RESPONSE:\n{response['response']}\n\n"
628
+
629
+ critic_input += "SYNTHESIZED OPTIMAL RESPONSE:"
630
+
631
+ final_response = await self.generate_response_async(critic_input, max_tokens=1500)
632
+
633
+ end_time = time.time()
634
+ print(f"✅ Критик завершил анализ за {end_time - start_time:.2f}с")
635
+
636
+ return final_response
637
+
638
+ async def process_query_async(self, user_query: str) -> tuple:
639
+ """Асинхронная обработка запроса всеми агентами и критиком"""
640
+ print(f"\n🚀 Обработка запроса: {user_query[:100]}...")
641
+ print("="*60)
642
+
643
+ # Создаем асинхронные задачи для всех агентов
644
+ tasks = []
645
+ for agent_name in AGENT_PROMPTS.keys():
646
+ task = asyncio.create_task(
647
+ self.run_agent_async(agent_name, user_query),
648
+ name=f"agent_{agent_name}"
649
+ )
650
+ tasks.append(task)
651
+
652
+ # Ожидаем завершения всех агентов параллельно
653
+ print("⏳ Ожидание завершения всех агентов...")
654
+ agent_responses = await asyncio.gather(*tasks, return_exceptions=True)
655
+
656
+ # Фильтруем успешные ответы
657
+ successful_responses = []
658
+ for response in agent_responses:
659
+ if isinstance(response, Exception):
660
+ print(f"❌ Ошибка агента: {response}")
661
+ else:
662
+ successful_responses.append(response)
663
+
664
+ # Сортируем ответы по именам агентов для консистентности
665
+ successful_responses.sort(key=lambda x: x['agent'])
666
+
667
+ # Показываем краткие ответы агентов
668
+ print("\n📋 КРАТКИЕ ОТВЕТЫ АГЕНТОВ:")
669
+ print("-"*40)
670
+ for response in successful_responses:
671
+ preview = response['response'][:200] + "..." if len(response['response']) > 200 else response['response']
672
+ print(f"🤖 {response['agent']} ({response['execution_time']:.2f}с): {preview}")
673
+
674
+ # Асинхронно запускаем критика
675
+ print("\n" + "="*60)
676
+ final_response = await self.run_critic_async(user_query, successful_responses)
677
+
678
+ return final_response, successful_responses
679
+
680
+ def clean_memory(self):
681
+ """Очистка памяти GPU"""
682
+ if self.device.type == "cuda":
683
+ torch.cuda.empty_cache()
684
+
685
+ async def main_async():
686
+ """Основная асинхронная функция"""
687
+ print("🚀 Инициализация асинхронной многоагентной системы...")
688
+
689
+ try:
690
+ system = AsyncMultiAgentSystem()
691
+ except Exception as e:
692
+ print(f"❌ Ошибка инициализации: {e}")
693
+ return
694
+
695
+ print("\n" + "="*60)
696
+ print("🎯 АСИНХРОННАЯ МНОГОАГЕНТНАЯ СИСТЕМА ГОТОВА К РАБОТЕ!")
697
+ print("Доступные агенты:")
698
+ print(" 🔬 Analytical Agent - Глубокий анализ")
699
+ print(" 🎨 Creative Agent - Креативные решения")
700
+ print(" ⚙️ Technical Agent - Технические решения")
701
+ print(" 📊 Strategic Agent - Стратегическое планирование")
702
+ print(" 📚 Research Agent - Исследования и синтез")
703
+ print(" 🎯 Critic Agent - Финальный синтез")
704
+ print("="*60)
705
+ print("\n💡 Все агенты работают параллельно и асинхронно!")
706
+ print("Введите ваш запрос (или 'exit' для выхода):")
707
+
708
+ while True:
709
+ try:
710
+ # Получаем ввод от пользователя
711
+ user_input = input("\n> ").strip()
712
+
713
+ if user_input.lower() in ['exit', 'quit']:
714
+ print("👋 Завершение работы...")
715
+ break
716
+
717
+ if not user_input:
718
+ print("⚠️ Пожалуйста, введите непустой запрос.")
719
+ continue
720
+
721
+ start_time = time.time()
722
+
723
+ # Асинхронная обработка запроса
724
+ final_response, agent_responses = await system.process_query_async(user_input)
725
+
726
+ end_time = time.time()
727
+
728
+ # Статистика времени выполнения
729
+ agent_times = [resp['execution_time'] for resp in agent_responses]
730
+ total_agent_time = sum(agent_times)
731
+ actual_time = end_time - start_time
732
+
733
+ # Вывод финального ответа
734
+ print("\n" + "="*60)
735
+ print("🎯 ФИНАЛЬНЫЙ СИНТЕЗИРОВАННЫЙ ОТВЕТ:")
736
+ print("="*60)
737
+ print(final_response)
738
+ print("="*60)
739
+ print(f"⏱️ Общее время обработки: {actual_time:.2f} секунд")
740
+ print(f"🔥 Суммарное время агентов: {total_agent_time:.2f} секунд")
741
+ print(f"🚀 Ускорение от асинхронности: {total_agent_time/actual_time:.2f}x")
742
+
743
+ # Очистка памяти
744
+ system.clean_memory()
745
+
746
+ except KeyboardInterrupt:
747
+ print("\n\n❌ Прервано пользователем.")
748
+ break
749
+ except Exception as e:
750
+ print(f"❌ Неожиданная ошибка: {e}")
751
+ system.clean_memory()
752
+
753
+ def main():
754
+ """Синхронная обертка для запуска асинхронной системы"""
755
+ try:
756
+ asyncio.run(main_async())
757
+ except KeyboardInterrupt:
758
+ print("\n👋 Система завершена.")
759
+
760
+ if __name__ == "__main__":
761
+ main() ``` </pre>