Commit eb11acd2 authored by Travis Fischer's avatar Travis Fischer

feat: convert from browser to REST API

parent acf5261b
# ------------------------------------------------------------------------------
# This is an example .env file.
#
# All of these environment vars must be defined either in your environment or in
# a local .env file in order to run the demo for this project.
# ------------------------------------------------------------------------------
# -----------------------------------------------------------------------------
# ChatGPT
# -----------------------------------------------------------------------------
# see the readme for how to find this
SESSION_TOKEN=
......@@ -10,53 +10,53 @@
### Methods
- [close](ChatGPTAPI.md#close)
- [getIsSignedIn](ChatGPTAPI.md#getissignedin)
- [getLastMessage](ChatGPTAPI.md#getlastmessage)
- [getMessages](ChatGPTAPI.md#getmessages)
- [getPrompts](ChatGPTAPI.md#getprompts)
- [init](ChatGPTAPI.md#init)
- [ensureAuth](ChatGPTAPI.md#ensureauth)
- [getIsAuthenticated](ChatGPTAPI.md#getisauthenticated)
- [refreshAccessToken](ChatGPTAPI.md#refreshaccesstoken)
- [sendMessage](ChatGPTAPI.md#sendmessage)
## Constructors
### constructor
**new ChatGPTAPI**(`opts?`)
**new ChatGPTAPI**(`opts`)
Creates a new client wrapper around the unofficial ChatGPT REST API.
#### Parameters
| Name | Type | Description |
| :------ | :------ | :------ |
| `opts` | `Object` | - |
| `opts.chatUrl?` | `string` | **`Default Value`** `'https://chat.openai.com/'` * |
| `opts.headless?` | `boolean` | **`Default Value`** `false` * |
| `opts.apiBaseUrl?` | `string` | **`Default Value`** `'https://chat.openai.com/api'` * |
| `opts.backendApiBaseUrl?` | `string` | **`Default Value`** `'https://chat.openai.com/backend-api'` * |
| `opts.markdown?` | `boolean` | **`Default Value`** `true` * |
| `opts.userDataDir?` | `string` | **`Default Value`** `'/tmp/chatgpt'` * |
| `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/107.0.0.0 Safari/537.36'` * |
#### Defined in
[chatgpt-api.ts:20](https://github.com/transitive-bullshit/chatgpt-api/blob/ddd9545/src/chatgpt-api.ts#L20)
[chatgpt-api.ts:29](https://github.com/transitive-bullshit/chatgpt-api/blob/549e9b4/src/chatgpt-api.ts#L29)
## Methods
### close
### ensureAuth
**close**(): `Promise`<`void`\>
**ensureAuth**(): `Promise`<`string`\>
#### Returns
`Promise`<`void`\>
`Promise`<`string`\>
#### Defined in
[chatgpt-api.ts:186](https://github.com/transitive-bullshit/chatgpt-api/blob/ddd9545/src/chatgpt-api.ts#L186)
[chatgpt-api.ts:72](https://github.com/transitive-bullshit/chatgpt-api/blob/549e9b4/src/chatgpt-api.ts#L72)
___
### getIsSignedIn
### getIsAuthenticated
**getIsSignedIn**(): `Promise`<`boolean`\>
**getIsAuthenticated**(): `Promise`<`boolean`\>
#### Returns
......@@ -64,13 +64,13 @@ ___
#### Defined in
[chatgpt-api.ts:94](https://github.com/transitive-bullshit/chatgpt-api/blob/ddd9545/src/chatgpt-api.ts#L94)
[chatgpt-api.ts:63](https://github.com/transitive-bullshit/chatgpt-api/blob/549e9b4/src/chatgpt-api.ts#L63)
___
### getLastMessage
### refreshAccessToken
**getLastMessage**(): `Promise`<`string`\>
**refreshAccessToken**(): `Promise`<`string`\>
#### Returns
......@@ -78,68 +78,25 @@ ___
#### Defined in
[chatgpt-api.ts:104](https://github.com/transitive-bullshit/chatgpt-api/blob/ddd9545/src/chatgpt-api.ts#L104)
___
### getMessages
**getMessages**(): `Promise`<`string`[]\>
#### Returns
`Promise`<`string`[]\>
#### Defined in
[chatgpt-api.ts:124](https://github.com/transitive-bullshit/chatgpt-api/blob/ddd9545/src/chatgpt-api.ts#L124)
___
### getPrompts
**getPrompts**(): `Promise`<`string`[]\>
#### Returns
`Promise`<`string`[]\>
#### Defined in
[chatgpt-api.ts:114](https://github.com/transitive-bullshit/chatgpt-api/blob/ddd9545/src/chatgpt-api.ts#L114)
___
### init
**init**(`opts?`): `Promise`<`Page`\>
#### Parameters
| Name | Type |
| :------ | :------ |
| `opts` | `Object` |
| `opts.auth?` | ``"blocking"`` \| ``"eager"`` |
#### Returns
`Promise`<`Page`\>
#### Defined in
[chatgpt-api.ts:48](https://github.com/transitive-bullshit/chatgpt-api/blob/ddd9545/src/chatgpt-api.ts#L48)
[chatgpt-api.ts:163](https://github.com/transitive-bullshit/chatgpt-api/blob/549e9b4/src/chatgpt-api.ts#L163)
___
### sendMessage
**sendMessage**(`message`): `Promise`<`string`\>
**sendMessage**(`message`, `opts?`): `Promise`<`string`\>
Sends a message to ChatGPT, waits for the response to resolve, and returns
the response.
#### Parameters
| Name | Type |
| :------ | :------ |
| `message` | `string` |
| Name | Type | Description |
| :------ | :------ | :------ |
| `message` | `string` | The plaintext message to send. |
| `opts` | `Object` | - |
| `opts.converstationId?` | `string` | - |
| `opts.onProgress?` | (`partialResponse`: `string`) => `void` | - |
#### Returns
......@@ -147,4 +104,4 @@ ___
#### Defined in
[chatgpt-api.ts:162](https://github.com/transitive-bullshit/chatgpt-api/blob/ddd9545/src/chatgpt-api.ts#L162)
[chatgpt-api.ts:84](https://github.com/transitive-bullshit/chatgpt-api/blob/549e9b4/src/chatgpt-api.ts#L84)
......@@ -7,3 +7,386 @@
### Classes
- [ChatGPTAPI](classes/ChatGPTAPI.md)
### Type Aliases
- [AvailableModerationModels](modules.md#availablemoderationmodels)
- [ContentType](modules.md#contenttype)
- [ConversationJSONBody](modules.md#conversationjsonbody)
- [ConversationResponseEvent](modules.md#conversationresponseevent)
- [Message](modules.md#message)
- [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)
- [Prompt](modules.md#prompt)
- [PromptContent](modules.md#promptcontent)
- [Role](modules.md#role)
- [SessionResult](modules.md#sessionresult)
- [User](modules.md#user)
### Functions
- [markdownToText](modules.md#markdowntotext)
## Type Aliases
### AvailableModerationModels
Ƭ **AvailableModerationModels**: ``"text-moderation-playground"``
#### Defined in
[types.ts:104](https://github.com/transitive-bullshit/chatgpt-api/blob/549e9b4/src/types.ts#L104)
___
### ContentType
Ƭ **ContentType**: ``"text"``
#### Defined in
[types.ts:1](https://github.com/transitive-bullshit/chatgpt-api/blob/549e9b4/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
[types.ts:129](https://github.com/transitive-bullshit/chatgpt-api/blob/549e9b4/src/types.ts#L129)
___
### ConversationResponseEvent
Ƭ **ConversationResponseEvent**: `Object`
#### Type declaration
| Name | Type |
| :------ | :------ |
| `conversation_id?` | `string` |
| `error?` | `string` \| ``null`` |
| `message?` | [`Message`](modules.md#message) |
#### Defined in
[types.ts:246](https://github.com/transitive-bullshit/chatgpt-api/blob/549e9b4/src/types.ts#L246)
___
### 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` |
#### Defined in
[types.ts:252](https://github.com/transitive-bullshit/chatgpt-api/blob/549e9b4/src/types.ts#L252)
___
### MessageContent
Ƭ **MessageContent**: `Object`
#### Type declaration
| Name | Type |
| :------ | :------ |
| `content_type` | `string` |
| `parts` | `string`[] |
#### Defined in
[types.ts:265](https://github.com/transitive-bullshit/chatgpt-api/blob/549e9b4/src/types.ts#L265)
___
### 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
[types.ts:188](https://github.com/transitive-bullshit/chatgpt-api/blob/549e9b4/src/types.ts#L188)
___
### MessageFeedbackRating
Ƭ **MessageFeedbackRating**: ``"thumbsUp"`` \| ``"thumbsDown"``
#### Defined in
[types.ts:244](https://github.com/transitive-bullshit/chatgpt-api/blob/549e9b4/src/types.ts#L244)
___
### 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
[types.ts:217](https://github.com/transitive-bullshit/chatgpt-api/blob/549e9b4/src/types.ts#L217)
___
### MessageFeedbackTags
Ƭ **MessageFeedbackTags**: ``"harmful"`` \| ``"false"`` \| ``"not-helpful"``
#### Defined in
[types.ts:215](https://github.com/transitive-bullshit/chatgpt-api/blob/549e9b4/src/types.ts#L215)
___
### MessageMetadata
Ƭ **MessageMetadata**: `any`
#### Defined in
[types.ts:270](https://github.com/transitive-bullshit/chatgpt-api/blob/549e9b4/src/types.ts#L270)
___
### 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
[types.ts:72](https://github.com/transitive-bullshit/chatgpt-api/blob/549e9b4/src/types.ts#L72)
___
### 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
[types.ts:65](https://github.com/transitive-bullshit/chatgpt-api/blob/549e9b4/src/types.ts#L65)
___
### 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
[types.ts:92](https://github.com/transitive-bullshit/chatgpt-api/blob/549e9b4/src/types.ts#L92)
___
### 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
[types.ts:109](https://github.com/transitive-bullshit/chatgpt-api/blob/549e9b4/src/types.ts#L109)
___
### 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
[types.ts:156](https://github.com/transitive-bullshit/chatgpt-api/blob/549e9b4/src/types.ts#L156)
___
### 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
[types.ts:173](https://github.com/transitive-bullshit/chatgpt-api/blob/549e9b4/src/types.ts#L173)
___
### Role
Ƭ **Role**: ``"user"`` \| ``"assistant"``
#### Defined in
[types.ts:3](https://github.com/transitive-bullshit/chatgpt-api/blob/549e9b4/src/types.ts#L3)
___
### SessionResult
Ƭ **SessionResult**: `Object`
https://chat.openapi.com/api/auth/session
#### Type declaration
| Name | Type | Description |
| :------ | :------ | :------ |
| `accessToken` | `string` | The access token |
| `expires` | `string` | ISO date of the expiration date of the access token |
| `user` | [`User`](modules.md#user) | Object of the current user |
#### Defined in
[types.ts:8](https://github.com/transitive-bullshit/chatgpt-api/blob/549e9b4/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
[types.ts:25](https://github.com/transitive-bullshit/chatgpt-api/blob/549e9b4/src/types.ts#L25)
## Functions
### markdownToText
**markdownToText**(`markdown?`): `string`
#### Parameters
| Name | Type |
| :------ | :------ |
| `markdown?` | `string` |
#### Returns
`string`
#### Defined in
[utils.ts:4](https://github.com/transitive-bullshit/chatgpt-api/blob/549e9b4/src/utils.ts#L4)
......@@ -2,7 +2,7 @@ chatgpt / [Exports](modules.md)
# ChatGPT API <!-- omit in toc -->
> Node.js wrapper around [ChatGPT](https://openai.com/blog/chatgpt/). Uses headless Chrome until the official API is released.
> Node.js client for the unofficial [ChatGPT](https://openai.com/blog/chatgpt/) API.
[![NPM](https://img.shields.io/npm/v/chatgpt.svg)](https://www.npmjs.com/package/chatgpt) [![Build Status](https://github.com/transitive-bullshit/chatgpt-api/actions/workflows/test.yml/badge.svg)](https://github.com/transitive-bullshit/chatgpt-api/actions/workflows/test.yml) [![MIT License](https://img.shields.io/badge/license-MIT-blue)](https://github.com/transitive-bullshit/chatgpt-api/blob/main/license) [![Prettier Code Formatting](https://img.shields.io/badge/code_style-prettier-brightgreen.svg)](https://prettier.io)
......@@ -11,7 +11,8 @@ chatgpt / [Exports](modules.md)
- [Install](#install)
- [Usage](#usage)
- [Docs](#docs)
- [Related](#related)
- [Examples](#examples)
- [Credit](#credit)
- [License](#license)
## Intro
......@@ -22,12 +23,21 @@ You can use it to start building projects powered by ChatGPT like chatbots, webs
## How it works
We use headless Chromium via [Playwright](https://playwright.dev) to automate the webapp, so **you still need to have access to ChatGPT**. It just makes building API-like integrations much easier.
This package requires a valid session token from OpenAI's ChatGPT webapp to access it's unofficial REST API.
Chromium will be opened in non-headless mode by default, which is important because the first time you run `ChatGPTAPI.init()`, you'll need to log in manually. We launch Chromium with a persistent context, however, so you shouldn't need to keep re-logging in after the first time. When you log in the first time, _make sure that you also dismiss the welcome modal_.
1. Go to https://chat.openai.com/chat and log in or sign up
2. Open the dev tools console
3. Open `Application` > `Cookies`
![ChatGPT cookies](./media/cookies.png)
4. Copy the value for `__Secure-next-auth.session-token` and save it to your environment.
If you want to run the built-in demo,
> **Note**
> This package will switch to using the official API once it's released.
> **Note**
> We'll replace headless chrome with the official API once it's released.
> Prior to v1.0.0, this package used headless Chromium 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).
## Install
......@@ -47,64 +57,49 @@ import { ChatGPTAPI } from 'chatgpt'
async function example() {
const api = new ChatGPTAPI()
// open chromium and wait until you've logged in
await api.init({ auth: 'blocking' })
// ensure the API is properly authenticated (optional)
await api.ensureAuth()
// send a message and wait for the response
const response = await api.sendMessage(
'Write a python version of bubble sort. Do not include example usage.'
)
// response is a markdown-formatted string
console.log(response)
}
```
Which outputs a similar reponse to this (as a markdown string, including the _```python_ code block prefix):
```python
def bubble_sort(lst):
# Set the initial flag to True to start the loop
swapped = True
# Keep looping until there are no more swaps
while swapped:
# Set the flag to False initially
swapped = False
# Loop through the list
for i in range(len(lst) - 1):
# If the current element is greater than the next element,
# swap them and set the flag to True
if lst[i] > lst[i + 1]:
lst[i], lst[i + 1] = lst[i + 1], lst[i]
swapped = True
# Return the sorted list
return lst
```
By default, ChatGPT responses are parsed as markdown using [html-to-md](https://github.com/stonehank/html-to-md). I've found that this works really well during my testing, but if you'd rather output plaintext, you can use:
```ts
const api = new ChatGPTAPI({ markdown: false })
```
A full [example](./src/example.ts) is included for testing purposes:
```bash
# clone repo
# install node deps
# then run
# 1. clone repo
# 2. install node deps
# 3. set `SESSION_TOKEN` in .env
# 4. run:
npx tsx src/example.ts
```
## Docs
See the [auto-generated docs](./docs/classes/ChatGPTAPI.md) for more info on methods parameters.
See the [auto-generated docs](./docs/classes/ChatGPTAPI.md) for more info on methods and parameters.
## Examples
All of these awesome projects use the `chatgpt` package. 🤯
- [Twitter Bot](https://github.com/transitive-bullshit/chatgpt-twitter-bot) powered by ChatGPT ✨
- Mention [@ChatGPTBot](https://twitter.com/ChatGPTBot) on Twitter with your prompt to try it out
- [Chrome Extension](https://github.com/gragland/chatgpt-everywhere) ([demo](https://twitter.com/gabe_ragland/status/1599466486422470656))
- [VSCode Extension](https://github.com/mpociot/chatgpt-vscode) ([demo](https://twitter.com/marcelpociot/status/1599180144551526400))
- [Go Telegram Bot](https://github.com/m1guelpf/chatgpt-telegram)
- [Lovelines.xyz](https://lovelines.xyz)
If you create a cool integration, feel free to open a PR and add it to the list.
## Related
## Credit
- Inspired by this [Go module](https://github.com/danielgross/whatsapp-gpt) by [Daniel Gross](https://github.com/danielgross)
- [Python port](https://github.com/taranjeet/chatgpt-api)
## License
......
{
"name": "chatgpt",
"version": "0.4.2",
"description": "Node.js wrapper around ChatGPT. Uses headless Chrome until the official API is released.",
"description": "Node.js client for the unofficial ChatGPT API.",
"author": "Travis Fischer <travis@transitivebullsh.it>",
"repository": "transitive-bullshit/chatgpt-api",
"license": "MIT",
......@@ -34,18 +34,22 @@
"test:prettier": "prettier '**/*.{js,jsx,ts,tsx}' --check"
},
"dependencies": {
"html-to-md": "npm:@fisch0920/html-to-md@^0.8.1",
"playwright": "^1.28.1"
"eventsource-parser": "^0.0.5",
"expiry-map": "^2.0.0",
"node-fetch": "^3.3.0",
"remark": "^14.0.2",
"strip-markdown": "^5.0.0",
"uuid": "^9.0.0"
},
"devDependencies": {
"@trivago/prettier-plugin-sort-imports": "^4.0.0",
"@types/node": "^18.11.9",
"@types/uuid": "^9.0.0",
"del-cli": "^5.0.0",
"delay": "^5.0.0",
"dotenv-safe": "^8.2.0",
"husky": "^8.0.2",
"lint-staged": "^13.0.3",
"npm-run-all": "^4.1.5",
"ora": "^6.1.2",
"prettier": "^2.8.0",
"tsup": "^6.5.0",
"tsx": "^3.12.1",
......
This diff is collapsed.
# ChatGPT API <!-- omit in toc -->
> Node.js wrapper around [ChatGPT](https://openai.com/blog/chatgpt/). Uses headless Chrome until the official API is released.
> Node.js client for the unofficial [ChatGPT](https://openai.com/blog/chatgpt/) API.
[![NPM](https://img.shields.io/npm/v/chatgpt.svg)](https://www.npmjs.com/package/chatgpt) [![Build Status](https://github.com/transitive-bullshit/chatgpt-api/actions/workflows/test.yml/badge.svg)](https://github.com/transitive-bullshit/chatgpt-api/actions/workflows/test.yml) [![MIT License](https://img.shields.io/badge/license-MIT-blue)](https://github.com/transitive-bullshit/chatgpt-api/blob/main/license) [![Prettier Code Formatting](https://img.shields.io/badge/code_style-prettier-brightgreen.svg)](https://prettier.io)
......@@ -10,7 +10,7 @@
- [Usage](#usage)
- [Docs](#docs)
- [Examples](#examples)
- [Related](#related)
- [Credit](#credit)
- [License](#license)
## Intro
......@@ -21,17 +21,21 @@ You can use it to start building projects powered by ChatGPT like chatbots, webs
## How it works
It uses headless Chromium via [Playwright](https://playwright.dev) to automate the webapp, so **you still need to have access to ChatGPT**. It just makes building API-like integrations much easier.
This package requires a valid session token from OpenAI's ChatGPT webapp to access it's unofficial REST API.
Chromium will be opened in non-headless mode by default, which is important because the first time you run `ChatGPTAPI.init()`, you'll need to log in manually. We launch Chromium with a persistent session, however, so you shouldn't need to keep re-logging in after the first time.
1. Go to https://chat.openai.com/chat and log in or sign up
2. Open the dev tools console
3. Open `Application` > `Cookies`
![ChatGPT cookies](./media/cookies.png)
4. Copy the value for `__Secure-next-auth.session-token` and save it to your environment.
When you log in the first time, we recommend dismissing the welcome modal so you can watch the progress. This isn't strictly necessary, but it helps to understand what's going on.
If you want to run the built-in demo,
- [Demo video](https://www.loom.com/share/0c44525b07354d679f30c45d8eec6271) showing how the initial auth flow works (29 seconds)
- [Demo video](https://www.loom.com/share/98e712dbddf843289e2b6615095bbdd7) showing how it works if you're already authed (13 seconds)
> **Note**
> This package will switch to using the official API once it's released.
> **Note**
> We'll replace headless chrome with the official API once it's released.
> Prior to v1.0.0, this package used headless Chromium 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).
## Install
......@@ -51,8 +55,8 @@ import { ChatGPTAPI } from 'chatgpt'
async function example() {
const api = new ChatGPTAPI()
// open chromium and wait until you've logged in
await api.init({ auth: 'blocking' })
// ensure the API is properly authenticated (optional)
await api.ensureAuth()
// send a message and wait for the response
const response = await api.sendMessage(
......@@ -64,18 +68,13 @@ async function example() {
}
```
By default, ChatGPT responses are parsed as markdown using [html-to-md](https://github.com/stonehank/html-to-md). I've found that this works really well during my testing, but if you'd rather output plaintext, you can use:
```ts
const api = new ChatGPTAPI({ markdown: false })
```
A full [example](./src/example.ts) is included for testing purposes:
```bash
# clone repo
# install node deps
# then run
# 1. clone repo
# 2. install node deps
# 3. set `SESSION_TOKEN` in .env
# 4. run:
npx tsx src/example.ts
```
......@@ -97,10 +96,9 @@ All of these awesome projects use the `chatgpt` package. 🤯
If you create a cool integration, feel free to open a PR and add it to the list.
## Related
## Credit
- Inspired by this [Go module](https://github.com/danielgross/whatsapp-gpt) by [Daniel Gross](https://github.com/danielgross)
- [Python port](https://github.com/taranjeet/chatgpt-api)
## License
......
This diff is collapsed.
import delay from 'delay'
import { oraPromise } from 'ora'
import dotenv from 'dotenv-safe'
import { ChatGPTAPI } from './chatgpt-api'
dotenv.config()
/**
* Example CLI for testing functionality.
*/
async function main() {
const api = new ChatGPTAPI()
await api.init()
const isSignedIn = await api.getIsSignedIn()
if (!isSignedIn) {
// Wait until the user signs in via the chromium browser
await oraPromise(
new Promise<void>(async (resolve, reject) => {
do {
try {
await delay(1000)
const isSignedIn = await api.getIsSignedIn()
if (isSignedIn) {
return resolve()
}
} catch (err) {
return reject(err)
}
} while (true)
}),
'Please sign in to ChatGPT and dismiss the welcome modal'
)
}
const api = new ChatGPTAPI({ sessionToken: process.env.SESSION_TOKEN })
await api.ensureAuth()
const response = await api.sendMessage(
// 'Write a TypeScript function for conway sort.'
'Write a python version of bubble sort. Do not include example usage.'
)
// const prompts = await api.getPrompts()
// const messages = await api.getMessages()
// console.log('prompts', prompts)
// console.log('messages', messages)
// Wait forever; useful for debugging chromium sessions
// await new Promise(() => {})
await api.close()
return response
}
main().then((res) => {
console.log(res)
})
main()
.then((res) => {
console.log(res)
})
.catch((err) => {
console.error(err)
process.exit(1)
})
export * from './chatgpt-api'
export * from './chatgpt-api-types'
export * from './types'
export * from './utils'
export type ContentType = 'text'
export type Role = 'user' | 'assistant'
/**
* https://chat.openapi.com/api/auth/session
*/
......@@ -5,7 +9,7 @@ export type SessionResult = {
/**
* Object of the current user
*/
user: APIUser
user: User
/**
* ISO date of the expiration date of the access token
......@@ -18,7 +22,7 @@ export type SessionResult = {
accessToken: string
}
export type APIUser = {
export type User = {
/**
* ID of the user
*/
......@@ -62,10 +66,10 @@ export type ModelsResult = {
/**
* Array of models
*/
models: APIModel[]
models: Model[]
}
export type APIModel = {
export type Model = {
/**
* Name of the model
*/
......@@ -136,7 +140,7 @@ export type ConversationJSONBody = {
/**
* Prompts to provide
*/
messages: APIPrompt[]
messages: Prompt[]
/**
* The model to use
......@@ -149,11 +153,11 @@ export type ConversationJSONBody = {
parent_message_id: string
}
export type APIPrompt = {
export type Prompt = {
/**
* The content of the prompt
*/
content: APIPromptContent
content: PromptContent
/**
* The ID of the prompt
......@@ -163,14 +167,14 @@ export type APIPrompt = {
/**
* The role played in the prompt
*/
role: APIPromptRole
role: Role
}
export type APIPromptContent = {
export type PromptContent = {
/**
* The content type of the prompt
*/
content_type: APIPromptContentType
content_type: ContentType
/**
* The parts to the prompt
......@@ -178,10 +182,6 @@ export type APIPromptContent = {
parts: string[]
}
export type APIPromptContentType = 'text'
export type APIPromptRole = 'user'
/**
* https://chat.openapi.com/backend-api/conversation/message_feedback
*/
......@@ -199,12 +199,12 @@ export type MessageFeedbackJSONBody = {
/**
* The rating
*/
rating: APIMessageFeedbackRating
rating: MessageFeedbackRating
/**
* Tags to give the rating
*/
tags?: APIMessageFeedbackTags[]
tags?: MessageFeedbackTags[]
/**
* The text to include
......@@ -212,7 +212,7 @@ export type MessageFeedbackJSONBody = {
text?: string
}
export type APIMessageFeedbackTags = 'harmful' | 'false' | 'not-helpful'
export type MessageFeedbackTags = 'harmful' | 'false' | 'not-helpful'
export type MessageFeedbackResult = {
/**
......@@ -233,7 +233,7 @@ export type MessageFeedbackResult = {
/**
* The rating
*/
rating: APIMessageFeedbackRating
rating: MessageFeedbackRating
/**
* The text the server received, including tags
......@@ -241,4 +241,30 @@ export type MessageFeedbackResult = {
text?: string
}
export type APIMessageFeedbackRating = 'thumbsUp' | 'thumbsDown'
export type MessageFeedbackRating = 'thumbsUp' | 'thumbsDown'
export type ConversationResponseEvent = {
message?: Message
conversation_id?: string
error?: string | null
}
export type Message = {
id: string
content: MessageContent
role: string
user: string | null
create_time: string | null
update_time: string | null
end_turn: null
weight: number
recipient: string
metadata: MessageMetadata
}
export type MessageContent = {
content_type: string
parts: string[]
}
export type MessageMetadata = any
import { remark } from 'remark'
import stripMarkdown from 'strip-markdown'
export function markdownToText(markdown?: string): string {
return remark()
.use(stripMarkdown)
.processSync(markdown ?? '')
.toString()
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment