下面是一个使用 golang 实现 chatgpt openai 接口代理的简单案例:
package main
import (
"bytes"
"encoding/json"
"io/ioutil"
"log"
"net/http"
)
const (
openAIEndpoint = "https://api.openai.com/v1/engines/davinci-codex/completions"
apiKey = "YOUR_API_KEY"
)
type OpenAIRequest struct {
Prompt string `json:"prompt"`
MaxTokens int `json:"max_tokens"`
Temperature float32 `json:"temperature"`
}
type OpenAIResponse struct {
Choices []struct {
Text string `json:"text"`
} `json:"choices"`
}
func main() {
http.HandleFunc("/chatgpt", handleChatGPT)
log.Fatal(http.ListenAndServe(":8080", nil))
}
func handleChatGPT(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
w.WriteHeader(http.StatusMethodNotAllowed)
return
}
var req OpenAIRequest
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
w.WriteHeader(http.StatusBadRequest)
return
}
defer r.Body.Close()
reqJSON, err := json.Marshal(req)
if err != nil {
log.Printf("Error marshalling request: %v", err)
w.WriteHeader(http.StatusInternalServerError)
return
}
client := &http.Client{}
openAIReq, err := http.NewRequest(http.MethodPost, openAIEndpoint, bytes.NewReader(reqJSON))
if err != nil {
log.Printf("Error creating OpenAI request: %v", err)
w.WriteHeader(http.StatusInternalServerError)
return
}
openAIReq.Header.Set("Authorization", "Bearer "+apiKey)
openAIReq.Header.Set("Content-Type", "application/json")
resp, err := client.Do(openAIReq)
if err != nil {
log.Printf("Error sending request to OpenAI: %v", err)
w.WriteHeader(http.StatusInternalServerError)
return
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
log.Printf("Error reading response from OpenAI: %v", err)
w.WriteHeader(http.StatusInternalServerError)
return
}
var openAIResp OpenAIResponse
if err := json.Unmarshal(body, &openAIResp); err != nil {
log.Printf("Error unmarshalling response from OpenAI: %v", err)
w.WriteHeader(http.StatusInternalServerError)
return
}
if len(openAIResp.Choices) == 0 {
log.Println("No response from OpenAI")
w.WriteHeader(http.StatusInternalServerError)
return
}
response := struct {
Message string `json:"message"`
}{
Message: openAIResp.Choices[0].Text,
}
respJSON, err := json.Marshal(response)
if err != nil {
log.Printf("Error marshalling response: %v", err)
w.WriteHeader(http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/json")
w.Write(respJSON)
}
在上面的代码中,我们定义了一个 handleChatGPT 的回调函数来处理 chatgpt 请求。当接收到请求时,我们首先检查请求方法是否为 POST,如果不是,则返回 Method Not Allowed。
然后,我们将请求体解析为一个 OpenAIRequest 对象,并将其转换为 JSON 格式。然后,我们使用 http 包创建一个新的 POST 请求,并添加必要的头部信息。
接下来,我们向 OpenAI 发送请求,并读取其响应。我们将响应反序列化为 OpenAIResponse 对象,并从中提取出生成的文本。最后,我们将响应对象转换为 JSON 格式并返回给客户端。
请注意,在这个示例中,我们假设 chatgpt 请求是通过 POST 请求发送的,并且请求体中包含一个 prompt 字段和一些其他参数。你需要根据自己的需求对代码进行修改来支持不同的请求格式。同时,你需要将 apiKey 替换为你在 OpenAI 上创建的 API 密钥。




