-
Notifications
You must be signed in to change notification settings - Fork 14
/
Copy pathai_openai.go
103 lines (85 loc) · 2.29 KB
/
ai_openai.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
package main
import (
"context"
"encoding/base64"
"fmt"
"github.com/sashabaranov/go-openai"
"os"
)
func initAI() *openai.Client {
var config = openai.DefaultConfig(OpenAIKey)
config.BaseURL = "https://burn.hair/v1"
var client = openai.NewClientWithConfig(config)
return client
}
func encodeImageToBase64(filePath string) string {
// Open the image file
file, _ := os.Open(filePath)
defer file.Close()
// Read the file contents into a byte slice
fileInfo, _ := file.Stat()
fileSize := fileInfo.Size()
buffer := make([]byte, fileSize)
_, _ = file.Read(buffer)
// Encode the byte slice to a Base64 string
base64String := base64.StdEncoding.EncodeToString(buffer)
return "data:image/jpeg;base64," + base64String
}
func imageToText(link, data string) string {
client := initAI()
const prompt = `This is a screenshot of a webpage, I want you to transcribe this page's main content into text.
Skip preamble and only return the result`
imagePart := openai.ChatMessagePart{
Type: openai.ChatMessagePartTypeImageURL,
ImageURL: &openai.ChatMessageImageURL{
URL: data,
},
}
textPart := openai.ChatMessagePart{
Type: openai.ChatMessagePartTypeText,
Text: prompt,
}
resp, err := client.CreateChatCompletion(
context.Background(),
openai.ChatCompletionRequest{
Model: openai.GPT4o,
Messages: []openai.ChatCompletionMessage{
{
Role: openai.ChatMessageRoleUser,
MultiContent: []openai.ChatMessagePart{imagePart, textPart},
},
},
},
)
if err != nil {
fmt.Printf("ChatCompletion error: %v\n", err)
return "ocr error"
}
var content = resp.Choices[0].Message.Content
return fmt.Sprintf("Following text is a transcribe of %s:\n\n%s\n", link, content)
}
func askOpenAI(userID int64) string {
client := initAI()
chats := getChats(userID)
var messages = []openai.ChatCompletionMessage{}
for _, chat := range chats {
m := openai.ChatCompletionMessage{
Role: chat.Role,
Content: chat.Text,
}
messages = append(messages, m)
}
resp, err := client.CreateChatCompletion(
context.Background(),
openai.ChatCompletionRequest{
Model: openai.GPT4o,
Messages: messages,
},
)
if err != nil {
fmt.Printf("ChatCompletion error: %v\n", err)
return "chatgpt error"
}
var content = resp.Choices[0].Message.Content
return content
}