-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathai.go
90 lines (75 loc) · 2.52 KB
/
ai.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
package main
import (
"context"
"encoding/json"
"fmt"
"os"
"strings"
"github.com/sashabaranov/go-openai"
"google.golang.org/api/customsearch/v1"
"google.golang.org/api/option"
)
func init() {
customsearchService, err := customsearch.NewService(context.Background(), option.WithAPIKey(os.Getenv("GOOGLE_SEARCH_API_KEY")))
if err != nil {
panic(err)
}
search = customsearchService
}
var (
search *customsearch.Service
searchID = os.Getenv("GOOGLE_SEARCH_ENDPOINT")
client = openai.NewClient(os.Getenv("OPENAI_API_KEY"))
)
func generateRecipe(g Generate) (Recipe, error) {
resp, err := client.CreateChatCompletion(
context.Background(),
openai.ChatCompletionRequest{
Model: openai.GPT3Dot5Turbo,
Messages: []openai.ChatCompletionMessage{
{
Role: openai.ChatMessageRoleSystem,
Content: `You are an assistant to come up with food recipes. You should respond in JSON format, like this for example:
{
"name": "French Omelette with Cheese",
"description": "This is a delicious version of the classic, creamy French omelette with your choice of cheese.",
"ingredients": ["3 large eggs", "Kosher salt", "freshly ground black pepper"],
"instructions": ["In a medium bowl, beat eggs until last traces of white are mixed in.", "Season with salt and pepper", "Melt butter in a skillet and add eggs."]
}`,
},
{
Role: openai.ChatMessageRoleUser,
Content: makePrompt(g),
},
},
},
)
if err != nil {
return Recipe{}, err
}
var recipe Recipe
err = json.Unmarshal([]byte(resp.Choices[0].Message.Content), &recipe)
if err != nil {
return Recipe{}, fmt.Errorf("%w for string %s", err, resp.Choices[0].Message.Content)
}
result, err := search.Cse.List().Cx(searchID).Q(recipe.Name).SearchType("image").ImgType("photo").Do()
if err != nil {
return Recipe{}, err
}
recipe.Image = result.Items[0].Link
return recipe, nil
}
func makePrompt(g Generate) string {
str := ""
if len(g.InludeIngredients) > 0 {
str += fmt.Sprintf("I have these ingredients: %s.\n", g.InludeIngredients)
}
if len(g.ExcludeIngredients) > 0 {
str += fmt.Sprintf("I don't have these ingredients: %s.\n", g.ExcludeIngredients)
}
str += fmt.Sprintf("Come up with a recipe in the style of one of these places: %s.\n", strings.Join(g.Locations, ", "))
str += fmt.Sprintf("It should include these flavors: %s.\n", strings.Join(g.Flavors, ", "))
str += fmt.Sprintf("It can be one of these: %s.\n", strings.Join(g.Times, ", "))
str += "You can include other ingredients."
return str
}