|
| 1 | +package chatgpt |
| 2 | + |
| 3 | +import ( |
| 4 | + "encoding/json" |
| 5 | + "errors" |
| 6 | + "github.com/PuerkitoBio/goquery" |
| 7 | + "github.com/go-resty/resty/v2" |
| 8 | + if_expression "github.com/golang-infrastructure/go-if-expression" |
| 9 | + "github.com/golang-infrastructure/go-pointer" |
| 10 | + "github.com/google/uuid" |
| 11 | + "strings" |
| 12 | +) |
| 13 | + |
| 14 | +// ------------------------------------------------- 请求相关 ------------------------------------------------------------ |
| 15 | + |
| 16 | +type Request struct { |
| 17 | + Action string `json:"action"` |
| 18 | + Messages []RequestMessage `json:"messages"` |
| 19 | + ConversationID *string `json:"conversation_id"` |
| 20 | + ParentMessageID *string `json:"parent_message_id"` |
| 21 | + Model string `json:"model"` |
| 22 | +} |
| 23 | + |
| 24 | +type RequestMessage struct { |
| 25 | + ID string `json:"id"` |
| 26 | + Role string `json:"role"` |
| 27 | + Content RequestContent `json:"content"` |
| 28 | +} |
| 29 | + |
| 30 | +type RequestContent struct { |
| 31 | + ContentType string `json:"content_type"` |
| 32 | + Parts []string `json:"parts"` |
| 33 | +} |
| 34 | + |
| 35 | +func NewRequest(question, conversationID, parentMessageID string) *Request { |
| 36 | + return &Request{ |
| 37 | + Action: "next", |
| 38 | + ConversationID: pointer.ToPointerOrNil(conversationID), |
| 39 | + Messages: []RequestMessage{ |
| 40 | + { |
| 41 | + ID: uuid.New().String(), |
| 42 | + Role: "user", |
| 43 | + Content: RequestContent{ |
| 44 | + ContentType: "text", |
| 45 | + Parts: []string{question}, |
| 46 | + }, |
| 47 | + }, |
| 48 | + }, |
| 49 | + ParentMessageID: pointer.ToPointerOrNil(parentMessageID), |
| 50 | + Model: "text-davinci-002-render", |
| 51 | + } |
| 52 | +} |
| 53 | + |
| 54 | +// ------------------------------------------------- 响应相关 ------------------------------------------------------------ |
| 55 | + |
| 56 | +type Response struct { |
| 57 | + Message ResponseMessage `json:"message"` |
| 58 | + ConversationID string `json:"conversation_id"` |
| 59 | + Error any `json:"error"` |
| 60 | +} |
| 61 | + |
| 62 | +type ResponseMessage struct { |
| 63 | + ID string `json:"id"` |
| 64 | + Role string `json:"role"` |
| 65 | + User any `json:"user"` |
| 66 | + CreateTime any `json:"create_time"` |
| 67 | + UpdateTime any `json:"update_time"` |
| 68 | + Content ResponseContent `json:"content"` |
| 69 | + EndTurn any `json:"end_turn"` |
| 70 | + Weight float64 `json:"weight"` |
| 71 | + Metadata ResponseMetadata `json:"metadata"` |
| 72 | + Recipient string `json:"recipient"` |
| 73 | +} |
| 74 | + |
| 75 | +type ResponseContent struct { |
| 76 | + ContentType string `json:"content_type"` |
| 77 | + Parts []string `json:"parts"` |
| 78 | +} |
| 79 | + |
| 80 | +type ResponseMetadata struct { |
| 81 | +} |
| 82 | + |
| 83 | +// ------------------------------------------------- -------------------------------------------------------------------- |
| 84 | + |
| 85 | +const ConversationAPIURL = "https://chat.openai.com/backend-api/conversation" |
| 86 | + |
| 87 | +type ChatGPT struct { |
| 88 | + jwt string |
| 89 | + authorization string |
| 90 | + |
| 91 | + userAgent string |
| 92 | + |
| 93 | + conversationID string |
| 94 | + parentMessageID string |
| 95 | +} |
| 96 | + |
| 97 | +func NewChat(jwt string) *ChatGPT { |
| 98 | + return &ChatGPT{ |
| 99 | + jwt: jwt, |
| 100 | + authorization: "Bearer " + jwt, |
| 101 | + userAgent: "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/105.0.0.0 Safari/537.36", |
| 102 | + } |
| 103 | +} |
| 104 | + |
| 105 | +func (x *ChatGPT) Talk(question string) (*Response, error) { |
| 106 | + conversationID := if_expression.Return(x.conversationID != "", x.conversationID, "") |
| 107 | + parentMessageID := if_expression.Return(x.parentMessageID != "", x.parentMessageID, uuid.New().String()) |
| 108 | + response, err := x.sendConversationMessage(question, conversationID, parentMessageID) |
| 109 | + if err != nil { |
| 110 | + return nil, err |
| 111 | + } |
| 112 | + x.conversationID = response.ConversationID |
| 113 | + x.parentMessageID = response.Message.ID |
| 114 | + return response, nil |
| 115 | +} |
| 116 | + |
| 117 | +func (x *ChatGPT) sendConversationMessage(question, conversationID, parentMessageID string) (*Response, error) { |
| 118 | + request := NewRequest(question, conversationID, parentMessageID) |
| 119 | + requestBytes, err := json.Marshal(request) |
| 120 | + if err != nil { |
| 121 | + return nil, err |
| 122 | + } |
| 123 | + response, err := resty. |
| 124 | + New(). |
| 125 | + R(). |
| 126 | + SetHeader("User-Agent", x.userAgent). |
| 127 | + SetHeader("Authorization", x.authorization). |
| 128 | + SetHeader("Content-Type", "application/json"). |
| 129 | + SetBody(string(requestBytes)). |
| 130 | + Post(ConversationAPIURL) |
| 131 | + if err != nil { |
| 132 | + return nil, err |
| 133 | + } |
| 134 | + responseString := response.String() |
| 135 | + arr := strings.Split(responseString, "\n\n") |
| 136 | + index := len(arr) - 3 |
| 137 | + if index >= len(arr) || index < 1 { |
| 138 | + return nil, x.buildErrMessage(responseString) |
| 139 | + } |
| 140 | + arr = strings.Split(arr[index], "data: ") |
| 141 | + if len(arr) < 2 { |
| 142 | + return nil, x.buildErrMessage(responseString) |
| 143 | + } |
| 144 | + chatResponse := &Response{} |
| 145 | + if err = json.Unmarshal([]byte(arr[1]), chatResponse); err != nil { |
| 146 | + return nil, err |
| 147 | + } |
| 148 | + return chatResponse, nil |
| 149 | +} |
| 150 | + |
| 151 | +// 在调用失败的时候尝试返回更友好的信息 |
| 152 | +func (x *ChatGPT) buildErrMessage(responseString string) error { |
| 153 | + errContent := x.tryExtractErrorMessage(responseString) |
| 154 | + if errContent != "" { |
| 155 | + return errors.New(errContent) |
| 156 | + } else { |
| 157 | + return errors.New(responseString) |
| 158 | + } |
| 159 | +} |
| 160 | + |
| 161 | +// 尝试从响应中抽取出错误信息 |
| 162 | +func (x *ChatGPT) tryExtractErrorMessage(responseString string) string { |
| 163 | + doc, err := goquery.NewDocumentFromReader(strings.NewReader(responseString)) |
| 164 | + if err != nil { |
| 165 | + return "" |
| 166 | + } |
| 167 | + return doc.Find("#content").Text() |
| 168 | +} |
| 169 | + |
| 170 | +func (x *ChatGPT) GetConversationID() string { |
| 171 | + return x.conversationID |
| 172 | +} |
| 173 | + |
| 174 | +func (x *ChatGPT) SetConversationID(conversationID string) { |
| 175 | + x.conversationID = conversationID |
| 176 | +} |
| 177 | + |
| 178 | +func (x *ChatGPT) GetParentMessageID() string { |
| 179 | + return x.parentMessageID |
| 180 | +} |
| 181 | + |
| 182 | +func (x *ChatGPT) SetParentMessageID(parentMessageID string) { |
| 183 | + x.parentMessageID = parentMessageID |
| 184 | +} |
| 185 | + |
| 186 | +func (x *ChatGPT) GetUserAgent() string { |
| 187 | + return x.userAgent |
| 188 | +} |
| 189 | + |
| 190 | +func (x *ChatGPT) SetUserAgent(userAgent string) { |
| 191 | + x.userAgent = userAgent |
| 192 | +} |
| 193 | + |
| 194 | +func (x *ChatGPT) SetJWT(jwt string) { |
| 195 | + x.jwt = jwt |
| 196 | + x.authorization = "Bearer " + jwt |
| 197 | +} |
0 commit comments