Эх сурвалжийг харах

Eliza-014 Add Template functions

gremlin 4 жил өмнө
parent
commit
4ca9a1f6f1
5 өөрчлөгдсөн 139 нэмэгдсэн , 27 устгасан
  1. 33 2
      bots/eliza.json
  2. 33 2
      bots/ivanka.json
  3. 36 18
      eliza/eliza.go
  4. 33 0
      eliza/functions.go
  5. 4 5
      main.go

+ 33 - 2
bots/eliza.json

@@ -1,6 +1,6 @@
 {
     "name": "Eliza",
-    "version": "v0.0.3",
+    "version": "v0.0.4",
     "commands": {
         "version": [
             ""
@@ -23,6 +23,37 @@
         "Ciao"
     ],
     "psychobabble": [
+        {
+            "similarQuestions": [
+                "what'?s the day of the week",
+                "whats the day of the week",
+                "what is the day of the week",
+                "what day is it"
+            ],
+            "responses": [
+                "its {{ dayOfWeek }}"
+            ]
+        },
+        {
+            "similarQuestions": [
+                "what'?s the date",
+                "whats the date",
+                "what is the date"
+            ],
+            "responses": [
+                "its {{ fullDate }}"
+            ]
+        },
+        {
+            "similarQuestions": [
+                "year",
+                "what year",
+                "what year is it"
+            ],
+            "responses": [
+                "its {{ year }}"
+            ]
+        },
         {
             "similarQuestions": [
                 "i need (.*)"
@@ -70,7 +101,7 @@
                 "(.*) your name?"
             ],
             "responses": [
-                "My name is {{.Session.User}}",
+                "My name is {{.Session.Bot}}",
                 "I thought that would be self explanatory.",
                 "....Look up."
             ]

+ 33 - 2
bots/ivanka.json

@@ -1,6 +1,6 @@
 {
     "name": "Ivanka",
-    "version": "v0.0.3",
+    "version": "v0.0.4",
     "commands": {
         "version": [
             ""
@@ -23,6 +23,37 @@
         "Ciao"
     ],
     "psychobabble": [
+        {
+            "similarQuestions": [
+                "what'?s the day of the week",
+                "whats the day of the week",
+                "what is the day of the week",
+                "what day is it"
+            ],
+            "responses": [
+                "its {{ dayOfWeek }}"
+            ]
+        },
+        {
+            "similarQuestions": [
+                "what'?s the date",
+                "whats the date",
+                "what is the date"
+            ],
+            "responses": [
+                "its {{ fullDate }}"
+            ]
+        },
+        {
+            "similarQuestions": [
+                "year",
+                "what year",
+                "what year is it"
+            ],
+            "responses": [
+                "its {{ year }}"
+            ]
+        },
         {
             "similarQuestions": [
                 "i need (.*)"
@@ -70,7 +101,7 @@
                 "(.*) your name?"
             ],
             "responses": [
-                "My name is {{.Session.User}}",
+                "My name is {{.Session.Bot}}",
                 "I thought that would be self explanatory.",
                 "....Look up."
             ]

+ 36 - 18
eliza/eliza.go

@@ -33,9 +33,11 @@ type ChatbotContext struct {
 
 // ChatbotInteraction defines a individual question/answer interaction with a caller
 type ChatbotInteraction struct {
-	Time     string `json:"time,omitempty" yaml:"time,omitempty"`
-	Question string `json:"question,omitempty" yaml:"question,omitempty"`
-	Answer   string `json:"answer,omitempty" yaml:"answer,omitempty"`
+	Time         string `json:"time,omitempty" yaml:"time,omitempty"`
+	Question     string `json:"question,omitempty" yaml:"question,omitempty"`
+	PatternGroup string `json:"patternGroup,omitempty" yaml:"patternGroup,omitempty"`
+	Pattern      string `json:"pattern,omitempty" yaml:"pattern,omitempty"`
+	Answer       string `json:"answer,omitempty" yaml:"answer,omitempty"`
 }
 
 // SessionData defines information about the current bot and its interaction within a specific session
@@ -54,37 +56,34 @@ func NewBotPersonality(personality *Personality, context *ChatbotContext) *Chatb
 
 }
 
-// Greetings will return a random introductory sentence for ELIZA.
-func (p *Chatbot) Greetings() string {
-	return p.randChoice(p.Personality.Introductions)
+func NewChatbotInteraction(question, patterngroup, answer string) ChatbotInteraction {
+	return ChatbotInteraction{Time: time.Now().UTC().String(), Question: question, PatternGroup: patterngroup, Answer: answer}
 }
 
-// GoodbyeResponse will return a random goodbye sentence for ELIZA.
-func (p *Chatbot) GoodbyeResponse() string {
-	return p.randChoice(p.Personality.Goodbyes)
+func NewChatbotInteractionWithPattern(question, patterngroup, pattern, answer string) ChatbotInteraction {
+	return ChatbotInteraction{Time: time.Now().UTC().String(), Question: question, PatternGroup: patterngroup, Pattern: pattern, Answer: answer}
 }
 
 // ReplyTo will construct a reply for a given statement using ELIZA's rules.
-func (p *Chatbot) ReplyTo(statement string) string {
+func (p *Chatbot) ReplyTo(statement string) ChatbotInteraction {
 	// First, preprocess the statement for more effective matching
 	statement = p.preprocess(statement)
 
 	// Then, we check if this is a quit statement
 	if p.IsQuitStatement(statement) {
-		return p.GoodbyeResponse()
+		return NewChatbotInteraction(statement, "QuitResponses", p.GoodbyeResponse())
 	}
 
 	// Next, we try to match the statement to a statement that ELIZA can
 	// recognize, and construct a pre-determined, appropriate response.
 	for _, similarQuestionResponse := range p.Personality.Psychobabble {
-		for _, question := range similarQuestionResponse.SimilarQuestions {
-			re := regexp.MustCompile(question)
+		for _, questionPattern := range similarQuestionResponse.SimilarQuestions {
+			re := regexp.MustCompile(questionPattern)
 			matches := re.FindStringSubmatch(statement)
 
 			// If the statement matched any recognizable statements.
 			if len(matches) > 0 {
-				// If we matched a regex group in parentheses, get the first match.
-				// The matched regex group will match a "fragment" that will form
+				// If we matched a regex group in parentheses, get the first match. The matched regex group will match a "fragment" that will form
 				// part of the response, for added realism.
 				var fragment string
 				if len(matches) > 1 {
@@ -98,13 +97,23 @@ func (p *Chatbot) ReplyTo(statement string) string {
 					response = fmt.Sprintf(response, fragment)
 				}
 				//			fmt.Printf("For Statement \"%s\" got a hit with pattern \"%s\" Responded With \"%s\"\n", statement, pattern, response)
-				return p.replacePlaceHolders(response)
+				return NewChatbotInteractionWithPattern(statement, "Psychobabble", questionPattern, p.replacePlaceHolders(response))
 			}
 		}
 	}
 
 	// If no patterns were matched, return a default response.
-	return p.replacePlaceHolders(p.randChoice(p.Personality.DefaultResponses))
+	return NewChatbotInteraction(statement, "DefaultResponses", p.replacePlaceHolders(p.randChoice(p.Personality.DefaultResponses)))
+}
+
+// Greetings will return a random introductory sentence for ELIZA.
+func (p *Chatbot) Greetings() string {
+	return p.randChoice(p.Personality.Introductions)
+}
+
+// GoodbyeResponse will return a random goodbye sentence for ELIZA.
+func (p *Chatbot) GoodbyeResponse() string {
+	return p.randChoice(p.Personality.Goodbyes)
 }
 
 // IsQuitStatement returns if the statement is a quit statement
@@ -152,7 +161,16 @@ func (p *Chatbot) randChoice(list []string) string {
  */
 func (p *Chatbot) replacePlaceHolders(answer string) string {
 	var tBuffer bytes.Buffer
-	t := template.Must(template.New("answer").Parse(answer))
+	funcsMap := template.FuncMap{
+		"dayOfWeek": dayOfWeek,
+		"fullDate":  date,
+		"year":      year,
+	}
+
+	rawTemplate := template.New("answer")
+	tmpl := rawTemplate.Funcs(funcsMap)
+
+	t, _ := tmpl.Parse(answer)
 	t.Execute(&tBuffer, p.Context)
 
 	return tBuffer.String()

+ 33 - 0
eliza/functions.go

@@ -0,0 +1,33 @@
+package eliza
+
+import (
+	"fmt"
+	"time"
+)
+
+func year() string {
+	year, _, _ := time.Now().Date()
+	return fmt.Sprintf("%d", year)
+}
+
+func date() string {
+	dw := time.Now().Weekday()
+	mon := time.Now().Month()
+	dom := time.Now().Day()
+	s := "th"
+	if dom == 1 || dom == 21 || dom == 31 {
+		s = "st"
+	}
+	if dom == 2 || dom == 22 {
+		s = "nd"
+	}
+	if dom == 3 {
+		s = "rd"
+	}
+	return fmt.Sprintf("%s %d%s %s", dw, dom, s, mon)
+}
+
+func dayOfWeek() string {
+	dt := time.Now().Weekday()
+	return dt.String()
+}

+ 4 - 5
main.go

@@ -144,20 +144,19 @@ func chantboInteractiontEndpoint(c echo.Context) error {
 	// Return Eliza's response's so long as the user doesn't give a quit statement
 	chatboxContext := eliza.ChatbotContext{infrastructure.Version, sessionData}
 	character := eliza.NewBotPersonality(&personality, &chatboxContext)
-	answer := character.ReplyTo(question)
+	botResponse := character.ReplyTo(question)
 
-	msg := fmt.Sprintf("Bot [%s %s] Session ID [%s] Question [%s] Answer [%s]", botname, personality.Version, sessionID, question, answer)
+	msg := fmt.Sprintf("Bot [%s %s] Session ID [%s] Question [%s] Answer [%s]", botname, personality.Version, sessionID, question, botResponse.Answer)
 	fmt.Println(msg)
 
 	// update cache
 	// OK addToConversation
-	botInteraction := eliza.ChatbotInteraction{time.Now().UTC().String(), question, answer}
-	sessionData.Conversation = append(sessionData.Conversation, botInteraction)
+	sessionData.Conversation = append(sessionData.Conversation, botResponse)
 
 	storeConversation(sessionID, sessionData)
 
 	// Return Eliza's answer
-	return c.String(http.StatusOK, answer)
+	return c.String(http.StatusOK, botResponse.Answer)
 }
 
 /***********************************************************************************************