Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fetch failed (OpenAI API banned in certain countries like China) #419

Closed
TyCoding opened this issue Mar 2, 2023 · 52 comments
Closed

fetch failed (OpenAI API banned in certain countries like China) #419

TyCoding opened this issue Mar 2, 2023 · 52 comments

Comments

@TyCoding
Copy link

TyCoding commented Mar 2, 2023

Describe the feature

api request error

fetch failed

@ws02589111
Copy link

same error and use http api directly is worked

@iAqu
Copy link

iAqu commented Mar 2, 2023

same error

@iSonce
Copy link

iSonce commented Mar 2, 2023

same error, error message: "fetch failed"

@Kylin93CN
Copy link

maybe need use http proxy , i think...

@Charhua
Copy link

Charhua commented Mar 2, 2023

same error

@transitive-bullshit
Copy link
Owner

Can you please provide more details on the error you're seeing, including some code snippets for how you're using this package?

This error could mean almost anything, and I won't be able to help without more info.

@ws02589111
Copy link

Can you please provide more details on the error you're seeing, including some code snippets for how you're using this package?

This error could mean almost anything, and I won't be able to help without more info.

{"err":"TypeError: fetch failed\n at Object.fetch (node:internal/deps/undici/undici:11118:11)\n at (/app/node_modules/chatgpt/build/index.js:262:25)"}

@gefeiyanga
Copy link

Can you please provide more details on the error you're seeing, including some code snippets for how you're using this package?
This error could mean almost anything, and I won't be able to help without more info.

{"err":"TypeError: fetch failed\n at Object.fetch (node:internal/deps/undici/undici:11118:11)\n at (/app/node_modules/chatgpt/build/index.js:262:25)"}
好像是中国地区ip被ban了,大家报错的都是在国内吗?

@transitive-bullshit
Copy link
Owner

Can you paste the full JS/TS code that you're using to call ChatGPTAPI?

Also, which Node.js version are you using?

@Charhua
Copy link

Charhua commented Mar 2, 2023

您能否提供有关您看到的错误的更多详细信息,包括您如何使用此软件包的一些代码片段?此错误可能意味着几乎任何事情,如果没有更多信息,我将无法提供帮助。

{“err”:“TypeError: fetch failed\n at Object.fetch (node:internal/deps/undici/undici:11118:11)\n at (/app/node_modules/chatgpt/build/index.js:262:25)”} 好像是中国地区ip被ban了,大家报错的都是在国内吗?

yes

@ws02589111
Copy link

Can you please provide more details on the error you're seeing, including some code snippets for how you're using this package?
This error could mean almost anything, and I won't be able to help without more info.

{"err":"TypeError: fetch failed\n at Object.fetch (node:internal/deps/undici/undici:11118:11)\n at (/app/node_modules/chatgpt/build/index.js:262:25)"}
好像是中国地区ip被ban了,大家报错的都是在国内吗?

Sorry,maybe this is really true

@ZoeLeee
Copy link

ZoeLeee commented Mar 2, 2023

same error

TypeError: fetch failed
    at Object.fetch (node:internal/deps/undici/undici:11118:11)
    at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
    at async file:///home/lizhou/projects/chatgpt/node_modules/chatgpt/build/index.js:265:25 {
  cause: ConnectTimeoutError: Connect Timeout Error
      at onConnectTimeout (node:internal/deps/undici/undici:6625:28)
      at node:internal/deps/undici/undici:6583:50
      at Immediate._onImmediate (node:internal/deps/undici/undici:6614:13)
      at process.processImmediate (node:internal/timers:471:21) {
    code: 'UND_ERR_CONNECT_TIMEOUT'
  }
}

@transitive-bullshit
Copy link
Owner

Yes, I believe that IP addresses in China are banned from calling the OpenAI API.

If you have this problem, you have a few workarounds:

  1. Use a proxy and pass a custom fetch to the ChatGPTAPI constructor which uses you proxy. Note: you'll still need a valid OpenAI API key from their website.
  2. Using a VPN might solve your problem, depending on how aggressive the firewall is.
  3. Use ChatGPTUnofficialProxyAPI instead of ChatGPTAPI, which may not have the same IP bans.

@Kylin93CN
Copy link

axios has the "proxy" function, but chatGPTAPI use the 'origin fetch' TAT

@iSonce
Copy link

iSonce commented Mar 2, 2023

Yes, I believe that IP addresses in China are banned from calling the OpenAI API.

