// 如果有.env文件, 则导入库 go get -u github.com/joho/godotenv
godotenv.Load()apiKey:=os.Getenv("GPT_API_KEY")baseUrl:=os.Getenv("GPT_BASE_URL")model:=os.Getenv("GPT_MODEL")
varhistory[]gpt3.ChatCompletionRequestMessage=[]gpt3.ChatCompletionRequestMessage{{Role:"system",Content:"你是 Kimi,由 Moonshot AI 提供的人工智能助手,你更擅长中文和英文的对话。你会为用户提供安全,有帮助,准确的回答。同时,你会拒绝一切涉及恐怖主义,种族歧视,黄色暴力等问题的回答。Moonshot AI 为专有名词,不可翻译成其他语言。",},}
history=append(history,gpt3.ChatCompletionRequestMessage{Role:"user",// Content: "How much water should I drink per day?",
Content:"我每天喝多少水合适?",Name:"Me",})
packagemainimport("bufio""context""fmt""log""os""strings""github.com/PullRequestInc/go-gpt3""github.com/joho/godotenv")varhistory[]gpt3.ChatCompletionRequestMessage=[]gpt3.ChatCompletionRequestMessage{{Role:"system",Content:"你是 Kimi,由 Moonshot AI 提供的人工智能助手,你更擅长中文和英文的对话。你会为用户提供安全,有帮助,准确的回答。同时,你会拒绝一切涉及恐怖主义,种族歧视,黄色暴力等问题的回答。Moonshot AI 为专有名词,不可翻译成其他语言。",},}var(apiKey,baseUrl,modelstring)funcmain(){// load the GPT key from file
godotenv.Load()apiKey=os.Getenv("GPT_API_KEY")baseUrl=os.Getenv("GPT_BASE_URL")model=os.Getenv("GPT_MODEL")ifapiKey==""{log.Fatal("Missing GPT_API_KEY.")}ifmodel==""{log.Fatal("Missing GPT_MODEL.")}// instantiate a gpt3.CompletionRequest using github.com/PullRequestInc/go-gpt3
client:=gpt3.NewClient(apiKey,gpt3.WithBaseURL(baseUrl))// create a Context for the execution of requests.
ctx:=context.Background()// send the prompt questions and receive the repsonse via client.
for{reader:=bufio.NewReader(os.Stdin)fmt.Print("\n> ")line,err:=reader.ReadString('\n')iferr!=nil{log.Fatal("err: reader.ReadString: ",err.Error())}complete(ctx,client,line)}}funccomplete(ctxcontext.Context,clientgpt3.Client,questionstring){// send a stream request and receive a stream response via client
streamRequest:=makeQuestion(question)fmt.Print("assistant: \n ")varresultstrings.Buildererr:=client.ChatCompletionStream(ctx,streamRequest,func(ccsr*gpt3.ChatCompletionStreamResponse)error{for_,c:=rangeccsr.Choices[0].Delta.Content{fmt.Print(string(c))}//fmt.Print(ccsr.Choices[0].Delta.Content)
result.WriteString(ccsr.Choices[0].Delta.Content)returnnil})iferr!=nil{log.Fatal("err: client.ChatCompletionStream: ",err.Error())}history=append(history,gpt3.ChatCompletionRequestMessage{Role:"assistant",Content:result.String(),})}funcmakeQuestion(questionstring)gpt3.ChatCompletionRequest{// 加入历史对话
history=append(history,gpt3.ChatCompletionRequestMessage{Role:"user",// Content: "How much water should I drink per day?",
Content:question,Name:"Me",})returngpt3.ChatCompletionRequest{Model:model,Messages:history,Stream:true,}}