OpenClaw AI Agent | Code Generation & Refactoring Guide
OpenClaw AI Agent - Code Generation Guide
OpenClaw is an open-source AI agent specifically designed for software development tasks, with a focus on code generation, refactoring, and project scaffolding.
Overview
OpenClaw emphasizes:
- Code-first approach - Every interaction produces runnable code
- Language agnostic - Supports 20+ programming languages
- IDE integration - Works as extension for VSCode, IntelliJ, and Vim
- Test generation - Automatically creates tests for generated code
Key Features
| Feature | Description |
|---|---|
| Code Generation | Generate functions, classes, and entire modules |
| Refactoring | Restructure code while preserving behavior |
| Test Creation | Auto-generate unit and integration tests |
| Documentation | Generate docstrings and README files |
| Code Review | Analyze code for bugs and improvements |
Installation
CLI Installation
# via npmnpm install -g @openclaw/cli
# via pippip install openclawIDE Extensions
- VSCode: Search “OpenClaw” in Extensions marketplace
- IntelliJ: Install from JetBrains marketplace
- Vim/Neovim: Use plugin manager
Plug 'openclaw/vim-openclaw'
Configuration
Config File (~/.openclaw/config.json)
{ "provider": "anthropic", "apiKey": "${ANTHROPIC_API_KEY}", "model": "claude-sonnet-4-20250514", "language": "python", "features": { "autoTest": true, "autoDocs": true, "typeHints": true }, "style": { "indent": 4, "lineLength": 88, "formatter": "black" }}Per-Project Config (.openclaw.json)
{ "language": "typescript", "framework": "react", "testing": "jest", "exclude": ["node_modules", "dist", "build"], "include": ["src/**/*.ts", "src/**/*.tsx"]}Usage
CLI Commands
Generate Code:
openclaw generate "Create a React component for a todo list"Refactor:
openclaw refactor src/utils.js --target "improve performance"Create Tests:
openclaw test src/calculator.jsReview Code:
openclaw review src/Generate Documentation:
openclaw docs src/ --output API.mdInteractive Mode
openclaw --interactive# orocl # shorthandProvider Configuration
Anthropic (Recommended)
{ "provider": "anthropic", "apiKey": "${ANTHROPIC_API_KEY}", "model": "claude-sonnet-4-20250514"}OpenAI
{ "provider": "openai", "apiKey": "${OPENAI_API_KEY}", "model": "gpt-4o"}Google Gemini
{ "provider": "google", "apiKey": "${GEMINI_API_KEY}", "model": "gemini-2.5-pro"}Local Models (Ollama)
{ "provider": "ollama", "baseUrl": "http://localhost:11434", "model": "codellama:13b"}Language Support
OpenClaw supports these languages with full feature parity:
| Language | Generation | Refactor | Tests | Docs |
|---|---|---|---|---|
| Python | ✅ | ✅ | ✅ | ✅ |
| TypeScript | ✅ | ✅ | ✅ | ✅ |
| JavaScript | ✅ | ✅ | ✅ | ✅ |
| Java | ✅ | ✅ | ✅ | ✅ |
| Go | ✅ | ✅ | ✅ | ✅ |
| Rust | ✅ | ✅ | ✅ | ✅ |
| C/C++ | ✅ | ✅ | ⚠️ | ✅ |
| Ruby | ✅ | ✅ | ✅ | ✅ |
| PHP | ✅ | ✅ | ✅ | ✅ |
| Swift | ✅ | ✅ | ⚠️ | ✅ |
| Kotlin | ✅ | ✅ | ✅ | ✅ |
⚠️ = Partial support
Code Generation Examples
Python
openclaw generate "Create a FastAPI endpoint for user authentication with JWT"Output:
from fastapi import FastAPI, Depends, HTTPExceptionfrom fastapi.security import HTTPBearerimport jwtfrom datetime import datetime, timedelta
app = FastAPI()security = HTTPBearer()
SECRET_KEY = "your-secret-key"ALGORITHM = "HS256"
def create_token(user_id: str) -> str: expire = datetime.utcnow() + timedelta(hours=24) payload = {"sub": user_id, "exp": expire} return jwt.encode(payload, SECRET_KEY, algorithm=ALGORITHM)
@app.post("/auth/login")async def login(credentials: LoginCredentials): # Implementation passReact Component
openclaw generate "Create a responsive navbar with mobile hamburger menu"Output:
import React, { useState } from 'react';import { Menu, X } from 'lucide-react';
export const Navbar: React.FC = () => { const [isOpen, setIsOpen] = useState(false);
return ( <nav className="bg-white shadow-lg"> {/* Component implementation */} </nav> );};Refactoring Examples
Convert Callbacks to Async/Await
openclaw refactor src/api.js --pattern "callback-to-async"Extract Components
openclaw refactor src/pages/Home.tsx --action "extract-component" --name "UserCard"Add TypeScript Types
openclaw refactor src/ --action "add-types"Testing Integration
Generate Tests
# Generate unit testsopenclaw test src/calculator.py
# Generate with specific frameworkopenclaw test src/calc.ts --framework jest
# Generate integration testsopenclaw test src/api --type integrationTest Coverage
# Analyze test coverageopenclaw coverage
# Generate missing tests for uncovered codeopenclaw test --cover-onlyTroubleshooting
”Model not responding”
- Check API key:
echo $ANTHROPIC_API_KEY - Verify provider status
- Try a different model
”Generated code has errors”
- Enable stricter mode:
"strict": truein config - Use review mode before applying:
openclaw review --dry-run - Specify language version:
"pythonVersion": "3.11"
”Context too large”
- Use
--filesflag to limit scope - Enable context compression:
"compressContext": true - Break into smaller tasks
IDE extension not working
- Check OpenClaw CLI is installed:
openclaw --version - Verify config file exists
- Restart IDE
Comparison
| Feature | OpenClaw | GitHub Copilot | Cursor | Cody |
|---|---|---|---|---|
| Open Source | ✅ | ❌ | ❌ | Partial |
| Self-hosted | ✅ | ❌ | ❌ | Partial |
| Multi-provider | ✅ | ❌ | Partial | ✅ |
| Test generation | ✅ | ⚠️ | ✅ | ✅ |
| Refactoring | ✅ | ❌ | ✅ | ✅ |
| Price | Free | $10/mo | $20/mo | $9/mo |
Best Practices
- Commit before refactoring - Always commit changes before running refactor commands
- Review generated code - Don’t blindly accept AI-generated code
- Use specific prompts - Vague prompts produce generic code
- Set up project config - Create
.openclaw.jsonfor consistent results - Combine with linting - Run linters after generation