-
Notifications
You must be signed in to change notification settings - Fork 73
Expand file tree
/
Copy pathagent_chat.py
More file actions
235 lines (190 loc) · 6.9 KB
/
agent_chat.py
File metadata and controls
235 lines (190 loc) · 6.9 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
#!/usr/bin/env python3
"""
Agent chat functionality for OpenHands CLI.
Provides a conversation interface with an AI agent using OpenHands patterns.
"""
import logging
import os
import sys
import traceback
# Ensure we use the agent-sdk openhands package, not the main OpenHands package
# Remove the main OpenHands code path if it exists
if "/openhands/code" in sys.path:
sys.path.remove("/openhands/code")
from prompt_toolkit import PromptSession, print_formatted_text
from prompt_toolkit.formatted_text import HTML
from prompt_toolkit.shortcuts import clear
from pydantic import SecretStr
from openhands_cli.tui import CommandCompleter, display_banner, display_help
try:
from openhands.sdk import (
LLM,
Agent,
Conversation,
EventType,
LLMConfig,
Message,
TextContent,
Tool,
)
from openhands.tools import (
BashExecutor,
FileEditorExecutor,
execute_bash_tool,
str_replace_editor_tool,
)
except ImportError as e:
print_formatted_text(HTML(f"<red>Error importing OpenHands SDK: {e}</red>"))
print_formatted_text(
HTML("<yellow>Please ensure the openhands-sdk is properly installed.</yellow>")
)
sys.exit(1)
logger = logging.getLogger(__name__)
def setup_agent() -> tuple[LLM | None, Agent | None, Conversation | None, int]:
"""Setup the agent with environment variables.
Returns:
tuple: (llm, agent, conversation, exit_code) where exit_code is 0 for success, non-zero for error
"""
try:
# Get API configuration from environment
api_key = os.getenv("LITELLM_API_KEY") or os.getenv("OPENAI_API_KEY")
model = os.getenv("LITELLM_MODEL", "gpt-4o-mini")
base_url = os.getenv("LITELLM_BASE_URL")
if not api_key:
print_formatted_text(
HTML(
"<red>Error: No API key found. Please set LITELLM_API_KEY or OPENAI_API_KEY environment variable.</red>"
)
)
return None, None, None, 1
# Configure LLM
llm_config = LLMConfig(
model=model,
api_key=SecretStr(api_key) if api_key else None,
)
if base_url:
llm_config.base_url = base_url
llm = LLM(config=llm_config)
# Setup tools
cwd = os.getcwd()
bash = BashExecutor(working_dir=cwd)
file_editor = FileEditorExecutor()
tools: list[Tool] = [
execute_bash_tool.set_executor(executor=bash),
str_replace_editor_tool.set_executor(executor=file_editor),
]
# Create agent
agent = Agent(llm=llm, tools=tools)
# Setup conversation with callback
def conversation_callback(event: EventType) -> None:
logger.debug(f"Conversation event: {str(event)[:200]}...")
conversation = Conversation(agent=agent, callbacks=[conversation_callback])
print_formatted_text(
HTML(f"<green>✓ Agent initialized with model: {model}</green>")
)
return llm, agent, conversation, 0
except Exception as e:
print_formatted_text(HTML(f"<red>Error setting up agent: {str(e)}</red>"))
traceback.print_exc()
return None, None, None, 2
def display_welcome(session_id: str = "chat") -> None:
"""Display welcome message."""
clear()
display_banner(session_id)
print_formatted_text(HTML("<gold>Let's start building!</gold>"))
print_formatted_text(
HTML(
"<green>What do you want to build? <grey>Type /help for help</grey></green>"
)
)
print()
def run_agent_chat() -> int:
"""Run the agent chat session using the agent SDK.
Returns:
int: Exit code (0 for success, non-zero for error)
"""
# Setup agent
llm, agent, conversation, exit_code = setup_agent()
if not agent or not conversation:
return exit_code
# Generate session ID
import uuid
session_id = str(uuid.uuid4())[:8]
display_welcome(session_id)
# Create prompt session with command completer
session = PromptSession(completer=CommandCompleter())
# Main chat loop
while True:
try:
# Get user input
user_input = session.prompt(
HTML("<gold>> </gold>"),
multiline=False,
)
if not user_input.strip():
continue
# Handle commands
command = user_input.strip().lower()
if command == "/exit":
print_formatted_text(HTML("<yellow>Goodbye! 👋</yellow>"))
break
elif command == "/clear":
display_welcome(session_id)
continue
elif command == "/help":
display_help()
continue
elif command == "/status":
print_formatted_text(HTML(f"<grey>Session ID: {session_id}</grey>"))
print_formatted_text(HTML("<grey>Status: Active</grey>"))
continue
elif command == "/new":
print_formatted_text(
HTML("<yellow>Starting new conversation...</yellow>")
)
session_id = str(uuid.uuid4())[:8]
display_welcome(session_id)
continue
# Send message to agent
print_formatted_text(HTML("<green>Agent: </green>"), end="")
try:
# Create message and send to conversation
message = Message(
role="user",
content=[TextContent(text=user_input)],
)
conversation.send_message(message)
conversation.run()
# Get the last response from the conversation
# For simplicity, we'll just indicate the agent processed the request
print_formatted_text(
HTML("<green>✓ Agent has processed your request.</green>")
)
except Exception as e:
print_formatted_text(HTML(f"<red>Error: {str(e)}</red>"))
print() # Add spacing
except KeyboardInterrupt:
print_formatted_text(
HTML("\n<yellow>Chat interrupted. Type /exit to quit.</yellow>")
)
continue
except EOFError:
print_formatted_text(HTML("\n<yellow>Goodbye! 👋</yellow>"))
break
return 0
def main() -> int:
"""Main entry point for agent chat.
Returns:
int: Exit code (0 for success, non-zero for error)
"""
try:
return run_agent_chat()
except KeyboardInterrupt:
print_formatted_text(HTML("\n<yellow>Goodbye! 👋</yellow>"))
return 0
except Exception as e:
print_formatted_text(HTML(f"<red>Unexpected error: {str(e)}</red>"))
logger.error(f"Main error: {e}")
return 3
if __name__ == "__main__":
sys.exit(main())