GPT3.5的模型接口已经出来了一段时间,之前使用Vue.js对接过该模型的接口
现在使用Golang来对接实现一下这个接口
对第三方库github.com/sashabaranov/go-openai 进行二次封装
import ( "context" "fmt" "github.com/sashabaranov/go-openai" "github.com/tidwall/gjson" "log" "strings" ) type ChatGptTool struct { Secret string Client *openai.Client } type Gpt3Dot5Message openai.ChatCompletionMessage func NewChatGptTool(secret string) *ChatGptTool { config := openai.DefaultConfig(secret) config.BaseURL = "https://openai.geekr.cool/v1" client := openai.NewClientWithConfig(config) //client := openai.NewClient(secret) return &ChatGptTool{ Secret: secret, Client: client, } } /** 调用gpt3.5接口 */ func (this *ChatGptTool) ChatGPT3Dot5Turbo(messages []Gpt3Dot5Message) (string, error) { reqMessages := make([]openai.ChatCompletionMessage, 0) for _, row := range messages { reqMessage := openai.ChatCompletionMessage{ Role: row.Role, Content: row.Content, Name: row.Name, } reqMessages = append(reqMessages, reqMessage) } resp, err := this.Client.CreateChatCompletion( context.Background(), openai.ChatCompletionRequest{ Model: openai.GPT3Dot5Turbo, Messages: reqMessages, }, ) if err != nil { log.Println("ChatGPT3Dot5Turbo error: ", err) return "", err } return resp.Choices[0].Message.Content, nil }
测试用例如下面所示
func TestChatGPT3Dot5Turbo(t *testing.T) { gpt := NewChatGptTool("你的Key") message := []Gpt3Dot5Message{ { Role: "system", Content: "你是一个精通开发的资深工程师,熟悉全栈技术,任何问题都难不倒你", }, { Role: "user", Content: "帮我使用golang开发一个在线客服系统", }, } res, err := gpt.ChatGPT3Dot5Turbo(message) log.Println(res, err) }