-
Notifications
You must be signed in to change notification settings - Fork 464
/
Copy pathindex.ts
276 lines (236 loc) · 9.28 KB
/
index.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
import * as dotenv from 'dotenv'
import 'isomorphic-fetch'
import type { ChatGPTAPIOptions, ChatMessage, SendMessageOptions } from 'chatgpt'
import { ChatGPTAPI, ChatGPTUnofficialProxyAPI } from 'chatgpt'
import { SocksProxyAgent } from 'socks-proxy-agent'
import httpsProxyAgent from 'https-proxy-agent'
import fetch from 'node-fetch'
import type { AuditConfig } from 'src/storage/model'
import type { TextAuditService } from '../utils/textAudit'
import { textAuditServices } from '../utils/textAudit'
import { getCacheConfig, getOriginConfig } from '../storage/config'
import { sendResponse } from '../utils'
import { isNotEmptyString } from '../utils/is'
import type { ApiModel, ChatContext, ChatGPTUnofficialProxyAPIOptions, ModelConfig } from '../types'
import type { RequestOptions } from './types'
const { HttpsProxyAgent } = httpsProxyAgent
dotenv.config()
const ErrorCodeMessage: Record<string, string> = {
401: '[OpenAI] 提供错误的API密钥 | Incorrect API key provided',
403: '[OpenAI] 服务器拒绝访问,请稍后再试 | Server refused to access, please try again later',
502: '[OpenAI] 错误的网关 | Bad Gateway',
503: '[OpenAI] 服务器繁忙,请稍后再试 | Server is busy, please try again later',
504: '[OpenAI] 网关超时 | Gateway Time-out',
500: '[OpenAI] 服务器繁忙,请稍后再试 | Internal Server Error',
}
let apiModel: ApiModel
let api: ChatGPTAPI | ChatGPTUnofficialProxyAPI
let auditService: TextAuditService
export async function initApi() {
// More Info: https://github.com/transitive-bullshit/chatgpt-api
const config = await getCacheConfig()
if (!config.apiKey && !config.accessToken)
throw new Error('Missing OPENAI_API_KEY or OPENAI_ACCESS_TOKEN environment variable')
if (isNotEmptyString(config.apiKey)) {
const OPENAI_API_BASE_URL = config.apiBaseUrl
const OPENAI_API_MODEL = config.apiModel
const model = isNotEmptyString(OPENAI_API_MODEL) ? OPENAI_API_MODEL : 'gpt-3.5-turbo'
const options: ChatGPTAPIOptions = {
apiKey: config.apiKey,
completionParams: { model },
debug: !config.apiDisableDebug,
}
// increase max token limit if use gpt-4
if (model.toLowerCase().includes('gpt-4')) {
// if use 32k model
if (model.toLowerCase().includes('32k')) {
options.maxModelTokens = 32768
options.maxResponseTokens = 8192
}
else {
options.maxModelTokens = 8192
options.maxResponseTokens = 2048
}
}
if (isNotEmptyString(OPENAI_API_BASE_URL))
options.apiBaseUrl = `${OPENAI_API_BASE_URL}/v1`
await setupProxy(options)
api = new ChatGPTAPI({ ...options })
apiModel = 'ChatGPTAPI'
}
else {
const model = isNotEmptyString(config.apiModel) ? config.apiModel : 'gpt-3.5-turbo'
const options: ChatGPTUnofficialProxyAPIOptions = {
accessToken: config.accessToken,
apiReverseProxyUrl: isNotEmptyString(config.reverseProxy) ? config.reverseProxy : 'https://bypass.churchless.tech/api/conversation',
model,
debug: !config.apiDisableDebug,
}
await setupProxy(options)
api = new ChatGPTUnofficialProxyAPI({ ...options })
apiModel = 'ChatGPTUnofficialProxyAPI'
}
}
async function chatReplyProcess(options: RequestOptions) {
const config = await getCacheConfig()
const model = isNotEmptyString(config.apiModel) ? config.apiModel : 'gpt-3.5-turbo'
const { message, lastContext, process, systemMessage, temperature, top_p } = options
try {
const timeoutMs = (await getCacheConfig()).timeoutMs
let options: SendMessageOptions = { timeoutMs }
if (apiModel === 'ChatGPTAPI') {
if (isNotEmptyString(systemMessage))
options.systemMessage = systemMessage
options.completionParams = { model, temperature, top_p }
}
if (lastContext != null) {
if (apiModel === 'ChatGPTAPI')
options.parentMessageId = lastContext.parentMessageId
else
options = { ...lastContext }
}
const response = await api.sendMessage(message, {
...options,
onProgress: (partialResponse) => {
process?.(partialResponse)
},
})
return sendResponse({ type: 'Success', data: response })
}
catch (error: any) {
const code = error.statusCode
global.console.log(error)
if (Reflect.has(ErrorCodeMessage, code))
return sendResponse({ type: 'Fail', message: ErrorCodeMessage[code] })
return sendResponse({ type: 'Fail', message: error.message ?? 'Please check the back-end console' })
}
}
export function initAuditService(audit: AuditConfig) {
if (!audit || !audit.options || !audit.options.apiKey || !audit.options.apiSecret)
return
const Service = textAuditServices[audit.provider]
auditService = new Service(audit.options)
}
async function containsSensitiveWords(audit: AuditConfig, text: string): Promise<boolean> {
if (audit.customizeEnabled && isNotEmptyString(audit.sensitiveWords)) {
const textLower = text.toLowerCase()
const notSafe = audit.sensitiveWords.split('\n').filter(d => textLower.includes(d.trim().toLowerCase())).length > 0
if (notSafe)
return true
}
if (audit.enabled) {
if (!auditService)
initAuditService(audit)
return await auditService.containsSensitiveWords(text)
}
return false
}
let cachedBanlance: number | undefined
let cacheExpiration = 0
async function fetchBalance() {
const now = new Date().getTime()
if (cachedBanlance && cacheExpiration > now)
return Promise.resolve(cachedBanlance.toFixed(3))
// 计算起始日期和结束日期
const [startDate, endDate] = formatDate()
const config = await getCacheConfig()
const OPENAI_API_KEY = config.apiKey
const OPENAI_API_BASE_URL = config.apiBaseUrl
if (!isNotEmptyString(OPENAI_API_KEY))
return Promise.resolve('-')
const API_BASE_URL = isNotEmptyString(OPENAI_API_BASE_URL)
? OPENAI_API_BASE_URL
: 'https://api.openai.com'
// 查是否订阅
const urlSubscription = `${API_BASE_URL}/v1/dashboard/billing/subscription`
// 查普通账单
// const urlBalance = `${API_BASE_URL}/dashboard/billing/credit_grants`
// 查使用量
const urlUsage = `${API_BASE_URL}/v1/dashboard/billing/usage?start_date=${startDate}&end_date=${endDate}`
const headers = {
'Authorization': `Bearer ${OPENAI_API_KEY}`,
'Content-Type': 'application/json',
}
let socksAgent
let httpsAgent
if (isNotEmptyString(config.socksProxy)) {
socksAgent = new SocksProxyAgent({
hostname: config.socksProxy.split(':')[0],
port: parseInt(config.socksProxy.split(':')[1]),
userId: isNotEmptyString(config.socksAuth) ? config.socksAuth.split(':')[0] : undefined,
password: isNotEmptyString(config.socksAuth) ? config.socksAuth.split(':')[1] : undefined,
})
}
else if (isNotEmptyString(config.httpsProxy)) {
httpsAgent = new HttpsProxyAgent(config.httpsProxy)
}
try {
// 获取API限额
let response = await fetch(urlSubscription, { agent: socksAgent === undefined ? httpsAgent : socksAgent, headers })
if (!response.ok) {
console.error('您的账户已被封禁,请登录OpenAI进行查看。')
return
}
const subscriptionData = await response.json()
const totalAmount = subscriptionData.hard_limit_usd
// 获取已使用量
response = await fetch(urlUsage, { agent: socksAgent === undefined ? httpsAgent : socksAgent, headers })
const usageData = await response.json()
const totalUsage = usageData.total_usage / 100
// 计算剩余额度
cachedBanlance = totalAmount - totalUsage
cacheExpiration = now + 60 * 60 * 1000
return Promise.resolve(cachedBanlance.toFixed(3))
}
catch (error) {
global.console.error(error)
return Promise.resolve('-')
}
}
function formatDate() {
const today = new Date();
const year = today.getFullYear();
const month = today.getMonth() + 1;
const formattedFirstDay = `${year}-${month.toString().padStart(2, '0')}-01`;
const formattedToday = `${year}-${month.toString().padStart(2, '0')}-${today.getDate().toString().padStart(2, '0')}`;
return [formattedFirstDay, formattedToday];
}
async function chatConfig() {
const config = await getOriginConfig() as ModelConfig
config.balance = await fetchBalance()
return sendResponse<ModelConfig>({
type: 'Success',
data: config,
})
}
async function setupProxy(options: ChatGPTAPIOptions | ChatGPTUnofficialProxyAPIOptions) {
const config = await getCacheConfig()
if (isNotEmptyString(config.socksProxy)) {
const agent = new SocksProxyAgent({
hostname: config.socksProxy.split(':')[0],
port: parseInt(config.socksProxy.split(':')[1]),
userId: isNotEmptyString(config.socksAuth) ? config.socksAuth.split(':')[0] : undefined,
password: isNotEmptyString(config.socksAuth) ? config.socksAuth.split(':')[1] : undefined,
})
options.fetch = (url, options) => {
return fetch(url, { agent, ...options })
}
}
else {
if (isNotEmptyString(config.httpsProxy)) {
const httpsProxy = config.httpsProxy
if (httpsProxy) {
const agent = new HttpsProxyAgent(httpsProxy)
options.fetch = (url, options) => {
return fetch(url, { agent, ...options })
}
}
}
}
}
function currentModel(): ApiModel {
return apiModel
}
initApi()
export type { ChatContext, ChatMessage }
export { chatReplyProcess, chatConfig, currentModel, containsSensitiveWords }