67 lines
1.9 KiB
Go
67 lines
1.9 KiB
Go
package openai
|
|
|
|
import (
|
|
"beacon/config"
|
|
"beacon/utils"
|
|
"context"
|
|
"encoding/base64"
|
|
"fmt"
|
|
"mime/multipart"
|
|
"net/http"
|
|
|
|
"github.com/openai/openai-go"
|
|
"github.com/openai/openai-go/option"
|
|
)
|
|
|
|
// encodeImageToBase64 是一个辅助函数,用于读取图像文件,
|
|
// 检测其 MIME 类型,并将其编码为 Base64 数据 URI。
|
|
func encodeImageToBase64(file *multipart.FileHeader) (string, error) {
|
|
// 1. 读取文件字节。
|
|
bytes := utils.FileStreamToBytes(file)
|
|
|
|
// 2. 检测文件的 MIME 类型。
|
|
// 这对于构建正确的数据 URI至关重要。
|
|
mimeType := http.DetectContentType(bytes)
|
|
|
|
// 3. 对文件字节进行 Base64 编码。
|
|
encodedStr := base64.StdEncoding.EncodeToString(bytes)
|
|
|
|
// 4. 构建并返回完整的数据 URI 字符串。
|
|
return fmt.Sprintf("data:%s;base64,%s", mimeType, encodedStr), nil
|
|
}
|
|
|
|
func GetOllamaAICaptcha(file *multipart.FileHeader) (error, string) {
|
|
client := openai.NewClient(
|
|
option.WithAPIKey(config.Conf.OpenAIConfig.ApiKey), // defaults to os.LookupEnv("OPENAI_API_KEY")
|
|
option.WithBaseURL(config.Conf.OpenAIConfig.BaseURL),
|
|
)
|
|
|
|
base64Image, _ := encodeImageToBase64(file)
|
|
|
|
var message []openai.ChatCompletionContentPartUnionParam
|
|
message = append(message,
|
|
openai.ChatCompletionContentPartUnionParam{
|
|
OfImageURL: &openai.ChatCompletionContentPartImageParam{
|
|
ImageURL: openai.ChatCompletionContentPartImageImageURLParam{
|
|
URL: base64Image,
|
|
},
|
|
},
|
|
},
|
|
openai.ChatCompletionContentPartUnionParam{
|
|
OfText: &openai.ChatCompletionContentPartTextParam{
|
|
Text: config.Conf.OpenAIConfig.Prompt,
|
|
},
|
|
},
|
|
)
|
|
chatCompletion, err := client.Chat.Completions.New(context.TODO(), openai.ChatCompletionNewParams{
|
|
Messages: []openai.ChatCompletionMessageParamUnion{
|
|
openai.UserMessage(message),
|
|
},
|
|
Model: config.Conf.OpenAIConfig.Model,
|
|
})
|
|
if err != nil {
|
|
return err, ""
|
|
}
|
|
return nil, chatCompletion.Choices[0].Message.Content
|
|
}
|