Godel Agent Tutorial: Setup and Usage Guide
Introduction
This tutorial provides a practical guide for setting up and using Godel Agent, a self-referential agent framework for recursive self-improvement. The guide focuses on essential implementation details and best practices.
1. Installation and Setup
Basic Installation
# Clone the repository
git clone https://github.com/Arvid-pku/Godel_Agent.git
cd Godel_Agent
# Install dependencies
pip install -r requirements.txt
API Configuration
# Create key.env in project root
# IMPORTANT: Never commit this file to version control
with open('key.env', 'w') as f:
f.write('your-openai-api-key-here')
Project Structure Verification
def verify_setup():
required_files = [
'src/main.py',
'src/agent_module.py',
'src/logic.py',
'src/goal_prompt.md',
'key.env'
]
for file in required_files:
if not os.path.exists(file):
raise FileNotFoundError(f"Missing required file: {file}")
2. Basic Usage
Initialize and Run Agent
from agent_module import Agent
def run_basic_agent():
# Initialize with default settings
agent = Agent(key_path="key.env")
# Reset agent state
agent.reinit()
# Start evolution process
agent.evolve()
return agent
Monitor Evolution Progress
def monitor_progress(agent):
print(f"Evolution steps: {action_counter['evolve']}")
print(f"History length: {len(agent.optimize_history)}")
print(f"Error count: {action_counter['error_handle']}")
3. Advanced Configuration
Custom Task Implementation
class CustomTask:
def __init__(self):
self.name = "Custom Task"
self.description = """
Detailed task description and requirements
"""
def evaluate(self, solver):
try:
# Implement your evaluation logic
result = solver(self.test_input)
accuracy = self.calculate_accuracy(result)
feedback = self.generate_feedback(result)
return feedback, accuracy
except Exception as e:
return f"Evaluation failed: {str(e)}", 0.0
Response Format Configuration
def configure_llm_response(agent, task_type="reasoning"):
configs = {
"reasoning": {
"model": "gpt-4o",
"temperature": 0.8,
"return_dict_keys": ["reasoning", "answer"],
"requirements": "Step-by-step reasoning required"
},
"direct": {
"model": "gpt-3.5-turbo",
"temperature": 0.3,
"return_dict_keys": ["answer"],
"requirements": "Direct answer required"
}
}
return configs.get(task_type, configs["reasoning"])
4. Safety and Error Handling
Code Validation System
def validate_code_changes(code_string):
# Security checks
forbidden_patterns = [
"import logging",
"import subprocess",
"eval(",
"exec(",
"os.system"
]
for pattern in forbidden_patterns:
if pattern in code_string:
raise SecurityError(f"Forbidden pattern found: {pattern}")
# Syntax validation
try:
ast.parse(code_string)
except SyntaxError as e:
raise ValueError(f"Invalid Python syntax: {str(e)}")
return True
Resource Management
class ResourceManager:
def __init__(self):
self.limits = {
"max_evolution_steps": 30,
"max_history_length": 100,
"max_tokens": 4096
}
def check_limits(self, agent):
if action_counter["evolve"] >= self.limits["max_evolution_steps"]:
raise RuntimeError("Evolution step limit reached")
if len(agent.optimize_history) >= self.limits["max_history_length"]:
# Trim history
agent.optimize_history = agent.optimize_history[-50:]
5. Debugging and Monitoring
Debug Mode Implementation
class DebugMode:
def __init__(self, agent):
self.agent = agent
self.debug_log = []
def log_action(self, action_name, args, result):
log_entry = {
"timestamp": datetime.now().isoformat(),
"action": action_name,
"arguments": args,
"result": result
}
self.debug_log.append(log_entry)
def print_status(self):
print("\nDebug Status:")
print(f"Actions executed: {len(self.debug_log)}")
print(f"Last action: {self.debug_log[-1] if self.debug_log else 'None'}")
Performance Monitoring
def monitor_performance(agent):
metrics = {
"evolution_progress": action_counter["evolve"],
"success_rate": 1 - (action_counter["error_handle"] / max(1, sum(action_counter.values()))),
"history_size": len(agent.optimize_history)
}
return metrics
6. Best Practices
Task Definition
def define_task(task_description, evaluation_criteria):
"""
Create a well-structured task definition
Parameters:
task_description (str): Clear description of the task
evaluation_criteria (dict): Metrics for success
"""
return {
"description": task_description,
"criteria": evaluation_criteria,
"timestamp": datetime.now().isoformat()
}
Evolution Management
def manage_evolution(agent, max_steps=30):
"""
Managed evolution with safeguards
"""
steps_taken = 0
while steps_taken < max_steps:
try:
# Monitor resources
ResourceManager().check_limits(agent)
# Execute evolution step
agent.evolve()
# Update counter
steps_taken += 1
# Check for convergence
if check_convergence(agent):
break
except Exception as e:
print(f"Evolution step failed: {str(e)}")
break
return steps_taken
7. Troubleshooting Guide
Common issues and solutions:
- API Connection Issues
def troubleshoot_api():
try:
# Verify API key
if not os.path.exists('key.env'):
return "Missing API key file"
# Test API connection
with open('key.env', 'r') as f:
key = f.read().strip()
openai.api_key = key
response = openai.ChatCompletion.create(
model="gpt-3.5-turbo",
messages=[{"role": "user", "content": "test"}]
)
return "API connection successful"
except Exception as e:
return f"API Error: {str(e)}"
- Evolution Stalling
def diagnose_evolution(agent):
if action_counter["evolve"] > 25:
return "Approaching evolution limit"
if action_counter["error_handle"] > action_counter["evolve"] * 0.5:
return "High error rate detected"
return "Evolution proceeding normally"
8. Final Tips
- Always start with a clean environment using
agent.reinit()
- Monitor evolution progress regularly
- Implement proper error handling for all custom code
- Keep task definitions clear and specific
- Regularly check resource usage and limits
- Use the debug mode during development
- Maintain backups of