handle old conversations

This commit is contained in:
Erik Winter 2023-05-18 10:38:40 +02:00
parent 9c77046f3b
commit decaf484cd
2 changed files with 33 additions and 37 deletions

View File

@ -26,7 +26,7 @@ func (g GPT) Complete(conv *Conversation) (string, error) {
})
}
req := openai.ChatCompletionRequest{
Model: openai.GPT3Dot5Turbo,
Model: openai.GPT4,
Messages: msg,
}

View File

@ -119,35 +119,41 @@ func (m *Matrix) InviteHandler() (event.Type, mautrix.EventHandler) {
func (m *Matrix) RespondHandler() (event.Type, mautrix.EventHandler) {
return event.EventMessage, func(source mautrix.EventSource, evt *event.Event) {
content := evt.Content.AsMessage()
eventID := evt.ID
m.client.Log.Info().
Str("content", content.Body).
Msg("Received message")
Msg("received message")
conv := m.conversations.FindByEventID(eventID)
if conv != nil {
m.client.Log.Info().
Str("event_id", eventID.String()).
Msg("already known message, ignoring")
return
}
parentID := id.EventID("")
if relatesTo := content.GetRelatesTo(); relatesTo != nil {
parentID = relatesTo.GetReplyTo()
}
if parentID != "" {
conv = m.conversations.FindByEventID(parentID)
}
if conv != nil {
conv.Add(Message{
EventID: eventID,
ParentID: parentID,
Role: openai.ChatMessageRoleUser,
Content: content.Body,
})
m.client.Log.Info().Msg("found parent, appending message to conversation")
} else {
conv = NewConversation(content.Body)
m.conversations = append(m.conversations, conv)
m.client.Log.Info().Msg("no parent found, starting new conversation")
}
if evt.Sender != id.UserID(m.config.UserID) {
eventID := evt.ID
parentID := id.EventID("")
if relatesTo := content.GetRelatesTo(); relatesTo != nil {
parentID = relatesTo.GetReplyTo()
}
// find existing conversation and add message, or start a new one
var conv *Conversation
if parentID != "" {
conv = m.conversations.FindByEventID(parentID)
}
if conv != nil {
conv.Add(Message{
EventID: eventID,
ParentID: parentID,
Role: openai.ChatMessageRoleUser,
Content: content.Body,
})
} else {
conv = NewConversation(content.Body)
m.conversations = append(m.conversations, conv)
}
// get reply from GPT
reply, err := m.gptClient.Complete(conv)
if err != nil {
@ -161,22 +167,12 @@ func (m *Matrix) RespondHandler() (event.Type, mautrix.EventHandler) {
EventID: eventID,
},
}
resp, err := m.client.SendMessageEvent(evt.RoomID, event.EventMessage, &formattedReply)
if err != nil {
if _, err := m.client.SendMessageEvent(evt.RoomID, event.EventMessage, &formattedReply); err != nil {
m.client.Log.Err(err).Msg("failed to send message")
return
}
// add reply to conversation
conv.Add(Message{
EventID: resp.EventID,
Role: openai.ChatMessageRoleAssistant,
Content: reply,
ParentID: eventID,
})
m.client.Log.Info().Str("message", fmt.Sprintf("%+v", formattedReply.Body)).Msg("Sent reply")
}
}
}