-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathclaude_code_agentic.py
More file actions
356 lines (305 loc) · 12.3 KB
/
claude_code_agentic.py
File metadata and controls
356 lines (305 loc) · 12.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
"""
Claude Code-like agentic implementation using Anthropic API with tools.
Implements exploration and iteration like Claude Code CLI.
"""
import os
import subprocess
import tempfile
import logging
from typing import Optional, Dict, Any, List
from anthropic import Anthropic
# Set up logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
def run_agentic_claude_on_repo(
repo_url: str,
feature_description: str,
branch_name: str,
github_token: str,
anthropic_key: str,
max_iterations: int = 15
) -> Dict[str, Any]:
"""
Clone repo, run agentic Claude to implement feature, return changes.
Claude can explore files and iterate like Claude Code CLI.
Args:
repo_url: GitHub repo URL
feature_description: What to implement
branch_name: Branch name for changes
github_token: GitHub access token
anthropic_key: Anthropic API key
max_iterations: Max tool use iterations
Returns:
Dict with success status and branch info
"""
try:
# Create temp directory for repo
with tempfile.TemporaryDirectory() as tmpdir:
logger.info(f"Cloning {repo_url} to {tmpdir}")
# Clone repo with auth
auth_url = repo_url.replace('https://', f'https://{github_token}@')
clone_result = subprocess.run(
['git', 'clone', auth_url, tmpdir],
capture_output=True,
text=True,
timeout=60
)
if clone_result.returncode != 0:
return {
'success': False,
'message': f'Failed to clone repo: {clone_result.stderr}'
}
logger.info(f"Cloned successfully, creating branch {branch_name}")
# Create new branch
subprocess.run(
['git', 'checkout', '-b', branch_name],
cwd=tmpdir,
check=True
)
# Get default branch
default_branch_result = subprocess.run(
['git', 'remote', 'show', 'origin'],
cwd=tmpdir,
capture_output=True,
text=True
)
default_branch = 'main'
for line in default_branch_result.stdout.split('\n'):
if 'HEAD branch:' in line:
default_branch = line.split(':')[1].strip()
break
# Run agentic Claude with file access
client = Anthropic(api_key=anthropic_key)
# Define tools Claude can use
tools = [
{
"name": "read_file",
"description": "Read contents of a file in the repository. Use this to explore existing code.",
"input_schema": {
"type": "object",
"properties": {
"file_path": {
"type": "string",
"description": "Path to file relative to repo root"
}
},
"required": ["file_path"]
}
},
{
"name": "list_files",
"description": "List files in a directory. Use this to explore repo structure.",
"input_schema": {
"type": "object",
"properties": {
"dir_path": {
"type": "string",
"description": "Directory path relative to repo root (use '.' for root)"
},
"recursive": {
"type": "boolean",
"description": "List files recursively"
}
},
"required": ["dir_path"]
}
},
{
"name": "write_file",
"description": "Write or update a file. Use this to implement the feature.",
"input_schema": {
"type": "object",
"properties": {
"file_path": {
"type": "string",
"description": "Path to file relative to repo root"
},
"content": {
"type": "string",
"description": "Full file contents to write"
}
},
"required": ["file_path", "content"]
}
},
{
"name": "bash",
"description": "Run a bash command in the repo directory. Use for git status, grep, find, etc.",
"input_schema": {
"type": "object",
"properties": {
"command": {
"type": "string",
"description": "Bash command to run"
}
},
"required": ["command"]
}
}
]
# Initial prompt
messages = [{
"role": "user",
"content": f"""You are implementing a feature in a cloned GitHub repository.
**Feature to implement:** {feature_description}
**Your task:**
1. First, explore the repository structure to understand the codebase
2. Find existing relevant files (use list_files, read_file, bash grep/find)
3. Understand the existing patterns and architecture
4. Implement the feature by modifying existing files (prefer editing over creating new files)
5. When done, tell me "IMPLEMENTATION_COMPLETE"
**Available tools:**
- read_file: Read any file to understand code
- list_files: List directory contents
- write_file: Write/update files
- bash: Run commands (git status, grep, find, etc.)
**Guidelines:**
- Explore first, code second
- Modify existing files rather than creating new ones
- Follow existing code patterns
- Be thorough in understanding before implementing
Start by exploring the repository structure."""
}]
iteration = 0
while iteration < max_iterations:
iteration += 1
logger.info(f"Iteration {iteration}/{max_iterations}")
# Call Claude with tools
response = client.messages.create(
model="claude-sonnet-4-20250514",
max_tokens=8000,
tools=tools,
messages=messages
)
logger.info(f"Response stop_reason: {response.stop_reason}")
# Check if Claude is done
if response.stop_reason == "end_turn":
# Check if Claude said implementation is complete
for block in response.content:
if hasattr(block, 'text') and 'IMPLEMENTATION_COMPLETE' in block.text:
logger.info("Claude finished implementation")
break
break
# Process tool calls
if response.stop_reason == "tool_use":
# Add Claude's response to messages
messages.append({
"role": "assistant",
"content": response.content
})
# Execute tools and collect results
tool_results = []
for block in response.content:
if block.type == "tool_use":
tool_name = block.name
tool_input = block.input
tool_id = block.id
logger.info(f"Tool: {tool_name}, Input: {tool_input}")
# Execute tool
result = execute_tool(tool_name, tool_input, tmpdir)
tool_results.append({
"type": "tool_result",
"tool_use_id": tool_id,
"content": result
})
# Add tool results to messages
messages.append({
"role": "user",
"content": tool_results
})
else:
# Unexpected stop reason
break
# Stage and commit all changes
logger.info("Staging changes...")
subprocess.run(['git', 'add', '-A'], cwd=tmpdir, check=True)
# Check if there are changes
status_result = subprocess.run(
['git', 'status', '--porcelain'],
cwd=tmpdir,
capture_output=True,
text=True
)
if not status_result.stdout.strip():
return {
'success': False,
'message': 'No changes were made by Claude'
}
# Commit
subprocess.run(
['git', 'commit', '-m', f'feat: {feature_description}\n\nGenerated by Claude Code (agentic) via Omi'],
cwd=tmpdir,
check=True
)
# Push
logger.info(f"Pushing branch {branch_name}...")
push_result = subprocess.run(
['git', 'push', 'origin', branch_name],
cwd=tmpdir,
capture_output=True,
text=True
)
if push_result.returncode != 0:
return {
'success': False,
'message': f'Failed to push: {push_result.stderr}'
}
return {
'success': True,
'branch': branch_name,
'default_branch': default_branch,
'message': f'Implemented and pushed to {branch_name}'
}
except Exception as e:
logger.error(f"Error: {e}", exc_info=True)
return {
'success': False,
'message': str(e)
}
def execute_tool(tool_name: str, tool_input: Dict, repo_dir: str) -> str:
"""Execute a tool and return the result."""
try:
if tool_name == "read_file":
file_path = os.path.join(repo_dir, tool_input['file_path'])
with open(file_path, 'r') as f:
content = f.read()
return content[:10000] # Limit to 10k chars
elif tool_name == "list_files":
dir_path = os.path.join(repo_dir, tool_input['dir_path'])
recursive = tool_input.get('recursive', False)
if recursive:
result = subprocess.run(
['find', '.', '-type', 'f'],
cwd=dir_path,
capture_output=True,
text=True
)
else:
result = subprocess.run(
['ls', '-la'],
cwd=dir_path,
capture_output=True,
text=True
)
return result.stdout[:5000] # Limit output
elif tool_name == "write_file":
file_path = os.path.join(repo_dir, tool_input['file_path'])
os.makedirs(os.path.dirname(file_path), exist_ok=True)
with open(file_path, 'w') as f:
f.write(tool_input['content'])
return f"Successfully wrote {len(tool_input['content'])} chars to {tool_input['file_path']}"
elif tool_name == "bash":
result = subprocess.run(
tool_input['command'],
shell=True,
cwd=repo_dir,
capture_output=True,
text=True,
timeout=30
)
output = result.stdout + result.stderr
return output[:5000] # Limit output
else:
return f"Unknown tool: {tool_name}"
except Exception as e:
return f"Error executing {tool_name}: {str(e)}"