forked from gofireflyio/aiac
-
Notifications
You must be signed in to change notification settings - Fork 0
/
completion.go
64 lines (55 loc) · 1.36 KB
/
completion.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
package libaiac
import (
"context"
"fmt"
"strings"
)
type completionResponse struct {
Choices []struct {
Text string `json:"text"`
Index int64 `json:"index"`
FinishReason string `json:"finish_reason"`
} `json:"choices"`
Usage struct {
TotalTokens int64 `json:"total_tokens"`
} `json:"usage"`
}
// Complete sends a request to OpenAI's Completions API using the provided model
// and prompt, and returns the response
func (client *Client) Complete(
ctx context.Context,
model Model,
prompt string,
) (res Response, err error) {
var answer completionResponse
err = client.NewRequest("POST", "/completions").
JSONBody(map[string]interface{}{
"model": model.Name,
"prompt": prompt,
"max_tokens": model.MaxTokens - len(prompt),
"temperature": 0.2,
}).
Into(&answer).
RunContext(ctx)
if err != nil {
return res, fmt.Errorf("failed sending prompt: %w", err)
}
if len(answer.Choices) == 0 {
return res, ErrNoResults
}
if answer.Choices[0].FinishReason != "stop" {
return res, fmt.Errorf(
"%w: %s",
ErrResultTruncated,
answer.Choices[0].FinishReason,
)
}
res.FullOutput = strings.TrimSpace(answer.Choices[0].Text)
res.APIKeyUsed = client.apiKey
res.TokensUsed = answer.Usage.TotalTokens
var ok bool
if res.Code, ok = ExtractCode(res.FullOutput); !ok {
res.Code = res.FullOutput
}
return res, nil
}