-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
176 lines (146 loc) · 3.62 KB
/
main.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
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
package main
import (
"context"
"encoding/json"
"fmt"
"github.com/Azure/azure-sdk-for-go/sdk/azcore"
"os"
"os/exec"
"runtime"
"strings"
"github.com/Azure/azure-sdk-for-go/sdk/ai/azopenai"
"github.com/Azure/azure-sdk-for-go/sdk/azcore/to"
"github.com/erikgeiser/promptkit/confirmation"
"github.com/mattn/go-shellwords"
"github.com/urfave/cli/v2"
)
// Fill in your Azure credentials.
const baseUrl = "https://EXAMPLE.openai.azure.com"
const model = "gpt-4o"
const apiKey = "AZURE_API_KEY"
func main() {
keyCredential := azcore.NewKeyCredential(apiKey)
client, err := azopenai.NewClientWithKeyCredential(baseUrl, keyCredential, nil)
if err != nil {
fmt.Println(err)
return
}
ctx := context.Background()
app := &cli.App{
Name: "how",
Description: "Copilot for your terminal",
Usage: "how <question>",
Version: "1.0.5",
Action: func(c *cli.Context) error {
q := strings.Join(c.Args().Slice(), " ")
return getAnswer(client, &ctx, q)
},
}
if err := app.Run(os.Args); err != nil {
fmt.Printf("Error: %s\n", err)
}
}
func getAnswer(client *azopenai.Client, ctx *context.Context, query string) error {
if query == "" {
return fmt.Errorf("no question provided")
}
req := azopenai.ChatCompletionsOptions{
DeploymentName: to.Ptr(model),
MaxTokens: to.Ptr(int32(400)),
Messages: startConversation(query),
Temperature: to.Ptr(float32(0)),
}
resp, err := client.GetChatCompletions(*ctx, req, nil)
if err != nil {
return err
}
ans := *resp.Choices[0].Message.Content
var answer Answer
if err := json.Unmarshal([]byte(ans), &answer); err != nil {
newErr := fmt.Errorf("%s\nRaw Output:\n%s", err, ans)
return newErr
}
outputAnswer(answer)
return nil
}
func startConversation(query string) []azopenai.ChatRequestMessageClassification {
var systemPrompt string
if runtime.GOOS == "windows" {
systemPrompt = "You are a proficient PowerShell user."
} else {
systemPrompt = "You are a proficient terminal user."
}
return []azopenai.ChatRequestMessageClassification{
&azopenai.ChatRequestSystemMessage{
Content: to.Ptr(systemPrompt),
},
&azopenai.ChatRequestUserMessage{
Content: azopenai.NewChatRequestUserMessageContent(makePrompt(query)),
},
}
}
func makePrompt(query string) string {
prompt := `
Use terminal command to complete the task delimited by triple quotes.
Provide answer in JSON format. "command" key contains the command to run.
"explanation" key contains the explanation of the command.
Do not add any markdown annotations.
If no such command exists, provide an empty string for "command" key.
"""
%s
"""
`
p := fmt.Sprintf(prompt, query)
return p
}
func outputAnswer(answer Answer) {
if answer.Command == "" {
fmt.Println("No such command exists.")
return
}
output := `
Command:
%s
Explanation:
%s
`
fmt.Printf(output, answer.Command, answer.Explanation)
sp := confirmation.New("Execute the command?", confirmation.Undecided)
ready, err := sp.RunPrompt()
if err != nil {
fmt.Println(err)
return
}
if ready {
fmt.Println("")
if err := executeCommand(answer.Command); err != nil {
fmt.Println(err)
return
}
} else {
fmt.Println("OK!")
}
}
func executeCommand(command string) error {
args, err := shellwords.Parse(command)
if err != nil {
return err
}
var cmd *exec.Cmd
if len(args) > 1 {
cmd = exec.Command(args[0], args[1:]...)
} else {
cmd = exec.Command(args[0])
}
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
err = cmd.Run()
if err != nil {
return err
}
return nil
}
type Answer struct {
Command string `json:"command"`
Explanation string `json:"explanation"`
}