-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
171 lines (136 loc) · 5.18 KB
/
main.py
File metadata and controls
171 lines (136 loc) · 5.18 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
#!/usr/bin/env python3
"""
AI Code Agent - Command Line Interface
"""
import sys
import logging
import json
from pathlib import Path
from src.agent import CodeAgent
# Configure logging - suppress verbose Gemini logs
logging.basicConfig(level=logging.WARNING)
# Only show specific loggers if needed
logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)
# Session file path
SESSION_FILE = Path.home() / ".ai_code_agent_session.json"
def load_session(working_dir: str):
"""Load previous session if exists for this directory."""
try:
if SESSION_FILE.exists():
with open(SESSION_FILE, 'r', encoding='utf-8') as f:
session_data = json.load(f)
# Check if session is for the same working directory
if session_data.get('working_dir') == working_dir:
return session_data.get('messages', [])
except (json.JSONDecodeError, KeyError, OSError):
pass
return []
def save_session(working_dir: str, messages):
"""Save current session to file."""
try:
session_data = {
'working_dir': working_dir,
'messages': messages
}
with open(SESSION_FILE, 'w', encoding='utf-8') as f:
json.dump(session_data, f, ensure_ascii=False, indent=2)
except OSError:
pass # Ignore save errors
def clear_session():
"""Clear the current session."""
try:
if SESSION_FILE.exists():
SESSION_FILE.unlink()
print("🗑️ Session cleared!")
except OSError:
print("❌ Could not clear session")
def interactive_chat():
"""
Start an interactive chat session.
"""
try:
# Initialize the agent
agent = CodeAgent()
# Load previous conversation
previous_messages = load_session(agent.working_dir)
if previous_messages:
agent.load_conversation_history(previous_messages)
print(f"💾 Loaded previous conversation ({len(previous_messages)} messages)")
print("🤖 AI Code Agent - Interactive Mode")
print(f"📁 Working directory: {agent.working_dir}")
print("=" * 50)
print("Type 'q' to quit, 'clear' to clear history, 'help' for commands")
print("=" * 50)
while True:
try:
# Get user input
user_input = input("\n💬 You: ").strip()
if not user_input:
continue
# Handle special commands
if user_input.lower() == 'q' or user_input.lower() == 'quit':
print("👋 Goodbye!")
break
elif user_input.lower() == 'clear':
clear_session()
agent.messages = []
print("🗑️ Conversation history cleared!")
continue
elif user_input.lower() == 'help':
print("\n📋 Commands:")
print(" q, quit - Exit the chat")
print(" clear - Clear conversation history")
print(" help - Show this help message")
continue
# Process the request
print("\n🤖 Assistant:")
response = agent.chat(user_input, verbose=False)
print(response)
# Save conversation after each exchange
save_session(agent.working_dir, agent.export_conversation_history())
except KeyboardInterrupt:
print("\n👋 Interrupted by user")
break
except ValueError as e:
print(f"❌ Configuration Error: {e}")
print("Make sure you have set the GEMINI_API_KEY environment variable.")
except Exception as e:
print(f"❌ Unexpected Error: {e}")
def main():
"""
Main entry point for the AI Code Agent CLI.
"""
# Check for command line arguments
if len(sys.argv) > 1:
# Handle clear command
if sys.argv[1] == "--clear":
clear_session()
return
# Single command mode (legacy support)
request = sys.argv[1]
verbose = "--verbose" in sys.argv[2:]
try:
agent = CodeAgent()
if verbose:
print("🤖 AI Code Agent starting...")
print(f"📁 Working directory: {agent.working_dir}")
print(f"💬 Request: {request}")
print("=" * 50)
response = agent.chat(request, verbose=verbose)
if verbose:
print("=" * 50)
print("🎯 Final Response:")
print(response)
return
except ValueError as e:
print(f"❌ Configuration Error: {e}")
print("Make sure you have set the GEMINI_API_KEY environment variable.")
return
except Exception as e:
print(f"❌ Unexpected Error: {e}")
return
# Default: Interactive mode
interactive_chat()
if __name__ == "__main__":
main()