├── .gitignore ├── LICENSE ├── README.md ├── event.json ├── example_cloudformation.png ├── example_lambda.gif ├── samconfig.toml ├── src ├── index.mjs ├── package.json └── streamOpenAIResponse.mjs ├── template.yml └── test_locally.sh /.gitignore: -------------------------------------------------------------------------------- 1 | # Created by https://www.toptal.com/developers/gitignore/api/osx,sam,node,linux,windows 2 | # Edit at https://www.toptal.com/developers/gitignore?templates=osx,sam,node,linux,windows 3 | 4 | *package-lock.json 5 | 6 | ### Linux ### 7 | *~ 8 | 9 | # temporary files which can be created if a process still has a handle open of a deleted file 10 | .fuse_hidden* 11 | 12 | # KDE directory preferences 13 | .directory 14 | 15 | # Linux trash folder which might appear on any partition or disk 16 | .Trash-* 17 | 18 | # .nfs files are created when an open file is removed but is still being accessed 19 | .nfs* 20 | 21 | ### Node ### 22 | # Logs 23 | logs 24 | *.log 25 | npm-debug.log* 26 | yarn-debug.log* 27 | yarn-error.log* 28 | lerna-debug.log* 29 | .pnpm-debug.log* 30 | 31 | # Diagnostic reports (https://nodejs.org/api/report.html) 32 | report.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json 33 | 34 | # Runtime data 35 | pids 36 | *.pid 37 | *.seed 38 | *.pid.lock 39 | 40 | # Directory for instrumented libs generated by jscoverage/JSCover 41 | lib-cov 42 | 43 | # Coverage directory used by tools like istanbul 44 | coverage 45 | *.lcov 46 | 47 | # nyc test coverage 48 | .nyc_output 49 | 50 | # Grunt intermediate storage (https://gruntjs.com/creating-plugins#storing-task-files) 51 | .grunt 52 | 53 | # Bower dependency directory (https://bower.io/) 54 | bower_components 55 | 56 | # node-waf configuration 57 | .lock-wscript 58 | 59 | # Compiled binary addons (https://nodejs.org/api/addons.html) 60 | build/Release 61 | 62 | # Dependency directories 63 | node_modules/ 64 | jspm_packages/ 65 | 66 | # Snowpack dependency directory (https://snowpack.dev/) 67 | web_modules/ 68 | 69 | # TypeScript cache 70 | *.tsbuildinfo 71 | 72 | # Optional npm cache directory 73 | .npm 74 | 75 | # Optional eslint cache 76 | .eslintcache 77 | 78 | # Optional stylelint cache 79 | .stylelintcache 80 | 81 | # Microbundle cache 82 | .rpt2_cache/ 83 | .rts2_cache_cjs/ 84 | .rts2_cache_es/ 85 | .rts2_cache_umd/ 86 | 87 | # Optional REPL history 88 | .node_repl_history 89 | 90 | # Output of 'npm pack' 91 | *.tgz 92 | 93 | # Yarn Integrity file 94 | .yarn-integrity 95 | 96 | # dotenv environment variable files 97 | .env 98 | .env.development.local 99 | .env.test.local 100 | .env.production.local 101 | .env.local 102 | 103 | # parcel-bundler cache (https://parceljs.org/) 104 | .cache 105 | .parcel-cache 106 | 107 | # Next.js build output 108 | .next 109 | out 110 | 111 | # Nuxt.js build / generate output 112 | .nuxt 113 | dist 114 | 115 | # Gatsby files 116 | .cache/ 117 | # Comment in the public line in if your project uses Gatsby and not Next.js 118 | # https://nextjs.org/blog/next-9-1#public-directory-support 119 | # public 120 | 121 | # vuepress build output 122 | .vuepress/dist 123 | 124 | # vuepress v2.x temp and cache directory 125 | .temp 126 | 127 | # Docusaurus cache and generated files 128 | .docusaurus 129 | 130 | # Serverless directories 131 | .serverless/ 132 | 133 | # FuseBox cache 134 | .fusebox/ 135 | 136 | # DynamoDB Local files 137 | .dynamodb/ 138 | 139 | # TernJS port file 140 | .tern-port 141 | 142 | # Stores VSCode versions used for testing VSCode extensions 143 | .vscode-test 144 | 145 | # yarn v2 146 | .yarn/cache 147 | .yarn/unplugged 148 | .yarn/build-state.yml 149 | .yarn/install-state.gz 150 | .pnp.* 151 | 152 | ### Node Patch ### 153 | # Serverless Webpack directories 154 | .webpack/ 155 | 156 | # Optional stylelint cache 157 | 158 | # SvelteKit build / generate output 159 | .svelte-kit 160 | 161 | ### OSX ### 162 | # General 163 | .DS_Store 164 | .AppleDouble 165 | .LSOverride 166 | 167 | # Icon must end with two \r 168 | Icon 169 | 170 | 171 | # Thumbnails 172 | ._* 173 | 174 | # Files that might appear in the root of a volume 175 | .DocumentRevisions-V100 176 | .fseventsd 177 | .Spotlight-V100 178 | .TemporaryItems 179 | .Trashes 180 | .VolumeIcon.icns 181 | .com.apple.timemachine.donotpresent 182 | 183 | # Directories potentially created on remote AFP share 184 | .AppleDB 185 | .AppleDesktop 186 | Network Trash Folder 187 | Temporary Items 188 | .apdisk 189 | 190 | ### SAM ### 191 | # Ignore build directories for the AWS Serverless Application Model (SAM) 192 | # Info: https://aws.amazon.com/serverless/sam/ 193 | # Docs: https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/serverless-sam-reference.html 194 | 195 | **/.aws-sam 196 | 197 | ### Windows ### 198 | # Windows thumbnail cache files 199 | Thumbs.db 200 | Thumbs.db:encryptable 201 | ehthumbs.db 202 | ehthumbs_vista.db 203 | 204 | # Dump file 205 | *.stackdump 206 | 207 | # Folder config file 208 | [Dd]esktop.ini 209 | 210 | # Recycle Bin used on file shares 211 | $RECYCLE.BIN/ 212 | 213 | # Windows Installer files 214 | *.cab 215 | *.msi 216 | *.msix 217 | *.msm 218 | *.msp 219 | 220 | # Windows shortcuts 221 | *.lnk 222 | 223 | # End of https://www.toptal.com/developers/gitignore/api/osx,sam,node,linux,windows -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 |
2 | Streaming is now officially supported by OpenAI: https://github.com/openai/openai-node 3 |

