Shortcut to my personal portfolio site.
npx transitive-bullshit
- transitivebullsh.it - Source for the portfolio site itself.
MIT © Travis Fischer
Support my OSS work by following me on twitter
AI agent stdlib that works with any LLM and TypeScript AI SDK.
License: MIT License
Shortcut to my personal portfolio site.
npx transitive-bullshit
MIT © Travis Fischer
Support my OSS work by following me on twitter
Currently the ChatGPTAPI
constructor allows you to set the apiBaseURL
and the backendAPIBaseURL
however the auth url used for authentication in the refreshAccessTokens
function is hardcoded to https://chat.openai.com/api/auth/session. To avoid issues with CORS I would like to be able to modify the auth url so it would go through a koa proxy.
Alternatively this could be resolved by implementing a proxy configuration as described by #47
Forgive the noob question, but can I run this in browser js? I tried putting it into a static webpage, but I got some errors. Now I think I'm realizing this is only intended to run in node.js.
file:///code/node_modules/chatgpt/src/fetch-sse.ts:13
throw new Error(`ChatGPTAPI error ${res.status || res.statusText}`)
^
Error: ChatGPTAPI error 503
at fetchSSE (file:///code/node_modules/chatgpt/src/fetch-sse.ts:13:11)
at processTicksAndRejections (node:internal/process/task_queues:96:5)
env version: node: 16.18.0
Sometimes the request will freeze and never finish, might be useful to have a timeout in ms attribute.
When trying to log in with Google I get...
This browser or app may not be secure.
Try using a different browser. If you’re already using a supported browser, you can try again to sign in.
I'm getting this error when authenticating, but I did verify I have the undici library installed. I'm on windows... maybe doing something dumb?
(node:11744) UnhandledPromiseRejectionWarning: Error: ChatGPT failed to refresh auth token. TypeError: _undici.fetch is not a function
Headless Chrome seems a bit overkill for a Node.js API wrapper, and may not work on all machines (see line 36 in chatgpt-api.ts). The ChatGPT API allows direct requests given a CSRF token (which doesn't seem to change in my testing) and a session token, which can be obtained through the /api/auth/session
endpoint.
Appreciate your effort getting things to work after Dec 11 changes 🙏
I built a simple node app that can take a prompt and print the response on terminal window.
In my case it seems to always open a new Chrome window/instance (thus prompting a new captcha) each time I enter a new prompt. I haven't used puppeteer before but looks like it's opening a new window each time, but there might be a way to reuse an already open window? 🤔 Please ignore if it already does that.
Some digging led me to links below:
https://medium.com/@jaredpotter1/connecting-puppeteer-to-existing-chrome-window-8a10828149e0
Error: Failed to launch the browser process! spawn /Applications/Google Chrome.app/Contents/MacOS/Google Chrome ENOENT
TROUBLESHOOTING: https://github.com/puppeteer/puppeteer/blob/main/docs/troubleshooting.md
at onClose (C:\Users\User\Desktop\New folder\node_modules\puppeteer-core\lib\cjs\puppeteer\node\BrowserRunner.js:299:20)
at ChildProcess.<anonymous> (C:\Users\User\Desktop\New folder\node_modules\puppeteer-core\lib\cjs\puppeteer\node\BrowserRunner.js:293:24)
at ChildProcess.emit (node:events:513:28)
at ChildProcess._handle.onexit (node:internal/child_process:289:12)
at onErrorNT (node:internal/child_process:476:16)
at process.processTicksAndRejections (node:internal/process/task_queues:82:21)
Error: Failed to launch the browser process! spawn /Applications/Google Chrome.app/Contents/MacOS/Google Chrome ENOENT
TROUBLESHOOTING: https://github.com/puppeteer/puppeteer/blob/main/docs/troubleshooting.md
at onClose (C:\Users\User\Desktop\New folder\node_modules\puppeteer-core\lib\cjs\puppeteer\node\BrowserRunner.js:299:20)
at ChildProcess.<anonymous> (C:\Users\User\Desktop\New folder\node_modules\puppeteer-core\lib\cjs\puppeteer\node\BrowserRunner.js:293:24)
at ChildProcess.emit (node:events:513:28)
at ChildProcess._handle.onexit (node:internal/child_process:289:12)
at onErrorNT (node:internal/child_process:476:16)
at process.processTicksAndRejections (node:internal/process/task_queues:82:21)
Already installed chatgpt, but getting Module not found: Error: Can't resolve 'chatgpt'
Can you add commonjs support? The workaround of dynamic import does not work for me.
node-fetch
v3 can't use require(), can downgrade to v2.6.7
My error is in the chatgpt package, it says that it needs a main module but it is not finding any. I am trying to use this package with react native.
The error:
Error: While trying to resolve module chatgpt
from file D:\Acadamics and Work\Work\Software Projects\ChatgptAssistant\frontend\src\screens\Home\Home.tsx
, the package D:\Acadamics and Work\Work\Software Projects\ChatgptAssistant\frontend\node_modules\chatgpt\package.json
was successfully found. However, this package itself specifies a main
module field that could not be resolved (D:\Acadamics and Work\Work\Software Projects\ChatgptAssistant\frontend\node_modules\chatgpt\index
. Indeed, none of these files exist:
Hi! Very excited to use this lib, looks very polished for the amount of time that has passed since chatGPT was launched! I am trying to initialise a client, but keep getting an ChatGPT failed to refresh auth token. Error: Unauthorized
error. I copy the value for the __Secure-next-auth.session-token
cookie. Have tried the other ones as well, but they don't work either.
When I look at the requests being sent, I can see that the session request returns a 304, and the body is empty. I assume that that is not what is supposed to happen, as the same request on the openAI website does not return an empty body. Any ideas why this could be happening?
Hello,
Was able to install and use it for simple requests, but when it takes a bit to formulate a response I get the error
[ERROR] Error: ChatGPTAPI error 429
use nestjs
const chatgpt_1 = require("chatgpt");
^
Error [ERR_REQUIRE_ESM]: require() of ES Module
/app/qqbot/service/bin/node_modules/undici/lib/fetch/index.js:1921
fetchParams.controller.controller.error(new TypeError('terminated', {
^
TypeError: terminated
at Fetch.onAborted (/app/qqbot/service/bin/node_modules/undici/lib/fetch/index.js:1921:49)
at Fetch.emit (node:events:390:28)
at Fetch.emit (node:domain:475:12)
at Fetch.terminate (/app/qqbot/service/bin/node_modules/undici/lib/fetch/index.js:93:10)
at Object.onError (/app/qqbot/service/bin/node_modules/undici/lib/fetch/index.js:2062:34)
at Request.onError (/app/qqbot/service/bin/node_modules/undici/lib/core/request.js:265:27)
at null.errorRequest (/app/qqbot/service/bin/node_modules/undici/lib/client.js:1739:13)
at TLSSocket.onSocketClose (/app/qqbot/service/bin/node_modules/undici/lib/client.js:998:5)
at TLSSocket.emit (node:events:402:35)
at TLSSocket.emit (node:domain:475:12)
how can i do for that?
here is error:
AggregateError:
Error: ChatGPT failed to refresh auth token. TypeError [ERR_INVALID_CHAR]: Invalid character in header content ["cookie"]
at w.refreshAccessToken (/var/task/dist/index-6d56a3b6.js:21385:2251)
at async w.sendMessage (/var/task/dist/index-6d56a3b6.js:21385:1039)
at async search (/var/task/dist/index-6d56a3b6.js:21400:10)
at async /var/task/dist/index-6d56a3b6.js:21483:24
at async Promise.all (index 1)
at async middleware (/var/task/node_modules/.pnpm/@[email protected]/node_modules/@octokit/webhooks/dist-node/index.js:355:5)
at async Server.<anonymous> (/var/task/___vc/__helpers.js:813:13)
Because my network environment is not that good, I need a proxy option to use the chatgpt
It seems that if I don't close a conversion, the speed will become slower and slower.
Is there a way to close a conversation?
I used your library in nextjs project/src/pages/api and deployed it to vercel, the environment is Node.js 16, and it reported an error 'res.body.getReader is not a function'.
hi ,I'm use react.js build,but show a CORS error :
Access to fetch at 'https://chat.openai.com/api/auth/session' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
This is currently the biggest hindrance with this package (and any other approach which uses the unofficial REST API).
At some point, session tokens expire. This is currently recognized and handled by throwing an error with the message ChatGPT failed to refresh auth token. Error: session token has expired
, but most long-running integrations will need a better solution for this going forwards.
I found this project.
Apparently they managed to login instead of requiring to copy paste the cookie.
https://github.com/rawandahmad698/PyChatGPT
Uncaught (in promise) Error: ChatGPT failed to refresh auth token. Error: Unauthorized
Thanks for making the API, it works pretty well until a very annoying bug surfaces:
if you make multiple queries consecutively, after about several queries, calling api.sendMessage()
would exit without the program any error output at the console.
I'm using node v16.18.1, if that matters.
By login using Google, the only thing that requires user operations appears to be the 2-step verification from Google, and this can be done away using your smart phone.
Or is it going to be detected by Google after a few tries?
Like this:
...
await page.goto('https://chat.openai.com/auth/login')
await page.waitForSelector('#__next .btn-primary', { timeout })
await delay(1000)
try {
if (email && password) {
await Promise.all([
page.click('#__next .btn-primary'),
page.waitForNavigation({
waitUntil: 'networkidle0'
})
])
await page.waitForSelector('button[data-provider="google"]', { timeout });
await page.click('button[data-provider="google"]');
await page.waitForNavigation({
waitUntil: 'networkidle0'
})
await page.type('input[type="email"]', email, { delay: 50 })
await page.keyboard.press("Enter");
await delay(3000);
await page.keyboard.type(password, { delay: 50 });
await page.keyboard.press("Enter");
}
} catch (err) {
await browser.close();
throw err;
}
await page.waitForSelector("items-center");
...
Hi, first of all thanks for your effort for publishing this api.
This is greatly helpful for making project in my side.
Due to problem for implementing this api to my hybrid app, I am asking this question.
Is it possible to use this api in my react-native app?
Please give me an answer with update.
Regards.
conversationId
conversationId
is passedSee #26 which I need to review
This is mainly due to how large the remark
dependency is: https://bundlephobia.com/[email protected],[email protected],[email protected],[email protected],[email protected],[email protected]
On the flip-side, it is really convenient to have this package support outputting plaintext.
Would love to hear what other people think?
ChatGPT failed to refresh auth token. Error: Unauthorized
wondering if i'm doing something wrong but
with version 1.3.0 installed like this:
{
"dependencies": {
"chatgpt": "^1.3.0"
}
}
and trying to import it like this:
let { ChatGPTAPI } = require("chatgpt");
i'm still getting this error:
Error [ERR_REQUIRE_ESM]: Must use import to load ES Module: /var/task/node_modules/chatgpt/build/index.js require() of ES modules is not supported.
am i doing anything wrong?
Hi,
I want to contribute to your project. I can make translation, code, 2D graphics - icons, logos. Will you be interested?
Thank you in advance.
Valeriia Zhuravska
Hello, I am now getting a 403 Forbidden error
Been playing around with the api. Here are a couple fixes that could make it work better
its not working for me with sessionToken (kept getting unauthorized), so i modified it to use the entire cookie string and it works.
Hello, I am now getting a 403 Forbidden error when use chatgpt-api version 2.2.
After modify demo-conversation.ts file's api paramter, run it,then throw exception as below:
(node:6860) ExperimentalWarning: The Fetch API is an experimental feature. This
feature could change at any time
(Use `node --trace-warnings ...` to show where the warning was created)
ChatGPTError: ChatGPT failed to refresh auth token. Error: 403 Forbidden
at ChatGPTAPI.refreshAccessToken (c:\Users\Administrator\Desktop\TestChatGPT
\chatgpt-api-main (1)\src\chatgpt-api.ts:342:21)
at process.processTicksAndRejections (node:internal/process/task_queues:95:5
)
at ChatGPTAPI.ensureAuth (c:\Users\Administrator\Desktop\TestChatGPT\chatgpt
-api-main (1)\src\chatgpt-api.ts:264:12)
at main (c:\Users\Administrator\Desktop\TestChatGPT\chatgpt-api-main (1)\dem
os\demo-conversation.ts:36:3) {
response: Response {
[Symbol(realm)]: null,
[Symbol(state)]: {
aborted: false,
rangeRequested: false,
timingAllowPassed: true,
requestIncludesCredentials: true,
type: 'default',
status: 403,
timingInfo: [Object],
cacheState: '',
statusText: 'Forbidden',
headersList: [HeadersList],
urlList: [Array],
body: [Object]
},
[Symbol(headers)]: HeadersList {
[Symbol(headers map)]: [Map],
[Symbol(headers map sorted)]: null
}
},
statusCode: 403,
statusText: 'Forbidden',
originalError: ChatGPTError: 403 Forbidden
at <anonymous> (c:\Users\Administrator\Desktop\TestChatGPT\chatgpt-api-mai
n (1)\src\chatgpt-api.ts:298:25)
at process.processTicksAndRejections (node:internal/process/task_queues:95
:5)
at ChatGPTAPI.refreshAccessToken (c:\Users\Administrator\Desktop\TestChatG
PT\chatgpt-api-main (1)\src\chatgpt-api.ts:292:19)
at ChatGPTAPI.ensureAuth (c:\Users\Administrator\Desktop\TestChatGPT\chatg
pt-api-main (1)\src\chatgpt-api.ts:264:12)
at main (c:\Users\Administrator\Desktop\TestChatGPT\chatgpt-api-main (1)\d
emos\demo-conversation.ts:36:3) {
response: Response {
[Symbol(realm)]: null,
[Symbol(state)]: [Object],
[Symbol(headers)]: [HeadersList]
},
statusCode: 403,
statusText: 'Forbidden'
}
}
and my demo-conversation.ts as below
import dotenv from 'dotenv-safe'
import { oraPromise } from 'ora'
import { ChatGPTAPI } from '../src'
import { getOpenAIAuthInfo } from './openai-auth-puppeteer'
//dotenv.config()
/**
* Demo CLI for testing conversation support.
*
* ```
* npx tsx src/demo-conversation.ts
* ```
*/
async function main() {
//const email = process.env.EMAIL
//const password = process.env.PASSWORD
/*
const authInfo = await getOpenAIAuthInfo({
email,
password
})
const api = new ChatGPTAPI({ ...authInfo })
*/
const api = new ChatGPTAPI({
sessionToken: "**my sessionToken*",
clearanceToken: "IGIXGUiyKUrNckUjBZ.NiGTOYn7bKjjfmRDYAmU8aXQ-1670850561-0-160",
userAgent: 'Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/108.0.0.0 Safari/537.36' // needs to match your browser's user agent
})
await api.ensureAuth()
const conversation = api.getConversation()
const prompt = 'What is OpenAI?'
const response = await oraPromise(conversation.sendMessage(prompt), {
text: prompt
})
console.log(response)
const prompt2 = 'Did they made OpenGPT?'
console.log(
await oraPromise(conversation.sendMessage(prompt2), {
text: prompt2
})
)
const prompt3 = 'Who founded this institute?'
console.log(
await oraPromise(conversation.sendMessage(prompt3), {
text: prompt3
})
)
const prompt4 = 'Who is that?'
console.log(
await oraPromise(conversation.sendMessage(prompt4), {
text: prompt4
})
)
}
main().catch((err) => {
console.error(err)
process.exit(1)
})
the code is here
const fs = require('fs')
const puppeteer = require('puppeteer-extra')
puppeteer.use(require('puppeteer-extra-plugin-stealth')())
const sleep = duration => new Promise(resolve => setTimeout(resolve, duration))
async function start() {
const browser = await puppeteer.launch({
executablePath: '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome',
headless: false,
args: ['--proxy-server=127.0.0.1:7890'],
ignoreHTTPSErrors: true
})
const page = (await browser.pages())[0]
await page.goto('https://chat.openai.com')
await page.waitForSelector('#__next .btn-primary')
// wait for networkidle
await sleep(10 * 1000)
await page.click('#__next .btn-primary')
await page.waitForNavigation({
waitUntil: 'networkidle0'
})
await page.type('#username', 'username')
await page.click('button[name="action"]')
await page.waitForSelector('#password')
// await page.screenshot({
// path: 'screenshot.png'
// })
await page.type('#password', 'password')
await page.click('button[name="action"]')
await page.waitForNavigation({
waitUntil: 'networkidle0'
})
fs.writeFileSync('cookies.json', JSON.stringify(await page.cookies()))
// await sleep(60 * 1000)
await browser.close()
}
start()
.then(() => {
process.exit(0)
})
.catch(() => {
process.exit(1)
})
i found official example there are some models and parameter choices,this look like fixed. Are you interested in configuring it?
Not a big deal, but I believe the following should include PASSWORD instead of EMAIL
password: process.env.EMAIL
It shouldn't take much effort to make this package work in both Node.js + browser environments.
This could be really important, for instance, for running on Edge runtimes like CF workers, Vercel edge functions, trusted code in Chrome extensions, etc.
Note
This package is not meant to be run client-side in a browser because it contains a reference to your private session token.
Responses sometimes hang with nothing returning. This could be due to increasing server load or some rate limiting features.
Is it possible to add a timeout/throw error for each request?
(node:1754) ExperimentalWarning: The Fetch API is an experimental feature. This feature could change at any time
(Use node --trace-warnings ...
to show where the warning was created)
How do i get rid of it?, this is generated when I used console.log();
webpack 5.66.0 compiled successfully in 3940 ms
Error [ERR_REQUIRE_ESM]: Must use import to load ES Module: xxx/node_modules/chatgpt/build/index.js
require() of ES modules is not supported.
require() of xxx/node_modules/chatgpt/build/index.js from xxx/dist/src/modules/chat/Chat.service.js is an ES module file as it is a .js file whose nearest parent package.json contains "type": "module" which defines all .js files in that package scope as ES modules.
Instead rename index.js to end in .cjs, change the requiring code to use import(), or remove "type": "module" from xxx/node_modules/chatgpt/package.json.
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.