If you have this problem, you have a few workarounds:

  1. Use a proxy and pass a custom fetch to the ChatGPTAPI constructor which uses you proxy. Note: you'll still need a valid OpenAI API key from their website.
  2. Using a VPN might solve your problem, depending on how aggressive the firewall is.
  3. Use ChatGPTUnofficialProxyAPI instead of ChatGPTAPI, which may not have the same IP bans.

Thanks for your help!

@Charhua
Copy link

Charhua commented Mar 2, 2023

Yes, I believe that IP addresses in China are banned from calling the OpenAI API.

If you have this problem, you have a few workarounds:

  1. Use a proxy and pass a custom to the constructor which uses you proxy. Note: you'll still need a valid OpenAI API key from their website.fetch``ChatGPTAPI
  2. Using a VPN might solve your problem, depending on how aggressive the firewall is.
  3. Use instead of , which may not have the same IP bans.ChatGPTUnofficialProxyAPI``ChatGPTAPI

Thanks

@transitive-bullshit transitive-bullshit changed the title fetch failed fetch failed (OpenAI API banned in certain countries like China) Mar 2, 2023
@huluohu
Copy link

huluohu commented Mar 2, 2023

Can you add a proxy option in ChatGPTAPI, please?

@ws02589111
Copy link

ws02589111 commented Mar 2, 2023

Can you add a proxy option in ChatGPTAPI, please?

This code can help you

npm install https-proxy-agent node-fetch
const api = new ChatGPTAPI({
  fetch: (url, options = {}) => {
        const defaultOptions = {
            agent: require('https-proxy-agent')('http://your-proxy-address:port')
        };

        const mergedOptions = {
            ...defaultOptions,
            ...options
        };

        return require('node-fetch').default(url, mergedOptions);
    }
})

@huluohu
Copy link

huluohu commented Mar 2, 2023

Can you add a proxy option in ChatGPTAPI, please?

This code can help you

npm install https-proxy-agent node-fetch
const api = new ChatGPTAPI({
  fetch: (url, options = {}) => {
        const defaultOptions = {
            agent: require('https-proxy-agent')('http://your-proxy-address:port')
        };

        const mergedOptions = {
            ...defaultOptions,
            ...options
        };

        return require('node-fetch').default(url, mergedOptions);
    }
})

ok, i'm try ,Thank you!

@Get-wy
Copy link

Get-wy commented Mar 3, 2023

同样的错误

TypeError: fetch failed
    at Object.fetch (node:internal/deps/undici/undici:11118:11)
    at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
    at async file:///home/lizhou/projects/chatgpt/node_modules/chatgpt/build/index.js:265:25 {
  cause: ConnectTimeoutError: Connect Timeout Error
      at onConnectTimeout (node:internal/deps/undici/undici:6625:28)
      at node:internal/deps/undici/undici:6583:50
      at Immediate._onImmediate (node:internal/deps/undici/undici:6614:13)
      at process.processImmediate (node:internal/timers:471:21) {
    code: 'UND_ERR_CONNECT_TIMEOUT'
  }
}

Yes, I encountered the same mistake. My project has been put into operation in production

@Get-wy
Copy link

Get-wy commented Mar 3, 2023

Yes, I believe that IP addresses in China are banned from calling the OpenAI API.

If you have this problem, you have a few workarounds:

  1. Use a proxy and pass a custom fetch to the ChatGPTAPI constructor which uses you proxy. Note: you'll still need a valid OpenAI API key from their website.
  2. Using a VPN might solve your problem, depending on how aggressive the firewall is.
  3. Use ChatGPTUnofficialProxyAPI instead of ChatGPTAPI, which may not have the same IP bans.

Using ChatGPTUnofficialProxyAPI also can not in China

@gefeiyanga
Copy link

image
image

I can get result by using curl, but also fetch failed.

@mamahui
Copy link

mamahui commented Mar 3, 2023

ok, i tried, but i'm fialed;

this is my code please help me check this code thanks;

const api = new ChatGPTAPI({
apiKey,
fetch: (url, options = {}) => {
const defaultOptions = {
agent: require('https-proxy-agent')('http://127.0.0.1:8899')
};

const mergedOptions = {
  ...defaultOptions,
  ...options
};

return require('node-fetch').default(url, mergedOptions);

}
});

@mamahui
Copy link

mamahui commented Mar 3, 2023

sorry to ask ; but i really want to know how to get the 'http://your-proxy-address:port' thanks

@brooklynb7
Copy link

brooklynb7 commented Mar 3, 2023

