docs: update readme and auto-gen docs

pull/284/head
Travis Fischer 2023-02-01 04:58:25 -06:00
rodzic 531e180e3f
commit 3a0259c128
9 zmienionych plików z 307 dodań i 1751 usunięć

Wyświetl plik

@ -1,167 +0,0 @@
[chatgpt](../readme.md) / [Exports](../modules.md) / AChatGPTAPI
# Class: AChatGPTAPI
## Hierarchy
- **`AChatGPTAPI`**
↳ [`ChatGPTAPI`](ChatGPTAPI.md)
↳ [`ChatGPTAPIBrowser`](ChatGPTAPIBrowser.md)
## Table of contents
### Constructors
- [constructor](AChatGPTAPI.md#constructor)
### Methods
- [closeSession](AChatGPTAPI.md#closesession)
- [getIsAuthenticated](AChatGPTAPI.md#getisauthenticated)
- [initSession](AChatGPTAPI.md#initsession)
- [refreshSession](AChatGPTAPI.md#refreshsession)
- [resetSession](AChatGPTAPI.md#resetsession)
- [sendMessage](AChatGPTAPI.md#sendmessage)
## Constructors
### constructor
**new AChatGPTAPI**()
## Methods
### closeSession
`Abstract` **closeSession**(): `Promise`<`void`\>
Closes the active session.
**`Throws`**
An error if it fails.
#### Returns
`Promise`<`void`\>
#### Defined in
[src/abstract-chatgpt-api.ts:69](https://github.com/transitive-bullshit/chatgpt-api/blob/83bb9cf/src/abstract-chatgpt-api.ts#L69)
___
### getIsAuthenticated
`Abstract` **getIsAuthenticated**(): `Promise`<`boolean`\>
#### Returns
`Promise`<`boolean`\>
`true` if the client is authenticated with a valid session or `false`
otherwise.
#### Defined in
[src/abstract-chatgpt-api.ts:39](https://github.com/transitive-bullshit/chatgpt-api/blob/83bb9cf/src/abstract-chatgpt-api.ts#L39)
___
### initSession
`Abstract` **initSession**(): `Promise`<`void`\>
Performs any async initialization work required to ensure that this API is
properly authenticated.
**`Throws`**
An error if the session failed to initialize properly.
#### Returns
`Promise`<`void`\>
#### Defined in
[src/abstract-chatgpt-api.ts:10](https://github.com/transitive-bullshit/chatgpt-api/blob/83bb9cf/src/abstract-chatgpt-api.ts#L10)
___
### refreshSession
`Abstract` **refreshSession**(): `Promise`<`any`\>
Refreshes the current ChatGPT session.
Useful for bypassing 403 errors when Cloudflare clearance tokens expire.
**`Throws`**
An error if it fails.
#### Returns
`Promise`<`any`\>
Access credentials for the new session.
#### Defined in
[src/abstract-chatgpt-api.ts:49](https://github.com/transitive-bullshit/chatgpt-api/blob/83bb9cf/src/abstract-chatgpt-api.ts#L49)
___
### resetSession
**resetSession**(): `Promise`<`any`\>
Closes the current ChatGPT session and starts a new one.
Useful for bypassing 401 errors when sessions expire.
**`Throws`**
An error if it fails.
#### Returns
`Promise`<`any`\>
Access credentials for the new session.
#### Defined in
[src/abstract-chatgpt-api.ts:59](https://github.com/transitive-bullshit/chatgpt-api/blob/83bb9cf/src/abstract-chatgpt-api.ts#L59)
___
### sendMessage
`Abstract` **sendMessage**(`message`, `opts?`): `Promise`<[`ChatResponse`](../modules.md#chatresponse)\>
Sends a message to ChatGPT, waits for the response to resolve, and returns
the response.
If you want to receive a stream of partial responses, use `opts.onProgress`.
#### Parameters
| Name | Type | Description |
| :------ | :------ | :------ |
| `message` | `string` | The prompt message to send |
| `opts?` | [`SendMessageOptions`](../modules.md#sendmessageoptions) | - |
#### Returns
`Promise`<[`ChatResponse`](../modules.md#chatresponse)\>
The response from ChatGPT, including `conversationId`, `messageId`, and
the `response` text.
#### Defined in
[src/abstract-chatgpt-api.ts:30](https://github.com/transitive-bullshit/chatgpt-api/blob/83bb9cf/src/abstract-chatgpt-api.ts#L30)

Wyświetl plik

@ -2,34 +2,15 @@
# Class: ChatGPTAPI
## Hierarchy
- [`AChatGPTAPI`](AChatGPTAPI.md)
**`ChatGPTAPI`**
## Table of contents
### Constructors
- [constructor](ChatGPTAPI.md#constructor)
### Accessors
- [clearanceToken](ChatGPTAPI.md#clearancetoken)
- [sessionToken](ChatGPTAPI.md#sessiontoken)
- [user](ChatGPTAPI.md#user)
- [userAgent](ChatGPTAPI.md#useragent)
### Methods
- [closeSession](ChatGPTAPI.md#closesession)
- [getIsAuthenticated](ChatGPTAPI.md#getisauthenticated)
- [initSession](ChatGPTAPI.md#initsession)
- [refreshSession](ChatGPTAPI.md#refreshsession)
- [resetSession](ChatGPTAPI.md#resetsession)
- [sendMessage](ChatGPTAPI.md#sendmessage)
- [sendModeration](ChatGPTAPI.md#sendmoderation)
## Constructors
@ -37,228 +18,31 @@
**new ChatGPTAPI**(`opts`)
Creates a new client wrapper around the unofficial ChatGPT REST API.
Note that your IP address and `userAgent` must match the same values that you used
to obtain your `clearanceToken`.
Creates a new client wrapper around OpenAI's completion API using the
unofficial ChatGPT model.
#### Parameters
| Name | Type | Description |
| :------ | :------ | :------ |
| `opts` | `Object` | - |
| `opts.accessToken?` | `string` | **`Default Value`** `undefined` * |
| `opts.accessTokenTTL?` | `number` | **`Default Value`** 1 hour * |
| `opts.apiBaseUrl?` | `string` | **`Default Value`** `'https://chat.openai.com/api'` * |
| `opts.backendApiBaseUrl?` | `string` | **`Default Value`** `'https://chat.openai.com/backend-api'` * |
| `opts.clearanceToken` | `string` | = **Required** Cloudflare `cf_clearance` cookie value (see readme for instructions) |
| `opts.debug?` | `boolean` | **`Default Value`** `false` * |
| `opts.headers?` | `Record`<`string`, `string`\> | **`Default Value`** `undefined` * |
| `opts.markdown?` | `boolean` | **`Default Value`** `true` * |
| `opts.sessionToken` | `string` | = **Required** OpenAI session token which can be found in a valid session's cookies (see readme for instructions) |
| `opts.userAgent?` | `string` | **`Default Value`** `Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/108.0.0.0 Safari/537.36'` * |
#### Overrides
[AChatGPTAPI](AChatGPTAPI.md).[constructor](AChatGPTAPI.md#constructor)
| `opts.apiBaseUrl?` | `string` | **`Default Value`** `'https://api.openai.com'` * |
| `opts.apiKey` | `string` | - |
| `opts.completionParams?` | [`CompletionParams`](../modules/openai.md#completionparams) | - |
| `opts.debug?` | `boolean` | **`Default Value`** `false` * |
| `opts.getMessageById?` | [`GetMessageByIdFunction`](../modules.md#getmessagebyidfunction) | - |
| `opts.messageStore?` | `Keyv`<`any`, `Record`<`string`, `unknown`\>\> | - |
| `opts.upsertMessage?` | [`UpsertMessageFunction`](../modules.md#upsertmessagefunction) | - |
#### Defined in
[src/chatgpt-api.ts:45](https://github.com/transitive-bullshit/chatgpt-api/blob/83bb9cf/src/chatgpt-api.ts#L45)
## Accessors
### clearanceToken
`get` **clearanceToken**(): `string`
Gets the current Cloudflare clearance token (`cf_clearance` cookie value).
#### Returns
`string`
#### Defined in
[src/chatgpt-api.ts:143](https://github.com/transitive-bullshit/chatgpt-api/blob/83bb9cf/src/chatgpt-api.ts#L143)
___
### sessionToken
`get` **sessionToken**(): `string`
Gets the current session token.
#### Returns
`string`
#### Defined in
[src/chatgpt-api.ts:138](https://github.com/transitive-bullshit/chatgpt-api/blob/83bb9cf/src/chatgpt-api.ts#L138)
___
### user
`get` **user**(): [`User`](../modules.md#user)
Gets the currently signed-in user, if authenticated, `null` otherwise.
#### Returns
[`User`](../modules.md#user)
#### Defined in
[src/chatgpt-api.ts:133](https://github.com/transitive-bullshit/chatgpt-api/blob/83bb9cf/src/chatgpt-api.ts#L133)
___
### userAgent
`get` **userAgent**(): `string`
Gets the current user agent.
#### Returns
`string`
#### Defined in
[src/chatgpt-api.ts:148](https://github.com/transitive-bullshit/chatgpt-api/blob/83bb9cf/src/chatgpt-api.ts#L148)
[src/chatgpt-api.ts:36](https://github.com/transitive-bullshit/chatgpt-api/blob/531e180/src/chatgpt-api.ts#L36)
## Methods
### closeSession
**closeSession**(): `Promise`<`void`\>
Closes the active session.
**`Throws`**
An error if it fails.
#### Returns
`Promise`<`void`\>
#### Overrides
[AChatGPTAPI](AChatGPTAPI.md).[closeSession](AChatGPTAPI.md#closesession)
#### Defined in
[src/chatgpt-api.ts:470](https://github.com/transitive-bullshit/chatgpt-api/blob/83bb9cf/src/chatgpt-api.ts#L470)
___
### getIsAuthenticated
**getIsAuthenticated**(): `Promise`<`boolean`\>
#### Returns
`Promise`<`boolean`\>
`true` if the client has a valid acces token or `false` if refreshing
the token fails.
#### Overrides
[AChatGPTAPI](AChatGPTAPI.md).[getIsAuthenticated](AChatGPTAPI.md#getisauthenticated)
#### Defined in
[src/chatgpt-api.ts:367](https://github.com/transitive-bullshit/chatgpt-api/blob/83bb9cf/src/chatgpt-api.ts#L367)
___
### initSession
**initSession**(): `Promise`<`void`\>
Refreshes the client's access token which will succeed only if the session
is valid.
#### Returns
`Promise`<`void`\>
#### Overrides
[AChatGPTAPI](AChatGPTAPI.md).[initSession](AChatGPTAPI.md#initsession)
#### Defined in
[src/chatgpt-api.ts:156](https://github.com/transitive-bullshit/chatgpt-api/blob/83bb9cf/src/chatgpt-api.ts#L156)
___
### refreshSession
**refreshSession**(): `Promise`<`string`\>
Attempts to refresh the current access token using the ChatGPT
`sessionToken` cookie.
Access tokens will be cached for up to `accessTokenTTL` milliseconds to
prevent refreshing access tokens too frequently.
**`Throws`**
An error if refreshing the access token fails.
#### Returns
`Promise`<`string`\>
A valid access token
#### Overrides
[AChatGPTAPI](AChatGPTAPI.md).[refreshSession](AChatGPTAPI.md#refreshsession)
#### Defined in
[src/chatgpt-api.ts:386](https://github.com/transitive-bullshit/chatgpt-api/blob/83bb9cf/src/chatgpt-api.ts#L386)
___
### resetSession
**resetSession**(): `Promise`<`any`\>
Closes the current ChatGPT session and starts a new one.
Useful for bypassing 401 errors when sessions expire.
**`Throws`**
An error if it fails.
#### Returns
`Promise`<`any`\>
Access credentials for the new session.
#### Inherited from
[AChatGPTAPI](AChatGPTAPI.md).[resetSession](AChatGPTAPI.md#resetsession)
#### Defined in
[src/abstract-chatgpt-api.ts:59](https://github.com/transitive-bullshit/chatgpt-api/blob/83bb9cf/src/abstract-chatgpt-api.ts#L59)
___
### sendMessage
**sendMessage**(`message`, `opts?`): `Promise`<[`ChatResponse`](../modules.md#chatresponse)\>
**sendMessage**(`text`, `opts?`): `Promise`<[`ChatMessage`](../interfaces/ChatMessage.md)\>
Sends a message to ChatGPT, waits for the response to resolve, and returns
the response.
@ -270,41 +54,17 @@ helper.
#### Parameters
| Name | Type | Description |
| :------ | :------ | :------ |
| `message` | `string` | The prompt message to send |
| `opts` | [`SendMessageOptions`](../modules.md#sendmessageoptions) | - |
| Name | Type |
| :------ | :------ |
| `text` | `string` |
| `opts` | [`SendMessageOptions`](../modules.md#sendmessageoptions) |
#### Returns
`Promise`<[`ChatResponse`](../modules.md#chatresponse)\>
`Promise`<[`ChatMessage`](../interfaces/ChatMessage.md)\>
The response from ChatGPT
#### Overrides
[AChatGPTAPI](AChatGPTAPI.md).[sendMessage](AChatGPTAPI.md#sendmessage)
#### Defined in
[src/chatgpt-api.ts:180](https://github.com/transitive-bullshit/chatgpt-api/blob/83bb9cf/src/chatgpt-api.ts#L180)
___
### sendModeration
**sendModeration**(`input`): `Promise`<[`ModerationsJSONResult`](../modules.md#moderationsjsonresult)\>
#### Parameters
| Name | Type |
| :------ | :------ |
| `input` | `string` |
#### Returns
`Promise`<[`ModerationsJSONResult`](../modules.md#moderationsjsonresult)\>
#### Defined in
[src/chatgpt-api.ts:324](https://github.com/transitive-bullshit/chatgpt-api/blob/83bb9cf/src/chatgpt-api.ts#L324)
[src/chatgpt-api.ts:109](https://github.com/transitive-bullshit/chatgpt-api/blob/531e180/src/chatgpt-api.ts#L109)

Wyświetl plik

@ -1,277 +0,0 @@
[chatgpt](../readme.md) / [Exports](../modules.md) / ChatGPTAPIBrowser
# Class: ChatGPTAPIBrowser
## Hierarchy
- [`AChatGPTAPI`](AChatGPTAPI.md)
**`ChatGPTAPIBrowser`**
## Table of contents
### Constructors
- [constructor](ChatGPTAPIBrowser.md#constructor)
### Accessors
- [isChatPage](ChatGPTAPIBrowser.md#ischatpage)
### Methods
- [\_onRequest](ChatGPTAPIBrowser.md#_onrequest)
- [\_onResponse](ChatGPTAPIBrowser.md#_onresponse)
- [closeSession](ChatGPTAPIBrowser.md#closesession)
- [getIsAuthenticated](ChatGPTAPIBrowser.md#getisauthenticated)
- [initSession](ChatGPTAPIBrowser.md#initsession)
- [refreshSession](ChatGPTAPIBrowser.md#refreshsession)
- [resetSession](ChatGPTAPIBrowser.md#resetsession)
- [resetThread](ChatGPTAPIBrowser.md#resetthread)
- [sendMessage](ChatGPTAPIBrowser.md#sendmessage)
## Constructors
### constructor
**new ChatGPTAPIBrowser**(`opts`)
Creates a new client for automating the ChatGPT webapp.
#### Parameters
| Name | Type | Description |
| :------ | :------ | :------ |
| `opts` | `Object` | - |
| `opts.captchaToken?` | `string` | **`Default Value`** `undefined` * |
| `opts.debug?` | `boolean` | **`Default Value`** `false` * |
| `opts.email` | `string` | - |
| `opts.executablePath?` | `string` | **`Default Value`** `undefined` * |
| `opts.isGoogleLogin?` | `boolean` | **`Default Value`** `false` * |
| `opts.isMicrosoftLogin?` | `boolean` | **`Default Value`** `false` * |
| `opts.isProAccount?` | `boolean` | **`Default Value`** `false` * |
| `opts.markdown?` | `boolean` | **`Default Value`** `true` * |
| `opts.minimize?` | `boolean` | **`Default Value`** `true` * |
| `opts.nopechaKey?` | `string` | **`Default Value`** `undefined` * |
| `opts.password` | `string` | - |
| `opts.proxyServer?` | `string` | **`Default Value`** `undefined` * |
| `opts.userDataDir?` | `string` | **`Default Value`** `random directory with email as prefix` * |
#### Overrides
[AChatGPTAPI](AChatGPTAPI.md).[constructor](AChatGPTAPI.md#constructor)
#### Defined in
[src/chatgpt-api-browser.ts:48](https://github.com/transitive-bullshit/chatgpt-api/blob/83bb9cf/src/chatgpt-api-browser.ts#L48)
## Accessors
### isChatPage
`get` **isChatPage**(): `boolean`
#### Returns
`boolean`
#### Defined in
[src/chatgpt-api-browser.ts:640](https://github.com/transitive-bullshit/chatgpt-api/blob/83bb9cf/src/chatgpt-api-browser.ts#L640)
## Methods
### \_onRequest
**_onRequest**(`request`): `void`
#### Parameters
| Name | Type |
| :------ | :------ |
| `request` | `HTTPRequest` |
#### Returns
`void`
#### Defined in
[src/chatgpt-api-browser.ts:255](https://github.com/transitive-bullshit/chatgpt-api/blob/83bb9cf/src/chatgpt-api-browser.ts#L255)
___
### \_onResponse
**_onResponse**(`response`): `Promise`<`void`\>
#### Parameters
| Name | Type |
| :------ | :------ |
| `response` | `HTTPResponse` |
#### Returns
`Promise`<`void`\>
#### Defined in
[src/chatgpt-api-browser.ts:292](https://github.com/transitive-bullshit/chatgpt-api/blob/83bb9cf/src/chatgpt-api-browser.ts#L292)
___
### closeSession
**closeSession**(): `Promise`<`void`\>
Closes the active session.
**`Throws`**
An error if it fails.
#### Returns
`Promise`<`void`\>
#### Overrides
[AChatGPTAPI](AChatGPTAPI.md).[closeSession](AChatGPTAPI.md#closesession)
#### Defined in
[src/chatgpt-api-browser.ts:586](https://github.com/transitive-bullshit/chatgpt-api/blob/83bb9cf/src/chatgpt-api-browser.ts#L586)
___
### getIsAuthenticated
**getIsAuthenticated**(): `Promise`<`boolean`\>
#### Returns
`Promise`<`boolean`\>
`true` if the client is authenticated with a valid session or `false`
otherwise.
#### Overrides
[AChatGPTAPI](AChatGPTAPI.md).[getIsAuthenticated](AChatGPTAPI.md#getisauthenticated)
#### Defined in
[src/chatgpt-api-browser.ts:425](https://github.com/transitive-bullshit/chatgpt-api/blob/83bb9cf/src/chatgpt-api-browser.ts#L425)
___
### initSession
**initSession**(): `Promise`<`void`\>
Performs any async initialization work required to ensure that this API is
properly authenticated.
**`Throws`**
An error if the session failed to initialize properly.
#### Returns
`Promise`<`void`\>
#### Overrides
[AChatGPTAPI](AChatGPTAPI.md).[initSession](AChatGPTAPI.md#initsession)
#### Defined in
[src/chatgpt-api-browser.ts:133](https://github.com/transitive-bullshit/chatgpt-api/blob/83bb9cf/src/chatgpt-api-browser.ts#L133)
___
### refreshSession
**refreshSession**(): `Promise`<`void`\>
Attempts to handle 403 errors by refreshing the page.
#### Returns
`Promise`<`void`\>
#### Overrides
[AChatGPTAPI](AChatGPTAPI.md).[refreshSession](AChatGPTAPI.md#refreshsession)
#### Defined in
[src/chatgpt-api-browser.ts:367](https://github.com/transitive-bullshit/chatgpt-api/blob/83bb9cf/src/chatgpt-api-browser.ts#L367)
___
### resetSession
**resetSession**(): `Promise`<`void`\>
Attempts to handle 401 errors by re-authenticating.
#### Returns
`Promise`<`void`\>
#### Overrides
[AChatGPTAPI](AChatGPTAPI.md).[resetSession](AChatGPTAPI.md#resetsession)
#### Defined in
[src/chatgpt-api-browser.ts:348](https://github.com/transitive-bullshit/chatgpt-api/blob/83bb9cf/src/chatgpt-api-browser.ts#L348)
___
### resetThread
**resetThread**(): `Promise`<`void`\>
#### Returns
`Promise`<`void`\>
#### Defined in
[src/chatgpt-api-browser.ts:578](https://github.com/transitive-bullshit/chatgpt-api/blob/83bb9cf/src/chatgpt-api-browser.ts#L578)
___
### sendMessage
**sendMessage**(`message`, `opts?`): `Promise`<[`ChatResponse`](../modules.md#chatresponse)\>
Sends a message to ChatGPT, waits for the response to resolve, and returns
the response.
If you want to receive a stream of partial responses, use `opts.onProgress`.
#### Parameters
| Name | Type | Description |
| :------ | :------ | :------ |
| `message` | `string` | The prompt message to send |
| `opts` | [`SendMessageOptions`](../modules.md#sendmessageoptions) | - |
#### Returns
`Promise`<[`ChatResponse`](../modules.md#chatresponse)\>
The response from ChatGPT, including `conversationId`, `messageId`, and
the `response` text.
#### Overrides
[AChatGPTAPI](AChatGPTAPI.md).[sendMessage](AChatGPTAPI.md#sendmessage)
#### Defined in
[src/chatgpt-api-browser.ts:439](https://github.com/transitive-bullshit/chatgpt-api/blob/83bb9cf/src/chatgpt-api-browser.ts#L439)

Wyświetl plik

@ -16,8 +16,6 @@
### Properties
- [originalError](ChatGPTError.md#originalerror)
- [response](ChatGPTError.md#response)
- [statusCode](ChatGPTError.md#statuscode)
- [statusText](ChatGPTError.md#statustext)
@ -39,7 +37,7 @@ Error.constructor
#### Defined in
node_modules/.pnpm/typescript@4.9.3/node_modules/typescript/lib/lib.es5.d.ts:1059
node_modules/.pnpm/typescript@4.9.5/node_modules/typescript/lib/lib.es5.d.ts:1059
**new ChatGPTError**(`message?`, `options?`)
@ -56,37 +54,17 @@ Error.constructor
#### Defined in
node_modules/.pnpm/typescript@4.9.3/node_modules/typescript/lib/lib.es2022.error.d.ts:30
node_modules/.pnpm/typescript@4.9.5/node_modules/typescript/lib/lib.es2022.error.d.ts:30
## Properties
### originalError
`Optional` **originalError**: `Error`
#### Defined in
[src/types.ts:297](https://github.com/transitive-bullshit/chatgpt-api/blob/83bb9cf/src/types.ts#L297)
___
### response
`Optional` **response**: `Response`
#### Defined in
[src/types.ts:296](https://github.com/transitive-bullshit/chatgpt-api/blob/83bb9cf/src/types.ts#L296)
___
### statusCode
`Optional` **statusCode**: `number`
#### Defined in
[src/types.ts:294](https://github.com/transitive-bullshit/chatgpt-api/blob/83bb9cf/src/types.ts#L294)
[src/types.ts:24](https://github.com/transitive-bullshit/chatgpt-api/blob/531e180/src/types.ts#L24)
___
@ -96,4 +74,4 @@ ___
#### Defined in
[src/types.ts:295](https://github.com/transitive-bullshit/chatgpt-api/blob/83bb9cf/src/types.ts#L295)
[src/types.ts:25](https://github.com/transitive-bullshit/chatgpt-api/blob/531e180/src/types.ts#L25)

Wyświetl plik

@ -0,0 +1,63 @@
[chatgpt](../readme.md) / [Exports](../modules.md) / ChatMessage
# Interface: ChatMessage
## Table of contents
### Properties
- [conversationId](ChatMessage.md#conversationid)
- [id](ChatMessage.md#id)
- [parentMessageId](ChatMessage.md#parentmessageid)
- [role](ChatMessage.md#role)
- [text](ChatMessage.md#text)
## Properties
### conversationId
`Optional` **conversationId**: `string`
#### Defined in
[src/types.ts:20](https://github.com/transitive-bullshit/chatgpt-api/blob/531e180/src/types.ts#L20)
___
### id
**id**: `string`
#### Defined in
[src/types.ts:16](https://github.com/transitive-bullshit/chatgpt-api/blob/531e180/src/types.ts#L16)
___
### parentMessageId
`Optional` **parentMessageId**: `string`
#### Defined in
[src/types.ts:19](https://github.com/transitive-bullshit/chatgpt-api/blob/531e180/src/types.ts#L19)
___
### role
**role**: [`Role`](../modules.md#role)
#### Defined in
[src/types.ts:18](https://github.com/transitive-bullshit/chatgpt-api/blob/531e180/src/types.ts#L18)
___
### text
**text**: `string`
#### Defined in
[src/types.ts:17](https://github.com/transitive-bullshit/chatgpt-api/blob/531e180/src/types.ts#L17)

Wyświetl plik

@ -4,408 +4,51 @@
## Table of contents
### Namespaces
- [openai](modules/openai.md)
### Classes
- [AChatGPTAPI](classes/AChatGPTAPI.md)
- [ChatGPTAPI](classes/ChatGPTAPI.md)
- [ChatGPTAPIBrowser](classes/ChatGPTAPIBrowser.md)
- [ChatGPTError](classes/ChatGPTError.md)
### Interfaces
- [ChatMessage](interfaces/ChatMessage.md)
### Type Aliases
- [AvailableModerationModels](modules.md#availablemoderationmodels)
- [ChatError](modules.md#chaterror)
- [ChatResponse](modules.md#chatresponse)
- [ContentType](modules.md#contenttype)
- [ConversationJSONBody](modules.md#conversationjsonbody)
- [ConversationResponseEvent](modules.md#conversationresponseevent)
- [Message](modules.md#message)
- [MessageActionType](modules.md#messageactiontype)
- [MessageContent](modules.md#messagecontent)
- [MessageFeedbackJSONBody](modules.md#messagefeedbackjsonbody)
- [MessageFeedbackRating](modules.md#messagefeedbackrating)
- [MessageFeedbackResult](modules.md#messagefeedbackresult)
- [MessageFeedbackTags](modules.md#messagefeedbacktags)
- [MessageMetadata](modules.md#messagemetadata)
- [Model](modules.md#model)
- [ModelsResult](modules.md#modelsresult)
- [ModerationsJSONBody](modules.md#moderationsjsonbody)
- [ModerationsJSONResult](modules.md#moderationsjsonresult)
- [OpenAIAuth](modules.md#openaiauth)
- [Prompt](modules.md#prompt)
- [PromptContent](modules.md#promptcontent)
- [GetMessageByIdFunction](modules.md#getmessagebyidfunction)
- [Role](modules.md#role)
- [SendConversationMessageOptions](modules.md#sendconversationmessageoptions)
- [SendMessageOptions](modules.md#sendmessageoptions)
- [SessionResult](modules.md#sessionresult)
- [User](modules.md#user)
### Functions
- [browserPostEventStream](modules.md#browserposteventstream)
- [defaultChromeExecutablePath](modules.md#defaultchromeexecutablepath)
- [getBrowser](modules.md#getbrowser)
- [getOpenAIAuth](modules.md#getopenaiauth)
- [getPage](modules.md#getpage)
- [initializeNopechaExtension](modules.md#initializenopechaextension)
- [isRelevantRequest](modules.md#isrelevantrequest)
- [markdownToText](modules.md#markdowntotext)
- [maximizePage](modules.md#maximizepage)
- [minimizePage](modules.md#minimizepage)
- [UpsertMessageFunction](modules.md#upsertmessagefunction)
## Type Aliases
### AvailableModerationModels
### GetMessageByIdFunction
Ƭ **AvailableModerationModels**: ``"text-moderation-playground"``
#### Defined in
[src/types.ts:109](https://github.com/transitive-bullshit/chatgpt-api/blob/83bb9cf/src/types.ts#L109)
___
### ChatError
Ƭ **ChatError**: `Object`
Ƭ **GetMessageByIdFunction**: (`id`: `string`) => `Promise`<[`ChatMessage`](interfaces/ChatMessage.md)\>
#### Type declaration
▸ (`id`): `Promise`<[`ChatMessage`](interfaces/ChatMessage.md)\>
Returns a chat message from a store by it's ID (or null if not found).
##### Parameters
| Name | Type |
| :------ | :------ |
| `conversationId?` | `string` |
| `error` | { `message`: `string` ; `statusCode?`: `number` ; `statusText?`: `string` } |
| `error.message` | `string` |
| `error.statusCode?` | `number` |
| `error.statusText?` | `string` |
| `messageId?` | `string` |
#### Defined in
[src/types.ts:300](https://github.com/transitive-bullshit/chatgpt-api/blob/83bb9cf/src/types.ts#L300)
___
### ChatResponse
Ƭ **ChatResponse**: `Object`
#### Type declaration
| Name | Type |
| :------ | :------ |
| `conversationId` | `string` |
| `messageId` | `string` |
| `response` | `string` |
#### Defined in
[src/types.ts:306](https://github.com/transitive-bullshit/chatgpt-api/blob/83bb9cf/src/types.ts#L306)
___
### ContentType
Ƭ **ContentType**: ``"text"``
#### Defined in
[src/types.ts:1](https://github.com/transitive-bullshit/chatgpt-api/blob/83bb9cf/src/types.ts#L1)
___
### ConversationJSONBody
Ƭ **ConversationJSONBody**: `Object`
https://chat.openapi.com/backend-api/conversation
#### Type declaration
| Name | Type | Description |
| :------ | :------ | :------ |
| `action` | `string` | The action to take |
| `conversation_id?` | `string` | The ID of the conversation |
| `messages` | [`Prompt`](modules.md#prompt)[] | Prompts to provide |
| `model` | `string` | The model to use |
| `parent_message_id` | `string` | The parent message ID |
#### Defined in
[src/types.ts:134](https://github.com/transitive-bullshit/chatgpt-api/blob/83bb9cf/src/types.ts#L134)
___
### ConversationResponseEvent
Ƭ **ConversationResponseEvent**: `Object`
#### Type declaration
| Name | Type |
| :------ | :------ |
| `conversation_id?` | `string` |
| `error?` | `string` \| ``null`` |
| `message?` | [`Message`](modules.md#message) |
#### Defined in
[src/types.ts:251](https://github.com/transitive-bullshit/chatgpt-api/blob/83bb9cf/src/types.ts#L251)
___
### Message
Ƭ **Message**: `Object`
#### Type declaration
| Name | Type |
| :------ | :------ |
| `content` | [`MessageContent`](modules.md#messagecontent) |
| `create_time` | `string` \| ``null`` |
| `end_turn` | ``null`` |
| `id` | `string` |
| `metadata` | [`MessageMetadata`](modules.md#messagemetadata) |
| `recipient` | `string` |
| `role` | `string` |
| `update_time` | `string` \| ``null`` |
| `user` | `string` \| ``null`` |
| `weight` | `number` |
##### Returns
`Promise`<[`ChatMessage`](interfaces/ChatMessage.md)\>
#### Defined in
[src/types.ts:257](https://github.com/transitive-bullshit/chatgpt-api/blob/83bb9cf/src/types.ts#L257)
___
### MessageActionType
Ƭ **MessageActionType**: ``"next"`` \| ``"variant"``
#### Defined in
[src/types.ts:276](https://github.com/transitive-bullshit/chatgpt-api/blob/83bb9cf/src/types.ts#L276)
___
### MessageContent
Ƭ **MessageContent**: `Object`
#### Type declaration
| Name | Type |
| :------ | :------ |
| `content_type` | `string` |
| `parts` | `string`[] |
#### Defined in
[src/types.ts:270](https://github.com/transitive-bullshit/chatgpt-api/blob/83bb9cf/src/types.ts#L270)
___
### MessageFeedbackJSONBody
Ƭ **MessageFeedbackJSONBody**: `Object`
https://chat.openapi.com/backend-api/conversation/message_feedback
#### Type declaration
| Name | Type | Description |
| :------ | :------ | :------ |
| `conversation_id` | `string` | The ID of the conversation |
| `message_id` | `string` | The message ID |
| `rating` | [`MessageFeedbackRating`](modules.md#messagefeedbackrating) | The rating |
| `tags?` | [`MessageFeedbackTags`](modules.md#messagefeedbacktags)[] | Tags to give the rating |
| `text?` | `string` | The text to include |
#### Defined in
[src/types.ts:193](https://github.com/transitive-bullshit/chatgpt-api/blob/83bb9cf/src/types.ts#L193)
___
### MessageFeedbackRating
Ƭ **MessageFeedbackRating**: ``"thumbsUp"`` \| ``"thumbsDown"``
#### Defined in
[src/types.ts:249](https://github.com/transitive-bullshit/chatgpt-api/blob/83bb9cf/src/types.ts#L249)
___
### MessageFeedbackResult
Ƭ **MessageFeedbackResult**: `Object`
#### Type declaration
| Name | Type | Description |
| :------ | :------ | :------ |
| `conversation_id` | `string` | The ID of the conversation |
| `message_id` | `string` | The message ID |
| `rating` | [`MessageFeedbackRating`](modules.md#messagefeedbackrating) | The rating |
| `text?` | `string` | The text the server received, including tags |
| `user_id` | `string` | The ID of the user |
#### Defined in
[src/types.ts:222](https://github.com/transitive-bullshit/chatgpt-api/blob/83bb9cf/src/types.ts#L222)
___
### MessageFeedbackTags
Ƭ **MessageFeedbackTags**: ``"harmful"`` \| ``"false"`` \| ``"not-helpful"``
#### Defined in
[src/types.ts:220](https://github.com/transitive-bullshit/chatgpt-api/blob/83bb9cf/src/types.ts#L220)
___
### MessageMetadata
Ƭ **MessageMetadata**: `any`
#### Defined in
[src/types.ts:275](https://github.com/transitive-bullshit/chatgpt-api/blob/83bb9cf/src/types.ts#L275)
___
### Model
Ƭ **Model**: `Object`
#### Type declaration
| Name | Type | Description |
| :------ | :------ | :------ |
| `is_special` | `boolean` | Whether or not the model is special |
| `max_tokens` | `number` | Max tokens of the model |
| `slug` | `string` | Name of the model |
#### Defined in
[src/types.ts:77](https://github.com/transitive-bullshit/chatgpt-api/blob/83bb9cf/src/types.ts#L77)
___
### ModelsResult
Ƭ **ModelsResult**: `Object`
https://chat.openapi.com/backend-api/models
#### Type declaration
| Name | Type | Description |
| :------ | :------ | :------ |
| `models` | [`Model`](modules.md#model)[] | Array of models |
#### Defined in
[src/types.ts:70](https://github.com/transitive-bullshit/chatgpt-api/blob/83bb9cf/src/types.ts#L70)
___
### ModerationsJSONBody
Ƭ **ModerationsJSONBody**: `Object`
https://chat.openapi.com/backend-api/moderations
#### Type declaration
| Name | Type | Description |
| :------ | :------ | :------ |
| `input` | `string` | Input for the moderation decision |
| `model` | [`AvailableModerationModels`](modules.md#availablemoderationmodels) | The model to use in the decision |
#### Defined in
[src/types.ts:97](https://github.com/transitive-bullshit/chatgpt-api/blob/83bb9cf/src/types.ts#L97)
___
### ModerationsJSONResult
Ƭ **ModerationsJSONResult**: `Object`
https://chat.openapi.com/backend-api/moderations
#### Type declaration
| Name | Type | Description |
| :------ | :------ | :------ |
| `blocked` | `boolean` | Whether or not the input is blocked |
| `flagged` | `boolean` | Whether or not the input is flagged |
| `moderation_id` | `string` | The ID of the decision |
#### Defined in
[src/types.ts:114](https://github.com/transitive-bullshit/chatgpt-api/blob/83bb9cf/src/types.ts#L114)
___
### OpenAIAuth
Ƭ **OpenAIAuth**: `Object`
Represents everything that's required to pass into `ChatGPTAPI` in order
to authenticate with the unofficial ChatGPT API.
#### Type declaration
| Name | Type |
| :------ | :------ |
| `clearanceToken` | `string` |
| `sessionToken` | `string` |
| `userAgent` | `string` |
#### Defined in
[src/openai-auth.ts:29](https://github.com/transitive-bullshit/chatgpt-api/blob/83bb9cf/src/openai-auth.ts#L29)
___
### Prompt
Ƭ **Prompt**: `Object`
#### Type declaration
| Name | Type | Description |
| :------ | :------ | :------ |
| `content` | [`PromptContent`](modules.md#promptcontent) | The content of the prompt |
| `id` | `string` | The ID of the prompt |
| `role` | [`Role`](modules.md#role) | The role played in the prompt |
#### Defined in
[src/types.ts:161](https://github.com/transitive-bullshit/chatgpt-api/blob/83bb9cf/src/types.ts#L161)
___
### PromptContent
Ƭ **PromptContent**: `Object`
#### Type declaration
| Name | Type | Description |
| :------ | :------ | :------ |
| `content_type` | [`ContentType`](modules.md#contenttype) | The content type of the prompt |
| `parts` | `string`[] | The parts to the prompt |
#### Defined in
[src/types.ts:178](https://github.com/transitive-bullshit/chatgpt-api/blob/83bb9cf/src/types.ts#L178)
[src/types.ts:29](https://github.com/transitive-bullshit/chatgpt-api/blob/531e180/src/types.ts#L29)
___
@ -415,17 +58,7 @@ ___
#### Defined in
[src/types.ts:3](https://github.com/transitive-bullshit/chatgpt-api/blob/83bb9cf/src/types.ts#L3)
___
### SendConversationMessageOptions
Ƭ **SendConversationMessageOptions**: `Omit`<[`SendMessageOptions`](modules.md#sendmessageoptions), ``"conversationId"`` \| ``"parentMessageId"``\>
#### Defined in
[src/types.ts:288](https://github.com/transitive-bullshit/chatgpt-api/blob/83bb9cf/src/types.ts#L288)
[src/types.ts:1](https://github.com/transitive-bullshit/chatgpt-api/blob/531e180/src/types.ts#L1)
___
@ -438,297 +71,41 @@ ___
| Name | Type |
| :------ | :------ |
| `abortSignal?` | `AbortSignal` |
| `action?` | [`MessageActionType`](modules.md#messageactiontype) |
| `conversationId?` | `string` |
| `messageId?` | `string` |
| `onProgress?` | (`partialResponse`: [`ChatResponse`](modules.md#chatresponse)) => `void` |
| `onProgress?` | (`partialResponse`: [`ChatMessage`](interfaces/ChatMessage.md)) => `void` |
| `parentMessageId?` | `string` |
| `promptPrefix?` | `string` |
| `promptSuffix?` | `string` |
| `stream?` | `boolean` |
| `timeoutMs?` | `number` |
#### Defined in
[src/types.ts:278](https://github.com/transitive-bullshit/chatgpt-api/blob/83bb9cf/src/types.ts#L278)
[src/types.ts:3](https://github.com/transitive-bullshit/chatgpt-api/blob/531e180/src/types.ts#L3)
___
### SessionResult
### UpsertMessageFunction
Ƭ **SessionResult**: `Object`
https://chat.openapi.com/api/auth/session
Ƭ **UpsertMessageFunction**: (`message`: [`ChatMessage`](interfaces/ChatMessage.md)) => `Promise`<`void`\>
#### Type declaration
| Name | Type | Description |
| :------ | :------ | :------ |
| `accessToken` | `string` | The access token |
| `error?` | `string` \| ``null`` | If there was an error associated with this request |
| `expires` | `string` | ISO date of the expiration date of the access token |
| `user` | [`User`](modules.md#user) | Authenticated user |
▸ (`message`): `Promise`<`void`\>
#### Defined in
Upserts a chat message to a store.
[src/types.ts:8](https://github.com/transitive-bullshit/chatgpt-api/blob/83bb9cf/src/types.ts#L8)
___
### User
Ƭ **User**: `Object`
#### Type declaration
| Name | Type | Description |
| :------ | :------ | :------ |
| `email?` | `string` | Email of the user |
| `features` | `string`[] | Features the user is in |
| `groups` | `string`[] | Groups the user is in |
| `id` | `string` | ID of the user |
| `image` | `string` | Image of the user |
| `name` | `string` | Name of the user |
| `picture` | `string` | Picture of the user |
#### Defined in
[src/types.ts:30](https://github.com/transitive-bullshit/chatgpt-api/blob/83bb9cf/src/types.ts#L30)
## Functions
### browserPostEventStream
**browserPostEventStream**(`url`, `accessToken`, `body`, `timeoutMs?`): `Promise`<[`ChatError`](modules.md#chaterror) \| [`ChatResponse`](modules.md#chatresponse)\>
This function is injected into the ChatGPT webapp page using puppeteer. It
has to be fully self-contained, so we copied a few third-party sources and
included them in here.
#### Parameters
##### Parameters
| Name | Type |
| :------ | :------ |
| `url` | `string` |
| `accessToken` | `string` |
| `body` | [`ConversationJSONBody`](modules.md#conversationjsonbody) |
| `timeoutMs?` | `number` |
| `message` | [`ChatMessage`](interfaces/ChatMessage.md) |
#### Returns
`Promise`<[`ChatError`](modules.md#chaterror) \| [`ChatResponse`](modules.md#chatresponse)\>
#### Defined in
[src/utils.ts:79](https://github.com/transitive-bullshit/chatgpt-api/blob/83bb9cf/src/utils.ts#L79)
___
### defaultChromeExecutablePath
**defaultChromeExecutablePath**(): `string`
Gets the default path to chrome's executable for the current platform.
#### Returns
`string`
#### Defined in
[src/openai-auth.ts:469](https://github.com/transitive-bullshit/chatgpt-api/blob/83bb9cf/src/openai-auth.ts#L469)
___
### getBrowser
**getBrowser**(`opts?`): `Promise`<`Browser`\>
Launches a non-puppeteer instance of Chrome. Note that in my testing, I wasn't
able to use the built-in `puppeteer` version of Chromium because Cloudflare
recognizes it and blocks access.
#### Parameters
| Name | Type |
| :------ | :------ |
| `opts` | `PuppeteerLaunchOptions` & { `captchaToken?`: `string` ; `debug?`: `boolean` ; `minimize?`: `boolean` ; `nopechaKey?`: `string` ; `proxyServer?`: `string` ; `timeoutMs?`: `number` } |
#### Returns
`Promise`<`Browser`\>
#### Defined in
[src/openai-auth.ts:299](https://github.com/transitive-bullshit/chatgpt-api/blob/83bb9cf/src/openai-auth.ts#L299)
___
### getOpenAIAuth
**getOpenAIAuth**(`__namedParameters`): `Promise`<[`OpenAIAuth`](modules.md#openaiauth)\>
Bypasses OpenAI's use of Cloudflare to get the cookies required to use
ChatGPT. Uses Puppeteer with a stealth plugin under the hood.
If you pass `email` and `password`, then it will log into the account and
include a `sessionToken` in the response.
If you don't pass `email` and `password`, then it will just return a valid
`clearanceToken`.
This can be useful because `clearanceToken` expires after ~2 hours, whereas
`sessionToken` generally lasts much longer. We recommend renewing your
`clearanceToken` every hour or so and creating a new instance of `ChatGPTAPI`
with your updated credentials.
#### Parameters
| Name | Type |
| :------ | :------ |
| `__namedParameters` | `Object` |
| `__namedParameters.browser?` | `Browser` |
| `__namedParameters.captchaToken?` | `string` |
| `__namedParameters.email?` | `string` |
| `__namedParameters.executablePath?` | `string` |
| `__namedParameters.isGoogleLogin?` | `boolean` |
| `__namedParameters.isMicrosoftLogin?` | `boolean` |
| `__namedParameters.minimize?` | `boolean` |
| `__namedParameters.nopechaKey?` | `string` |
| `__namedParameters.page?` | `Page` |
| `__namedParameters.password?` | `string` |
| `__namedParameters.proxyServer?` | `string` |
| `__namedParameters.timeoutMs?` | `number` |
#### Returns
`Promise`<[`OpenAIAuth`](modules.md#openaiauth)\>
#### Defined in
[src/openai-auth.ts:50](https://github.com/transitive-bullshit/chatgpt-api/blob/83bb9cf/src/openai-auth.ts#L50)
___
### getPage
**getPage**(`browser`, `opts`): `Promise`<`Page`\>
#### Parameters
| Name | Type |
| :------ | :------ |
| `browser` | `Browser` |
| `opts` | `Object` |
| `opts.proxyServer?` | `string` |
#### Returns
`Promise`<`Page`\>
#### Defined in
[src/openai-auth.ts:262](https://github.com/transitive-bullshit/chatgpt-api/blob/83bb9cf/src/openai-auth.ts#L262)
___
### initializeNopechaExtension
**initializeNopechaExtension**(`browser`, `opts`): `Promise`<`void`\>
#### Parameters
| Name | Type |
| :------ | :------ |
| `browser` | `Browser` |
| `opts` | `Object` |
| `opts.debug?` | `boolean` |
| `opts.minimize?` | `boolean` |
| `opts.nopechaKey?` | `string` |
| `opts.proxyServer?` | `string` |
| `opts.timeoutMs?` | `number` |
#### Returns
##### Returns
`Promise`<`void`\>
#### Defined in
[src/openai-auth.ts:434](https://github.com/transitive-bullshit/chatgpt-api/blob/83bb9cf/src/openai-auth.ts#L434)
___
### isRelevantRequest
**isRelevantRequest**(`url`): `boolean`
#### Parameters
| Name | Type |
| :------ | :------ |
| `url` | `string` |
#### Returns
`boolean`
#### Defined in
[src/utils.ts:45](https://github.com/transitive-bullshit/chatgpt-api/blob/83bb9cf/src/utils.ts#L45)
___
### markdownToText
**markdownToText**(`markdown?`): `string`
#### Parameters
| Name | Type |
| :------ | :------ |
| `markdown?` | `string` |
#### Returns
`string`
#### Defined in
[src/utils.ts:18](https://github.com/transitive-bullshit/chatgpt-api/blob/83bb9cf/src/utils.ts#L18)
___
### maximizePage
**maximizePage**(`page`): `Promise`<`void`\>
#### Parameters
| Name | Type |
| :------ | :------ |
| `page` | `Page` |
#### Returns
`Promise`<`void`\>
#### Defined in
[src/utils.ts:35](https://github.com/transitive-bullshit/chatgpt-api/blob/83bb9cf/src/utils.ts#L35)
___
### minimizePage
**minimizePage**(`page`): `Promise`<`void`\>
#### Parameters
| Name | Type |
| :------ | :------ |
| `page` | `Page` |
#### Returns
`Promise`<`void`\>
#### Defined in
[src/utils.ts:25](https://github.com/transitive-bullshit/chatgpt-api/blob/83bb9cf/src/utils.ts#L25)
[src/types.ts:32](https://github.com/transitive-bullshit/chatgpt-api/blob/531e180/src/types.ts#L32)

Wyświetl plik

@ -0,0 +1,90 @@
[chatgpt](../readme.md) / [Exports](../modules.md) / openai
# Namespace: openai
## Table of contents
### Type Aliases
- [CompletionParams](openai.md#completionparams)
- [CompletionResponse](openai.md#completionresponse)
- [CompletionResponseChoices](openai.md#completionresponsechoices)
- [CompletionResponseUsage](openai.md#completionresponseusage)
## Type Aliases
### CompletionParams
Ƭ **CompletionParams**: `Object`
#### Type declaration
| Name | Type | Description |
| :------ | :------ | :------ |
| `best_of?` | `number` | Generates `best_of` completions server-side and returns the \"best\" (the one with the highest log probability per token). Results cannot be streamed. When used with `n`, `best_of` controls the number of candidate completions and `n` specifies how many to return – `best_of` must be greater than `n`. **Note:** Because this parameter generates many completions, it can quickly consume your token quota. Use carefully and ensure that you have reasonable settings for `max_tokens` and `stop`. |
| `echo?` | `boolean` | Echo back the prompt in addition to the completion |
| `frequency_penalty?` | `number` | Number between -2.0 and 2.0. Positive values penalize new tokens based on their existing frequency in the text so far, decreasing the model\'s likelihood to repeat the same line verbatim. [See more information about frequency and presence penalties.](/docs/api-reference/parameter-details) |
| `logit_bias?` | `Record`<`string`, `number`\> | Modify the likelihood of specified tokens appearing in the completion. Accepts a json object that maps tokens (specified by their token ID in the GPT tokenizer) to an associated bias value from -100 to 100. You can use this [tokenizer tool](/tokenizer?view=bpe) (which works for both GPT-2 and GPT-3) to convert text to token IDs. Mathematically, the bias is added to the logits generated by the model prior to sampling. The exact effect will vary per model, but values between -1 and 1 should decrease or increase likelihood of selection; values like -100 or 100 should result in a ban or exclusive selection of the relevant token. As an example, you can pass `{\"50256\": -100}` to prevent the <\|endoftext\|> token from being generated. |
| `logprobs?` | `number` | Include the log probabilities on the `logprobs` most likely tokens, as well the chosen tokens. For example, if `logprobs` is 5, the API will return a list of the 5 most likely tokens. The API will always return the `logprob` of the sampled token, so there may be up to `logprobs+1` elements in the response. The maximum value for `logprobs` is 5. If you need more than this, please contact us through our [Help center](https://help.openai.com) and describe your use case. |
| `max_tokens?` | `number` | The maximum number of tokens to generate in the completion. The token count of your prompt plus `max_tokens` cannot exceed the model\'s context length. Most models have a context length of 2048 tokens (except for the newest models, which support 4096). |
| `model` | `string` | ID of the model to use. |
| `presence_penalty?` | `number` | Number between -2.0 and 2.0. Positive values penalize new tokens based on whether they appear in the text so far, increasing the model\'s likelihood to talk about new topics. [See more information about frequency and presence penalties.](/docs/api-reference/parameter-details) |
| `prompt` | `string` | The string prompt to generate a completion for. |
| `stop?` | `string`[] | Up to 4 sequences where the API will stop generating further tokens. The returned text will not contain the stop sequence. |
| `suffix?` | `string` | The suffix that comes after a completion of inserted text. |
| `temperature?` | `number` | What [sampling temperature](https://towardsdatascience.com/how-to-sample-from-language-models-682bceb97277) to use. Higher values means the model will take more risks. Try 0.9 for more creative applications, and 0 (argmax sampling) for ones with a well-defined answer. We generally recommend altering this or `top_p` but not both. |
| `top_p?` | `number` | An alternative to sampling with temperature, called nucleus sampling, where the model considers the results of the tokens with top_p probability mass. So 0.1 means only the tokens comprising the top 10% probability mass are considered. We generally recommend altering this or `temperature` but not both. |
| `user?` | `string` | A unique identifier representing your end-user, which will help OpenAI to monitor and detect abuse. [Learn more](/docs/usage-policies/end-user-ids). |
#### Defined in
[src/types.ts:35](https://github.com/transitive-bullshit/chatgpt-api/blob/531e180/src/types.ts#L35)
___
### CompletionResponse
Ƭ **CompletionResponse**: `Object`
#### Type declaration
| Name | Type |
| :------ | :------ |
| `choices` | [`CompletionResponseChoices`](openai.md#completionresponsechoices) |
| `created` | `number` |
| `id` | `string` |
| `model` | `string` |
| `object` | `string` |
| `usage?` | [`CompletionResponseUsage`](openai.md#completionresponseusage) |
#### Defined in
[src/types.ts:117](https://github.com/transitive-bullshit/chatgpt-api/blob/531e180/src/types.ts#L117)
___
### CompletionResponseChoices
Ƭ **CompletionResponseChoices**: { `finish_reason?`: `string` ; `index?`: `number` ; `logprobs?`: { `text_offset?`: `number`[] ; `token_logprobs?`: `number`[] ; `tokens?`: `string`[] ; `top_logprobs?`: `object`[] } \| ``null`` ; `text?`: `string` }[]
#### Defined in
[src/types.ts:126](https://github.com/transitive-bullshit/chatgpt-api/blob/531e180/src/types.ts#L126)
___
### CompletionResponseUsage
Ƭ **CompletionResponseUsage**: `Object`
#### Type declaration
| Name | Type |
| :------ | :------ |
| `completion_tokens` | `number` |
| `prompt_tokens` | `number` |
| `total_tokens` | `number` |
#### Defined in
[src/types.ts:138](https://github.com/transitive-bullshit/chatgpt-api/blob/531e180/src/types.ts#L138)

Wyświetl plik

@ -1,31 +1,21 @@
chatgpt / [Exports](modules.md)
# Update January 12, 2023 <!-- omit in toc -->
# Update February 1, 2023 <!-- omit in toc -->
This package allows you to access ChatGPT from Node.js – even with OpenAI's Cloudflare protections. It uses a **fully automated browser-based solution**, which uses Puppeteer and CAPTCHA solvers under the hood. 🔥
This package no longer requires any browser hacks – **it is now using the official OpenAI API** with a leaked, unofficial ChatGPT model. 🔥
```ts
import { ChatGPTAPIBrowser } from 'chatgpt'
import { ChatGPTAPI } from 'chatgpt'
const api = new ChatGPTAPIBrowser({
email: process.env.OPENAI_EMAIL,
password: process.env.OPENAI_PASSWORD
const api = new ChatGPTAPI({
apiKey: process.env.OPENAI_API_KEY
})
await api.initSession()
const result = await api.sendMessage('Hello World!')
console.log(result.response)
const res = await api.sendMessage('Hello World!')
console.log(res.text)
```
This solution is not lightweight, but it does work a lot more consistently than the previous REST API-based approach. For example, I'm currently using this approach to automate N concurrent OpenAI accounts for my [Twitter bot](https://github.com/transitive-bullshit/chatgpt-twitter-bot). 😂
We recently added support for CAPTCHA automation using either [nopecha](https://nopecha.com/) or [2captcha](https://2captcha.com). Keep in mind that this package will be updated to use the official API as soon as it's released, so things should get much easier over time. 💪
There are some restrictions to be aware of, however:
- Cloudflare doesn't like requests coming from data center IPs, so you'll likely either need to run it locally or use a residential IP proxy.
- You should only have one `sendMessage` request at a time per browser instance and OpenAI account.
- It can be difficult to reliably process `sendMessage` requests after awhile. My best advice for handling this is to wrap your usage in some basic retry logic as well as a daemon which restarts your Node.js process every hour or so. This is unfortunately a by-product of there not being an official API, so keep that in mind before using this in production.
The updated solution is significantly more lightweight and robust compared with previous versions.
If you run into any issues, we do have a pretty active [Discord](https://discord.gg/v9gERj825w) with a bunch of ChatGPT hackers from the Node.js & Python communities.
@ -51,10 +41,6 @@ Thanks && cheers,
- [Usage](#usage)
- [Docs](#docs)
- [Demos](#demos)
- [Authentication](#authentication)
- [CAPTCHAs](#captchas)
- [Using Proxies](#using-proxies)
- [Restrictions](#restrictions)
- [Projects](#projects)
- [Compatibility](#compatibility)
- [Credits](#credits)
@ -69,91 +55,61 @@ You can use it to start building projects powered by ChatGPT like chatbots, webs
## Install
```bash
npm install chatgpt puppeteer
npm install chatgpt
```
`puppeteer` is an optional peer dependency used to automate bypassing the Cloudflare protections via `getOpenAIAuth`. The main API wrapper uses `fetch` directly.
## Usage
Sign up for an [OpenAI API key](https://platform.openai.com/overview) and store it in your environment.
```ts
import { ChatGPTAPIBrowser } from 'chatgpt'
import { ChatGPTAPI } from 'chatgpt'
async function example() {
// use puppeteer to bypass cloudflare (headful because of captchas)
const api = new ChatGPTAPIBrowser({
email: process.env.OPENAI_EMAIL,
password: process.env.OPENAI_PASSWORD
const api = new ChatGPTAPI({
apiKey: process.env.OPENAI_API_KEY
})
await api.initSession()
const result = await api.sendMessage('Hello World!')
console.log(result.response)
const res = await api.sendMessage('Hello World!')
console.log(res.text)
}
```
<details>
<summary>Or, if you want to use the REST-based version: (not advised at this time)</summary>
If you want to track the conversation, use the `conversationId` and `id` in the result object, and pass them to `sendMessage` as `conversationId` and `parentMessageId` respectively.
```ts
import { ChatGPTAPI, getOpenAIAuth } from 'chatgpt'
async function example() {
// use puppeteer to bypass cloudflare (headful because of captchas)
const openAIAuth = await getOpenAIAuth({
email: process.env.OPENAI_EMAIL,
password: process.env.OPENAI_PASSWORD
})
const api = new ChatGPTAPI({ ...openAIAuth })
await api.initSession()
// send a message and wait for the response
const result = await api.sendMessage('Write a python version of bubble sort.')
// result.response is a markdown-formatted string
console.log(result.response)
}
```
</details>
ChatGPT responses are formatted as markdown by default. If you want to work with plaintext instead, you can use:
```ts
const api = new ChatGPTAPIBrowser({ email, password, markdown: false })
```
If you want to track the conversation, use the `conversationId` and `messageId` in the result object, and pass them to `sendMessage` as `conversationId` and `parentMessageId` respectively.
```ts
const api = new ChatGPTAPIBrowser({ email, password })
await api.initSession()
const api = new ChatGPTAPI({ apiKey: process.env.OPENAI_API_KEY })
// send a message and wait for the response
let res = await api.sendMessage('What is OpenAI?')
console.log(res.response)
console.log(res.text)
// send a follow-up
res = await api.sendMessage('Can you expand on that?', {
conversationId: res.conversationId,
parentMessageId: res.messageId
parentMessageId: res.id
})
console.log(res.response)
console.log(res.text)
// send another follow-up
// send a follow-up
res = await api.sendMessage('What were we talking about?', {
conversationId: res.conversationId,
parentMessageId: res.messageId
parentMessageId: res.id
})
console.log(res.response)
console.log(res.text)
```
Sometimes, ChatGPT will hang for an extended period of time before beginning to respond. This may be due to rate limiting or it may be due to OpenAI's servers being overloaded.
You can add streaming via the `onProgress` handler:
To mitigate these issues, you can add a timeout like this:
```ts
// timeout after 2 minutes (which will also abort the underlying HTTP request)
const res = await api.sendMessage('Write me a 500 word essay on frogs.', {
onProgress: (partialResponse) => console.log(partialResponse)
})
```
You can add a timeout using the `timeoutMs` option:
```ts
// timeout after 2 minutes (which will also abort the underlying HTTP request)
@ -168,18 +124,12 @@ const response = await api.sendMessage('this is a timeout test', {
```js
async function example() {
// To use ESM in CommonJS, you can use a dynamic import
const { ChatGPTAPI, getOpenAIAuth } = await import('chatgpt')
const { ChatGPTAPI } = await import('chatgpt')
const openAIAuth = await getOpenAIAuth({
email: process.env.OPENAI_EMAIL,
password: process.env.OPENAI_PASSWORD
})
const api = new ChatGPTAPI({ apiKey: process.env.OPENAI_API_KEY })
const api = new ChatGPTAPI({ ...openAIAuth })
await api.initSession()
const result = await api.sendMessage('Hello World!')
console.log(result)
const res = await api.sendMessage('Hello World!')
console.log(res.text)
}
```
@ -187,7 +137,7 @@ async function example() {
### Docs
See the [auto-generated docs](./docs/classes/ChatGPTAPI.md) for more info on methods and parameters. Here are the [docs](./docs/classes/ChatGPTAPIBrowser.md) for the browser-based version.
See the [auto-generated docs](./docs/classes/ChatGPTAPI.md) for more info on methods and parameters. Here are the [docs](./docs/classes/ChatGPTAPI.md) for the browser-based version.
### Demos
@ -195,7 +145,7 @@ To run the included demos:
1. clone repo
2. install node deps
3. set `OPENAI_EMAIL` and `OPENAI_PASSWORD` in .env
3. set `OPENAI_API_KEY` in .env
A [basic demo](./demos/demo.ts) is included for testing purposes:
@ -203,12 +153,6 @@ A [basic demo](./demos/demo.ts) is included for testing purposes:
npx tsx demos/demo.ts
```
A [google auth demo](./demos/demo-google-auth.ts):
```bash
npx tsx demos/demo-google-auth.ts
```
A [demo showing on progress handler](./demos/demo-on-progress.ts):
```bash
@ -223,93 +167,15 @@ A [conversation demo](./demos/demo-conversation.ts):
npx tsx demos/demo-conversation.ts
```
### Authentication
Lastly, a [persitence demo](./demos/demo-persistence.ts) shows how to store messages in Redis for persistence:
The authentication section relates to the REST-based version (using `getOpenAIAuth` + `ChatGPTAPI`). The browser-based solution, `ChatGPTAPIBrowser`, takes care of all the authentication for you.
On December 11, 2022, OpenAI added some additional Cloudflare protections which make it more difficult to access the unofficial API.
You'll need a valid OpenAI "session token" and Cloudflare "clearance token" in order to use the API.
We've provided an automated, Puppeteer-based solution `getOpenAIAuth` to fetch these for you, but you may still run into cases where you have to manually pass the CAPTCHA. We're working on a solution to automate this further.
You can also get these tokens manually, but keep in mind that the `clearanceToken` only lasts for max 2 hours.
<details>
<summary>Getting tokens manually</summary>
To get session token manually:
1. Go to https://chat.openai.com/chat and log in or sign up.
2. Open dev tools.
3. Open `Application` > `Cookies`.
![ChatGPT cookies](./media/session-token.png)
4. Copy the value for `__Secure-next-auth.session-token` and save it to your environment. This will be your `sessionToken`.
5. Copy the value for `cf_clearance` and save it to your environment. This will be your `clearanceToken`.
6. Copy the value of the `user-agent` header from any request in your `Network` tab, or copy the result of `navigator.userAgent` command on `Console` tab. This will be your `userAgent`.
Pass `sessionToken`, `clearanceToken`, and `userAgent` to the `ChatGPTAPI` constructor.
</details>
> **Note**
> This package will switch to using the official API once it's released, which will make this process much simpler.
### CAPTCHAs
The browser portions of this package use Puppeteer to automate as much as possible, including solving all CAPTCHAs. 🔥
Basic Cloudflare CAPTCHAs are handled by default, but if you want to automate the email + password Recaptchas, you'll need to sign up for one of these paid providers:
- [nopecha](https://nopecha.com/) - Uses AI to solve CAPTCHAS
- Faster and cheaper
- Set the `NOPECHA_KEY` env var to your nopecha API key
- [Demo video](https://user-images.githubusercontent.com/552829/208235991-de4890f2-e7ba-4b42-bf55-4fcd792d4b19.mp4) of nopecha solving the login Recaptcha (41 seconds)
- [2captcha](https://2captcha.com) - Uses real people to solve CAPTCHAS
- More well-known solution that's been around longer
- Set the `CAPTCHA_TOKEN` env var to your 2captcha API token
Alternatively, if your OpenAI account uses Google Auth, you shouldn't encounter any of the more complicated Recaptchas — and can avoid using these third-party providers. To use Google auth, make sure your OpenAI account is using Google and then set `isGoogleLogin` to `true` whenever you're passing your `email` and `password`. For example:
```ts
const api = new ChatGPTAPIBrowser({
email: process.env.OPENAI_EMAIL,
password: process.env.OPENAI_PASSWORD,
isGoogleLogin: true
})
```bash
npx tsx demos/demo-conversation.ts
```
### Using Proxies
Any [keyv adaptor](https://github.com/jaredwray/keyv) is supported for persistence, and there are overrides if you'd like to use a different way of storing / retrieving messages.
The browser implementation supports setting a proxy server. This is useful if you're running into rate limiting issues or if you want to use a proxy to hide your IP address.
To use a proxy, pass the `proxyServer` option to the `ChatGPTAPIBrowser` constructor, or simply set the `PROXY_SERVER` env var. For more information on the format, see [here](https://www.chromium.org/developers/design-documents/network-settings).
```ts
const api = new ChatGPTAPIBrowser({
email: process.env.OPENAI_EMAIL,
password: process.env.OPENAI_PASSWORD,
proxyServer: '<ip>:<port>'
})
```
You can also set the `PROXY_VALIDATE_IP` env var to your proxy's IP address. This will be used to validate that the proxy is working correctly, and will throw an error if it's not.
### Restrictions
These restrictions are for the `getOpenAIAuth` + `ChatGPTAPI` solution, which uses the unofficial API. The browser-based solution, `ChatGPTAPIBrowser`, generally doesn't have any of these restrictions.
**Please read carefully**
- You must use `node >= 18` at the moment. I'm using `v19.2.0` in my testing.
- Cloudflare `cf_clearance` **tokens expire after 2 hours**, so right now we recommend that you refresh your `cf_clearance` token every hour or so.
- Your `user-agent` and `IP address` **must match** from the real browser window you're logged in with to the one you're using for `ChatGPTAPI`.
- This means that you currently can't log in with your laptop and then run the bot on a server or proxy somewhere.
- Cloudflare will still sometimes ask you to complete a CAPTCHA, so you may need to keep an eye on it and manually resolve the CAPTCHA.
- You should not be using this account while the bot is using it, because that browser window may refresh one of your tokens and invalidate the bot's session.
> **Note**
> Prior to v1.0.0, this package used a headless browser via [Playwright](https://playwright.dev/) to automate the web UI. Here are the [docs for the initial browser version](https://github.com/transitive-bullshit/chatgpt-api/tree/v0.4.2).
Note that persisting message is very important for remembering the context of previous conversations.
## Projects
@ -382,11 +248,11 @@ If you create a cool integration, feel free to open a PR and add it to the list.
## Compatibility
This package is ESM-only. It supports:
- Node.js >= 18
- Node.js 17, 16, and 14 were supported in earlier versions, but OpenAI's Cloudflare update caused a bug with `undici` on v17 and v16 that needs investigation. So for now, use `node >= 18`
- We recommend against using `chatgpt` from client-side browser code because it would expose your private session token
- This package is ESM-only.
- This package supports `node >= 14`.
- This module assumes that `fetch` is installed.
- In `node >= 18`, it's installed by default.
- In `node < 18`, you need to install a polyfill like `unfetch/polyfill`
- If you want to build a website using `chatgpt`, we recommend using it only from your backend API
## Credits

230
readme.md
Wyświetl plik

@ -1,29 +1,19 @@
# Update January 12, 2023 <!-- omit in toc -->
# Update February 1, 2023 <!-- omit in toc -->
This package allows you to access ChatGPT from Node.js – even with OpenAI's Cloudflare protections. It uses a **fully automated browser-based solution**, which uses Puppeteer and CAPTCHA solvers under the hood. 🔥
This package no longer requires any browser hacks – **it is now using the official OpenAI API** with a leaked, unofficial ChatGPT model. 🔥
```ts
import { ChatGPTAPIBrowser } from 'chatgpt'
import { ChatGPTAPI } from 'chatgpt'
const api = new ChatGPTAPIBrowser({
email: process.env.OPENAI_EMAIL,
password: process.env.OPENAI_PASSWORD
const api = new ChatGPTAPI({
apiKey: process.env.OPENAI_API_KEY
})
await api.initSession()
const result = await api.sendMessage('Hello World!')
console.log(result.response)
const res = await api.sendMessage('Hello World!')
console.log(res.text)
```
This solution is not lightweight, but it does work a lot more consistently than the previous REST API-based approach. For example, I'm currently using this approach to automate N concurrent OpenAI accounts for my [Twitter bot](https://github.com/transitive-bullshit/chatgpt-twitter-bot). 😂
We recently added support for CAPTCHA automation using either [nopecha](https://nopecha.com/) or [2captcha](https://2captcha.com). Keep in mind that this package will be updated to use the official API as soon as it's released, so things should get much easier over time. 💪
There are some restrictions to be aware of, however:
- Cloudflare doesn't like requests coming from data center IPs, so you'll likely either need to run it locally or use a residential IP proxy.
- You should only have one `sendMessage` request at a time per browser instance and OpenAI account.
- It can be difficult to reliably process `sendMessage` requests after awhile. My best advice for handling this is to wrap your usage in some basic retry logic as well as a daemon which restarts your Node.js process every hour or so. This is unfortunately a by-product of there not being an official API, so keep that in mind before using this in production.
The updated solution is significantly more lightweight and robust compared with previous versions.
If you run into any issues, we do have a pretty active [Discord](https://discord.gg/v9gERj825w) with a bunch of ChatGPT hackers from the Node.js & Python communities.
@ -49,10 +39,6 @@ Thanks && cheers,
- [Usage](#usage)
- [Docs](#docs)
- [Demos](#demos)
- [Authentication](#authentication)
- [CAPTCHAs](#captchas)
- [Using Proxies](#using-proxies)
- [Restrictions](#restrictions)
- [Projects](#projects)
- [Compatibility](#compatibility)
- [Credits](#credits)
@ -67,91 +53,61 @@ You can use it to start building projects powered by ChatGPT like chatbots, webs
## Install
```bash
npm install chatgpt puppeteer
npm install chatgpt
```
`puppeteer` is an optional peer dependency used to automate bypassing the Cloudflare protections via `getOpenAIAuth`. The main API wrapper uses `fetch` directly.
## Usage
Sign up for an [OpenAI API key](https://platform.openai.com/overview) and store it in your environment.
```ts
import { ChatGPTAPIBrowser } from 'chatgpt'
import { ChatGPTAPI } from 'chatgpt'
async function example() {
// use puppeteer to bypass cloudflare (headful because of captchas)
const api = new ChatGPTAPIBrowser({
email: process.env.OPENAI_EMAIL,
password: process.env.OPENAI_PASSWORD
const api = new ChatGPTAPI({
apiKey: process.env.OPENAI_API_KEY
})
await api.initSession()
const result = await api.sendMessage('Hello World!')
console.log(result.response)
const res = await api.sendMessage('Hello World!')
console.log(res.text)
}
```
<details>
<summary>Or, if you want to use the REST-based version: (not advised at this time)</summary>
If you want to track the conversation, use the `conversationId` and `id` in the result object, and pass them to `sendMessage` as `conversationId` and `parentMessageId` respectively.
```ts
import { ChatGPTAPI, getOpenAIAuth } from 'chatgpt'
async function example() {
// use puppeteer to bypass cloudflare (headful because of captchas)
const openAIAuth = await getOpenAIAuth({
email: process.env.OPENAI_EMAIL,
password: process.env.OPENAI_PASSWORD
})
const api = new ChatGPTAPI({ ...openAIAuth })
await api.initSession()
// send a message and wait for the response
const result = await api.sendMessage('Write a python version of bubble sort.')
// result.response is a markdown-formatted string
console.log(result.response)
}
```
</details>
ChatGPT responses are formatted as markdown by default. If you want to work with plaintext instead, you can use:
```ts
const api = new ChatGPTAPIBrowser({ email, password, markdown: false })
```
If you want to track the conversation, use the `conversationId` and `messageId` in the result object, and pass them to `sendMessage` as `conversationId` and `parentMessageId` respectively.
```ts
const api = new ChatGPTAPIBrowser({ email, password })
await api.initSession()
const api = new ChatGPTAPI({ apiKey: process.env.OPENAI_API_KEY })
// send a message and wait for the response
let res = await api.sendMessage('What is OpenAI?')
console.log(res.response)
console.log(res.text)
// send a follow-up
res = await api.sendMessage('Can you expand on that?', {
conversationId: res.conversationId,
parentMessageId: res.messageId
parentMessageId: res.id
})
console.log(res.response)
console.log(res.text)
// send another follow-up
// send a follow-up
res = await api.sendMessage('What were we talking about?', {
conversationId: res.conversationId,
parentMessageId: res.messageId
parentMessageId: res.id
})
console.log(res.response)
console.log(res.text)
```
Sometimes, ChatGPT will hang for an extended period of time before beginning to respond. This may be due to rate limiting or it may be due to OpenAI's servers being overloaded.
You can add streaming via the `onProgress` handler:
To mitigate these issues, you can add a timeout like this:
```ts
// timeout after 2 minutes (which will also abort the underlying HTTP request)
const res = await api.sendMessage('Write me a 500 word essay on frogs.', {
onProgress: (partialResponse) => console.log(partialResponse)
})
```
You can add a timeout using the `timeoutMs` option:
```ts
// timeout after 2 minutes (which will also abort the underlying HTTP request)
@ -166,18 +122,12 @@ const response = await api.sendMessage('this is a timeout test', {
```js
async function example() {
// To use ESM in CommonJS, you can use a dynamic import
const { ChatGPTAPI, getOpenAIAuth } = await import('chatgpt')
const { ChatGPTAPI } = await import('chatgpt')
const openAIAuth = await getOpenAIAuth({
email: process.env.OPENAI_EMAIL,
password: process.env.OPENAI_PASSWORD
})
const api = new ChatGPTAPI({ apiKey: process.env.OPENAI_API_KEY })
const api = new ChatGPTAPI({ ...openAIAuth })
await api.initSession()
const result = await api.sendMessage('Hello World!')
console.log(result)
const res = await api.sendMessage('Hello World!')
console.log(res.text)
}
```
@ -185,7 +135,7 @@ async function example() {
### Docs
See the [auto-generated docs](./docs/classes/ChatGPTAPI.md) for more info on methods and parameters. Here are the [docs](./docs/classes/ChatGPTAPIBrowser.md) for the browser-based version.
See the [auto-generated docs](./docs/classes/ChatGPTAPI.md) for more info on methods and parameters. Here are the [docs](./docs/classes/ChatGPTAPI.md) for the browser-based version.
### Demos
@ -193,7 +143,7 @@ To run the included demos:
1. clone repo
2. install node deps
3. set `OPENAI_EMAIL` and `OPENAI_PASSWORD` in .env
3. set `OPENAI_API_KEY` in .env
A [basic demo](./demos/demo.ts) is included for testing purposes:
@ -201,12 +151,6 @@ A [basic demo](./demos/demo.ts) is included for testing purposes:
npx tsx demos/demo.ts
```
A [google auth demo](./demos/demo-google-auth.ts):
```bash
npx tsx demos/demo-google-auth.ts
```
A [demo showing on progress handler](./demos/demo-on-progress.ts):
```bash
@ -221,93 +165,15 @@ A [conversation demo](./demos/demo-conversation.ts):
npx tsx demos/demo-conversation.ts
```
### Authentication
Lastly, a [persitence demo](./demos/demo-persistence.ts) shows how to store messages in Redis for persistence:
The authentication section relates to the REST-based version (using `getOpenAIAuth` + `ChatGPTAPI`). The browser-based solution, `ChatGPTAPIBrowser`, takes care of all the authentication for you.
On December 11, 2022, OpenAI added some additional Cloudflare protections which make it more difficult to access the unofficial API.
You'll need a valid OpenAI "session token" and Cloudflare "clearance token" in order to use the API.
We've provided an automated, Puppeteer-based solution `getOpenAIAuth` to fetch these for you, but you may still run into cases where you have to manually pass the CAPTCHA. We're working on a solution to automate this further.
You can also get these tokens manually, but keep in mind that the `clearanceToken` only lasts for max 2 hours.
<details>
<summary>Getting tokens manually</summary>
To get session token manually:
1. Go to https://chat.openai.com/chat and log in or sign up.
2. Open dev tools.
3. Open `Application` > `Cookies`.
![ChatGPT cookies](./media/session-token.png)
4. Copy the value for `__Secure-next-auth.session-token` and save it to your environment. This will be your `sessionToken`.
5. Copy the value for `cf_clearance` and save it to your environment. This will be your `clearanceToken`.
6. Copy the value of the `user-agent` header from any request in your `Network` tab, or copy the result of `navigator.userAgent` command on `Console` tab. This will be your `userAgent`.
Pass `sessionToken`, `clearanceToken`, and `userAgent` to the `ChatGPTAPI` constructor.
</details>
> **Note**
> This package will switch to using the official API once it's released, which will make this process much simpler.
### CAPTCHAs
The browser portions of this package use Puppeteer to automate as much as possible, including solving all CAPTCHAs. 🔥
Basic Cloudflare CAPTCHAs are handled by default, but if you want to automate the email + password Recaptchas, you'll need to sign up for one of these paid providers:
- [nopecha](https://nopecha.com/) - Uses AI to solve CAPTCHAS
- Faster and cheaper
- Set the `NOPECHA_KEY` env var to your nopecha API key
- [Demo video](https://user-images.githubusercontent.com/552829/208235991-de4890f2-e7ba-4b42-bf55-4fcd792d4b19.mp4) of nopecha solving the login Recaptcha (41 seconds)
- [2captcha](https://2captcha.com) - Uses real people to solve CAPTCHAS
- More well-known solution that's been around longer
- Set the `CAPTCHA_TOKEN` env var to your 2captcha API token
Alternatively, if your OpenAI account uses Google Auth, you shouldn't encounter any of the more complicated Recaptchas — and can avoid using these third-party providers. To use Google auth, make sure your OpenAI account is using Google and then set `isGoogleLogin` to `true` whenever you're passing your `email` and `password`. For example:
```ts
const api = new ChatGPTAPIBrowser({
email: process.env.OPENAI_EMAIL,
password: process.env.OPENAI_PASSWORD,
isGoogleLogin: true
})
```bash
npx tsx demos/demo-conversation.ts
```
### Using Proxies
Any [keyv adaptor](https://github.com/jaredwray/keyv) is supported for persistence, and there are overrides if you'd like to use a different way of storing / retrieving messages.
The browser implementation supports setting a proxy server. This is useful if you're running into rate limiting issues or if you want to use a proxy to hide your IP address.
To use a proxy, pass the `proxyServer` option to the `ChatGPTAPIBrowser` constructor, or simply set the `PROXY_SERVER` env var. For more information on the format, see [here](https://www.chromium.org/developers/design-documents/network-settings).
```ts
const api = new ChatGPTAPIBrowser({
email: process.env.OPENAI_EMAIL,
password: process.env.OPENAI_PASSWORD,
proxyServer: '<ip>:<port>'
})
```
You can also set the `PROXY_VALIDATE_IP` env var to your proxy's IP address. This will be used to validate that the proxy is working correctly, and will throw an error if it's not.
### Restrictions
These restrictions are for the `getOpenAIAuth` + `ChatGPTAPI` solution, which uses the unofficial API. The browser-based solution, `ChatGPTAPIBrowser`, generally doesn't have any of these restrictions.
**Please read carefully**
- You must use `node >= 18` at the moment. I'm using `v19.2.0` in my testing.
- Cloudflare `cf_clearance` **tokens expire after 2 hours**, so right now we recommend that you refresh your `cf_clearance` token every hour or so.
- Your `user-agent` and `IP address` **must match** from the real browser window you're logged in with to the one you're using for `ChatGPTAPI`.
- This means that you currently can't log in with your laptop and then run the bot on a server or proxy somewhere.
- Cloudflare will still sometimes ask you to complete a CAPTCHA, so you may need to keep an eye on it and manually resolve the CAPTCHA.
- You should not be using this account while the bot is using it, because that browser window may refresh one of your tokens and invalidate the bot's session.
> **Note**
> Prior to v1.0.0, this package used a headless browser via [Playwright](https://playwright.dev/) to automate the web UI. Here are the [docs for the initial browser version](https://github.com/transitive-bullshit/chatgpt-api/tree/v0.4.2).
Note that persisting message is very important for remembering the context of previous conversations.
## Projects
@ -380,11 +246,11 @@ If you create a cool integration, feel free to open a PR and add it to the list.
## Compatibility
This package is ESM-only. It supports:
- Node.js >= 18
- Node.js 17, 16, and 14 were supported in earlier versions, but OpenAI's Cloudflare update caused a bug with `undici` on v17 and v16 that needs investigation. So for now, use `node >= 18`
- We recommend against using `chatgpt` from client-side browser code because it would expose your private session token
- This package is ESM-only.
- This package supports `node >= 14`.
- This module assumes that `fetch` is installed.
- In `node >= 18`, it's installed by default.
- In `node < 18`, you need to install a polyfill like `unfetch/polyfill`
- If you want to build a website using `chatgpt`, we recommend using it only from your backend API
## Credits