Guest User

Untitled

a guest
Mar 31st, 2025
396
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 7.39 KB | None | 0 0
  1. import os
  2. import anthropic
  3. import google.generativeai as genai
  4. import time
  5. import argparse
  6. from datetime import datetime
  7.  
  8. # Initialize clients
  9. claude_client = anthropic.Anthropic(
  10. api_key=os.environ.get("ANTHROPIC_API_KEY"),
  11. )
  12.  
  13. # Configure the Gemini API
  14. genai.configure(api_key=os.environ.get("GOOGLE_API_KEY"))
  15.  
  16. # Configuration
  17. MAX_ITERATIONS = 3
  18. CLAUDE_MODEL = "claude-3-7-sonnet-20250219"
  19. GEMINI_MODEL = "gemini-2.5-pro-exp-03-25"
  20. DEFAULT_PROMPT = """
  21. Task: Please iterate and improve on this procedural generation script. Potential things to add: multi-room layouts, non-rectangular rooms, hallways, etc.
  22. """
  23.  
  24. def load_from_file(filepath):
  25. """Load content from a file with enhanced error handling"""
  26. if not os.path.exists(filepath):
  27. print(f"Error: File {filepath} does not exist")
  28. return None
  29.  
  30. try:
  31. # First try with UTF-8 encoding
  32. with open(filepath, 'r', encoding='utf-8') as file:
  33. content = file.read()
  34. return content
  35. except UnicodeDecodeError:
  36. # If UTF-8 fails, try with a different encoding
  37. try:
  38. with open(filepath, 'r', encoding='latin-1') as file:
  39. content = file.read()
  40. print(f"Note: File loaded using latin-1 encoding instead of UTF-8")
  41. return content
  42. except Exception as e:
  43. print(f"Error reading file with latin-1 encoding: {e}")
  44. return None
  45. except Exception as e:
  46. print(f"Detailed error loading file {filepath}: {str(e)}")
  47. # Print additional debugging information
  48. print(f"File path: {os.path.abspath(filepath)}")
  49. print(f"File exists: {os.path.exists(filepath)}")
  50. print(f"File size: {os.path.getsize(filepath) if os.path.exists(filepath) else 'N/A'} bytes")
  51. print(f"File permissions: {oct(os.stat(filepath).st_mode & 0o777) if os.path.exists(filepath) else 'N/A'}")
  52. return None
  53.  
  54. def ask_claude(prompt, conversation_history):
  55. messages = conversation_history.copy()
  56. messages.append({"role": "user", "content": prompt})
  57.  
  58. response = claude_client.messages.create(
  59. model=CLAUDE_MODEL,
  60. max_tokens=60000,
  61. temperature=0.7,
  62. messages=messages
  63. )
  64.  
  65. return response.content[0].text
  66.  
  67. def ask_gemini(prompt):
  68. # Create a generative model
  69. model = genai.GenerativeModel(GEMINI_MODEL)
  70.  
  71. # For chat-style interactions
  72. chat = model.start_chat()
  73. response = chat.send_message(
  74. prompt,
  75. generation_config=genai.GenerationConfig(
  76. temperature=0.7
  77. )
  78. )
  79.  
  80. # Return the text from the response
  81. return response.text
  82.  
  83. def save_to_file(content, filename=None):
  84. """Save content to a file with timestamped filename if not specified"""
  85. if filename is None:
  86. timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
  87. filename = f"llm_collaboration_{timestamp}.md"
  88.  
  89. with open(filename, 'w', encoding='utf-8') as file:
  90. file.write(content)
  91.  
  92. print(f"\nOutput saved to: {filename}")
  93. return filename
  94.  
  95. def run_collaboration(initial_prompt, max_iterations=MAX_ITERATIONS):
  96. conversation_history = []
  97. full_output = f"# LLM Collaboration\nDate: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}\n\n"
  98. full_output += f"## Initial Task\n\n```\n{initial_prompt}\n```\n\n"
  99.  
  100. # Start with Claude
  101. print("Starting collaboration...")
  102. claude_response = ask_claude(initial_prompt, conversation_history)
  103. conversation_history.append({"role": "assistant", "content": claude_response})
  104.  
  105. full_output += f"## Claude (Iteration 1)\n\n{claude_response}\n\n"
  106. print("\n=== CLAUDE (Iteration 1) ===\n")
  107. print(claude_response)
  108.  
  109. for i in range(2, max_iterations + 1):
  110. # Gemini's turn
  111. gemini_prompt = f"""
  112. You are collaborating with another AI (Claude) in coding a solution for the user's task.
  113. Here is Claude's latest contribution:
  114.  
  115. {claude_response}
  116.  
  117. Review the concepts, then improve upon it. You can:
  118. 1. Suggest architectural improvements
  119. 2. Enhance the implementation
  120. 3. Add missing features
  121. 4. Fix any issues you see
  122. 5. Build upon the existing design
  123.  
  124. Provide your improved version of the design and explain your changes.
  125. """
  126. gemini_response = ask_gemini(gemini_prompt)
  127. full_output += f"## Gemini (Iteration {i})\n\n{gemini_response}\n\n"
  128.  
  129. print(f"\n=== GEMINI (Iteration {i}) ===\n")
  130. print(gemini_response)
  131.  
  132. # Claude's turn
  133. claude_prompt = f"""
  134. You are collaborating with another AI (Gemini) in coding a solution for the user's task.
  135. Here is Gemini's latest contribution based on your previous work:
  136.  
  137. {gemini_response}
  138.  
  139. Review the design, then improve upon it. You can:
  140. 1. Suggest architectural improvements
  141. 2. Enhance the implementation
  142. 3. Add missing features
  143. 4. Fix any issues you see
  144. 5. Build upon the existing design
  145.  
  146. Provide your improved version of the design and explain your changes.
  147. """
  148. conversation_history.append({"role": "user", "content": claude_prompt})
  149. claude_response = ask_claude(claude_prompt, conversation_history)
  150. conversation_history.append({"role": "assistant", "content": claude_response})
  151.  
  152. full_output += f"## Claude (Iteration {i})\n\n{claude_response}\n\n"
  153. print(f"\n=== CLAUDE (Iteration {i}) ===\n")
  154. print(claude_response)
  155.  
  156. # Optional: Add a small delay to not hit rate limits
  157. time.sleep(1)
  158.  
  159. # Final assessment - ask Claude to summarize the collaboration
  160. final_prompt = """
  161. Now that we've gone through several iterations of collaboration, please provide:
  162. 1. A summary of how the design evolved
  163. 2. The final architecture and implementation
  164. 3. Any areas that could be further improved with additional iterations
  165. """
  166. conversation_history.append({"role": "user", "content": final_prompt})
  167. final_summary = ask_claude(final_prompt, conversation_history)
  168.  
  169. full_output += f"## Final Collaboration Summary\n\n{final_summary}\n\n"
  170. print("\n=== FINAL COLLABORATION SUMMARY ===\n")
  171. print(final_summary)
  172.  
  173. # Save complete output to file
  174. filename = save_to_file(full_output)
  175.  
  176. # Optionally, save just the final solution to a separate file
  177. save_to_file(final_summary, "final_solution.md")
  178.  
  179. return filename
  180.  
  181. def parse_arguments():
  182. parser = argparse.ArgumentParser(description='LLM Collaboration Tool')
  183. parser.add_argument('--file', '-f', type=str, help='Path to input file containing task and/or code')
  184. parser.add_argument('--iterations', '-i', type=int, default=MAX_ITERATIONS,
  185. help=f'Number of iteration rounds (default: {MAX_ITERATIONS})')
  186. return parser.parse_args()
  187.  
  188. if __name__ == "__main__":
  189. args = parse_arguments()
  190.  
  191. # Load initial prompt from file if specified, otherwise use default
  192. initial_prompt = DEFAULT_PROMPT
  193. if args.file:
  194. file_content = load_from_file(args.file)
  195. if file_content:
  196. initial_prompt = file_content
  197. else:
  198. print(f"Could not load file {args.file}, using default prompt")
  199.  
  200. output_file = run_collaboration(initial_prompt, args.iterations)
  201. print(f"Complete collaboration log saved to {output_file}")
  202. print("Final solution saved to final_solution.md")
Advertisement
Add Comment
Please, Sign In to add comment