-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
111 lines (88 loc) · 2.46 KB
/
main.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
108
109
110
111
package main
import (
"fmt"
"strings"
"github.com/hypermodeinc/modus/sdk/go/pkg/http"
"github.com/hypermodeinc/modus/sdk/go/pkg/models"
"github.com/hypermodeinc/modus/sdk/go/pkg/models/openai"
pg "github.com/hypermodeinc/modus/sdk/go/pkg/postgresql"
)
// Generate text using an AI model
func GenerateText(prompt string) (*string, error) {
// The imported ChatModel type follows the OpenAI Chat completion model input format.
model, err := models.GetModel[openai.ChatModel]("text-generator")
if err != nil {
return nil, err
}
input, err := model.CreateInput(
openai.NewSystemMessage("You are a helpful assistant. Try and be as concise as possible."),
openai.NewUserMessage(prompt),
)
if err != nil {
return nil, err
}
input.Temperature = 0.7
output, err := model.Invoke(input)
if err != nil {
return nil, err
}
outputStr := strings.TrimSpace(output.Choices[0].Message.Content)
return &outputStr, nil
}
// A single quote from the Zenquotes API
type Quote struct {
Quote string `json:"q"`
Author string `json:"a"`
}
// Fetch a random quote from the Zenquotes API
func FetchQuote() (*Quote, error) {
req := http.NewRequest("https://zenquotes.io/api/random")
res, err := http.Fetch(req, nil)
if err != nil {
return nil, err
}
var quotes []Quote
res.JSON("es)
if len(quotes) == 0 {
return nil, fmt.Errorf("no quotes found")
}
return "es[0], nil
}
// Use an AI model to generate quote author information
func FetchQuoteAndAuthorInfo() (quote *Quote, info *string, err error) {
quote, err = FetchQuote()
if err != nil {
return nil, nil, err
}
info, err = GenerateText(fmt.Sprintf("Give me a information about %s, limit it to 1 sentence.", quote.Author))
if err != nil {
return nil, nil, err
}
return quote, info, nil
}
// Insert quote into database
func FetchQuoteAddToDB() (uint, error) {
quote, info, err := FetchQuoteAndAuthorInfo()
if err != nil {
return 0, err
}
rows, err := pg.Execute("postgres", "INSERT INTO quotes (quote, author, info) VALUES ($1, $2, $3)", quote.Quote, quote.Author, *info)
if err != nil {
return 0, err
}
return rows, nil
}
// Quote including author information
type DBQuote struct {
Quote string `json:"quote"`
Author string `json:"author"`
Info string `json:"info"`
}
// Fetch all quotes from database
func FetchQuotesFromDB() ([]DBQuote, error) {
rows, _, err := pg.Query[DBQuote]("postgres", "SELECT quote, author, info FROM quotes")
if err != nil {
return nil, err
}
return rows, nil
}