|
| 1 | +#!/usr/bin/env python3 |
| 2 | +""" |
| 3 | +Agent chat functionality for OpenHands CLI. |
| 4 | +Provides a conversation interface with an AI agent using OpenHands patterns. |
| 5 | +""" |
| 6 | + |
| 7 | +import logging |
| 8 | +import os |
| 9 | +import sys |
| 10 | +import traceback |
| 11 | + |
| 12 | +# Ensure we use the agent-sdk openhands package, not the main OpenHands package |
| 13 | +# Remove the main OpenHands code path if it exists |
| 14 | +if "/openhands/code" in sys.path: |
| 15 | + sys.path.remove("/openhands/code") |
| 16 | + |
| 17 | +from prompt_toolkit import PromptSession, print_formatted_text |
| 18 | +from prompt_toolkit.formatted_text import HTML |
| 19 | +from prompt_toolkit.shortcuts import clear |
| 20 | +from pydantic import SecretStr |
| 21 | + |
| 22 | +try: |
| 23 | + from openhands.core.agent.codeact_agent import CodeActAgent |
| 24 | + from openhands.core.config import LLMConfig |
| 25 | + from openhands.core.conversation import Conversation |
| 26 | + from openhands.core.event import EventType |
| 27 | + from openhands.core.llm import LLM, Message, TextContent |
| 28 | + from openhands.core.tool import Tool |
| 29 | + from openhands.tools.execute_bash import BashExecutor, execute_bash_tool |
| 30 | + from openhands.tools.str_replace_editor import ( |
| 31 | + FileEditorExecutor, |
| 32 | + str_replace_editor_tool, |
| 33 | + ) |
| 34 | +except ImportError as e: |
| 35 | + print_formatted_text(HTML(f"<red>Error importing OpenHands SDK: {e}</red>")) |
| 36 | + print_formatted_text( |
| 37 | + HTML("<yellow>Please ensure the openhands-sdk is properly installed.</yellow>") |
| 38 | + ) |
| 39 | + sys.exit(1) |
| 40 | + |
| 41 | + |
| 42 | +logger = logging.getLogger(__name__) |
| 43 | + |
| 44 | + |
| 45 | +def setup_agent() -> tuple[LLM | None, CodeActAgent | None, Conversation | None]: |
| 46 | + """Setup the agent with environment variables.""" |
| 47 | + try: |
| 48 | + # Get API configuration from environment |
| 49 | + api_key = os.getenv("LITELLM_API_KEY") or os.getenv("OPENAI_API_KEY") |
| 50 | + model = os.getenv("LITELLM_MODEL", "gpt-4o-mini") |
| 51 | + base_url = os.getenv("LITELLM_BASE_URL") |
| 52 | + |
| 53 | + if not api_key: |
| 54 | + print_formatted_text( |
| 55 | + HTML( |
| 56 | + "<red>Error: No API key found. Please set LITELLM_API_KEY or OPENAI_API_KEY environment variable.</red>" |
| 57 | + ) |
| 58 | + ) |
| 59 | + return None, None, None |
| 60 | + |
| 61 | + # Configure LLM |
| 62 | + llm_config = LLMConfig( |
| 63 | + model=model, |
| 64 | + api_key=SecretStr(api_key) if api_key else None, |
| 65 | + ) |
| 66 | + |
| 67 | + if base_url: |
| 68 | + llm_config.base_url = base_url |
| 69 | + |
| 70 | + llm = LLM(config=llm_config) |
| 71 | + |
| 72 | + # Setup tools |
| 73 | + cwd = os.getcwd() |
| 74 | + bash = BashExecutor(working_dir=cwd) |
| 75 | + file_editor = FileEditorExecutor() |
| 76 | + tools: list[Tool] = [ |
| 77 | + execute_bash_tool.set_executor(executor=bash), |
| 78 | + str_replace_editor_tool.set_executor(executor=file_editor), |
| 79 | + ] |
| 80 | + |
| 81 | + # Create agent |
| 82 | + agent = CodeActAgent(llm=llm, tools=tools) |
| 83 | + |
| 84 | + # Setup conversation with callback |
| 85 | + def conversation_callback(event: EventType) -> None: |
| 86 | + logger.debug(f"Conversation event: {str(event)[:200]}...") |
| 87 | + |
| 88 | + conversation = Conversation(agent=agent, callbacks=[conversation_callback]) |
| 89 | + |
| 90 | + print_formatted_text( |
| 91 | + HTML(f"<green>✓ Agent initialized with model: {model}</green>") |
| 92 | + ) |
| 93 | + return llm, agent, conversation |
| 94 | + |
| 95 | + except Exception as e: |
| 96 | + print_formatted_text(HTML(f"<red>Error setting up agent: {str(e)}</red>")) |
| 97 | + traceback.print_exc() |
| 98 | + return None, None, None |
| 99 | + |
| 100 | + |
| 101 | +def display_welcome() -> None: |
| 102 | + """Display welcome message.""" |
| 103 | + clear() |
| 104 | + print_formatted_text(HTML("<gold>🤖 OpenHands Agent Chat</gold>")) |
| 105 | + print_formatted_text(HTML("<grey>AI Agent Conversation Interface</grey>")) |
| 106 | + print() |
| 107 | + print_formatted_text(HTML("<skyblue>Commands:</skyblue>")) |
| 108 | + print_formatted_text(HTML(" <white>/exit</white> - Exit the chat")) |
| 109 | + print_formatted_text(HTML(" <white>/clear</white> - Clear the screen")) |
| 110 | + print_formatted_text(HTML(" <white>/help</white> - Show this help")) |
| 111 | + print() |
| 112 | + print_formatted_text( |
| 113 | + HTML("<green>Type your message and press Enter to chat with the agent.</green>") |
| 114 | + ) |
| 115 | + print() |
| 116 | + |
| 117 | + |
| 118 | +def run_agent_chat() -> None: |
| 119 | + """Run the agent chat session using the agent SDK.""" |
| 120 | + # Setup agent |
| 121 | + llm, agent, conversation = setup_agent() |
| 122 | + if not agent or not conversation: |
| 123 | + return |
| 124 | + |
| 125 | + display_welcome() |
| 126 | + |
| 127 | + # Create prompt session |
| 128 | + session = PromptSession() |
| 129 | + |
| 130 | + # Main chat loop |
| 131 | + while True: |
| 132 | + try: |
| 133 | + # Get user input |
| 134 | + user_input = session.prompt( |
| 135 | + HTML("<blue>You: </blue>"), |
| 136 | + multiline=False, |
| 137 | + ) |
| 138 | + |
| 139 | + if not user_input.strip(): |
| 140 | + continue |
| 141 | + |
| 142 | + # Handle commands |
| 143 | + if user_input.strip().lower() == "/exit": |
| 144 | + print_formatted_text(HTML("<yellow>Goodbye! 👋</yellow>")) |
| 145 | + break |
| 146 | + elif user_input.strip().lower() == "/clear": |
| 147 | + clear() |
| 148 | + display_welcome() |
| 149 | + continue |
| 150 | + elif user_input.strip().lower() == "/help": |
| 151 | + display_welcome() |
| 152 | + continue |
| 153 | + |
| 154 | + # Send message to agent |
| 155 | + print_formatted_text(HTML("<green>Agent: </green>"), end="") |
| 156 | + |
| 157 | + try: |
| 158 | + # Create message and send to conversation |
| 159 | + message = Message( |
| 160 | + role="user", |
| 161 | + content=[TextContent(text=user_input)], |
| 162 | + ) |
| 163 | + |
| 164 | + conversation.send_message(message) |
| 165 | + conversation.run() |
| 166 | + |
| 167 | + # Get the last response from the conversation |
| 168 | + # For simplicity, we'll just indicate the agent processed the request |
| 169 | + print_formatted_text( |
| 170 | + HTML("<green>✓ Agent has processed your request.</green>") |
| 171 | + ) |
| 172 | + |
| 173 | + except Exception as e: |
| 174 | + print_formatted_text(HTML(f"<red>Error: {str(e)}</red>")) |
| 175 | + |
| 176 | + print() # Add spacing |
| 177 | + |
| 178 | + except KeyboardInterrupt: |
| 179 | + print_formatted_text( |
| 180 | + HTML("\n<yellow>Chat interrupted. Type /exit to quit.</yellow>") |
| 181 | + ) |
| 182 | + continue |
| 183 | + except EOFError: |
| 184 | + print_formatted_text(HTML("\n<yellow>Goodbye! 👋</yellow>")) |
| 185 | + break |
| 186 | + |
| 187 | + |
| 188 | +def main() -> None: |
| 189 | + """Main entry point for agent chat.""" |
| 190 | + try: |
| 191 | + run_agent_chat() |
| 192 | + except KeyboardInterrupt: |
| 193 | + print_formatted_text(HTML("\n<yellow>Goodbye! 👋</yellow>")) |
| 194 | + except Exception as e: |
| 195 | + print_formatted_text(HTML(f"<red>Unexpected error: {str(e)}</red>")) |
| 196 | + logger.error(f"Main error: {e}") |
| 197 | + |
| 198 | + |
| 199 | +if __name__ == "__main__": |
| 200 | + main() |
0 commit comments