This works for me.
Thanks all guys!

import { ChatGPTAPI } from "chatgpt";
import proxy from "https-proxy-agent";
import nodeFetch from "node-fetch";

async function example() {
  const api = new ChatGPTAPI({
    apiKey: process.env.OPENAI_API_KEY || "",
    fetch: (url, options = {}) => {
      const defaultOptions = {
        agent: proxy("http://proxy"),
      };

      const mergedOptions = {
        ...defaultOptions,
        ...options,
      };

      return nodeFetch(url, mergedOptions);
    },
  });

  const res = await api.sendMessage("Hello World!");
  console.log(res.text);
}

@mamahui
Copy link

mamahui commented Mar 3, 2023

" http://proxy" this address get from where thanks

@gefeiyanga
Copy link

" http://proxy" this address get from where thanks

Such as http://127.0.0.1:1234
It is your Proxy address.

@gefeiyanga
Copy link

But I got 'Error: OpenAI error 503' sometimes.

@transitive-bullshit
Copy link
Owner

If you're looking for a proxy, check out https://www.webshare.io

@xmenbe
Copy link

xmenbe commented Mar 4, 2023

There is no reliable mainland agent recommended

@cuicui-V5
Copy link

This works for me. Thanks all guys!

import { ChatGPTAPI } from "chatgpt";
import proxy from "https-proxy-agent";
import nodeFetch from "node-fetch";

async function example() {
  const api = new ChatGPTAPI({
    apiKey: process.env.OPENAI_API_KEY || "",
    fetch: (url, options = {}) => {
      const defaultOptions = {
        agent: proxy("http://proxy"),
      };

      const mergedOptions = {
        ...defaultOptions,
        ...options,
      };

      return nodeFetch(url, mergedOptions);
    },
  });

  const res = await api.sendMessage("Hello World!");
  console.log(res.text);
}

sad , It's not work for me , fxxk gfw

FetchError: request to https://api.openai.com/v1/chat/completions failed, reason: Client network socket disconnected before secure TLS connection was established

@Song-Mao
Copy link

Song-Mao commented Mar 5, 2023

但我有时会收到“错误:OpenAI 错误 503”。

同样的错误,直接使用http api是可行的

I also encountered the same problem when I started the local service using node. Starting the global proxy can be called normally in the browser, but starting the local service using node will time out. Have you solved it?

@cuicui-V5
Copy link

not yet .
Maybe we need a transparent proxy, consider a software router.

@ws02589111
Copy link

This works for me. Thanks all guys!

import { ChatGPTAPI } from "chatgpt";
import proxy from "https-proxy-agent";
import nodeFetch from "node-fetch";

async function example() {
  const api = new ChatGPTAPI({
    apiKey: process.env.OPENAI_API_KEY || "",
    fetch: (url, options = {}) => {
      const defaultOptions = {
        agent: proxy("http://proxy"),
      };

      const mergedOptions = {
        ...defaultOptions,
        ...options,
      };

      return nodeFetch(url, mergedOptions);
    },
  });

  const res = await api.sendMessage("Hello World!");
  console.log(res.text);
}

sad , It's not work for me , fxxk gfw

FetchError: request to https://api.openai.com/v1/chat/completions failed, reason: Client network socket disconnected before secure TLS connection was established

I had the same issue when I tested, it's because of my proxy is socks5 and http type in different env.
So, you can try socks-proxy-agent instead of https-proxy-agent

@Unfantasy
Copy link

same error

TypeError: fetch failed
    at Object.fetch (node:internal/deps/undici/undici:11118:11)
    at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
    at async file:///home/lizhou/projects/chatgpt/node_modules/chatgpt/build/index.js:265:25 {
  cause: ConnectTimeoutError: Connect Timeout Error
      at onConnectTimeout (node:internal/deps/undici/undici:6625:28)
      at node:internal/deps/undici/undici:6583:50
      at Immediate._onImmediate (node:internal/deps/undici/undici:6614:13)
      at process.processImmediate (node:internal/timers:471:21) {
    code: 'UND_ERR_CONNECT_TIMEOUT'
  }
}

I got the same error, have you resolve it?

@chengfengfengwang
Copy link

chengfengfengwang commented Mar 6, 2023

How to add a proxy when directly running at the CLI, like "npx chatgpt 'your prompt here'"?

I have add proxy "export https_proxy=http://127.0.0.1:7890 http_proxy=http://127.0.0.1:7890 all_proxy=socks5://127.0.0.1:7890" but it still not work.

