/
wolframalpha.go
88 lines (73 loc) · 2.33 KB
/
wolframalpha.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
package mutators
import (
"bytes"
"fmt"
"io"
"net/http"
"net/url"
"github.com/batmac/ccat/pkg/globalctx"
"github.com/batmac/ccat/pkg/secretprovider"
)
func init() {
singleRegister("wa", wolframalphashort,
withDescription("query wolfram alpha Short Answers API (APPID in $WA_APPID)"),
withCategory("external APIs"))
singleRegister("waspoken", wolframalphaspoken,
withDescription("query wolfram alpha Spoken API (APPID in $WA_APPID)"),
withCategory("external APIs"))
singleRegister("wasimple", wolframalphasimple,
withDescription("query wolfram alpha Simple API (output is an image, APPID in $WA_APPID)"),
withCategory("external APIs"),
withExpectingBinary())
// https://products.wolframalpha.com/llm-api/documentation
singleRegister("wallm", wolframalphallm,
withDescription("query wolfram alpha LLM API (APPID in $WA_APPID)"),
withCategory("external APIs"))
}
func wolframalphashort(w io.WriteCloser, r io.ReadCloser, _ any) (int64, error) {
return wolframalpha(w, r, "result", "i")
}
func wolframalphaspoken(w io.WriteCloser, r io.ReadCloser, _ any) (int64, error) {
return wolframalpha(w, r, "spoken", "i")
}
func wolframalphasimple(w io.WriteCloser, r io.ReadCloser, _ any) (int64, error) {
return wolframalpha(w, r, "simple", "i")
}
func wolframalphallm(w io.WriteCloser, r io.ReadCloser, _ any) (int64, error) {
return wolframalpha(w, r, "llm-api", "input")
}
func wolframalpha(w io.WriteCloser, r io.ReadCloser, t string, queryField string) (int64, error) {
baseURL := "https://api.wolframalpha.com/v1/" + t + "?"
query, err := io.ReadAll(r) // NOT streamable
if err != nil {
return 0, err
}
if len(query) == 0 {
return 0, nil
}
appID, _ := secretprovider.GetSecret("wolfram", "WA_APPID")
if appID == "" {
return 0, fmt.Errorf("no appid found in $WA_APPID")
}
// build query url values
q := url.Values{
queryField: {string(query)},
"appid": {appID},
}
res, err := http.Get(baseURL + q.Encode())
if err != nil {
return 0, err
}
data, err := io.ReadAll(res.Body)
if err != nil {
return 0, err
}
res.Body.Close()
// fmt.Println(string(data))
expectingBinary := globalctx.Get("expectingBinary")
// ensure data last char is a newline
if (expectingBinary == nil || !expectingBinary.(bool)) && data[len(data)-1] != '\n' {
data = append(data, '\n')
}
return io.Copy(w, bytes.NewReader(data))
}