-
Notifications
You must be signed in to change notification settings - Fork 0
/
aiModel.go
93 lines (75 loc) · 2.23 KB
/
aiModel.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
package main
import (
"fmt"
"strings"
"github.com/hypermodeinc/modus/sdk/go/pkg/models"
"github.com/hypermodeinc/modus/sdk/go/pkg/models/openai"
)
func InvokeModel(modelName, instruction, prompt string) (string, error) {
var err error
var output any
if strings.Contains(modelName, "gpt") || strings.Contains(modelName, "Meta") {
output, err = invokeOpenAIModel(modelName, instruction, prompt)
} else {
output, err = invokeGeminiModel(modelName, instruction, prompt)
}
if err != nil {
return "", err
}
if result, ok := output.(string); ok {
return result, nil
}
return "", fmt.Errorf("unexpected output type")
}
func invokeOpenAIModel(modelName, instruction, prompt string) (string, error) {
model, err := models.GetModel[openai.ChatModel](modelName)
if err != nil {
return "", err
}
input, err := model.CreateInput(
openai.NewSystemMessage(instruction),
openai.NewUserMessage(prompt),
)
if err != nil {
return "", err
}
input.Temperature = 0.7
output, err := model.Invoke(input)
if err != nil {
return "", err
}
return strings.TrimSpace(output.Choices[0].Message.Content), nil
}
func invokeGeminiModel(modelName, instruction, prompt string) (string, error) {
model, err := models.GetModel[GeminiModel](modelName)
if err != nil {
return "", err
}
combinedText := instruction
if prompt != "" {
combinedText = fmt.Sprintf("%s and \n your task: %s", instruction, prompt)
}
input := &GeminiModelInput{
Contents: []struct {
Parts []struct {
Text string `json:"text"`
} `json:"parts"`
}{
{
Parts: []struct {
Text string `json:"text"`
}{
{Text: combinedText},
},
},
},
}
output, err := model.Invoke(input)
if err != nil {
return "", err
}
if len(output.Candidates) > 0 && len(output.Candidates[0].Content.Parts) > 0 {
return output.Candidates[0].Content.Parts[0].Text, nil
}
return "", fmt.Errorf("no valid text found in the response")
}