Skip to content

Commit

Permalink
chore: extract proxy setup code into reusable function (Chanzhaoyu#583)
Browse files Browse the repository at this point in the history
  • Loading branch information
kirklin authored and jingChen55 committed Mar 27, 2023
1 parent 97ff045 commit 4447a3d
Showing 1 changed file with 21 additions and 34 deletions.
55 changes: 21 additions & 34 deletions service/src/chatgpt/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,25 @@ if (!process.env.OPENAI_API_KEY && !process.env.OPENAI_ACCESS_TOKEN)
throw new Error('Missing OPENAI_API_KEY or OPENAI_ACCESS_TOKEN environment variable')

let api: ChatGPTAPI | ChatGPTUnofficialProxyAPI
function setupProxy(options) {
if (process.env.SOCKS_PROXY_HOST && process.env.SOCKS_PROXY_PORT) {
const agent = new SocksProxyAgent({
hostname: process.env.SOCKS_PROXY_HOST,
port: process.env.SOCKS_PROXY_PORT,
})
options.fetch = (url, options) => {
return fetch(url, { agent, ...options })
}
}

const httpsProxy = process.env.HTTPS_PROXY || process.env.https_proxy || process.env.ALL_PROXY || process.env.all_proxy
if (httpsProxy) {
const agent = new HttpsProxyAgent(httpsProxy)
options.fetch = (url, options) => {
return fetch(url, { agent, ...options })
}
}
}

(async () => {
// More Info: https://github.com/transitive-bullshit/chatgpt-api
Expand All @@ -45,23 +64,7 @@ let api: ChatGPTAPI | ChatGPTUnofficialProxyAPI
if (process.env.OPENAI_API_BASE_URL && process.env.OPENAI_API_BASE_URL.trim().length > 0)
options.apiBaseUrl = process.env.OPENAI_API_BASE_URL

if (process.env.SOCKS_PROXY_HOST && process.env.SOCKS_PROXY_PORT) {
const agent = new SocksProxyAgent({
hostname: process.env.SOCKS_PROXY_HOST,
port: process.env.SOCKS_PROXY_PORT,
})
options.fetch = (url, options) => {
return fetch(url, { agent, ...options })
}
}

const httpsProxy = process.env.HTTPS_PROXY || process.env.https_proxy || process.env.ALL_PROXY || process.env.all_proxy
if (httpsProxy) {
const agent = new HttpsProxyAgent(httpsProxy)
options.fetch = (url, options) => {
return fetch(url, { agent, ...options })
}
}
setupProxy(options)

api = new ChatGPTAPI({ ...options })
apiModel = 'ChatGPTAPI'
Expand All @@ -72,23 +75,7 @@ let api: ChatGPTAPI | ChatGPTUnofficialProxyAPI
debug: false,
}

if (process.env.SOCKS_PROXY_HOST && process.env.SOCKS_PROXY_PORT) {
const agent = new SocksProxyAgent({
hostname: process.env.SOCKS_PROXY_HOST,
port: process.env.SOCKS_PROXY_PORT,
})
options.fetch = (url, options) => {
return fetch(url, { agent, ...options })
}
}

const httpsProxy = process.env.HTTPS_PROXY || process.env.https_proxy || process.env.ALL_PROXY || process.env.all_proxy
if (httpsProxy) {
const agent = new HttpsProxyAgent(httpsProxy)
options.fetch = (url, options) => {
return fetch(url, { agent, ...options })
}
}
setupProxy(options)

if (process.env.API_REVERSE_PROXY)
options.apiReverseProxyUrl = process.env.API_REVERSE_PROXY
Expand Down

0 comments on commit 4447a3d

Please sign in to comment.