Lambda-OpenAI-Stream

4 |
5 | 6 | ## About 7 | __Lambda-OpenAI-Stream__ lets you stream OpenAI responses via an AWS Lambda Function URL. It is a simple implementation in vanilla JS. The only (optional) dependency is dotenv. 8 | 9 | ![Example gif](example_lambda.gif?raw=true) 10 | 11 | ## Deployment 12 | ### Prerequisites 13 | * General AWS knowledge is helpful. 14 | * You need to have [Docker](https://docs.docker.com/engine/install/) installed locally. 15 | * You need to have [aws-sam](https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/install-sam-cli.html) installed locally and configured with your AWS account. 16 | 17 | ### Setup 18 | 1. Clone the repository 19 | ```sh 20 | git clone https://github.com/maxsagt/lambda-openai-stream.git 21 | ``` 22 | 2. Create the .env in ./src with your OpenAI API key: 23 | ``` 24 | OPENAI_API_KEY=abc123 25 | ``` 26 | 3. Install dotenv 27 | ```sh 28 | npm init 29 | npm install dotenv 30 | ``` 31 | 4. Build and test the Lambda function locally 32 | ```sh 33 | sam build 34 | sam local invoke -e event.json 35 | ``` 36 | 5. Deploy to AWS. Note that your AWS user or role needs (temporary) IAM permissions for AWS CloudFormation, S3, Lambda and IAM. 37 | ```sh 38 | sam build --cached --parallel 39 | # Use sam deploy --guided to control the AWS region. 40 | ``` 41 | 6. Done. Your Lambda Function URL is displayed in the terminal, and you can find it in AWS. 42 | ![Example](example_cloudformation.png?raw=true) 43 | 44 | ### ! Please note that this URL is publicly exposed and has no authorization configured at this point. 45 | 46 | ## Future Improvements 47 | - Add configurations for Amazon CloudFront and AWS WAF to introduce authentication 48 | - Add an index.html to show how the frontend could work. 49 | 50 | ## Feedback 51 | Feedback and contributions are welcome! 52 | -------------------------------------------------------------------------------- /event.json: -------------------------------------------------------------------------------- 1 | { 2 | "queryStringParameters": { 3 | "message": "Write a haiku." 4 | } 5 | } -------------------------------------------------------------------------------- /example_cloudformation.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/maxsagt/lambda-openai-stream/376f688de64655187ad926a97773ca1d381e144d/example_cloudformation.png -------------------------------------------------------------------------------- /example_lambda.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/maxsagt/lambda-openai-stream/376f688de64655187ad926a97773ca1d381e144d/example_lambda.gif -------------------------------------------------------------------------------- /samconfig.toml: -------------------------------------------------------------------------------- 1 | # samconfig.toml tells AWS-SAM in which way to deploy the resources in template.yml to AWS (which region etc.) 2 | # Alternatively, run "sam deploy --guided" to create your own configuration. 3 | 4 | version = 0.1 5 | [default.deploy.parameters] 6 | stack_name = "lambda-openai" 7 | resolve_s3 = true 8 | s3_prefix = "lambda-openai" 9 | region = "eu-central-1" 10 | confirm_changeset = false 11 | capabilities = "CAPABILITY_IAM" 12 | disable_rollback = true 13 | image_repositories = [] 14 | -------------------------------------------------------------------------------- /src/index.mjs: -------------------------------------------------------------------------------- 1 | "use strict"; 2 | 3 | import { streamOpenAIResponse } from './streamOpenAIResponse.mjs'; 4 | 5 | export const handler = awslambda.streamifyResponse( 6 | async (event, responseStream, _context) => { 7 | // Get current process time 8 | const startTime = process.hrtime(); 9 | 10 | // Start response stream 11 | const metadata = { 12 | statusCode: 200, 13 | headers: { 14 | "Content-Type": "application/json" 15 | } 16 | }; 17 | responseStream = awslambda.HttpResponseStream.from(responseStream, metadata); 18 | responseStream.write("\nRequest started."); 19 | responseStream.write(`\n---\n`); 20 | 21 | // Stream OpenAI response 1 22 | const res_1 = await streamOpenAIResponse(responseStream, { 23 | messages: [{ role: "user", content: event.queryStringParameters.message }], // The user's message (in testing from event.json) 24 | model: "gpt-3.5-turbo", 25 | temperature: 1, 26 | max_tokens: 100 27 | }); 28 | 29 | responseStream.write(`\n\n`); 30 | 31 | // Stream OpenAI response 2 32 | const res_2 = await streamOpenAIResponse(responseStream, { 33 | messages: [{ role: "user", content: "What is the meaning of this:\n\n" + res_1 + "\n\nAnswer: " }], 34 | model: "gpt-3.5-turbo", 35 | temperature: 0, 36 | max_tokens: 200 37 | }); 38 | 39 | // ... add more responses as needed here. 40 | 41 | // Return execution time (optional) 42 | const hrTime = process.hrtime(startTime); 43 | const totalSeconds = hrTime[0] + hrTime[1] / 1e9; 44 | const minutes = Math.floor(totalSeconds / 60); 45 | const seconds = (totalSeconds % 60).toFixed(2); 46 | responseStream.write(`\n---\n`); 47 | responseStream.write(`Execution Time: ${minutes} minutes ${seconds} seconds\n`); 48 | 49 | // End response stream 50 | responseStream.end(); 51 | } 52 | ); 53 | -------------------------------------------------------------------------------- /src/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "lambda-openai", 3 | "version": "1.0.0", 4 | "description": "", 5 | "main": "index.mjs", 6 | "scripts": { 7 | "test": "echo \"Error: no test specified\" && exit 1" 8 | }, 9 | "author": "", 10 | "license": "ISC", 11 | "dependencies": { 12 | "dotenv": "^16.3.1" 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /src/streamOpenAIResponse.mjs: -------------------------------------------------------------------------------- 1 | "use strict"; 2 | 3 | import dotenv from 'dotenv'; 4 | dotenv.config(); 5 | 6 | const apiKey = process.env.OPENAI_API_KEY; 7 | if (!apiKey) {throw new Error('Missing OPENAI_API_KEY environment variable')} 8 | 9 | // Function to fetch data from OpenAI API as streaming data 10 | async function fetchData(config) { 11 | 12 | config.stream = true; // Enforce streaming (currently non-streaming not supported) 13 | 14 | const response = await fetch("https://api.openai.com/v1/chat/completions", { 15 | method: "POST", 16 | headers: { 17 | "Content-Type": "application/json", 18 | "Authorization": `Bearer ${apiKey}` 19 | }, 20 | body: JSON.stringify(config) 21 | }); 22 | 23 | return response.body; 24 | } 25 | 26 | // A function to convert a chunk of streaming data (bytes) into objects. 27 | function processChunk(chunk) { 28 | // chunk contains bytes that we need to decode to a string 29 | const decoder = new TextDecoder(); 30 | const decodedChunk = decoder.decode(chunk); 31 | // Each chunk has one or more lines of the following format: 32 | // data: {"id":"chatcmpl-123","object":"chat.completion.chunk","created":1999999999,"model":"gpt-3.5-turbo-0613","choices":[{"index":0,"delta":{"content":" test"},"finish_reason":null}]} 33 | 34 | const lines = decodedChunk 35 | .split("\n") // Each line is seperated by a newline character 36 | .map(line => line.replace("data: ", "")) // For each individual line, remove the "data: " prefix 37 | .filter(line => line.length > 0 && line !== "[DONE]") // Remove empty lines and the "[DONE]" line 38 | .map(line => { 39 | try { 40 | return JSON.parse(line); // Parse each line as JSON 41 | } catch (error) { 42 | console.error('Error parsing line:', line); 43 | throw error; 44 | } 45 | }); 46 | 47 | return lines; 48 | } 49 | 50 | // A function to stream the response from OpenAI to the client 51 | export async function streamOpenAIResponse(responseStream, config) { 52 | // Declare a variable to hold the full response text as we receive it in chunks from the API. 53 | let responseFull = ''; 54 | 55 | try { 56 | const bodyStream = await fetchData(config); 57 | for await (const chunk of bodyStream) { 58 | const lines = processChunk(chunk); 59 | for (const line of lines) { 60 | const content = line.choices[0].delta.content; 61 | if (content) { 62 | responseStream.write(content); 63 | responseFull += content; 64 | } 65 | } 66 | } 67 | } catch (error) { 68 | console.error('Error in streamOpenAIResponse:', error); 69 | throw error; 70 | } 71 | return responseFull; 72 | } 73 | 74 | // Inspired by https://umaar.com/dev-tips/269-web-streams-openai/ 75 | -------------------------------------------------------------------------------- /template.yml: -------------------------------------------------------------------------------- 1 | # template.yml tells AWS-SAM what resources we need to build for our application. 2 | 3 | AWSTemplateFormatVersion: '2010-09-09' # Specifies the AWS CloudFormation template version. 4 | Transform: AWS::Serverless-2016-10-31 # Specifies that the file is an AWS SAM template. 5 | 6 | # What resources we want to create in AWS 7 | Resources: 8 | lambdaopenai: # The name of the resource. 9 | Type: AWS::Serverless::Function # The resource is a Lambda function. 10 | Properties: 11 | CodeUri: ./src # The location of the function code is in the current directory. 12 | Handler: index.handler # The file and the method in your code that AWS Lambda calls. 13 | Runtime: nodejs18.x # The runtime environment. 14 | Architectures: # arm64 or x86_64. 15 | - arm64 16 | MemorySize: 512 # Lambda function memory in MB. 17 | Timeout: 30 # The amount of time that Lambda allows a function to run before stopping it. 18 | FunctionUrlConfig: 19 | AuthType: NONE # The function can be called by anyone via a public URL. 20 | InvokeMode: RESPONSE_STREAM # The function is returning the response as stream. 21 | 22 | # When everything is done, return information about the created resources 23 | Outputs: 24 | endpoint: 25 | Description: "Lambda Function URL Endpoint" 26 | Value: 27 | Fn::GetAtt: lambdaopenaiUrl.FunctionUrl 28 | endpointexample: 29 | Description: "Lambda Function URL Endpoint Example" 30 | Value: !Sub 31 | - "${FunctionUrl}?message=Write%20a%20haiku." 32 | - FunctionUrl: !GetAtt lambdaopenaiUrl.FunctionUrl 33 | -------------------------------------------------------------------------------- /test_locally.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | sam build --cached --parallel 3 | sam local invoke --event event.json 4 | --------------------------------------------------------------------------------