Skip to content

Commit 2ad7567

Browse files
committed
perf: 优化部份判断
1 parent b3cfe7a commit 2ad7567

File tree

5 files changed

+63
-45
lines changed

5 files changed

+63
-45
lines changed

service/src/chatgpt/index.ts

Lines changed: 36 additions & 40 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ import { SocksProxyAgent } from 'socks-proxy-agent'
66
import { HttpsProxyAgent } from 'https-proxy-agent'
77
import fetch from 'node-fetch'
88
import { sendResponse } from '../utils'
9+
import { isNotEmptyString } from '../utils/is'
910
import type { ApiModel, ChatContext, ChatGPTUnofficialProxyAPIOptions, ModelConfig } from '../types'
1011

1112
const ErrorCodeMessage: Record<string, string> = {
@@ -27,42 +28,21 @@ if (!process.env.OPENAI_API_KEY && !process.env.OPENAI_ACCESS_TOKEN)
2728
throw new Error('Missing OPENAI_API_KEY or OPENAI_ACCESS_TOKEN environment variable')
2829

2930
let api: ChatGPTAPI | ChatGPTUnofficialProxyAPI
30-
function setupProxy(options) {
31-
if (process.env.SOCKS_PROXY_HOST && process.env.SOCKS_PROXY_PORT) {
32-
const agent = new SocksProxyAgent({
33-
hostname: process.env.SOCKS_PROXY_HOST,
34-
port: process.env.SOCKS_PROXY_PORT,
35-
})
36-
options.fetch = (url, options) => {
37-
return fetch(url, { agent, ...options })
38-
}
39-
}
40-
41-
const httpsProxy = process.env.HTTPS_PROXY || process.env.https_proxy || process.env.ALL_PROXY || process.env.all_proxy
42-
if (httpsProxy) {
43-
const agent = new HttpsProxyAgent(httpsProxy)
44-
options.fetch = (url, options) => {
45-
return fetch(url, { agent, ...options })
46-
}
47-
}
48-
}
4931

5032
(async () => {
5133
// More Info: https://github.com/transitive-bullshit/chatgpt-api
5234

5335
if (process.env.OPENAI_API_KEY) {
5436
const OPENAI_API_MODEL = process.env.OPENAI_API_MODEL
55-
const model = (typeof OPENAI_API_MODEL === 'string' && OPENAI_API_MODEL.length > 0)
56-
? OPENAI_API_MODEL
57-
: 'gpt-3.5-turbo'
37+
const model = isNotEmptyString(OPENAI_API_MODEL) ? OPENAI_API_MODEL : 'gpt-3.5-turbo'
5838

5939
const options: ChatGPTAPIOptions = {
6040
apiKey: process.env.OPENAI_API_KEY,
6141
completionParams: { model },
62-
debug: false,
42+
debug: true,
6343
}
6444

65-
if (process.env.OPENAI_API_BASE_URL && process.env.OPENAI_API_BASE_URL.trim().length > 0)
45+
if (isNotEmptyString(process.env.OPENAI_API_BASE_URL))
6646
options.apiBaseUrl = process.env.OPENAI_API_BASE_URL
6747

6848
setupProxy(options)
@@ -73,14 +53,14 @@ function setupProxy(options) {
7353
else {
7454
const options: ChatGPTUnofficialProxyAPIOptions = {
7555
accessToken: process.env.OPENAI_ACCESS_TOKEN,
76-
debug: false,
56+
debug: true,
7757
}
7858

79-
setupProxy(options)
80-
81-
if (process.env.API_REVERSE_PROXY)
59+
if (isNotEmptyString(process.env.API_REVERSE_PROXY))
8260
options.apiReverseProxyUrl = process.env.API_REVERSE_PROXY
8361

62+
setupProxy(options)
63+
8464
api = new ChatGPTUnofficialProxyAPI({ ...options })
8565
apiModel = 'ChatGPTUnofficialProxyAPI'
8666
}
@@ -91,9 +71,6 @@ async function chatReplyProcess(
9171
lastContext?: { conversationId?: string; parentMessageId?: string },
9272
process?: (chat: ChatMessage) => void,
9373
) {
94-
// if (!message)
95-
// return sendResponse({ type: 'Fail', message: 'Message is empty' })
96-
9774
try {
9875
let options: SendMessageOptions = { timeoutMs }
9976

@@ -123,20 +100,39 @@ async function chatReplyProcess(
123100
}
124101

125102
async function chatConfig() {
126-
const httpsProxy = process.env.HTTPS_PROXY || process.env.https_proxy || process.env.ALL_PROXY || process.env.all_proxy
103+
const reverseProxy = process.env.API_REVERSE_PROXY ?? '-'
104+
const socksProxy = (process.env.SOCKS_PROXY_HOST && process.env.SOCKS_PROXY_PORT) ? (`${process.env.SOCKS_PROXY_HOST}:${process.env.SOCKS_PROXY_PORT}`) : '-'
105+
const httpsProxy = (process.env.HTTPS_PROXY || process.env.ALL_PROXY) ?? '-'
127106

128-
return sendResponse({
107+
return sendResponse<ModelConfig>({
129108
type: 'Success',
130-
data: {
131-
apiModel,
132-
reverseProxy: process.env.API_REVERSE_PROXY,
133-
timeoutMs,
134-
socksProxy: (process.env.SOCKS_PROXY_HOST && process.env.SOCKS_PROXY_PORT) ? (`${process.env.SOCKS_PROXY_HOST}:${process.env.SOCKS_PROXY_PORT}`) : '-',
135-
httpsProxy,
136-
} as ModelConfig,
109+
data: { apiModel, reverseProxy, timeoutMs, socksProxy, httpsProxy },
137110
})
138111
}
139112

113+
function setupProxy(options: ChatGPTAPIOptions | ChatGPTUnofficialProxyAPIOptions) {
114+
if (process.env.SOCKS_PROXY_HOST && process.env.SOCKS_PROXY_PORT) {
115+
const agent = new SocksProxyAgent({
116+
hostname: process.env.SOCKS_PROXY_HOST,
117+
port: process.env.SOCKS_PROXY_PORT,
118+
})
119+
options.fetch = (url, options) => {
120+
return fetch(url, { agent, ...options })
121+
}
122+
}
123+
else {
124+
if (process.env.HTTPS_PROXY || process.env.ALL_PROXY) {
125+
const httpsProxy = process.env.HTTPS_PROXY || process.env.ALL_PROXY
126+
if (httpsProxy) {
127+
const agent = new HttpsProxyAgent(httpsProxy)
128+
options.fetch = (url, options) => {
129+
return fetch(url, { agent, ...options })
130+
}
131+
}
132+
}
133+
}
134+
}
135+
140136
export type { ChatContext, ChatMessage }
141137

142138
export { chatReplyProcess, chatConfig }

service/src/index.ts

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ import express from 'express'
22
import type { ChatContext, ChatMessage } from './chatgpt'
33
import { chatConfig, chatReplyProcess } from './chatgpt'
44
import { auth } from './middleware/auth'
5+
import { isNotEmptyString } from './utils/is'
56

67
const app = express()
78
const router = express.Router()
@@ -48,7 +49,7 @@ router.post('/config', async (req, res) => {
4849
router.post('/session', async (req, res) => {
4950
try {
5051
const AUTH_SECRET_KEY = process.env.AUTH_SECRET_KEY
51-
const hasAuth = typeof AUTH_SECRET_KEY === 'string' && AUTH_SECRET_KEY.length > 0
52+
const hasAuth = isNotEmptyString(AUTH_SECRET_KEY)
5253
res.send({ status: 'Success', message: '', data: { auth: hasAuth } })
5354
}
5455
catch (error) {

service/src/middleware/auth.ts

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,8 @@
1+
import { isNotEmptyString } from '../utils/is'
2+
13
const auth = async (req, res, next) => {
24
const AUTH_SECRET_KEY = process.env.AUTH_SECRET_KEY
3-
if (typeof AUTH_SECRET_KEY === 'string' && AUTH_SECRET_KEY.length > 0) {
5+
if (isNotEmptyString(AUTH_SECRET_KEY)) {
46
try {
57
const Authorization = req.header('Authorization')
68
if (!Authorization || Authorization.replace('Bearer ', '').trim() !== AUTH_SECRET_KEY.trim())

service/src/utils/index.ts

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,10 @@
1-
interface SendResponseOptions {
1+
interface SendResponseOptions<T = any> {
22
type: 'Success' | 'Fail'
33
message?: string
4-
data?: any
4+
data?: T
55
}
66

7-
export function sendResponse(options: SendResponseOptions) {
7+
export function sendResponse<T>(options: SendResponseOptions<T>) {
88
if (options.type === 'Success') {
99
return Promise.resolve({
1010
message: options.message ?? null,

service/src/utils/is.ts

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
export function isNumber<T extends number>(value: T | unknown): value is number {
2+
return Object.prototype.toString.call(value) === '[object Number]'
3+
}
4+
5+
export function isString<T extends string>(value: T | unknown): value is string {
6+
return Object.prototype.toString.call(value) === '[object String]'
7+
}
8+
9+
export function isNotEmptyString(value: any): boolean {
10+
return typeof value === 'string' && value.length > 0
11+
}
12+
13+
export function isBoolean<T extends boolean>(value: T | unknown): value is boolean {
14+
return Object.prototype.toString.call(value) === '[object Boolean]'
15+
}
16+
17+
export function isFunction<T extends (...args: any[]) => any | void | never>(value: T | unknown): value is T {
18+
return Object.prototype.toString.call(value) === '[object Function]'
19+
}

0 commit comments

Comments
 (0)