-
Notifications
You must be signed in to change notification settings - Fork 4
/
service.go
107 lines (89 loc) · 2 KB
/
service.go
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
// Copyright (C) 2014 Constantin Schomburg <me@cschomburg.com>
//
// Use of this source code is governed by an MIT-style
// license that can be found in the LICENSE file.
// Service know answers questions by asking multiple knowledge providers.
package know
import (
"strings"
"github.com/sarifsystems/sarif/sarif"
"github.com/sarifsystems/sarif/services"
"github.com/xconstruct/know"
)
var Module = &services.Module{
Name: "know",
Version: "1.0",
NewInstance: NewService,
}
type Config struct {
WolframApiKey string
}
type Dependencies struct {
Config services.Config
Client sarif.Client
}
type Service struct {
cfg Config
sarif.Client
}
func NewService(deps *Dependencies) *Service {
s := &Service{
Client: deps.Client,
}
deps.Config.Get(&s.cfg)
if s.cfg.WolframApiKey != "" {
know.Wolfram.SetApiKey(s.cfg.WolframApiKey)
}
return s
}
func (s *Service) Enable() error {
if err := s.Subscribe("knowledge/query", "", s.handleQuery); err != nil {
return err
}
return nil
}
func (s *Service) Disable() error { return nil }
type MessageAnswer struct {
Query string `json:"query"`
Answer string `json:"answer"`
Source string
}
func (m MessageAnswer) String() string {
ans := m.Answer
if ans == "" {
return "No answer found for '" + m.Query + "'."
}
if strings.Contains(ans, "\n") {
ans = ":\n" + ans
}
return m.Query + " is " + ans + "."
}
func (s *Service) handleQuery(msg sarif.Message) {
query := msg.Text
// Query and wait for first answer
answers, errs := know.Ask(query)
ans, ok := <-answers
if !ok {
// No answer found? Check for errors.
err, ok := <-errs
if !ok {
// No errors found? Send negative answer
pl := MessageAnswer{
Query: query,
}
s.Reply(msg, sarif.CreateMessage("knowledge/noanswer", pl))
return
}
// Error received, forward.
s.ReplyInternalError(msg, err)
return
}
// Send answer.
pl := MessageAnswer{
ans.Question,
ans.Answer,
ans.Provider,
}
s.Reply(msg, sarif.CreateMessage("knowledge/answer", pl))
return
}