commit cfbdfae65d5170a8a583ba2b5db2d79ead2a6819 Author: Kare-Udon Date: Sat Mar 4 23:50:11 2023 +0800 Updatex diff --git a/README.md b/README.md new file mode 100644 index 0000000..d106a41 --- /dev/null +++ b/README.md @@ -0,0 +1,7 @@ +# ChatGPT Web Backend API with Golang + +## Run + +```bash +OPEN_AI_KEY=sk-xxxxxxx go run main.go +``` \ No newline at end of file diff --git a/go.mod b/go.mod new file mode 100644 index 0000000..7e96f1d --- /dev/null +++ b/go.mod @@ -0,0 +1,34 @@ +module test + +go 1.19 + +require ( + github.com/gin-gonic/gin v1.9.0 + github.com/sashabaranov/go-openai v1.4.1 +) + +require ( + github.com/bytedance/sonic v1.8.0 // indirect + github.com/chenzhuoyu/base64x v0.0.0-20221115062448-fe3a3abad311 // indirect + github.com/gin-contrib/sse v0.1.0 // indirect + github.com/go-playground/locales v0.14.1 // indirect + github.com/go-playground/universal-translator v0.18.1 // indirect + github.com/go-playground/validator/v10 v10.11.2 // indirect + github.com/goccy/go-json v0.10.0 // indirect + github.com/json-iterator/go v1.1.12 // indirect + github.com/klauspost/cpuid/v2 v2.0.9 // indirect + github.com/leodido/go-urn v1.2.1 // indirect + github.com/mattn/go-isatty v0.0.17 // indirect + github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421 // indirect + github.com/modern-go/reflect2 v1.0.2 // indirect + github.com/pelletier/go-toml/v2 v2.0.6 // indirect + github.com/twitchyliquid64/golang-asm v0.15.1 // indirect + github.com/ugorji/go/codec v1.2.9 // indirect + golang.org/x/arch v0.0.0-20210923205945-b76863e36670 // indirect + golang.org/x/crypto v0.5.0 // indirect + golang.org/x/net v0.7.0 // indirect + golang.org/x/sys v0.5.0 // indirect + golang.org/x/text v0.7.0 // indirect + google.golang.org/protobuf v1.28.1 // indirect + gopkg.in/yaml.v3 v3.0.1 // indirect +) diff --git a/main.go b/main.go new file mode 100644 index 0000000..cb984b4 --- /dev/null +++ b/main.go @@ -0,0 +1,46 @@ +package main + +import ( + "context" + "github.com/gin-gonic/gin" + "github.com/sashabaranov/go-openai" + "os" +) + +func main() { + // get token + token := os.Getenv("OPEN_AI_KEY") + r := gin.Default() + // /getAns?msg=foobar + r.GET("/getAns", func(c *gin.Context) { + msg := c.Query("msg") + ans := GetChatGPTAns(token, msg) + c.JSON(200, gin.H{ + "answer": ans, + }) + }) + err := r.Run() + if err != nil { + return + } +} + +func GetChatGPTAns(token string, msg string) string { + c := openai.NewClient(token) + resp, err := c.CreateChatCompletion( + context.Background(), + openai.ChatCompletionRequest{ + Model: openai.GPT3Dot5Turbo, + Messages: []openai.ChatCompletionMessage{ + { + Role: openai.ChatMessageRoleUser, + Content: msg, + }, + }, + }, + ) + if err != nil { + return "" + } + return resp.Choices[0].Message.Content +}