-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.go
More file actions
85 lines (76 loc) · 2.1 KB
/
main.go
File metadata and controls
85 lines (76 loc) · 2.1 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
package main
import (
"context"
"encoding/json"
"fmt"
"log"
"net/http"
"os"
"github.com/gorilla/mux"
"github.com/joho/godotenv"
gogpt "github.com/sashabaranov/go-gpt3"
"github.com/ujjwall-R/go-chat-service/mongodb"
"go.mongodb.org/mongo-driver/mongo"
)
var TOKEN string
var c *gogpt.Client
var ctx context.Context
var coll *mongo.Collection
func getReplyFromBot(prompt string) string {
req := gogpt.CompletionRequest{
Model: gogpt.GPT3TextDavinci003,
MaxTokens: 10,
Prompt: prompt,
}
resp, err := c.CreateCompletion(ctx, req)
if err != nil {
return "Sorry, Kiara is not responding! Sorry, theres problem from ours end."
}
return resp.Choices[0].Text
}
func checkRoute(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode("chat service live")
}
func chatHandler(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
var user mongodb.User
err := json.NewDecoder(r.Body).Decode(&user)
if err != nil {
fmt.Println(err)
}
existingUser, err := mongodb.SearchUser(coll, user.Userid)
if err == nil {
newPrompt := fmt.Sprintf("%s Q) %s", existingUser.Prompt, user.Prompt)
message := getReplyFromBot(newPrompt)
newPrompt = fmt.Sprintf("%s A) %s \n", newPrompt, message)
err := mongodb.UpdateUser(coll, existingUser, newPrompt)
if err != nil {
fmt.Println("Error in updation")
}
json.NewEncoder(w).Encode(message)
return
}
message := getReplyFromBot(user.Prompt)
user.Prompt = fmt.Sprintf("Q)%s, A)%s \n", user.Prompt, message)
_, err = mongodb.AddUser(coll, user)
if err != nil {
fmt.Println("Error in Adding User")
}
json.NewEncoder(w).Encode(message)
return
}
func main() {
if err := godotenv.Load(); err != nil {
log.Println("No .env file found")
}
TOKEN = os.Getenv("OPENAI_TOKEN")
c = gogpt.NewClient(TOKEN)
ctx = context.Background()
coll = mongodb.DB()
r := mux.NewRouter()
r.HandleFunc("/", checkRoute).Methods("GET")
r.HandleFunc("/", chatHandler).Methods("POST")
fmt.Printf("Starting server at PORT 5001\n")
log.Fatal(http.ListenAndServe(":5001", r))
}