@luuziiyoo
Copy link

luuziiyoo commented Mar 6, 2023

> 直接在 CLI 上运行时如何添加代理,例如“npx chatgpt '您的提示'”?

我添加了代理“export https_proxy= http://127.0.0.1:7890 http_proxy= http://127.0.0.1:7890 all_proxy=socks5://127.0.0.1:7890”,但它仍然不起作用。
我的路由器已经翻过去了,电脑访问api没问题,同样的网络下还是不行也是那个错误,再电脑上弄一个代理服务器从这个电脑再回到路由器再出去才行

@cuicui-V5
Copy link

same error

TypeError: fetch failed
    at Object.fetch (node:internal/deps/undici/undici:11118:11)
    at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
    at async file:///home/lizhou/projects/chatgpt/node_modules/chatgpt/build/index.js:265:25 {
  cause: ConnectTimeoutError: Connect Timeout Error
      at onConnectTimeout (node:internal/deps/undici/undici:6625:28)
      at node:internal/deps/undici/undici:6583:50
      at Immediate._onImmediate (node:internal/deps/undici/undici:6614:13)
      at process.processImmediate (node:internal/timers:471:21) {
    code: 'UND_ERR_CONNECT_TIMEOUT'
  }
}

I got the same error, have you resolve it?

I solved this problem by nginx reverse proxy, you need a server outside the GFW

  • nginx config file

server {
	listen 443 ssl;
	server_name api.example.com;
	ssl_certificate /etc/nginx/ssl/cert.pem;
	ssl_certificate_key /etc/nginx/ssl/cert.key;
        ssl_protocols TLSv1.2 TLSv1.3;
	location / {
		proxy_pass https://api.openai.com/;
		proxy_set_header Host api.openai.com;
		proxy_set_header X-Real-IP $remote_addr;
	}
}
 
  • add the URL to the .env file
OPENAI_API_KEY=sk-xxxxxxxxxxxxxxxxxxxxx
OPENAI_BASE_URL=api.example.com/
  • config the api
export const api = new ChatGPTAPI({
    apiKey: process.env.OPENAI_API_KEY,
    apiBaseUrl: process.env.OPENAI_BASE_URL,
});

@ozbillwang
Copy link

ozbillwang commented Mar 11, 2023

got the error, but I tested from oversea (australia)

# I can confirm the api key is valid, because i used it in vs-code currently
$ export OPENAI_API_KEY="sk-TODOxxxx" 

$ npm install chatgpt

$ npx chatgpt "hello world"
file:///xxx/node_modules/chatgpt/build/index.js:144
      throw new Error("Invalid environment; fetch is not defined");
            ^
