feat: implement terminal messenger with conversation management
feat: implement terminal messenger with conversation management - Add terminal-based messenger client connecting to Verint API endpoint - Implement colorized output (blue for user input, green for assistant responses) - Add readline integration for arrow key navigation through input history - Implement conversation persistence with unique history files per conversation ID - Add conversation resume feature listing 5 most recent conversations - Store and auto-load model names per conversation - Display last 10 message exchanges when resuming conversations - Log full conversation history (user + assistant messages) with timestamps - Simplify codebase by consolidating file operations into reusable functions - Fix Sscanf error handling for conversation selection Features: - Request/response handling with conversation context via previous_response_id - Three file types per conversation: .tmp (readline history), _log.txt (full conversation), _meta.txt (model name) - Automatic conversation ID assignment after first message - Clean exit handling and proper resource cleanup
This commit is contained in:
@@ -6,6 +6,9 @@ import (
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"sort"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
@@ -43,14 +46,7 @@ type Messenger struct {
|
||||
}
|
||||
|
||||
func (m *Messenger) Send(input string) (string, error) {
|
||||
reqBody := Request{
|
||||
Input: input,
|
||||
Model: m.model,
|
||||
PreviousResponseID: m.prevID,
|
||||
Metadata: map[string]string{"channel": "text"},
|
||||
}
|
||||
|
||||
data, _ := json.Marshal(reqBody)
|
||||
data, _ := json.Marshal(Request{input, m.model, m.prevID, map[string]string{"channel": "text"}})
|
||||
resp, err := m.client.Post(apiURL, "application/json", bytes.NewBuffer(data))
|
||||
if err != nil {
|
||||
return "", err
|
||||
@@ -58,65 +54,152 @@ func (m *Messenger) Send(input string) (string, error) {
|
||||
defer resp.Body.Close()
|
||||
|
||||
body, _ := io.ReadAll(resp.Body)
|
||||
var response Response
|
||||
if err := json.Unmarshal(body, &response); err != nil {
|
||||
return "", err
|
||||
var r Response
|
||||
json.Unmarshal(body, &r)
|
||||
m.prevID = r.ID
|
||||
|
||||
if r.Status == "completed" && len(r.Output) > 0 && len(r.Output[0].Content) > 0 {
|
||||
return r.Output[0].Content[0].Text, nil
|
||||
}
|
||||
return "", fmt.Errorf("invalid response")
|
||||
}
|
||||
|
||||
m.prevID = response.ID
|
||||
|
||||
if response.Status != "completed" || len(response.Output) == 0 || len(response.Output[0].Content) == 0 {
|
||||
return "", fmt.Errorf("invalid response")
|
||||
func getConversations() []string {
|
||||
files, _ := filepath.Glob("/tmp/messenger_*_log.txt")
|
||||
type f struct {
|
||||
id string
|
||||
t time.Time
|
||||
}
|
||||
var list []f
|
||||
for _, file := range files {
|
||||
info, _ := os.Stat(file)
|
||||
id := strings.TrimSuffix(strings.TrimPrefix(filepath.Base(file), "messenger_"), "_log.txt")
|
||||
list = append(list, f{id, info.ModTime()})
|
||||
}
|
||||
sort.Slice(list, func(i, j int) bool { return list[i].t.After(list[j].t) })
|
||||
|
||||
return response.Output[0].Content[0].Text, nil
|
||||
var ids []string
|
||||
for i, item := range list {
|
||||
if i >= 5 {
|
||||
break
|
||||
}
|
||||
ids = append(ids, item.id)
|
||||
}
|
||||
return ids
|
||||
}
|
||||
|
||||
func readFile(path string) string {
|
||||
data, _ := os.ReadFile(path)
|
||||
return strings.TrimSpace(string(data))
|
||||
}
|
||||
|
||||
func writeFile(path, content string) {
|
||||
os.WriteFile(path, []byte(content), 0644)
|
||||
}
|
||||
|
||||
func appendFile(path, content string) {
|
||||
f, _ := os.OpenFile(path, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
|
||||
defer f.Close()
|
||||
f.WriteString(content)
|
||||
}
|
||||
|
||||
func showHistory(id string) {
|
||||
lines := strings.Split(readFile(fmt.Sprintf("/tmp/messenger_%s_log.txt", id)), "\n")
|
||||
start := len(lines) - 20
|
||||
if start < 0 {
|
||||
start = 0
|
||||
}
|
||||
fmt.Println("\n--- Previous Messages ---")
|
||||
for _, line := range lines[start:] {
|
||||
if strings.Contains(line, "You: ") {
|
||||
fmt.Printf(blue+"You: %s"+reset+"\n", strings.SplitN(line, "You: ", 2)[1])
|
||||
} else if strings.Contains(line, "Assistant: ") {
|
||||
fmt.Printf(green+"Assistant: %s"+reset+"\n", strings.SplitN(line, "Assistant: ", 2)[1])
|
||||
}
|
||||
}
|
||||
fmt.Println("-------------------------\n")
|
||||
}
|
||||
|
||||
func main() {
|
||||
fmt.Print("Enter model name (default: 'default'): ")
|
||||
var model string
|
||||
fmt.Scanln(&model)
|
||||
if model == "" {
|
||||
model = "default"
|
||||
var id, model string
|
||||
|
||||
// Check for recent conversations
|
||||
convs := getConversations()
|
||||
if len(convs) > 0 {
|
||||
fmt.Println("Recent conversations:")
|
||||
for i, cid := range convs {
|
||||
m := readFile(fmt.Sprintf("/tmp/messenger_%s_meta.txt", cid))
|
||||
fmt.Printf("%d. %s (model: %s)\n", i+1, cid, m)
|
||||
}
|
||||
fmt.Print("\nContinue? (enter number or 'n' for new): ")
|
||||
var choice string
|
||||
fmt.Scanln(&choice)
|
||||
var num int
|
||||
if _, err := fmt.Sscanf(choice, "%d", &num); err == nil && num >= 1 && num <= len(convs) {
|
||||
id = convs[num-1]
|
||||
model = readFile(fmt.Sprintf("/tmp/messenger_%s_meta.txt", id))
|
||||
fmt.Printf("Continuing: %s (model: %s)\n", id, model)
|
||||
showHistory(id)
|
||||
}
|
||||
}
|
||||
|
||||
messenger := &Messenger{
|
||||
client: &http.Client{Timeout: 10 * time.Second},
|
||||
model: model,
|
||||
if model == "" {
|
||||
fmt.Print("Enter model name (default: 'default'): ")
|
||||
fmt.Scanln(&model)
|
||||
if model == "" {
|
||||
model = "default"
|
||||
}
|
||||
}
|
||||
|
||||
m := &Messenger{&http.Client{Timeout: 10 * time.Second}, model, id}
|
||||
|
||||
fmt.Println("\n=== Terminal Messenger ===")
|
||||
fmt.Println("Use ↑/↓ arrows for history, type 'quit' to exit\n")
|
||||
fmt.Println("Use ↑/↓ for history, 'quit' to exit\n")
|
||||
|
||||
rl, err := readline.NewEx(&readline.Config{
|
||||
Prompt: blue + "You: " + reset,
|
||||
HistoryFile: "/tmp/messenger_history.tmp",
|
||||
})
|
||||
if err != nil {
|
||||
fmt.Println("Error:", err)
|
||||
return
|
||||
histFile := "/tmp/messenger_temp.tmp"
|
||||
if id != "" {
|
||||
histFile = fmt.Sprintf("/tmp/messenger_%s.tmp", id)
|
||||
}
|
||||
|
||||
rl, _ := readline.NewEx(&readline.Config{Prompt: blue + "You: " + reset, HistoryFile: histFile})
|
||||
defer rl.Close()
|
||||
|
||||
first := id == ""
|
||||
|
||||
for {
|
||||
input, err := rl.Readline()
|
||||
if err != nil || strings.TrimSpace(input) == "quit" || strings.TrimSpace(input) == "exit" {
|
||||
if err != nil || input == "quit" || input == "exit" {
|
||||
break
|
||||
}
|
||||
|
||||
input = strings.TrimSpace(input)
|
||||
if input == "" {
|
||||
if input = strings.TrimSpace(input); input == "" {
|
||||
continue
|
||||
}
|
||||
|
||||
response, err := messenger.Send(input)
|
||||
response, err := m.Send(input)
|
||||
if err != nil {
|
||||
fmt.Println("Error:", err)
|
||||
continue
|
||||
}
|
||||
|
||||
if first && m.prevID != "" {
|
||||
first = false
|
||||
rl.Close()
|
||||
rl, _ = readline.NewEx(&readline.Config{
|
||||
Prompt: blue + "You: " + reset,
|
||||
HistoryFile: fmt.Sprintf("/tmp/messenger_%s.tmp", m.prevID),
|
||||
})
|
||||
writeFile(fmt.Sprintf("/tmp/messenger_%s_meta.txt", m.prevID), m.model)
|
||||
fmt.Printf("(ID: %s)\n\n", m.prevID)
|
||||
}
|
||||
|
||||
if m.prevID != "" {
|
||||
ts := time.Now().Format("2006-01-02 15:04:05")
|
||||
logFile := fmt.Sprintf("/tmp/messenger_%s_log.txt", m.prevID)
|
||||
appendFile(logFile, fmt.Sprintf("[%s] You: %s\n[%s] Assistant: %s\n", ts, input, ts, response))
|
||||
}
|
||||
|
||||
fmt.Printf(green+"Assistant: %s"+reset+"\n\n", response)
|
||||
}
|
||||
|
||||
fmt.Println("Goodbye!")
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user