-
Notifications
You must be signed in to change notification settings - Fork 7
/
model.go
110 lines (90 loc) · 2.64 KB
/
model.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
// Package model provides functionalities for working with Large Language Models (LLMs).
package model
import (
"context"
"github.com/hupe1980/golc/callback"
"github.com/hupe1980/golc/schema"
)
type Options struct {
Stop []string
Callbacks []schema.Callback
ParentRunID string
Functions []schema.FunctionDefinition
}
func GeneratePrompt(ctx context.Context, model schema.Model, promptValue schema.PromptValue, optFns ...func(o *Options)) (*schema.ModelResult, error) {
if llm, ok := model.(schema.LLM); ok {
return LLMGenerate(ctx, llm, promptValue.String(), optFns...)
}
if cm, ok := model.(schema.ChatModel); ok {
return ChatModelGenerate(ctx, cm, promptValue.Messages(), optFns...)
}
// TODO
panic("invalid model type")
}
func LLMGenerate(ctx context.Context, model schema.LLM, prompt string, optFns ...func(o *Options)) (*schema.ModelResult, error) {
opts := Options{}
for _, fn := range optFns {
fn(&opts)
}
cm := callback.NewManager(opts.Callbacks, model.Callbacks(), model.Verbose(), func(mo *callback.ManagerOptions) {
if opts.ParentRunID != "" {
mo.ParentRunID = opts.ParentRunID
}
})
rm, err := cm.OnLLMStart(ctx, &schema.LLMStartManagerInput{
LLMType: model.Type(),
Prompt: prompt,
InvocationParams: model.InvocationParams(),
})
if err != nil {
return nil, err
}
result, err := model.Generate(ctx, prompt, func(o *schema.GenerateOptions) {
o.CallbackManger = rm
o.Stop = opts.Stop
})
if err != nil {
if cbErr := rm.OnModelError(ctx, &schema.ModelErrorManagerInput{
Error: err,
}); cbErr != nil {
return nil, cbErr
}
return nil, err
}
if err := rm.OnModelEnd(ctx, &schema.ModelEndManagerInput{
Result: result,
}); err != nil {
return nil, err
}
return result, nil
}
func ChatModelGenerate(ctx context.Context, model schema.ChatModel, messages schema.ChatMessages, optFns ...func(o *Options)) (*schema.ModelResult, error) {
opts := Options{}
for _, fn := range optFns {
fn(&opts)
}
cm := callback.NewManager(opts.Callbacks, model.Callbacks(), model.Verbose(), func(mo *callback.ManagerOptions) {
if opts.ParentRunID != "" {
mo.ParentRunID = opts.ParentRunID
}
})
rm, err := cm.OnChatModelStart(ctx, &schema.ChatModelStartManagerInput{
ChatModelType: model.Type(),
Messages: messages,
InvocationParams: model.InvocationParams(),
})
if err != nil {
return nil, err
}
res, err := model.Generate(ctx, messages, func(o *schema.GenerateOptions) {
o.CallbackManger = rm
o.Stop = opts.Stop
o.Functions = opts.Functions
})
if err != nil {
return nil, err
}
return &schema.ModelResult{
Generations: res.Generations,
}, nil
}