├── .env.example ├── .prettierrc ├── Dockerfile ├── package.json ├── README.md ├── src └── index.js ├── .gitignore └── LICENSE /.env.example: -------------------------------------------------------------------------------- 1 | API_KEY=sk-xxxxxxxxx -------------------------------------------------------------------------------- /.prettierrc: -------------------------------------------------------------------------------- 1 | { 2 | "printWidth": 1400, 3 | "singleQuote": true, 4 | "quoteProps": "consistent" 5 | } 6 | -------------------------------------------------------------------------------- /Dockerfile: -------------------------------------------------------------------------------- 1 | FROM node:18-alpine 2 | RUN addgroup -S appgroup && adduser -S appuser -G appgroup 3 | WORKDIR /app 4 | COPY package*.json ./ 5 | RUN npm install 6 | COPY . . 7 | RUN chown -R appuser:appgroup /app 8 | EXPOSE 9010 9 | USER appuser 10 | CMD [ "npm", "start" ] 11 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "chatgptapistream", 3 | "version": "1.0.0", 4 | "private": true, 5 | "type": "module", 6 | "scripts": { 7 | "start": "node src/index.js" 8 | }, 9 | "author": "gaoqing", 10 | "license": "MIT", 11 | "dependencies": { 12 | "dotenv": "^16.0.3", 13 | "openai": "^3.2.1", 14 | "ws": "^8.13.0" 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # ChatGPT API Stream 2 | 3 | Here is a simple demo that demonstrates how to use the ChatGPT API in stream mode. 4 | With this project, you can easily deploy a WebSocket server for engaging in a stream of conversations with ChatGPT. 5 | 6 | If you find this project useful, please help us by giving it a star. 7 | 8 | ## Newss 9 | 10 | - **2023-03-26**: project start 11 | 12 | ## Usage 13 | 14 | 0. Obtain an OpenAI API Key from [OpenAI API Keys](https://platform.openai.com/account/api-keys). 15 | 1. Download this project 16 | 2. Configure your [environment variables](.env.example) correctly. 17 | 3. Run 18 | ``` 19 | npm i 20 | npm run start 21 | ``` 22 | 23 | The WebSocket Server is start 24 | 25 | ## Test 26 | 27 | Here, I'm testing using the wscat tool, although you can use any WebSocket client to test. 28 | ``` 29 | npm i -g wscat 30 | wscat --connect ws://127.0.0.1:9010/chat/ 31 | ``` 32 | 33 | say any thing you want 34 | and it will reply message with stream mode 35 | 36 | ## Improve this project 37 | 38 | This project is always seeking ways to improve and welcomes feedback and contributions from its users. If you have any suggestions or ideas, please feel free to create an issue or submit a pull request on the GitHub repository. 39 | 40 | -------------------------------------------------------------------------------- /src/index.js: -------------------------------------------------------------------------------- 1 | import * as dotenv from 'dotenv'; 2 | dotenv.config(); 3 | 4 | // websocket server 5 | import { WebSocketServer } from 'ws'; 6 | const server = new WebSocketServer({ port: 9010 }); 7 | 8 | import { Configuration, OpenAIApi } from "openai" 9 | const url = 'https://api.openai.com/v1/models'; 10 | const configuration = new Configuration({ 11 | apiKey: process.env.API_KEY 12 | }); 13 | const openai = new OpenAIApi(configuration); 14 | 15 | server.on('connection', (socket) => { 16 | console.log('Client connected'); 17 | 18 | socket.on('message', async (message) => { 19 | console.log(`Received message: ${message}`); 20 | socket.send(`You said: ${message}`); 21 | chat(message.toString(), (data) => { 22 | socket.send(data); 23 | 24 | }) 25 | }); 26 | 27 | socket.on('close', () => { 28 | console.log('Client disconnected'); 29 | }); 30 | }); 31 | 32 | async function chat(content, handleMessage) { 33 | try { 34 | const completion = await openai.createChatCompletion({ 35 | model: "gpt-3.5-turbo", 36 | messages: [{ role: "user", content: content }], 37 | max_tokens: 100, 38 | temperature: 0, 39 | stream: true, 40 | }, { responseType: 'stream' }); 41 | 42 | completion.data.on('data', data => { 43 | const lines = data.toString().split('\n').filter(line => line.trim() !== ''); 44 | for (const line of lines) { 45 | const message = line.replace(/^data: /, ''); 46 | if (message === '[DONE]') { 47 | return; // Stream finished 48 | } 49 | try { 50 | console.log(`Receive stream message: ${message}`) 51 | handleMessage(message) 52 | } catch(error) { 53 | console.error('Could not JSON parse stream message', message, error); 54 | } 55 | } 56 | }); 57 | } catch (e) { 58 | console.log("OpenAI API fail: ", e) 59 | } 60 | } -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | .DS_Store 2 | # Logs 3 | 4 | logs 5 | _.log 6 | npm-debug.log_ 7 | yarn-debug.log* 8 | yarn-error.log* 9 | lerna-debug.log* 10 | .pnpm-debug.log* 11 | 12 | # Diagnostic reports (https://nodejs.org/api/report.html) 13 | 14 | report.[0-9]_.[0-9]_.[0-9]_.[0-9]_.json 15 | 16 | # Runtime data 17 | 18 | pids 19 | _.pid 20 | _.seed 21 | \*.pid.lock 22 | 23 | # Directory for instrumented libs generated by jscoverage/JSCover 24 | 25 | lib-cov 26 | 27 | # Coverage directory used by tools like istanbul 28 | 29 | coverage 30 | \*.lcov 31 | 32 | # nyc test coverage 33 | 34 | .nyc_output 35 | 36 | # Grunt intermediate storage (https://gruntjs.com/creating-plugins#storing-task-files) 37 | 38 | .grunt 39 | 40 | # Bower dependency directory (https://bower.io/) 41 | 42 | bower_components 43 | 44 | # node-waf configuration 45 | 46 | .lock-wscript 47 | 48 | # Compiled binary addons (https://nodejs.org/api/addons.html) 49 | 50 | build/Release 51 | 52 | # Dependency directories 53 | 54 | node_modules/ 55 | jspm_packages/ 56 | 57 | # Snowpack dependency directory (https://snowpack.dev/) 58 | 59 | web_modules/ 60 | 61 | # TypeScript cache 62 | 63 | \*.tsbuildinfo 64 | 65 | # Optional npm cache directory 66 | 67 | .npm 68 | 69 | # Optional eslint cache 70 | 71 | .eslintcache 72 | 73 | # Optional stylelint cache 74 | 75 | .stylelintcache 76 | 77 | # Microbundle cache 78 | 79 | .rpt2_cache/ 80 | .rts2_cache_cjs/ 81 | .rts2_cache_es/ 82 | .rts2_cache_umd/ 83 | 84 | # Optional REPL history 85 | 86 | .node_repl_history 87 | 88 | # Output of 'npm pack' 89 | 90 | \*.tgz 91 | 92 | # Yarn Integrity file 93 | 94 | .yarn-integrity 95 | 96 | # dotenv environment variable files 97 | 98 | .env 99 | .env.development.local 100 | .env.test.local 101 | .env.production.local 102 | .env.local 103 | 104 | # parcel-bundler cache (https://parceljs.org/) 105 | 106 | .cache 107 | .parcel-cache 108 | 109 | # Next.js build output 110 | 111 | .next 112 | out 113 | 114 | # Nuxt.js build / generate output 115 | 116 | .nuxt 117 | dist 118 | 119 | # Gatsby files 120 | 121 | .cache/ 122 | 123 | # Comment in the public line in if your project uses Gatsby and not Next.js 124 | 125 | # https://nextjs.org/blog/next-9-1#public-directory-support 126 | 127 | # public 128 | 129 | # vuepress build output 130 | 131 | .vuepress/dist 132 | 133 | # vuepress v2.x temp and cache directory 134 | 135 | .temp 136 | .cache 137 | 138 | # Docusaurus cache and generated files 139 | 140 | .docusaurus 141 | 142 | # Serverless directories 143 | 144 | .serverless/ 145 | 146 | # FuseBox cache 147 | 148 | .fusebox/ 149 | 150 | # DynamoDB Local files 151 | 152 | .dynamodb/ 153 | 154 | # TernJS port file 155 | 156 | .tern-port 157 | 158 | # Stores VSCode versions used for testing VSCode extensions 159 | 160 | .vscode-test 161 | 162 | # yarn v2 163 | 164 | .yarn/cache 165 | .yarn/unplugged 166 | .yarn/build-state.yml 167 | .yarn/install-state.gz 168 | .pnp.\* 169 | 170 | # wrangler project 171 | 172 | .dev.vars 173 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Creative Commons Legal Code 2 | 3 | CC0 1.0 Universal 4 | 5 | CREATIVE COMMONS CORPORATION IS NOT A LAW FIRM AND DOES NOT PROVIDE 6 | LEGAL SERVICES. DISTRIBUTION OF THIS DOCUMENT DOES NOT CREATE AN 7 | ATTORNEY-CLIENT RELATIONSHIP. CREATIVE COMMONS PROVIDES THIS 8 | INFORMATION ON AN "AS-IS" BASIS. CREATIVE COMMONS MAKES NO WARRANTIES 9 | REGARDING THE USE OF THIS DOCUMENT OR THE INFORMATION OR WORKS 10 | PROVIDED HEREUNDER, AND DISCLAIMS LIABILITY FOR DAMAGES RESULTING FROM 11 | THE USE OF THIS DOCUMENT OR THE INFORMATION OR WORKS PROVIDED 12 | HEREUNDER. 13 | 14 | Statement of Purpose 15 | 16 | The laws of most jurisdictions throughout the world automatically confer 17 | exclusive Copyright and Related Rights (defined below) upon the creator 18 | and subsequent owner(s) (each and all, an "owner") of an original work of 19 | authorship and/or a database (each, a "Work"). 20 | 21 | Certain owners wish to permanently relinquish those rights to a Work for 22 | the purpose of contributing to a commons of creative, cultural and 23 | scientific works ("Commons") that the public can reliably and without fear 24 | of later claims of infringement build upon, modify, incorporate in other 25 | works, reuse and redistribute as freely as possible in any form whatsoever 26 | and for any purposes, including without limitation commercial purposes. 27 | These owners may contribute to the Commons to promote the ideal of a free 28 | culture and the further production of creative, cultural and scientific 29 | works, or to gain reputation or greater distribution for their Work in 30 | part through the use and efforts of others. 31 | 32 | For these and/or other purposes and motivations, and without any 33 | expectation of additional consideration or compensation, the person 34 | associating CC0 with a Work (the "Affirmer"), to the extent that he or she 35 | is an owner of Copyright and Related Rights in the Work, voluntarily 36 | elects to apply CC0 to the Work and publicly distribute the Work under its 37 | terms, with knowledge of his or her Copyright and Related Rights in the 38 | Work and the meaning and intended legal effect of CC0 on those rights. 39 | 40 | 1. Copyright and Related Rights. A Work made available under CC0 may be 41 | protected by copyright and related or neighboring rights ("Copyright and 42 | Related Rights"). Copyright and Related Rights include, but are not 43 | limited to, the following: 44 | 45 | i. the right to reproduce, adapt, distribute, perform, display, 46 | communicate, and translate a Work; 47 | ii. moral rights retained by the original author(s) and/or performer(s); 48 | iii. publicity and privacy rights pertaining to a person's image or 49 | likeness depicted in a Work; 50 | iv. rights protecting against unfair competition in regards to a Work, 51 | subject to the limitations in paragraph 4(a), below; 52 | v. rights protecting the extraction, dissemination, use and reuse of data 53 | in a Work; 54 | vi. database rights (such as those arising under Directive 96/9/EC of the 55 | European Parliament and of the Council of 11 March 1996 on the legal 56 | protection of databases, and under any national implementation 57 | thereof, including any amended or successor version of such 58 | directive); and 59 | vii. other similar, equivalent or corresponding rights throughout the 60 | world based on applicable law or treaty, and any national 61 | implementations thereof. 62 | 63 | 2. Waiver. To the greatest extent permitted by, but not in contravention 64 | of, applicable law, Affirmer hereby overtly, fully, permanently, 65 | irrevocably and unconditionally waives, abandons, and surrenders all of 66 | Affirmer's Copyright and Related Rights and associated claims and causes 67 | of action, whether now known or unknown (including existing as well as 68 | future claims and causes of action), in the Work (i) in all territories 69 | worldwide, (ii) for the maximum duration provided by applicable law or 70 | treaty (including future time extensions), (iii) in any current or future 71 | medium and for any number of copies, and (iv) for any purpose whatsoever, 72 | including without limitation commercial, advertising or promotional 73 | purposes (the "Waiver"). Affirmer makes the Waiver for the benefit of each 74 | member of the public at large and to the detriment of Affirmer's heirs and 75 | successors, fully intending that such Waiver shall not be subject to 76 | revocation, rescission, cancellation, termination, or any other legal or 77 | equitable action to disrupt the quiet enjoyment of the Work by the public 78 | as contemplated by Affirmer's express Statement of Purpose. 79 | 80 | 3. Public License Fallback. Should any part of the Waiver for any reason 81 | be judged legally invalid or ineffective under applicable law, then the 82 | Waiver shall be preserved to the maximum extent permitted taking into 83 | account Affirmer's express Statement of Purpose. In addition, to the 84 | extent the Waiver is so judged Affirmer hereby grants to each affected 85 | person a royalty-free, non transferable, non sublicensable, non exclusive, 86 | irrevocable and unconditional license to exercise Affirmer's Copyright and 87 | Related Rights in the Work (i) in all territories worldwide, (ii) for the 88 | maximum duration provided by applicable law or treaty (including future 89 | time extensions), (iii) in any current or future medium and for any number 90 | of copies, and (iv) for any purpose whatsoever, including without 91 | limitation commercial, advertising or promotional purposes (the 92 | "License"). The License shall be deemed effective as of the date CC0 was 93 | applied by Affirmer to the Work. Should any part of the License for any 94 | reason be judged legally invalid or ineffective under applicable law, such 95 | partial invalidity or ineffectiveness shall not invalidate the remainder 96 | of the License, and in such case Affirmer hereby affirms that he or she 97 | will not (i) exercise any of his or her remaining Copyright and Related 98 | Rights in the Work or (ii) assert any associated claims and causes of 99 | action with respect to the Work, in either case contrary to Affirmer's 100 | express Statement of Purpose. 101 | 102 | 4. Limitations and Disclaimers. 103 | 104 | a. No trademark or patent rights held by Affirmer are waived, abandoned, 105 | surrendered, licensed or otherwise affected by this document. 106 | b. Affirmer offers the Work as-is and makes no representations or 107 | warranties of any kind concerning the Work, express, implied, 108 | statutory or otherwise, including without limitation warranties of 109 | title, merchantability, fitness for a particular purpose, non 110 | infringement, or the absence of latent or other defects, accuracy, or 111 | the present or absence of errors, whether or not discoverable, all to 112 | the greatest extent permissible under applicable law. 113 | c. Affirmer disclaims responsibility for clearing rights of other persons 114 | that may apply to the Work or any use thereof, including without 115 | limitation any person's Copyright and Related Rights in the Work. 116 | Further, Affirmer disclaims responsibility for obtaining any necessary 117 | consents, permissions or other rights required for any use of the 118 | Work. 119 | d. Affirmer understands and acknowledges that Creative Commons is not a 120 | party to this document and has no duty or obligation with respect to 121 | this CC0 or use of the Work. 122 | --------------------------------------------------------------------------------