-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.go
More file actions
117 lines (98 loc) · 2.5 KB
/
main.go
File metadata and controls
117 lines (98 loc) · 2.5 KB
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
package main
import (
"bufio"
"bytes"
"encoding/json"
"fmt"
"io/ioutil"
"log"
"net/http"
"os"
"os/exec"
"strings"
"github.com/joho/godotenv"
)
type NLPResult struct {
Keywords []string `json:"keywords"`
}
type OpenAIRequest struct {
Model string `json:"model"`
Messages []map[string]string `json:"messages"`
}
type OpenAIResponse struct {
Choices []struct {
Message struct {
Content string `json:"content"`
} `json:"message"`
} `json:"choices"`
}
func runNLP(input string) NLPResult {
cmd := exec.Command("python3", "nlp.py", input)
var out bytes.Buffer
cmd.Stdout = &out
if err := cmd.Run(); err != nil {
log.Fatalf("Failed to run Python NLP: %v", err)
}
var result NLPResult
if err := json.Unmarshal(out.Bytes(), &result); err != nil {
log.Fatalf("Failed to parse NLP JSON: %v", err)
}
return result
}
func queryOpenAI(prompt string) string {
godotenv.Load()
apiKey := os.Getenv("OPENAI_API_KEY")
if apiKey == "" {
log.Fatal("OPENAI_API_KEY not set")
}
requestBody := OpenAIRequest{
Model: "gpt-4.1-mini",
Messages: []map[string]string{
{"role": "user", "content": prompt},
},
}
body, _ := json.Marshal(requestBody)
req, _ := http.NewRequest("POST", "https://api.openai.com/v1/chat/completions", bytes.NewBuffer(body))
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Authorization", "Bearer "+apiKey)
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
log.Fatalf("Failed to query OpenAI: %v", err)
}
defer resp.Body.Close()
data, _ := ioutil.ReadAll(resp.Body)
if resp.StatusCode != http.StatusOK {
log.Fatalf("OpenAI API returned error: %s\nResponse: %s", resp.Status, string(data))
}
var response OpenAIResponse
if err := json.Unmarshal(data, &response); err != nil {
log.Fatalf("Failed to decode response: %v\nRaw response: %s", err, string(data))
}
if len(response.Choices) == 0 {
log.Fatal("OpenAI API returned no choices in response")
}
return response.Choices[0].Message.Content
}
func main() {
reader := os.Stdin
scanner := bufio.NewScanner(reader)
fmt.Println("GoBot Enhanced! Type a message (type 'exit' to quit):")
for {
fmt.Print("You: ")
if !scanner.Scan() {
break
}
input := scanner.Text()
if strings.ToLower(strings.TrimSpace(input)) == "exit" {
fmt.Println("GoBot: Goodbye!")
break
}
// NLP Processing
nlpResult := runNLP(input)
fmt.Println("Keywords:", nlpResult.Keywords)
// GPT Query
reply := queryOpenAI(input)
fmt.Println("GoBot:", reply)
}
}