mvp-factory-openhands/test-scripts/openhands-sdk-wrapper-worki...

171 lines
5.0 KiB
Python
Executable File

#!/usr/bin/env python3
"""
OpenHands SDK Wrapper for n8n Integration (WORKING VERSION)
Usage: python3 /home/bam/openhands-sdk-wrapper-working.py "task description"
This script runs OpenHands in SDK mode using the venv environment.
"""
import sys
import os
import json
import argparse
import shutil
from datetime import datetime
from pathlib import Path
def run_openhands_task(task, workspace="/home/bam", verbose=True):
"""
Execute an OpenHands task using the SDK
Args:
task: Task description string
workspace: Working directory path
verbose: Print detailed logs
Returns:
dict: Results including success status and output
"""
results = {
'success': False,
'task': task,
'workspace': workspace,
'timestamp': datetime.now().isoformat(),
'error': None,
'files_created': [],
'stdout': '',
'stderr': ''
}
try:
if verbose:
print(f"🚀 Starting OpenHands SDK execution...")
print(f"📋 Task: {task}")
print(f"📁 Workspace: {workspace}")
print("-" * 50)
# Create workspace directory if it doesn't exist
workspace_path = Path(workspace)
workspace_path.mkdir(parents=True, exist_ok=True)
# Import SDK components
sys.path.insert(0, '/tmp/software-agent-sdk/openhands-sdk')
from openhands.sdk import LLM, Agent, Conversation
# Load environment
env_file = '/home/bam/openhands/.env'
env_vars = {}
if os.path.exists(env_file):
with open(env_file, 'r') as f:
for line in f:
line = line.strip()
if line and '=' in line and not line.startswith('#'):
key, value = line.split('=', 1)
env_vars[key] = value
# Configure LLM
api_key = env_vars.get('MINIMAX_API_KEY')
if not api_key:
raise ValueError("MINIMAX_API_KEY not found in environment")
if verbose:
print(f"✅ API Key loaded")
llm = LLM(
model="openai/MiniMax-M2",
api_key=api_key,
base_url="https://api.minimax.io/v1"
)
if verbose:
print("✅ LLM configured successfully")
# Create agent (no specific tools needed - uses defaults)
agent = Agent(llm=llm)
if verbose:
print("✅ Agent created")
# Start conversation with workspace
conversation = Conversation(agent=agent, workspace=str(workspace_path))
if verbose:
print("💬 Conversation started")
print(f"📤 Sending task to agent...")
# Send task and run
conversation.send_message(task)
if verbose:
print("⏳ Running agent execution...")
print("(This may take a few minutes)")
# Run the conversation
conversation.run()
if verbose:
print("✅ Agent execution completed")
# List files created in workspace
files_created = []
if os.path.exists(str(workspace_path)):
for item in os.listdir(str(workspace_path)):
item_path = os.path.join(str(workspace_path), item)
if os.path.isfile(item_path) and not item.startswith('.'):
files_created.append(item)
results['files_created'] = files_created
results['success'] = True
if verbose:
print("-" * 50)
print(f"✅ Task completed successfully!")
print(f"📄 Files created: {files_created if files_created else 'None'}")
except Exception as e:
results['error'] = str(e)
results['stderr'] = str(e)
if verbose:
print(f"❌ Task failed: {e}")
import traceback
traceback.print_exc()
return results
def main():
"""Main entry point for the wrapper script"""
parser = argparse.ArgumentParser(description='OpenHands SDK Wrapper for n8n (Working)')
parser.add_argument('task', help='Task description to execute')
parser.add_argument('--workspace', default='/home/bam', help='Working directory')
parser.add_argument('--quiet', action='store_true', help='Suppress verbose output')
parser.add_argument('--json', action='store_true', help='Output results as JSON')
args = parser.parse_args()
# Run the task
results = run_openhands_task(
task=args.task,
workspace=args.workspace,
verbose=not args.quiet
)
# Output results
if args.json:
print(json.dumps(results, indent=2))
else:
if results['success']:
print("SUCCESS")
if results['files_created']:
print(f"Files created: {', '.join(results['files_created'])}")
else:
print("FAILED")
if results['error']:
print(f"Error: {results['error']}")
# Exit with appropriate code
sys.exit(0 if results['success'] else 1)
if __name__ == "__main__":
main()