-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcli.py
More file actions
executable file
·282 lines (231 loc) · 9.87 KB
/
cli.py
File metadata and controls
executable file
·282 lines (231 loc) · 9.87 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
import sys
import argparse
import uuid
from datetime import datetime
from core.llm_client import LLMClient
from core.logger import DialogueLogger
from core.rag_system import RAGSystem
from config.config import MODEL_NAME, RAG_CLI_KEY_TO_ID, RAG_ID_TO_NAME, RAG_ID_TO_DETAILS, RAG_CONFIGS, STARTER_MESSAGE, PERSONAS, DEFAULT_PERSONA, get_prompt
class ChatCLI:
def __init__(self, rag_config: str = "baseline", persona: str = DEFAULT_PERSONA):
"""Initialize the CLI chat interface
Args:
rag_config: RAG configuration ('baseline', 'crossencoder', or 'llm')
persona: Persona key ('neutral', 'friendly', 'professional')
"""
self.llm_client = LLMClient(model=MODEL_NAME)
self.llm_client.add_assistant_message(STARTER_MESSAGE)
self.persona_key = persona
self.persona_name = PERSONAS[self.persona_key]["name"]
self.rag_config_name = rag_config
self.rag_config = RAG_CLI_KEY_TO_ID[rag_config]
self.system_prompt = get_prompt(PERSONAS[self.persona_key]["prompt_key"])
self.running = True
# Initialize logger
self.session_id = str(uuid.uuid4())
self.logger = DialogueLogger()
self.session_log = self.logger.create_session(
self.session_id,
self.rag_config,
persona=self.persona_key,
model_name=MODEL_NAME
)
# Initialize RAG system
print(f"\nInitializing RAG system ({RAG_ID_TO_NAME[self.rag_config]})...")
self.rag_system = RAGSystem(config=self.rag_config)
print("RAG system ready.\n")
def print_header(self):
"""Print the CLI header"""
print("\n" + "="*60)
print("IndoGuide - CLI Interface")
print("="*60)
print(f"\nSession ID: {self.session_id}")
print(f"Persona: {self.persona_name}")
print(f"RAG Configuration: {RAG_ID_TO_NAME[self.rag_config]}")
print("\nIndoGuide is your smart travel companion designed to make")
print("exploring Indonesia effortless. Ask away information on must-see")
print("destinations, visas, transportation, safety, and local etiquettes,")
print("so you can travel with confidence. Whether you're planning your")
print("itinerary or navigating on the go, IndoGuide helps you experience")
print("Indonesia like a pro!")
print("\nCommands:")
print(" /reset - Start a new conversation")
print(" /history - Show conversation history")
print(" /config - Show current RAG configuration")
print(" /exit - Exit the CLI")
print("\nType your message and press Enter to chat.\n")
print("="*60 + "\n")
# Print starter message
self.print_message("assistant", STARTER_MESSAGE)
def print_message(self, role: str, content: str):
"""
Print a formatted message
Args:
role: 'user' or 'assistant'
content: Message content
"""
if role == "user":
print(f"\nYou: {content}")
elif role == "assistant":
print(f"\nAssistant: {content}")
def show_history(self):
"""Display the conversation history"""
messages = self.llm_client.get_messages()
if not messages:
print("\nNo conversation history yet.\n")
return
print("\n" + "="*60)
print("Conversation History")
print("="*60)
for i, msg in enumerate(messages, 1):
role_name = "You" if msg["role"] == "user" else "Assistant"
print(f"\n[{i}] {role_name}:")
print(f" {msg['content']}")
print("\n" + "="*60 + "\n")
def reset_conversation(self):
"""Reset the conversation"""
# Save current session
self.logger.save_session(self.session_log)
# Create new session
self.session_id = str(uuid.uuid4())
self.session_log = self.logger.create_session(
self.session_id,
self.rag_config,
persona=self.persona_key,
model_name=MODEL_NAME
)
self.llm_client.reset_conversation()
self.llm_client.add_assistant_message(STARTER_MESSAGE)
print(f"\nConversation reset. New session ID: {self.session_id}\n")
self.print_message("assistant", STARTER_MESSAGE)
def show_config(self):
"""Display current RAG configuration"""
print("\n" + "="*60)
print("Current RAG Configuration")
print("=" * 60)
config_name, details = RAG_ID_TO_DETAILS[self.rag_config]
print(f"\nConfiguration: {config_name}")
for detail in details:
print(detail)
print("\n" + "=" * 60 + "\n")
def handle_command(self, command: str) -> bool:
"""
Handle special commands
Args:
command: The command string
Returns:
True if command was handled, False otherwise
"""
command = command.lower().strip()
if command == "/exit":
print("\nSaving session and exiting...")
self.logger.save_session(self.session_log)
print("Goodbye!\n")
self.running = False
return True
elif command == "/reset":
self.reset_conversation()
return True
elif command == "/history":
self.show_history()
return True
elif command == "/config":
self.show_config()
return True
return False
def chat(self):
"""Main chat loop"""
self.print_header()
while self.running:
try:
# Get user input
user_input = input("You: ").strip()
# Skip empty input
if not user_input:
continue
# Handle commands
if user_input.startswith("/"):
self.handle_command(user_input)
continue
# Get user timestamp
user_timestamp = datetime.utcnow().strftime("%Y-%m-%d %H:%M:%S")
# Retrieve relevant context using RAG
print("\nRetrieving relevant information...", end="", flush=True)
retrieved_snippets = self.rag_system.retrieve(user_input)
context = self.rag_system.format_context(retrieved_snippets)
print(" Done.")
# Inject context into system prompt
augmented_prompt = context + "\n" + self.system_prompt
# If this is the first real turn (only starter message in history), inform the model
if len(self.llm_client.messages) == 1:
print("\nInforming model about starter message...")
augmented_prompt += f"\n\n[Context: You have just started the conversation with this greeting, so do not introduce yourself again: '{STARTER_MESSAGE}']"
# Log user turn with retrieved snippets
self.logger.add_turn(
self.session_log,
speaker="user",
utterance=user_input,
timestamp=user_timestamp,
retrieved_snippets=retrieved_snippets
)
# Get and stream assistant response
print("\nAssistant: ", end="", flush=True)
full_response = ""
for chunk in self.llm_client.chat_stream(
user_message=user_input,
system_prompt=augmented_prompt
):
print(chunk, end="", flush=True)
full_response += chunk
print("\n") # New line after response
# Get bot timestamp
bot_timestamp = datetime.utcnow().strftime("%Y-%m-%d %H:%M:%S")
# Log bot turn
self.logger.add_turn(
self.session_log,
speaker="assistant",
utterance=full_response,
timestamp=bot_timestamp
)
# Auto-save session after each turn
self.logger.save_session(self.session_log)
except KeyboardInterrupt:
print("\n\nGoodbye!\n")
break
except EOFError:
print("\n\nGoodbye!\n")
break
except Exception as e:
print(f"\nError: {e}\n")
continue
def main():
"""Main entry point for the CLI"""
# Generate help text dynamically from config
help_parts = ["RAG configuration: "]
for cli_key, config_id in RAG_CLI_KEY_TO_ID.items():
config_name = RAG_CONFIGS[config_id]["name"]
help_parts.append(f"{cli_key}={config_name}")
help_parts.append(f"(default: {list(RAG_CLI_KEY_TO_ID.keys())[0]})")
help_text = ", ".join(help_parts)
parser = argparse.ArgumentParser(
description="IndoGuide CLI - Interactive travel assistant for Indonesia"
)
parser.add_argument(
"--rag-config",
type=str,
choices=list(RAG_CLI_KEY_TO_ID.keys()),
default=list(RAG_CLI_KEY_TO_ID.keys())[0],
help=help_text
)
parser.add_argument(
"--persona",
type=str,
choices=list(PERSONAS.keys()),
default=DEFAULT_PERSONA,
help="Persona to use"
)
args = parser.parse_args()
cli = ChatCLI(rag_config=args.rag_config, persona=args.persona)
cli.chat()
if __name__ == "__main__":
main()