run_experiment.py 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158
  1. import requests
  2. import time
  3. import json
  4. import sys
  5. import os
  6. from typing import List, Dict, Any
  7. # Configuration
  8. API_BASE_URL = "http://localhost:8000/api/v1"
  9. USERNAME = "experiment_admin"
  10. PASSWORD = "admin_password"
  11. def login_or_register() -> str:
  12. """Authenticates the user and returns an access token."""
  13. # Try login
  14. login_url = f"{API_BASE_URL}/auth/login"
  15. payload = {
  16. "username": USERNAME,
  17. "password": PASSWORD
  18. }
  19. try:
  20. response = requests.post(login_url, data=payload)
  21. if response.status_code == 200:
  22. token = response.json().get("access_token")
  23. print(f"✅ Successfully logged in as {USERNAME}")
  24. return token
  25. elif response.status_code == 401 or response.status_code == 404:
  26. # Try register
  27. print(f"User {USERNAME} not found or password wrong. Attempting to register...")
  28. register_url = f"{API_BASE_URL}/auth/register"
  29. reg_payload = {
  30. "username": USERNAME,
  31. "password": PASSWORD
  32. }
  33. reg_response = requests.post(register_url, json=reg_payload)
  34. if reg_response.status_code == 200:
  35. print(f"✅ Successfully registered user {USERNAME}")
  36. # Login again
  37. response = requests.post(login_url, data=payload)
  38. if response.status_code == 200:
  39. return response.json().get("access_token")
  40. print(f"❌ Registration failed: {reg_response.text}")
  41. sys.exit(1)
  42. else:
  43. print(f"❌ Login failed: {response.text}")
  44. sys.exit(1)
  45. except requests.exceptions.ConnectionError:
  46. print("❌ Could not connect to the backend server. Is it running on http://localhost:8000?")
  47. sys.exit(1)
  48. def generate_personas(token: str, prompt: str, n: int) -> List[int]:
  49. """Calls the God Agent to generate personas and returns their IDs."""
  50. url = f"{API_BASE_URL}/god/generate"
  51. headers = {"Authorization": f"Bearer {token}"}
  52. payload = {
  53. "prompt": prompt,
  54. "n": n
  55. }
  56. print(f"🤖 God Agent is generating {n} personas based on prompt: '{prompt}'...")
  57. print(" (This may take 30-60 seconds, please wait...)")
  58. try:
  59. # Increased timeout for LLM generation
  60. response = requests.post(url, json=payload, headers=headers, timeout=120)
  61. if response.status_code == 200:
  62. personas = response.json()
  63. print(f"✅ Successfully generated {len(personas)} personas:")
  64. for p in personas:
  65. print(f" - {p['name']} ({p['title']})")
  66. return [p['id'] for p in personas]
  67. else:
  68. print(f"❌ Generation failed: {response.text}")
  69. return []
  70. except requests.exceptions.Timeout:
  71. print("❌ Request timed out. The model might be taking too long.")
  72. return []
  73. def create_forum(token: str, topic: str, participant_ids: List[int], duration: int = 30) -> int:
  74. """Creates a new forum."""
  75. url = f"{API_BASE_URL}/forums/"
  76. headers = {"Authorization": f"Bearer {token}"}
  77. payload = {
  78. "topic": topic,
  79. "participant_ids": participant_ids,
  80. "duration_minutes": duration
  81. }
  82. print(f"📝 Creating forum with topic: '{topic}'...")
  83. response = requests.post(url, json=payload, headers=headers)
  84. if response.status_code == 200:
  85. forum = response.json()
  86. print(f"✅ Forum created successfully (ID: {forum['id']})")
  87. return forum['id']
  88. else:
  89. print(f"❌ Failed to create forum: {response.text}")
  90. sys.exit(1)
  91. def start_forum(token: str, forum_id: int):
  92. """Starts the forum loop."""
  93. url = f"{API_BASE_URL}/forums/{forum_id}/start"
  94. headers = {"Authorization": f"Bearer {token}"}
  95. print(f"🚀 Starting forum {forum_id}...")
  96. response = requests.post(url, headers=headers)
  97. if response.status_code == 200:
  98. print(f"✅ Forum {forum_id} is now RUNNING!")
  99. print(f" You can view the discussion at: http://localhost:5173/forums/{forum_id}")
  100. else:
  101. print(f"❌ Failed to start forum: {response.text}")
  102. def main():
  103. print("=== MADF Experiment Automation Script ===")
  104. # 1. Configuration (Pre-defined for one-click execution)
  105. token = login_or_register()
  106. # Experiment 1: AI Impact on Art (Standard)
  107. exp1_topic = "人工智能生成内容(AIGC)是否会导致人类艺术创造力的枯竭?"
  108. exp1_prompt = "请生成4位不同背景的专家,包括一位持技术乐观主义的AI研究员,一位坚持传统技法的油画艺术家,一位关注版权与伦理的知识产权律师,以及一位研究数字文化的社会学家。他们将深入探讨AIGC对人类艺术未来的影响。"
  109. exp1_agents = 4
  110. exp1_duration = 20 # minutes
  111. print(f"\n🚀 Starting Experiment 1: {exp1_topic}")
  112. p_ids_1 = generate_personas(token, exp1_prompt, exp1_agents)
  113. if p_ids_1:
  114. f_id_1 = create_forum(token, exp1_topic, p_ids_1, exp1_duration)
  115. start_forum(token, f_id_1)
  116. # Experiment 2: Future of Work (Standard)
  117. # Note: To run purely ablation, we might need to modify backend config.
  118. # For now, let's run a second distinct topic to demonstrate capability.
  119. exp2_topic = "在后稀缺经济时代,工作的意义将如何重构?"
  120. exp2_prompt = "请生成3位具有前瞻性的思想家:一位主张全民基本收入(UBI)的经济学家,一位强调自我实现的心理学家,和一位通过算法管理自动化工厂的企业家。讨论当AI承担大部分劳动后,人类如何寻找存在意义。"
  121. exp2_agents = 3
  122. exp2_duration = 15
  123. print(f"\n🚀 Starting Experiment 2: {exp2_topic}")
  124. p_ids_2 = generate_personas(token, exp2_prompt, exp2_agents)
  125. if p_ids_2:
  126. f_id_2 = create_forum(token, exp2_topic, p_ids_2, exp2_duration)
  127. start_forum(token, f_id_2)
  128. print("\n=== All Experiments Launched ===")
  129. print("Please monitor the frontend dashboard.")
  130. if __name__ == "__main__":
  131. main()