Skip to content

Commit

Permalink
chore: extract proxy setup code into reusable function (#583)
Browse files Browse the repository at this point in the history
  • Loading branch information
kirklin authored Mar 17, 2023
1 parent 0b9aa05 commit 7b4cc44
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 @@ -27,6 +27,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 @@ -46,23 +65,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 @@ -73,23 +76,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 7b4cc44

Please sign in to comment.