64 lines
1.7 KiB
Go
64 lines
1.7 KiB
Go
package ai
|
|
|
|
import (
|
|
"context"
|
|
|
|
openai "github.com/sashabaranov/go-openai"
|
|
)
|
|
|
|
type openAIProvider struct {
|
|
client *openai.Client
|
|
model string
|
|
}
|
|
|
|
func newOpenAI(apiKey, model string) *openAIProvider {
|
|
if model == "" {
|
|
model = openai.GPT4oMini
|
|
}
|
|
return &openAIProvider{
|
|
client: openai.NewClient(apiKey),
|
|
model: model,
|
|
}
|
|
}
|
|
|
|
func (p *openAIProvider) Name() string { return "openai" }
|
|
|
|
func (p *openAIProvider) Summarize(ctx context.Context, prompt string, opts GenOptions) (string, error) {
|
|
request := openai.ChatCompletionRequest{
|
|
Model: p.model,
|
|
MaxCompletionTokens: opts.MaxOutputTokens,
|
|
Messages: []openai.ChatCompletionMessage{
|
|
{Role: openai.ChatMessageRoleUser, Content: prompt},
|
|
},
|
|
}
|
|
if opts.JSONMode {
|
|
request.ResponseFormat = &openai.ChatCompletionResponseFormat{Type: openai.ChatCompletionResponseFormatTypeJSONObject}
|
|
}
|
|
if len(opts.JSONSchema) > 0 {
|
|
request.ResponseFormat = &openai.ChatCompletionResponseFormat{Type: openai.ChatCompletionResponseFormatTypeJSONSchema, JSONSchema: &openai.ChatCompletionResponseFormatJSONSchema{Name: "title_relevance", Strict: true, Schema: opts.JSONSchema}}
|
|
}
|
|
resp, err := p.client.CreateChatCompletion(ctx, request)
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
if len(resp.Choices) == 0 {
|
|
return "", nil
|
|
}
|
|
if opts.RequireComplete && resp.Choices[0].FinishReason != openai.FinishReasonStop {
|
|
return "", errGenerationIncomplete
|
|
}
|
|
return resp.Choices[0].Message.Content, nil
|
|
}
|
|
|
|
func (p *openAIProvider) ListModels(ctx context.Context) ([]string, error) {
|
|
resp, err := p.client.ListModels(ctx)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
var models []string
|
|
for _, m := range resp.Models {
|
|
models = append(models, m.ID)
|
|
}
|
|
return models, nil
|
|
}
|