Error: Invalid environment; fetch is not defined
    at new ChatGPTAPI (file:///xxx/node_modules/chatgpt/build/index.js:144:13)
    at CAC.<anonymous> (file:///xxx/node_modules/chatgpt/bin/cli.js:65:19)
    at CAC.runMatchedCommand (file:///xxx/node_modules/cac/dist/index.mjs:610:34)
    at CAC.parse (file:///xxxnode_modules/cac/dist/index.mjs:537:12)
    at main (file:///xxx/node_modules/chatgpt/bin/cli.js:116:9)
    
$ npx chatgpt -k "sk-TODOxxxx" "hello world"
# got same error

# integrate with code to import the package, I got same error

@cuicui-V5
Copy link

got the error, but I tested from oversea (australia)

# I can confirm the api key is valid, because i used it in vs-code currently
$ export OPENAI_API_KEY="sk-TODOxxxx" 

$ npm install chatgpt

$ npx chatgpt "hello world"
file:///xxx/node_modules/chatgpt/build/index.js:144
      throw new Error("Invalid environment; fetch is not defined");
            ^
Error: Invalid environment; fetch is not defined
    at new ChatGPTAPI (file:///xxx/node_modules/chatgpt/build/index.js:144:13)
    at CAC.<anonymous> (file:///xxx/node_modules/chatgpt/bin/cli.js:65:19)
    at CAC.runMatchedCommand (file:///xxx/node_modules/cac/dist/index.mjs:610:34)
    at CAC.parse (file:///xxxnode_modules/cac/dist/index.mjs:537:12)
    at main (file:///xxx/node_modules/chatgpt/bin/cli.js:116:9)
    
$ npx chatgpt -k "sk-TODOxxxx" "hello world"
# got same error

# integrate with code to import the package, I got same error

Looks like this is unrelated to the API key. It seems that you don't have node-fetch installed or haven't configured it correctly

@ozbillwang
Copy link

Looks like this is unrelated to the API key. It seems that you don't have node-fetch installed or haven't configured it correctly

I have installed node-fetch, got same issue.

There should be no configure, except the environment variable OPENAI_API_KEY required.

I tested in an empty folder.

$ mkdir test
$ cd test

# I can confirm the api key is valid, because i used it in vs-code currently
$ export OPENAI_API_KEY="sk-TODOxxxx" 

$ npm install chatgpt
$ npm install node-fetch

$ npx chatgpt "hello world"
file:///xxx/node_modules/chatgpt/build/index.js:144
      throw new Error("Invalid environment; fetch is not defined");
            ^
Error: Invalid environment; fetch is not defined
    at new ChatGPTAPI (file:///xxx/node_modules/chatgpt/build/index.js:144:13)
    at CAC.<anonymous> (file:///xxx/node_modules/chatgpt/bin/cli.js:65:19)
    at CAC.runMatchedCommand (file:///xxx/node_modules/cac/dist/index.mjs:610:34)
    at CAC.parse (file:///xxxnode_modules/cac/dist/index.mjs:537:12)
    at main (file:///xxx/node_modules/chatgpt/bin/cli.js:116:9)
    
$ npx chatgpt -k "sk-TODOxxxx" "hello world"
# got same error

# integrate with code to import the package, I got same error

let me know what I missed.

@ozbillwang
Copy link

ozbillwang commented Mar 11, 2023

Know the reason now.

The package doesn't work with node:16, but works in docker image node:latest (that's node:19)

bill in /tmp/test  > docker run -ti --rm node:latest bash
Digest: sha256:83841d113e09345a28b146e431f15b062341c5449218e501ba45ef8f9cff6049
Status: Downloaded newer image for node:latest
root@aa43287f2285:/# mkdir test
root@aa43287f2285:/# cd test
root@aa43287f2285:/test# npm install chatgpt

added 64 packages in 15s

18 packages are looking for funding
  run `npm fund` for details
npm notice
npm notice New minor version of npm available! 9.5.0 -> 9.6.1
npm notice Changelog: https://github.com/npm/cli/releases/tag/v9.6.1
npm notice Run npm install -g [email protected] to update!
npm notice
root@aa43287f2285:/test# export OPENAI_API_KEY="sk-TODO"
root@aa43287f2285:/test# npm install node-fetch

added 6 packages, and audited 71 packages in 3s

21 packages are looking for funding
  run `npm fund` for details

found 0 vulnerabilities
root@aa43287f2285:/test# node -v
v19.7.0
root@aa43287f2285:/test# npx chatgpt "hello world"
Hello!
root@aa43287f2285:/test#

if I test the same commands, with docker image node:16, I saw the issue

Error: Invalid environment; fetch is not defined

Please confirm.

updates

work fine in docker image node:18 as well, and no need install node-fetch

@youngle316
Copy link
Contributor

It works for me

import { ChatGPTAPI } from "chatgpt";
import { HttpsProxyAgent } from "https-proxy-agent";
import nodeFetch from "node-fetch";

const api = new ChatGPTAPI({
	apiKey: (process.env.NEXT_PUBLIC_OPENAI_API_KEY as string) || "",
	fetch: (url, options = {}) => {
		const defaultOptions = {
			agent: new HttpsProxyAgent("http://127.0.0.1:7890"),
		};

		const mergedOptions = {
			...defaultOptions,
			...options,
		};

		return nodeFetch(url, mergedOptions);
	},
});

export { api };

@qyssss
Copy link

qyssss commented Mar 5, 2024

It works for me too

import { ChatGPTAPI } from "chatgpt";
import { HttpsProxyAgent } from "https-proxy-agent";
import nodeFetch from "node-fetch";

const api = new ChatGPTAPI({
	apiKey: (process.env.NEXT_PUBLIC_OPENAI_API_KEY as string) || "",
	fetch: (url, options = {}) => {
		const defaultOptions = {
			agent: new HttpsProxyAgent("http://127.0.0.1:7890"),
		};

		const mergedOptions = {
			...defaultOptions,
			...options,
		};

		return nodeFetch(url, mergedOptions);
	},
});

export { api };

@transitive-bullshit
Copy link
Owner

This project is undergoing a major revamp; closing out old issues as part of the prep process.

The chatgpt package is pretty outdated at this point. I recommend that you use the openai package or the openai-fetch package instead.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests