Compare commits
7 Commits
239ded18f3
...
db788760a3
Author | SHA1 | Date | |
---|---|---|---|
db788760a3 | |||
242ed886ec | |||
02a23b9035 | |||
b3913d0027 | |||
1184f9aaae | |||
a25d0d95e8 | |||
becaa5c7c0 |
239
pkg/cli/cmd.go
239
pkg/cli/cmd.go
@ -17,20 +17,28 @@ var (
|
||||
systemPromptFile string
|
||||
)
|
||||
|
||||
const (
|
||||
// Limit to number of conversations shown with `ls`, without --all
|
||||
LS_LIMIT int = 25
|
||||
)
|
||||
|
||||
func init() {
|
||||
inputCmds := []*cobra.Command{newCmd, promptCmd, replyCmd, retryCmd, continueCmd, editCmd}
|
||||
for _, cmd := range inputCmds {
|
||||
cmd.Flags().IntVar(&maxTokens, "length", *config.OpenAI.DefaultMaxLength, "Max response length in tokens")
|
||||
cmd.Flags().StringVar(&model, "model", *config.OpenAI.DefaultModel, "The language model to use")
|
||||
cmd.Flags().StringVar(&systemPrompt, "system-prompt", *config.ModelDefaults.SystemPrompt, "The system prompt to use.")
|
||||
cmd.Flags().StringVar(&systemPromptFile, "system-prompt-file", "", "A path to a file whose contents are used as the system prompt.")
|
||||
cmd.Flags().IntVar(&maxTokens, "length", *config.OpenAI.DefaultMaxLength, "Maximum response tokens")
|
||||
cmd.Flags().StringVar(&model, "model", *config.OpenAI.DefaultModel, "Which model to use model")
|
||||
cmd.Flags().StringVar(&systemPrompt, "system-prompt", *config.ModelDefaults.SystemPrompt, "System prompt")
|
||||
cmd.Flags().StringVar(&systemPromptFile, "system-prompt-file", "", "A path to a file containing the system prompt")
|
||||
cmd.MarkFlagsMutuallyExclusive("system-prompt", "system-prompt-file")
|
||||
}
|
||||
|
||||
renameCmd.Flags().Bool("generate", false, "Use the LLM to generate the conversation title.")
|
||||
lsCmd.Flags().Bool("all", false, fmt.Sprintf("Show all conversations, by default only the last %d are shown", LS_LIMIT))
|
||||
renameCmd.Flags().Bool("generate", false, "Generate a conversation title")
|
||||
|
||||
rootCmd.AddCommand(
|
||||
cloneCmd,
|
||||
continueCmd,
|
||||
editCmd,
|
||||
lsCmd,
|
||||
newCmd,
|
||||
promptCmd,
|
||||
@ -39,7 +47,6 @@ func init() {
|
||||
retryCmd,
|
||||
rmCmd,
|
||||
viewCmd,
|
||||
editCmd,
|
||||
)
|
||||
}
|
||||
|
||||
@ -47,11 +54,11 @@ func Execute() error {
|
||||
return rootCmd.Execute()
|
||||
}
|
||||
|
||||
func SystemPrompt() string {
|
||||
func getSystemPrompt() string {
|
||||
if systemPromptFile != "" {
|
||||
content, err := FileContents(systemPromptFile)
|
||||
if err != nil {
|
||||
Fatal("Could not read file contents at %s: %v", systemPromptFile, err)
|
||||
Fatal("Could not read file contents at %s: %v\n", systemPromptFile, err)
|
||||
}
|
||||
return content
|
||||
}
|
||||
@ -82,9 +89,9 @@ func fetchAndShowCompletion(messages []Message) ([]Message, error) {
|
||||
return replies, err
|
||||
}
|
||||
|
||||
// lookupConversationByShortname either returns the conversation found by the
|
||||
// lookupConversation either returns the conversation found by the
|
||||
// short name or exits the program
|
||||
func lookupConversationByShortname(shortName string) *Conversation {
|
||||
func lookupConversation(shortName string) *Conversation {
|
||||
c, err := store.ConversationByShortName(shortName)
|
||||
if err != nil {
|
||||
Fatal("Could not lookup conversation: %v\n", err)
|
||||
@ -95,6 +102,17 @@ func lookupConversationByShortname(shortName string) *Conversation {
|
||||
return c
|
||||
}
|
||||
|
||||
func lookupConversationE(shortName string) (*Conversation, error) {
|
||||
c, err := store.ConversationByShortName(shortName)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("Could not lookup conversation: %v", err)
|
||||
}
|
||||
if c.ID == 0 {
|
||||
return nil, fmt.Errorf("Conversation not found with short name: %s", shortName)
|
||||
}
|
||||
return c, nil
|
||||
}
|
||||
|
||||
// handleConversationReply handles sending messages to an existing
|
||||
// conversation, optionally persisting them. It displays the entire
|
||||
// conversation before
|
||||
@ -137,11 +155,11 @@ func handleConversationReply(c *Conversation, persist bool, toSend ...Message) {
|
||||
}
|
||||
}
|
||||
|
||||
// InputFromArgsOrEditor returns either the provided input from the args slice
|
||||
// inputFromArgsOrEditor returns either the provided input from the args slice
|
||||
// (joined with spaces), or if len(args) is 0, opens an editor and returns
|
||||
// whatever input was provided there. placeholder is a string which populates
|
||||
// the editor and gets stripped from the final output.
|
||||
func InputFromArgsOrEditor(args []string, placeholder string, existingMessage string) (message string) {
|
||||
func inputFromArgsOrEditor(args []string, placeholder string, existingMessage string) (message string) {
|
||||
var err error
|
||||
if len(args) == 0 {
|
||||
message, err = InputFromEditor(placeholder, "message.*.md", existingMessage)
|
||||
@ -155,17 +173,19 @@ func InputFromArgsOrEditor(args []string, placeholder string, existingMessage st
|
||||
}
|
||||
|
||||
var rootCmd = &cobra.Command{
|
||||
Use: "lmcli",
|
||||
Long: `lmcli - command-line interface with Large Language Models.`,
|
||||
Use: "lmcli <command> [flags]",
|
||||
Long: `lmcli - Large Language Model CLI`,
|
||||
SilenceErrors: true,
|
||||
SilenceUsage: true,
|
||||
Run: func(cmd *cobra.Command, args []string) {
|
||||
// execute `lm ls` by default
|
||||
cmd.Usage()
|
||||
},
|
||||
}
|
||||
|
||||
var lsCmd = &cobra.Command{
|
||||
Use: "ls",
|
||||
Short: "List existing conversations",
|
||||
Long: `List all existing conversations in descending order of recent activity.`,
|
||||
Short: "List conversations",
|
||||
Long: `List conversations in order of recent activity`,
|
||||
Run: func(cmd *cobra.Command, args []string) {
|
||||
conversations, err := store.Conversations()
|
||||
if err != nil {
|
||||
@ -173,25 +193,10 @@ var lsCmd = &cobra.Command{
|
||||
return
|
||||
}
|
||||
|
||||
// Example output
|
||||
// $ lmcli ls
|
||||
// last hour:
|
||||
// 98sg - 12 minutes ago - Project discussion
|
||||
// last day:
|
||||
// tj3l - 10 hours ago - Deep learning concepts
|
||||
// last week:
|
||||
// bwfm - 2 days ago - Machine learning study
|
||||
// 8n3h - 3 days ago - Weekend plans
|
||||
// f3n7 - 6 days ago - CLI development
|
||||
// last month:
|
||||
// 5hn2 - 8 days ago - Book club discussion
|
||||
// b7ze - 20 days ago - Gardening tips and tricks
|
||||
// last 6 months:
|
||||
// 3jn2 - 30 days ago - Web development best practices
|
||||
// 43jk - 2 months ago - Longboard maintenance
|
||||
// g8d9 - 3 months ago - History book club
|
||||
// 4lk3 - 4 months ago - Local events and meetups
|
||||
// 43jn - 6 months ago - Mobile photography techniques
|
||||
type Category struct {
|
||||
name string
|
||||
cutoff time.Duration
|
||||
}
|
||||
|
||||
type ConversationLine struct {
|
||||
timeSinceReply time.Duration
|
||||
@ -199,43 +204,41 @@ var lsCmd = &cobra.Command{
|
||||
}
|
||||
|
||||
now := time.Now()
|
||||
categories := []string{
|
||||
"recent",
|
||||
"last hour",
|
||||
"last 6 hours",
|
||||
"last day",
|
||||
"last week",
|
||||
"last month",
|
||||
"last 6 months",
|
||||
"older",
|
||||
|
||||
midnight := time.Date(now.Year(), now.Month(), now.Day(), 0, 0, 0, 0, now.Location())
|
||||
monthStart := time.Date(now.Year(), now.Month(), 1, 0, 0, 0, 0, now.Location())
|
||||
dayOfWeek := int(now.Weekday())
|
||||
categories := []Category{
|
||||
{"today", now.Sub(midnight)},
|
||||
{"yesterday", now.Sub(midnight.AddDate(0, 0, -1))},
|
||||
{"this week", now.Sub(midnight.AddDate(0, 0, -dayOfWeek))},
|
||||
{"last week", now.Sub(midnight.AddDate(0, 0, -(dayOfWeek + 7)))},
|
||||
{"this month", now.Sub(monthStart)},
|
||||
{"last month", now.Sub(monthStart.AddDate(0, -1, 0))},
|
||||
{"2 months ago", now.Sub(monthStart.AddDate(0, -2, 0))},
|
||||
{"3 months ago", now.Sub(monthStart.AddDate(0, -3, 0))},
|
||||
{"4 months ago", now.Sub(monthStart.AddDate(0, -4, 0))},
|
||||
{"5 months ago", now.Sub(monthStart.AddDate(0, -5, 0))},
|
||||
{"older", now.Sub(time.Time{})},
|
||||
}
|
||||
categorized := map[string][]ConversationLine{}
|
||||
|
||||
all, _ := cmd.Flags().GetBool("all")
|
||||
|
||||
for _, conversation := range conversations {
|
||||
lastMessage, err := store.LastMessage(&conversation)
|
||||
if lastMessage == nil || err != nil {
|
||||
continue
|
||||
}
|
||||
|
||||
messageAge := now.Sub(lastMessage.CreatedAt)
|
||||
|
||||
var category string
|
||||
switch {
|
||||
case messageAge <= 10*time.Minute:
|
||||
category = "recent"
|
||||
case messageAge <= time.Hour:
|
||||
category = "last hour"
|
||||
case messageAge <= 6*time.Hour:
|
||||
category = "last 6 hours"
|
||||
case messageAge <= 24*time.Hour:
|
||||
category = "last day"
|
||||
case messageAge <= 7*24*time.Hour:
|
||||
category = "last week"
|
||||
case messageAge <= 30*24*time.Hour:
|
||||
category = "last month"
|
||||
case messageAge <= 6*30*24*time.Hour: // Approximate as 6 months
|
||||
category = "last 6 months"
|
||||
default:
|
||||
category = "older"
|
||||
for _, c := range categories {
|
||||
if messageAge < c.cutoff {
|
||||
category = c.name
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
formatted := fmt.Sprintf(
|
||||
@ -244,23 +247,34 @@ var lsCmd = &cobra.Command{
|
||||
humanTimeElapsedSince(messageAge),
|
||||
conversation.Title,
|
||||
)
|
||||
|
||||
categorized[category] = append(
|
||||
categorized[category],
|
||||
ConversationLine{messageAge, formatted},
|
||||
)
|
||||
}
|
||||
|
||||
var conversationsPrinted int
|
||||
outer:
|
||||
for _, category := range categories {
|
||||
conversations, ok := categorized[category]
|
||||
conversations, ok := categorized[category.name]
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
|
||||
slices.SortFunc(conversations, func(a, b ConversationLine) int {
|
||||
return int(a.timeSinceReply - b.timeSinceReply)
|
||||
})
|
||||
fmt.Printf("%s:\n", category)
|
||||
|
||||
fmt.Printf("%s:\n", category.name)
|
||||
for _, conv := range conversations {
|
||||
if conversationsPrinted >= LS_LIMIT && !all {
|
||||
fmt.Printf("%d remaining message(s), use --all to view.\n", len(conversations)-conversationsPrinted)
|
||||
break outer
|
||||
}
|
||||
|
||||
fmt.Printf(" %s\n", conv.formatted)
|
||||
conversationsPrinted++
|
||||
}
|
||||
}
|
||||
},
|
||||
@ -280,7 +294,7 @@ var rmCmd = &cobra.Command{
|
||||
Run: func(cmd *cobra.Command, args []string) {
|
||||
var toRemove []*Conversation
|
||||
for _, shortName := range args {
|
||||
conversation := lookupConversationByShortname(shortName)
|
||||
conversation := lookupConversation(shortName)
|
||||
toRemove = append(toRemove, conversation)
|
||||
}
|
||||
var errors []error
|
||||
@ -314,6 +328,65 @@ var rmCmd = &cobra.Command{
|
||||
},
|
||||
}
|
||||
|
||||
var cloneCmd = &cobra.Command{
|
||||
Use: "clone <conversation>",
|
||||
Short: "Clone conversations",
|
||||
Long: `Clones the provided conversation.`,
|
||||
Args: func(cmd *cobra.Command, args []string) error {
|
||||
argCount := 1
|
||||
if err := cobra.MinimumNArgs(argCount)(cmd, args); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
},
|
||||
RunE: func(cmd *cobra.Command, args []string) error {
|
||||
shortName := args[0]
|
||||
toClone, err := lookupConversationE(shortName)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
messagesToCopy, err := store.Messages(toClone)
|
||||
if err != nil {
|
||||
return fmt.Errorf("Could not retrieve messages for conversation: %s", toClone.ShortName.String)
|
||||
}
|
||||
|
||||
clone := &Conversation{
|
||||
Title: toClone.Title + " - Clone",
|
||||
}
|
||||
if err := store.SaveConversation(clone); err != nil {
|
||||
return fmt.Errorf("Cloud not create clone: %s", err)
|
||||
}
|
||||
|
||||
var errors []error
|
||||
messageCnt := 0
|
||||
for _, message := range messagesToCopy {
|
||||
newMessage := message
|
||||
newMessage.ConversationID = clone.ID
|
||||
newMessage.ID = 0
|
||||
if err := store.SaveMessage(&newMessage); err != nil {
|
||||
errors = append(errors, err)
|
||||
} else {
|
||||
messageCnt++
|
||||
}
|
||||
}
|
||||
|
||||
if len(errors) > 0 {
|
||||
return fmt.Errorf("Messages failed to be cloned: %v", errors)
|
||||
}
|
||||
|
||||
fmt.Printf("Cloned %d messages to: %s\n", messageCnt, clone.Title)
|
||||
return nil
|
||||
},
|
||||
ValidArgsFunction: func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
|
||||
compMode := cobra.ShellCompDirectiveNoFileComp
|
||||
if len(args) != 0 {
|
||||
return nil, compMode
|
||||
}
|
||||
return store.ConversationShortNameCompletions(toComplete), compMode
|
||||
},
|
||||
}
|
||||
|
||||
var viewCmd = &cobra.Command{
|
||||
Use: "view <conversation>",
|
||||
Short: "View messages in a conversation",
|
||||
@ -327,7 +400,7 @@ var viewCmd = &cobra.Command{
|
||||
},
|
||||
Run: func(cmd *cobra.Command, args []string) {
|
||||
shortName := args[0]
|
||||
conversation := lookupConversationByShortname(shortName)
|
||||
conversation := lookupConversation(shortName)
|
||||
|
||||
messages, err := store.Messages(conversation)
|
||||
if err != nil {
|
||||
@ -358,7 +431,7 @@ var renameCmd = &cobra.Command{
|
||||
},
|
||||
Run: func(cmd *cobra.Command, args []string) {
|
||||
shortName := args[0]
|
||||
conversation := lookupConversationByShortname(shortName)
|
||||
conversation := lookupConversation(shortName)
|
||||
var err error
|
||||
|
||||
generate, _ := cmd.Flags().GetBool("generate")
|
||||
@ -370,7 +443,7 @@ var renameCmd = &cobra.Command{
|
||||
}
|
||||
} else {
|
||||
if len(args) < 2 {
|
||||
Fatal("Conversation title not provided.")
|
||||
Fatal("Conversation title not provided.\n")
|
||||
}
|
||||
title = strings.Join(args[1:], " ")
|
||||
}
|
||||
@ -392,7 +465,7 @@ var renameCmd = &cobra.Command{
|
||||
|
||||
var replyCmd = &cobra.Command{
|
||||
Use: "reply <conversation> [message]",
|
||||
Short: "Send a reply to a conversation",
|
||||
Short: "Reply to a conversation",
|
||||
Long: `Sends a reply to conversation and writes the response to stdout.`,
|
||||
Args: func(cmd *cobra.Command, args []string) error {
|
||||
argCount := 1
|
||||
@ -403,9 +476,9 @@ var replyCmd = &cobra.Command{
|
||||
},
|
||||
Run: func(cmd *cobra.Command, args []string) {
|
||||
shortName := args[0]
|
||||
conversation := lookupConversationByShortname(shortName)
|
||||
conversation := lookupConversation(shortName)
|
||||
|
||||
reply := InputFromArgsOrEditor(args[1:], "# How would you like to reply?\n", "")
|
||||
reply := inputFromArgsOrEditor(args[1:], "# How would you like to reply?\n", "")
|
||||
if reply == "" {
|
||||
Fatal("No reply was provided.\n")
|
||||
}
|
||||
@ -430,7 +503,7 @@ var newCmd = &cobra.Command{
|
||||
Short: "Start a new conversation",
|
||||
Long: `Start a new conversation with the Large Language Model.`,
|
||||
Run: func(cmd *cobra.Command, args []string) {
|
||||
messageContents := InputFromArgsOrEditor(args, "# What would you like to say?\n", "")
|
||||
messageContents := inputFromArgsOrEditor(args, "# What would you like to say?\n", "")
|
||||
if messageContents == "" {
|
||||
Fatal("No message was provided.\n")
|
||||
}
|
||||
@ -445,7 +518,7 @@ var newCmd = &cobra.Command{
|
||||
{
|
||||
ConversationID: conversation.ID,
|
||||
Role: MessageRoleSystem,
|
||||
OriginalContent: SystemPrompt(),
|
||||
OriginalContent: getSystemPrompt(),
|
||||
},
|
||||
{
|
||||
ConversationID: conversation.ID,
|
||||
@ -475,7 +548,7 @@ var promptCmd = &cobra.Command{
|
||||
Short: "Do a one-shot prompt",
|
||||
Long: `Prompt the Large Language Model and get a response.`,
|
||||
Run: func(cmd *cobra.Command, args []string) {
|
||||
message := InputFromArgsOrEditor(args, "# What would you like to say?\n", "")
|
||||
message := inputFromArgsOrEditor(args, "# What would you like to say?\n", "")
|
||||
if message == "" {
|
||||
Fatal("No message was provided.\n")
|
||||
}
|
||||
@ -483,7 +556,7 @@ var promptCmd = &cobra.Command{
|
||||
messages := []Message{
|
||||
{
|
||||
Role: MessageRoleSystem,
|
||||
OriginalContent: SystemPrompt(),
|
||||
OriginalContent: getSystemPrompt(),
|
||||
},
|
||||
{
|
||||
Role: MessageRoleUser,
|
||||
@ -500,7 +573,7 @@ var promptCmd = &cobra.Command{
|
||||
|
||||
var retryCmd = &cobra.Command{
|
||||
Use: "retry <conversation>",
|
||||
Short: "Retries the last conversation prompt.",
|
||||
Short: "Retry the last user reply in a conversation",
|
||||
Long: `Re-prompt the conversation up to the last user response. Can be used to regenerate the last assistant reply, or simply generate one if an error occurred.`,
|
||||
Args: func(cmd *cobra.Command, args []string) error {
|
||||
argCount := 1
|
||||
@ -511,7 +584,7 @@ var retryCmd = &cobra.Command{
|
||||
},
|
||||
Run: func(cmd *cobra.Command, args []string) {
|
||||
shortName := args[0]
|
||||
conversation := lookupConversationByShortname(shortName)
|
||||
conversation := lookupConversation(shortName)
|
||||
|
||||
messages, err := store.Messages(conversation)
|
||||
if err != nil {
|
||||
@ -544,7 +617,7 @@ var retryCmd = &cobra.Command{
|
||||
|
||||
var continueCmd = &cobra.Command{
|
||||
Use: "continue <conversation>",
|
||||
Short: "Continues where the previous prompt left off.",
|
||||
Short: "Continue a conversation from the last message",
|
||||
Long: `Re-prompt the conversation with all existing prompts. Useful if a reply was cut short.`,
|
||||
Args: func(cmd *cobra.Command, args []string) error {
|
||||
argCount := 1
|
||||
@ -555,7 +628,7 @@ var continueCmd = &cobra.Command{
|
||||
},
|
||||
Run: func(cmd *cobra.Command, args []string) {
|
||||
shortName := args[0]
|
||||
conversation := lookupConversationByShortname(shortName)
|
||||
conversation := lookupConversation(shortName)
|
||||
handleConversationReply(conversation, true)
|
||||
},
|
||||
ValidArgsFunction: func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
|
||||
@ -569,7 +642,7 @@ var continueCmd = &cobra.Command{
|
||||
|
||||
var editCmd = &cobra.Command{
|
||||
Use: "edit <conversation>",
|
||||
Short: "Edit the last user message in a conversation.",
|
||||
Short: "Edit the last user reply in a conversation",
|
||||
Args: func(cmd *cobra.Command, args []string) error {
|
||||
argCount := 1
|
||||
if err := cobra.MinimumNArgs(argCount)(cmd, args); err != nil {
|
||||
@ -579,7 +652,7 @@ var editCmd = &cobra.Command{
|
||||
},
|
||||
Run: func(cmd *cobra.Command, args []string) {
|
||||
shortName := args[0]
|
||||
conversation := lookupConversationByShortname(shortName)
|
||||
conversation := lookupConversation(shortName)
|
||||
|
||||
messages, err := store.Messages(conversation)
|
||||
if err != nil {
|
||||
@ -608,7 +681,7 @@ var editCmd = &cobra.Command{
|
||||
|
||||
existingContents := lastUserMessage.OriginalContent
|
||||
|
||||
newContents := InputFromArgsOrEditor(args[1:], "# Save when finished editing\n", existingContents)
|
||||
newContents := inputFromArgsOrEditor(args[1:], "# Save when finished editing\n", existingContents)
|
||||
if newContents == existingContents {
|
||||
Fatal("No edits were made.\n")
|
||||
}
|
||||
@ -617,7 +690,7 @@ var editCmd = &cobra.Command{
|
||||
Fatal("No message was provided.\n")
|
||||
}
|
||||
|
||||
for _, message := range(toRemove) {
|
||||
for _, message := range toRemove {
|
||||
err = store.DeleteMessage(&message)
|
||||
if err != nil {
|
||||
Warn("Could not delete message: %v\n", err)
|
||||
|
Loading…
Reference in New Issue
Block a user