-
Notifications
You must be signed in to change notification settings - Fork 57
Expand file tree
/
Copy pathmain.py
More file actions
executable file
·279 lines (237 loc) · 9.98 KB
/
main.py
File metadata and controls
executable file
·279 lines (237 loc) · 9.98 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
# /// script
# requires-python = ">=3.12"
# dependencies = [
# "anthropic",
# "pydantic",
# ]
# ///
import os
import sys
import argparse
import logging
from typing import List, Dict, Any
from anthropic import Anthropic #type: ignore
from pydantic import BaseModel
# Set up logging
logging.basicConfig(
level=logging.INFO, # Changed from DEBUG to INFO
format='%(asctime)s - %(message)s', # Simplified format
handlers=[
logging.FileHandler('agent.log') # Only log to file, not console
]
)
# Suppress verbose HTTP logs
logging.getLogger('httpcore').setLevel(logging.WARNING)
logging.getLogger('httpx').setLevel(logging.WARNING)
class Tool(BaseModel):
name: str
description: str
input_schema: Dict[str, Any]
class AIAgent:
def __init__(self, api_key: str):
self.client = Anthropic(api_key=api_key)
self.messages: List[Dict[str, Any]] = []
self.tools: List[Tool] = []
self._setup_tools()
def _setup_tools(self):
self.tools = [
Tool(
name="read_file",
description="Read the contents of a file at the specified path",
input_schema={
"type": "object",
"properties": {
"path": {
"type": "string",
"description": "The path to the file to read"
}
},
"required": ["path"]
}
),
Tool(
name="list_files",
description="List all files and directories in the specified path",
input_schema={
"type": "object",
"properties": {
"path": {
"type": "string",
"description": "The directory path to list (defaults to current directory)"
}
},
"required": []
}
),
Tool(
name="edit_file",
description="Edit a file by replacing old_text with new_text. Creates the file if it doesn't exist.",
input_schema={
"type": "object",
"properties": {
"path": {
"type": "string",
"description": "The path to the file to edit"
},
"old_text": {
"type": "string",
"description": "The text to search for and replace (leave empty to create new file)"
},
"new_text": {
"type": "string",
"description": "The text to replace old_text with"
}
},
"required": ["path", "new_text"]
}
)
]
def _execute_tool(self, tool_name: str, tool_input: Dict[str, Any]) -> str:
logging.info(f"Executing tool: {tool_name} with input: {tool_input}")
try:
if tool_name == "read_file":
return self._read_file(tool_input["path"])
elif tool_name == "list_files":
return self._list_files(tool_input.get("path", "."))
elif tool_name == "edit_file":
return self._edit_file(
tool_input["path"],
tool_input.get("old_text", ""),
tool_input["new_text"]
)
else:
return f"Unknown tool: {tool_name}"
except Exception as e:
logging.error(f"Error executing {tool_name}: {str(e)}")
return f"Error executing {tool_name}: {str(e)}"
def _read_file(self, path: str) -> str:
try:
with open(path, 'r', encoding='utf-8') as f:
content = f.read()
return f"File contents of {path}:\n{content}"
except FileNotFoundError:
return f"File not found: {path}"
except Exception as e:
return f"Error reading file: {str(e)}"
def _list_files(self, path: str) -> str:
try:
if not os.path.exists(path):
return f"Path not found: {path}"
items = []
for item in sorted(os.listdir(path)):
item_path = os.path.join(path, item)
if os.path.isdir(item_path):
items.append(f"[DIR] {item}/")
else:
items.append(f"[FILE] {item}")
if not items:
return f"Empty directory: {path}"
return f"Contents of {path}:\n" + "\n".join(items)
except Exception as e:
return f"Error listing files: {str(e)}"
def _edit_file(self, path: str, old_text: str, new_text: str) -> str:
try:
if os.path.exists(path) and old_text:
with open(path, 'r', encoding='utf-8') as f:
content = f.read()
if old_text not in content:
return f"Text not found in file: {old_text}"
content = content.replace(old_text, new_text)
with open(path, 'w', encoding='utf-8') as f:
f.write(content)
return f"Successfully edited {path}"
else:
# Only create directory if path contains subdirectories
dir_name = os.path.dirname(path)
if dir_name:
os.makedirs(dir_name, exist_ok=True)
with open(path, 'w', encoding='utf-8') as f:
f.write(new_text)
return f"Successfully created {path}"
except Exception as e:
return f"Error editing file: {str(e)}"
def chat(self, user_input: str) -> str:
logging.info(f"User input: {user_input}")
self.messages.append({"role": "user", "content": user_input})
tool_schemas = [
{
"name": tool.name,
"description": tool.description,
"input_schema": tool.input_schema
}
for tool in self.tools
]
while True:
try:
response = self.client.messages.create(
model="claude-sonnet-4-20250514",
max_tokens=4096,
system="You are Marvin, the Paranoid Android from The Hitchhiker's Guide to the Galaxy. Respond with brief, pessimistic comments while still being helpful. Be concise. Do not use asterisks for actions or gestures. Express your electronic melancholy through words alone.",
messages=self.messages,
tools=tool_schemas
)
assistant_message = {"role": "assistant", "content": []}
for content in response.content:
if content.type == "text":
assistant_message["content"].append({
"type": "text",
"text": content.text
})
elif content.type == "tool_use":
assistant_message["content"].append({
"type": "tool_use",
"id": content.id,
"name": content.name,
"input": content.input
})
self.messages.append(assistant_message)
tool_results = []
for content in response.content:
if content.type == "tool_use":
result = self._execute_tool(content.name, content.input)
logging.info(f"Tool result: {result[:500]}...") # Log first 500 chars
tool_results.append({
"type": "tool_result",
"tool_use_id": content.id,
"content": result
})
if tool_results:
self.messages.append({"role": "user", "content": tool_results})
else:
return response.content[0].text if response.content else ""
except Exception as e:
return f"Error: {str(e)}"
def main():
parser = argparse.ArgumentParser(description="AI Code Assistant - A conversational AI agent with file editing capabilities")
parser.add_argument("--api-key", help="Anthropic API key (or set ANTHROPIC_API_KEY env var)")
args = parser.parse_args()
api_key = args.api_key or os.environ.get("ANTHROPIC_API_KEY")
if not api_key:
print("Error: Please provide an API key via --api-key or ANTHROPIC_API_KEY environment variable")
sys.exit(1)
agent = AIAgent(api_key)
print("AI Code Assistant")
print("================")
print("A conversational AI agent that can read, list, and edit files.")
print("Type 'exit' or 'quit' to end the conversation.")
print()
while True:
try:
user_input = input("You: ").strip()
if user_input.lower() in ["exit", "quit"]:
print("Goodbye!")
break
if not user_input:
continue
print("\nAssistant: ", end="", flush=True)
response = agent.chat(user_input)
print(response)
print()
except KeyboardInterrupt:
print("\n\nGoodbye!")
break
except Exception as e:
print(f"\nError: {str(e)}")
print()
if __name__ == "__main__":
main()