Commit 8cd86fc7 authored by Travis Fischer's avatar Travis Fischer Committed by GitHub

Merge pull request #9 from transitive-bullshit/feat/use-unofficial-rest-api

parents acf5261b ed92e9de
# ------------------------------------------------------------------------------
# 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 @@ ...@@ -10,53 +10,53 @@
### Methods ### Methods
- [close](ChatGPTAPI.md#close) - [ensureAuth](ChatGPTAPI.md#ensureauth)
- [getIsSignedIn](ChatGPTAPI.md#getissignedin) - [getIsAuthenticated](ChatGPTAPI.md#getisauthenticated)
- [getLastMessage](ChatGPTAPI.md#getlastmessage) - [refreshAccessToken](ChatGPTAPI.md#refreshaccesstoken)
- [getMessages](ChatGPTAPI.md#getmessages)
- [getPrompts](ChatGPTAPI.md#getprompts)
- [init](ChatGPTAPI.md#init)
- [sendMessage](ChatGPTAPI.md#sendmessage) - [sendMessage](ChatGPTAPI.md#sendmessage)
## Constructors ## Constructors
### constructor ### constructor
**new ChatGPTAPI**(`opts?`) **new ChatGPTAPI**(`opts`)
Creates a new client wrapper around the unofficial ChatGPT REST API.
#### Parameters #### Parameters
| Name | Type | Description | | Name | Type | Description |
| :------ | :------ | :------ | | :------ | :------ | :------ |
| `opts` | `Object` | - | | `opts` | `Object` | - |
| `opts.chatUrl?` | `string` | **`Default Value`** `'https://chat.openai.com/'` * | | `opts.apiBaseUrl?` | `string` | **`Default Value`** `'https://chat.openai.com/api'` * |
| `opts.headless?` | `boolean` | **`Default Value`** `false` * | | `opts.backendApiBaseUrl?` | `string` | **`Default Value`** `'https://chat.openai.com/backend-api'` * |
| `opts.markdown?` | `boolean` | **`Default Value`** `true` * | | `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 #### Defined in
[chatgpt-api.ts:20](https://github.com/transitive-bullshit/chatgpt-api/blob/ddd9545/src/chatgpt-api.ts#L20) [chatgpt-api.ts:31](https://github.com/transitive-bullshit/chatgpt-api/blob/c9cef79/src/chatgpt-api.ts#L31)
## Methods ## Methods
### close ### ensureAuth
**close**(): `Promise`<`void`\> **ensureAuth**(): `Promise`<`string`\>
#### Returns #### Returns
`Promise`<`void`\> `Promise`<`string`\>
#### Defined in #### Defined in
[chatgpt-api.ts:186](https://github.com/transitive-bullshit/chatgpt-api/blob/ddd9545/src/chatgpt-api.ts#L186) [chatgpt-api.ts:74](https://github.com/transitive-bullshit/chatgpt-api/blob/c9cef79/src/chatgpt-api.ts#L74)
___ ___
### getIsSignedIn ### getIsAuthenticated
**getIsSignedIn**(): `Promise`<`boolean`\> **getIsAuthenticated**(): `Promise`<`boolean`\>
#### Returns #### Returns
...@@ -64,13 +64,13 @@ ___ ...@@ -64,13 +64,13 @@ ___
#### Defined in #### Defined in
[chatgpt-api.ts:94](https://github.com/transitive-bullshit/chatgpt-api/blob/ddd9545/src/chatgpt-api.ts#L94) [chatgpt-api.ts:65](https://github.com/transitive-bullshit/chatgpt-api/blob/c9cef79/src/chatgpt-api.ts#L65)
___ ___
### getLastMessage ### refreshAccessToken
**getLastMessage**(): `Promise`<`string`\> **refreshAccessToken**(): `Promise`<`string`\>
#### Returns #### Returns
...@@ -78,68 +78,25 @@ ___ ...@@ -78,68 +78,25 @@ ___
#### Defined in #### Defined in
[chatgpt-api.ts:104](https://github.com/transitive-bullshit/chatgpt-api/blob/ddd9545/src/chatgpt-api.ts#L104) [chatgpt-api.ts:165](https://github.com/transitive-bullshit/chatgpt-api/blob/c9cef79/src/chatgpt-api.ts#L165)
___
### 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)
___ ___
### sendMessage ### 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 #### Parameters
| Name | Type | | Name | Type | Description |
| :------ | :------ | | :------ | :------ | :------ |
| `message` | `string` | | `message` | `string` | The plaintext message to send. |
| `opts` | `Object` | - |
| `opts.converstationId?` | `string` | - |
| `opts.onProgress?` | (`partialResponse`: `string`) => `void` | - |
#### Returns #### Returns
...@@ -147,4 +104,4 @@ ___ ...@@ -147,4 +104,4 @@ ___
#### Defined in #### Defined in
[chatgpt-api.ts:162](https://github.com/transitive-bullshit/chatgpt-api/blob/ddd9545/src/chatgpt-api.ts#L162) [chatgpt-api.ts:86](https://github.com/transitive-bullshit/chatgpt-api/blob/c9cef79/src/chatgpt-api.ts#L86)
...@@ -7,3 +7,386 @@ ...@@ -7,3 +7,386 @@
### Classes ### Classes
- [ChatGPTAPI](classes/ChatGPTAPI.md) - [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/c9cef79/src/types.ts#L104)
___
### ContentType
Ƭ **ContentType**: ``"text"``
#### Defined in
[types.ts:1](https://github.com/transitive-bullshit/chatgpt-api/blob/c9cef79/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/c9cef79/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/c9cef79/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/c9cef79/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/c9cef79/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/c9cef79/src/types.ts#L188)
___
### MessageFeedbackRating
Ƭ **MessageFeedbackRating**: ``"thumbsUp"`` \| ``"thumbsDown"``
#### Defined in
[types.ts:244](https://github.com/transitive-bullshit/chatgpt-api/blob/c9cef79/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/c9cef79/src/types.ts#L217)
___
### MessageFeedbackTags
Ƭ **MessageFeedbackTags**: ``"harmful"`` \| ``"false"`` \| ``"not-helpful"``
#### Defined in
[types.ts:215](https://github.com/transitive-bullshit/chatgpt-api/blob/c9cef79/src/types.ts#L215)
___
### MessageMetadata
Ƭ **MessageMetadata**: `any`
#### Defined in
[types.ts:270](https://github.com/transitive-bullshit/chatgpt-api/blob/c9cef79/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/c9cef79/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/c9cef79/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/c9cef79/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/c9cef79/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/c9cef79/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/c9cef79/src/types.ts#L173)
___
### Role
Ƭ **Role**: ``"user"`` \| ``"assistant"``
#### Defined in
[types.ts:3](https://github.com/transitive-bullshit/chatgpt-api/blob/c9cef79/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/c9cef79/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/c9cef79/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/c9cef79/src/utils.ts#L4)
chatgpt / [Exports](modules.md) chatgpt / [Exports](modules.md)
<p align="center">
<img alt="Example usage" src="/media/demo.gif">
</p>
# ChatGPT API <!-- omit in toc --> # 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) [![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 +15,8 @@ chatgpt / [Exports](modules.md) ...@@ -11,7 +15,8 @@ chatgpt / [Exports](modules.md)
- [Install](#install) - [Install](#install)
- [Usage](#usage) - [Usage](#usage)
- [Docs](#docs) - [Docs](#docs)
- [Related](#related) - [Examples](#examples)
- [Credit](#credit)
- [License](#license) - [License](#license)
## Intro ## Intro
...@@ -22,12 +27,23 @@ You can use it to start building projects powered by ChatGPT like chatbots, webs ...@@ -22,12 +27,23 @@ You can use it to start building projects powered by ChatGPT like chatbots, webs
## How it works ## 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 ChatGPT to access it's unofficial REST API.
To get a session token:
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.
If you want to run the built-in demo, store this value as `SESSION_TOKEN` in a local `.env` file.
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_. > **Note**
> This package will switch to using the official API once it's released.
> **Note** > **Note**
> We'll replace headless chrome with the official API once it's released. > 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).
## Install ## Install
...@@ -45,66 +61,62 @@ pnpm add chatgpt ...@@ -45,66 +61,62 @@ pnpm add chatgpt
import { ChatGPTAPI } from 'chatgpt' import { ChatGPTAPI } from 'chatgpt'
async function example() { async function example() {
const api = new ChatGPTAPI() const api = new ChatGPTAPI({ sessionToken: process.env.SESSION_TOKEN })
// open chromium and wait until you've logged in // ensure the API is properly authenticated (optional)
await api.init({ auth: 'blocking' }) await api.ensureAuth()
// send a message and wait for the response // send a message and wait for the response
const response = await api.sendMessage( const response = await api.sendMessage(
'Write a python version of bubble sort. Do not include example usage.' 'Write a python version of bubble sort. Do not include example usage.'
) )
// response is a markdown-formatted string
console.log(response) console.log(response)
} }
``` ```
Which outputs a similar reponse to this (as a markdown string, including the _```python_ code block prefix): By default, the response will be formatted as markdown. If you want to work with plaintext only, you can use:
```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 ```ts
const api = new ChatGPTAPI({ markdown: false }) const api = new ChatGPTAPI({
sessionToken: process.env.SESSION_TOKEN,
markdown: false
})
``` ```
A full [example](./src/example.ts) is included for testing purposes: A full [example](./src/example.ts) is included for testing purposes:
```bash ```bash
# clone repo # 1. clone repo
# install node deps # 2. install node deps
# then run # 3. set `SESSION_TOKEN` in .env
# 4. run:
npx tsx src/example.ts npx tsx src/example.ts
``` ```
## Docs ## 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)
- [Github ProBot](https://github.com/oceanlvr/ChatGPTBot)
- [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) - Huge thanks to [@RomanHotsiy](https://github.com/RomanHotsiy), [@ElijahPepe](https://github.com/ElijahPepe), [@wong2](https://github.com/wong2), and all the other contributors 💪
- [Python port](https://github.com/taranjeet/chatgpt-api) - The original browser version was inspired by this [Go module](https://github.com/danielgross/whatsapp-gpt) by [Daniel Gross](https://github.com/danielgross)
## License ## License
......
# VHS documentation
#
# @see https://github.com/charmbracelet/vhs
#
# ```
# vhs < media/demo.tape
# ```
#
# Output:
# Output <path>.gif Create a GIF output at the given <path>
# Output <path>.mp4 Create an MP4 output at the given <path>
# Output <path>.webm Create a WebM output at the given <path>
#
# Require:
# Require <string> Ensure a program is on the $PATH to proceed
#
# Settings:
# Set FontSize <number> Set the font size of the terminal
# Set FontFamily <string> Set the font family of the terminal
# Set Height <number> Set the height of the terminal
# Set Width <number> Set the width of the terminal
# Set LetterSpacing <float> Set the font letter spacing (tracking)
# Set LineHeight <float> Set the font line height
# Set LoopOffset <float>% Set the starting frame offset for the GIF loop
# Set Theme <json|string> Set the theme of the terminal
# Set Padding <number> Set the padding of the terminal
# Set Framerate <number> Set the framerate of the recording
# Set PlaybackSpeed <float> Set the playback speed of the recording
#
# Sleep:
# Sleep <time> Sleep for a set amount of <time> in seconds
#
# Type:
# Type[@<time>] "<characters>" Type <characters> into the terminal with a
# <time> delay between each character
#
# Keys:
# Backspace[@<time>] [number] Press the Backspace key
# Down[@<time>] [number] Press the Down key
# Enter[@<time>] [number] Press the Enter key
# Space[@<time>] [number] Press the Space key
# Tab[@<time>] [number] Press the Tab key
# Left[@<time>] [number] Press the Left Arrow key
# Right[@<time>] [number] Press the Right Arrow key
# Up[@<time>] [number] Press the Up Arrow key
# Down[@<time>] [number] Press the Down Arrow key
# Ctrl+<key> Press the Control key + <key> (e.g. Ctrl+C)
#
# Display:
# Hide Hide the subsequent commands from the output
# Show Show the subsequent commands in the output
Output media/demo.gif
Hide
Require npx
#Set Shell bash
Set FontSize 17
Set Width 1200
Set Height 600
Set Padding 24
Set LoopOffset 75%
Type " "
Sleep 980ms
Backspace 1
Show
Type "npx tsx src/example.ts"
Sleep 500ms
Enter
Show
Sleep 8s
Sleep 8s
{ {
"name": "chatgpt", "name": "chatgpt",
"version": "0.4.2", "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>", "author": "Travis Fischer <travis@transitivebullsh.it>",
"repository": "transitive-bullshit/chatgpt-api", "repository": "transitive-bullshit/chatgpt-api",
"license": "MIT", "license": "MIT",
...@@ -11,7 +11,7 @@ ...@@ -11,7 +11,7 @@
".": { ".": {
"require": "./build/index.js", "require": "./build/index.js",
"import": "./build/index.mjs", "import": "./build/index.mjs",
"types": "./build/index.d.ts" "types": "./build/index.d.ts"
} }
}, },
"files": [ "files": [
...@@ -34,14 +34,19 @@ ...@@ -34,14 +34,19 @@
"test:prettier": "prettier '**/*.{js,jsx,ts,tsx}' --check" "test:prettier": "prettier '**/*.{js,jsx,ts,tsx}' --check"
}, },
"dependencies": { "dependencies": {
"html-to-md": "npm:@fisch0920/html-to-md@^0.8.1", "eventsource-parser": "^0.0.5",
"playwright": "^1.28.1" "expiry-map": "^2.0.0",
"node-fetch": "^3.3.0",
"remark": "^14.0.2",
"strip-markdown": "^5.0.0",
"uuid": "^9.0.0"
}, },
"devDependencies": { "devDependencies": {
"@trivago/prettier-plugin-sort-imports": "^4.0.0", "@trivago/prettier-plugin-sort-imports": "^4.0.0",
"@types/node": "^18.11.9", "@types/node": "^18.11.9",
"@types/uuid": "^9.0.0",
"del-cli": "^5.0.0", "del-cli": "^5.0.0",
"delay": "^5.0.0", "dotenv-safe": "^8.2.0",
"husky": "^8.0.2", "husky": "^8.0.2",
"lint-staged": "^13.0.3", "lint-staged": "^13.0.3",
"npm-run-all": "^4.1.5", "npm-run-all": "^4.1.5",
......
This diff is collapsed.
<p align="center">
<img alt="Example usage" src="/media/demo.gif">
</p>
# ChatGPT API <!-- omit in toc --> # 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) [![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 +14,7 @@ ...@@ -10,7 +14,7 @@
- [Usage](#usage) - [Usage](#usage)
- [Docs](#docs) - [Docs](#docs)
- [Examples](#examples) - [Examples](#examples)
- [Related](#related) - [Credit](#credit)
- [License](#license) - [License](#license)
## Intro ## Intro
...@@ -21,17 +25,23 @@ You can use it to start building projects powered by ChatGPT like chatbots, webs ...@@ -21,17 +25,23 @@ You can use it to start building projects powered by ChatGPT like chatbots, webs
## How it works ## 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 ChatGPT to access it's unofficial REST API.
To get a session token:
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 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.
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, store this value as `SESSION_TOKEN` in a local `.env` file.
- [Demo video](https://www.loom.com/share/0c44525b07354d679f30c45d8eec6271) showing how the initial auth flow works (29 seconds) > **Note**
- [Demo video](https://www.loom.com/share/98e712dbddf843289e2b6615095bbdd7) showing how it works if you're already authed (13 seconds) > This package will switch to using the official API once it's released.
> **Note** > **Note**
> We'll replace headless chrome with the official API once it's released. > 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).
## Install ## Install
...@@ -49,10 +59,10 @@ pnpm add chatgpt ...@@ -49,10 +59,10 @@ pnpm add chatgpt
import { ChatGPTAPI } from 'chatgpt' import { ChatGPTAPI } from 'chatgpt'
async function example() { async function example() {
const api = new ChatGPTAPI() const api = new ChatGPTAPI({ sessionToken: process.env.SESSION_TOKEN })
// open chromium and wait until you've logged in // ensure the API is properly authenticated (optional)
await api.init({ auth: 'blocking' }) await api.ensureAuth()
// send a message and wait for the response // send a message and wait for the response
const response = await api.sendMessage( const response = await api.sendMessage(
...@@ -64,18 +74,22 @@ async function example() { ...@@ -64,18 +74,22 @@ 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: By default, the response will be formatted as markdown. If you want to work with plaintext only, you can use:
```ts ```ts
const api = new ChatGPTAPI({ markdown: false }) const api = new ChatGPTAPI({
sessionToken: process.env.SESSION_TOKEN,
markdown: false
})
``` ```
A full [example](./src/example.ts) is included for testing purposes: A full [example](./src/example.ts) is included for testing purposes:
```bash ```bash
# clone repo # 1. clone repo
# install node deps # 2. install node deps
# then run # 3. set `SESSION_TOKEN` in .env
# 4. run:
npx tsx src/example.ts npx tsx src/example.ts
``` ```
...@@ -97,10 +111,10 @@ All of these awesome projects use the `chatgpt` package. 🤯 ...@@ -97,10 +111,10 @@ 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. 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) - Huge thanks to [@RomanHotsiy](https://github.com/RomanHotsiy), [@ElijahPepe](https://github.com/ElijahPepe), [@wong2](https://github.com/wong2), and all the other contributors 💪
- [Python port](https://github.com/taranjeet/chatgpt-api) - The original browser version was inspired by this [Go module](https://github.com/danielgross/whatsapp-gpt) by [Daniel Gross](https://github.com/danielgross)
## License ## License
......
This diff is collapsed.
import delay from 'delay' import dotenv from 'dotenv-safe'
import { oraPromise } from 'ora' import { oraPromise } from 'ora'
import { ChatGPTAPI } from './chatgpt-api' import { ChatGPTAPI } from './chatgpt-api'
dotenv.config()
/** /**
* Example CLI for testing functionality. * Example CLI for testing functionality.
*/ */
async function main() { async function main() {
const api = new ChatGPTAPI() const api = new ChatGPTAPI({ sessionToken: process.env.SESSION_TOKEN })
await api.init() await api.ensureAuth()
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) { const prompt =
return resolve()
}
} catch (err) {
return reject(err)
}
} while (true)
}),
'Please sign in to ChatGPT and dismiss the welcome modal'
)
}
const response = await api.sendMessage(
// 'Write a TypeScript function for conway sort.'
'Write a python version of bubble sort. Do not include example usage.' '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() const response = await oraPromise(api.sendMessage(prompt), {
text: prompt
})
return response return response
} }
main().then((res) => { main()
console.log(res) .then((res) => {
}) console.log(res)
})
.catch((err) => {
console.error(err)
process.exit(1)
})
export * from './chatgpt-api' 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 * https://chat.openapi.com/api/auth/session
*/ */
...@@ -5,7 +9,7 @@ export type SessionResult = { ...@@ -5,7 +9,7 @@ export type SessionResult = {
/** /**
* Object of the current user * Object of the current user
*/ */
user: APIUser user: User
/** /**
* ISO date of the expiration date of the access token * ISO date of the expiration date of the access token
...@@ -18,7 +22,7 @@ export type SessionResult = { ...@@ -18,7 +22,7 @@ export type SessionResult = {
accessToken: string accessToken: string
} }
export type APIUser = { export type User = {
/** /**
* ID of the user * ID of the user
*/ */
...@@ -62,10 +66,10 @@ export type ModelsResult = { ...@@ -62,10 +66,10 @@ export type ModelsResult = {
/** /**
* Array of models * Array of models
*/ */
models: APIModel[] models: Model[]
} }
export type APIModel = { export type Model = {
/** /**
* Name of the model * Name of the model
*/ */
...@@ -136,7 +140,7 @@ export type ConversationJSONBody = { ...@@ -136,7 +140,7 @@ export type ConversationJSONBody = {
/** /**
* Prompts to provide * Prompts to provide
*/ */
messages: APIPrompt[] messages: Prompt[]
/** /**
* The model to use * The model to use
...@@ -149,11 +153,11 @@ export type ConversationJSONBody = { ...@@ -149,11 +153,11 @@ export type ConversationJSONBody = {
parent_message_id: string parent_message_id: string
} }
export type APIPrompt = { export type Prompt = {
/** /**
* The content of the prompt * The content of the prompt
*/ */
content: APIPromptContent content: PromptContent
/** /**
* The ID of the prompt * The ID of the prompt
...@@ -163,14 +167,14 @@ export type APIPrompt = { ...@@ -163,14 +167,14 @@ export type APIPrompt = {
/** /**
* The role played in the prompt * The role played in the prompt
*/ */
role: APIPromptRole role: Role
} }
export type APIPromptContent = { export type PromptContent = {
/** /**
* The content type of the prompt * The content type of the prompt
*/ */
content_type: APIPromptContentType content_type: ContentType
/** /**
* The parts to the prompt * The parts to the prompt
...@@ -178,10 +182,6 @@ export type APIPromptContent = { ...@@ -178,10 +182,6 @@ export type APIPromptContent = {
parts: string[] parts: string[]
} }
export type APIPromptContentType = 'text'
export type APIPromptRole = 'user'
/** /**
* https://chat.openapi.com/backend-api/conversation/message_feedback * https://chat.openapi.com/backend-api/conversation/message_feedback
*/ */
...@@ -199,12 +199,12 @@ export type MessageFeedbackJSONBody = { ...@@ -199,12 +199,12 @@ export type MessageFeedbackJSONBody = {
/** /**
* The rating * The rating
*/ */
rating: APIMessageFeedbackRating rating: MessageFeedbackRating
/** /**
* Tags to give the rating * Tags to give the rating
*/ */
tags?: APIMessageFeedbackTags[] tags?: MessageFeedbackTags[]
/** /**
* The text to include * The text to include
...@@ -212,7 +212,7 @@ export type MessageFeedbackJSONBody = { ...@@ -212,7 +212,7 @@ export type MessageFeedbackJSONBody = {
text?: string text?: string
} }
export type APIMessageFeedbackTags = 'harmful' | 'false' | 'not-helpful' export type MessageFeedbackTags = 'harmful' | 'false' | 'not-helpful'
export type MessageFeedbackResult = { export type MessageFeedbackResult = {
/** /**
...@@ -233,7 +233,7 @@ export type MessageFeedbackResult = { ...@@ -233,7 +233,7 @@ export type MessageFeedbackResult = {
/** /**
* The rating * The rating
*/ */
rating: APIMessageFeedbackRating rating: MessageFeedbackRating
/** /**
* The text the server received, including tags * The text the server received, including tags
...@@ -241,4 +241,30 @@ export type MessageFeedbackResult = { ...@@ -241,4 +241,30 @@ export type MessageFeedbackResult = {
text?: string 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