|
| 1 | +package gpt |
| 2 | + |
| 3 | +import ( |
| 4 | + "bytes" |
| 5 | + "context" |
| 6 | + "errors" |
| 7 | + "fmt" |
| 8 | + "github.com/sashabaranov/go-openai" |
| 9 | + "github.com/zcong1993/leetcode-tool/pkg/leetcode" |
| 10 | + "io" |
| 11 | + "log" |
| 12 | + "text/template" |
| 13 | +) |
| 14 | + |
| 15 | +type Openai struct { |
| 16 | + model string |
| 17 | + client *openai.Client |
| 18 | +} |
| 19 | + |
| 20 | +func NewOpenai(apiKey, model string) *Openai { |
| 21 | + client := openai.NewClient(apiKey) |
| 22 | + return &Openai{ |
| 23 | + client: client, |
| 24 | + model: model, |
| 25 | + } |
| 26 | +} |
| 27 | + |
| 28 | +func (o *Openai) Chat(content string) (string, error) { |
| 29 | + stream, err := o.client.CreateChatCompletionStream( |
| 30 | + context.Background(), |
| 31 | + openai.ChatCompletionRequest{ |
| 32 | + Model: o.model, |
| 33 | + Messages: []openai.ChatCompletionMessage{ |
| 34 | + { |
| 35 | + Role: openai.ChatMessageRoleUser, |
| 36 | + Content: content, |
| 37 | + }, |
| 38 | + }, |
| 39 | + Stream: true, |
| 40 | + }, |
| 41 | + ) |
| 42 | + |
| 43 | + if err != nil { |
| 44 | + return "", fmt.Errorf("ChatCompletion error: %v", err) |
| 45 | + } |
| 46 | + |
| 47 | + defer stream.Close() |
| 48 | + |
| 49 | + ans := "" |
| 50 | + for { |
| 51 | + response, err := stream.Recv() |
| 52 | + if errors.Is(err, io.EOF) { |
| 53 | + break |
| 54 | + } |
| 55 | + |
| 56 | + if err != nil { |
| 57 | + return "", fmt.Errorf("Stream error: %v", err) |
| 58 | + } |
| 59 | + |
| 60 | + words := response.Choices[0].Delta.Content |
| 61 | + ans += words |
| 62 | + |
| 63 | + fmt.Printf(words) |
| 64 | + } |
| 65 | + |
| 66 | + return ans, nil |
| 67 | +} |
| 68 | + |
| 69 | +func (o *Openai) Hint(lc *leetcode.Leetcode, number string) (string, error) { |
| 70 | + meta, err := lc.GetMetaByNumber(number) |
| 71 | + if err != nil { |
| 72 | + return "", err |
| 73 | + } |
| 74 | + |
| 75 | + textLang := "中文" |
| 76 | + if lc.Config.Lang == "en" { |
| 77 | + textLang = "English" |
| 78 | + } |
| 79 | + |
| 80 | + var content bytes.Buffer |
| 81 | + err = hitTpl.Execute(&content, &HintData{ |
| 82 | + Lang: lc.Config.Lang, |
| 83 | + TextLang: textLang, |
| 84 | + Problem: meta.Content, |
| 85 | + }) |
| 86 | + if err != nil { |
| 87 | + log.Fatal(err) |
| 88 | + } |
| 89 | + return o.Chat(content.String()) |
| 90 | +} |
| 91 | + |
| 92 | +type HintData struct { |
| 93 | + Lang string |
| 94 | + TextLang string |
| 95 | + Problem string |
| 96 | +} |
| 97 | + |
| 98 | +var hitTpl = template.Must(template.New("hint").Parse(hitStr)) |
| 99 | + |
| 100 | +var hitStr = ` |
| 101 | +您是一个算法专家,请基于下面的算法题目,给出该算法的思路和复杂度, 使用 {{ .TextLang }} 回答 |
| 102 | +SETP1. 给出算法的归类,如递归,栈 |
| 103 | +SETP2. 若是存在暴力解法,给出思路和复杂度 |
| 104 | +SETP3. 给出最优解法和复杂度 |
| 105 | +SETP4. 代码实现,使用 {{ .Lang }} 语言,代码带注释和测试样例。 |
| 106 | +
|
| 107 | +{{ .Problem }} |
| 108 | +` |
0 commit comments