├── .gitignore ├── 00-api_gateway_managed_endpoint.ipynb ├── LICENSE ├── README.md ├── app.py ├── cdk.json ├── config ├── configs.json ├── example-configs.json └── sagemaker-invoke.json ├── construct ├── sagemaker_async_endpoint_construct.py └── sagemaker_endpoint_construct.py ├── docs └── diagram.png ├── functions ├── auth │ └── auth.py ├── falcon │ └── app.py ├── flan │ └── app.py ├── start_stop_endpoint │ └── app.py └── update_expiry │ └── app.py ├── requirements-dev.txt ├── requirements.txt ├── source.bat ├── stack ├── __init__.py ├── api_stack.py ├── endpoint_manager_stack.py ├── foundation_model_stack.py ├── lambda_stack.py ├── sagemaker_endpoint_manager_stack.py ├── stepfunction_stack.py └── util.py ├── tests ├── __init__.py └── unit │ ├── __init__.py │ └── test_sagemaker_jumpstart_generative_ai_app_stack.py └── utils ├── __init__.py └── sagemaker_helper.py /.gitignore: -------------------------------------------------------------------------------- 1 | *.swp 2 | package-lock.json 3 | __pycache__ 4 | .pytest_cache 5 | .venv 6 | *.egg-info 7 | 8 | # CDK asset staging directory 9 | .cdk.staging 10 | cdk.out 11 | -------------------------------------------------------------------------------- /00-api_gateway_managed_endpoint.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "attachments": {}, 5 | "cell_type": "markdown", 6 | "metadata": {}, 7 | "source": [ 8 | "# Deploying a auto start/stop Amazon SageMaker Foundation Model endpoint backed by a API Gateway/Lambda" 9 | ] 10 | }, 11 | { 12 | "attachments": {}, 13 | "cell_type": "markdown", 14 | "metadata": {}, 15 | "source": [ 16 | "In this notebook, we will run through examples of managing your SageMaker endpoint with the endpoint manager functionality.\n", 17 | "\n", 18 | "We will also walkthrough an example on how to interact with the API gateway endpoint secured by a Lambda authoerizer." 19 | ] 20 | }, 21 | { 22 | "cell_type": "code", 23 | "execution_count": null, 24 | "metadata": {}, 25 | "outputs": [], 26 | "source": [ 27 | "import requests\n", 28 | "import json\n", 29 | "import time" 30 | ] 31 | }, 32 | { 33 | "attachments": {}, 34 | "cell_type": "markdown", 35 | "metadata": {}, 36 | "source": [ 37 | "Set your API gateway URL and auth token\n", 38 | "\n", 39 | "`https://.execute-api..amazonaws.com/prod/`\n", 40 | "\n", 41 | "`'Authorization': ''`" 42 | ] 43 | }, 44 | { 45 | "cell_type": "code", 46 | "execution_count": null, 47 | "metadata": {}, 48 | "outputs": [], 49 | "source": [ 50 | "url='https://.execute-api.us-east-1.amazonaws.com/prod/'\n", 51 | "headers = {\n", 52 | " 'Content-Type': 'application/json',\n", 53 | " 'Accept': 'application/json',\n", 54 | " 'Authorization': '',\n", 55 | " # 'X-Amzn-SageMaker-Custom-Attributes': 'accept_eula=true' # Uncomment this line if you are using a llama2\n", 56 | "}" 57 | ] 58 | }, 59 | { 60 | "attachments": {}, 61 | "cell_type": "markdown", 62 | "metadata": {}, 63 | "source": [ 64 | "### Real-time Endpoint Management Functions\n", 65 | "When you create your endpoint for the first time, it will initialize it with the default provision time in minutes. You can check the available time left on your endpoint by either querying a specific endpoint or get a list of endpoint.\n", 66 | "\n", 67 | "#### Querying time left for a specific endpoint\n", 68 | "\n", 69 | "You can check the time left for a specific endpoint by querying the `endpoint-expiry` api as part of the endpoint manager functionality and passing in the `EndpointName`. Below is an example on how to do this:" 70 | ] 71 | }, 72 | { 73 | "cell_type": "code", 74 | "execution_count": null, 75 | "metadata": {}, 76 | "outputs": [], 77 | "source": [ 78 | "# Set endpoint you like to lookup\n", 79 | "endpoint_name = 'demo-Falcon40B-Endpoint'\n", 80 | "\n", 81 | "# Flan example\n", 82 | "# endpoint_name = 'demo-FlanT5-Endpoint'\n", 83 | "\n", 84 | "# endpoint_name = 'demo-LLama-Endpoint'\n", 85 | "\n", 86 | "# endpoint_name = 'demo-LLama2-Endpoint'" 87 | ] 88 | }, 89 | { 90 | "cell_type": "code", 91 | "execution_count": null, 92 | "metadata": {}, 93 | "outputs": [], 94 | "source": [ 95 | "response = requests.get(url=f\"{url}/endpoint-expiry?EndpointName={endpoint_name}\", headers=headers)\n", 96 | "print(json.dumps(response.json(), indent=2))" 97 | ] 98 | }, 99 | { 100 | "attachments": {}, 101 | "cell_type": "markdown", 102 | "metadata": {}, 103 | "source": [ 104 | "#### Querying time left for all managed endpoints\n", 105 | "\n", 106 | "You can also get a list of managed endpoints and their respective time left. This can be done by using the `endpoint-expiry` api as well." 107 | ] 108 | }, 109 | { 110 | "cell_type": "code", 111 | "execution_count": null, 112 | "metadata": {}, 113 | "outputs": [], 114 | "source": [ 115 | "response = requests.get(url=f\"{url}/endpoint-expiry\", headers=headers)\n", 116 | "print(json.dumps(response.json(), indent=2))" 117 | ] 118 | }, 119 | { 120 | "attachments": {}, 121 | "cell_type": "markdown", 122 | "metadata": {}, 123 | "source": [ 124 | "#### Extending your real-time endpoint expiry time\n", 125 | "The managed endpoint API also provides you with the ability to extend the expiry date. Below is an example on how you can extend an endpoint by 30 minutes." 126 | ] 127 | }, 128 | { 129 | "cell_type": "code", 130 | "execution_count": null, 131 | "metadata": {}, 132 | "outputs": [], 133 | "source": [ 134 | "payload = {\n", 135 | " \"EndpointName\": endpoint_name,\n", 136 | " \"minutes\": 30\n", 137 | "}\n", 138 | "response = requests.post(url=f\"{url}/endpoint-expiry\", headers=headers, json=payload)\n", 139 | "print(json.dumps(response.json(), indent=2))" 140 | ] 141 | }, 142 | { 143 | "attachments": {}, 144 | "cell_type": "markdown", 145 | "metadata": {}, 146 | "source": [ 147 | "#### Adding a new real-time endpoint\n", 148 | "With the endpoint management API, you can also add a new real-time endpoint with pre-existing Amazon SageMaker endpoint configurations.\n", 149 | "\n", 150 | "Note: You can use the endpoint manager for any model regardless if it is jumpstart or not as long as you have a define Amazon SageMaker endpoint configuration." 151 | ] 152 | }, 153 | { 154 | "cell_type": "code", 155 | "execution_count": null, 156 | "metadata": {}, 157 | "outputs": [], 158 | "source": [ 159 | "new_endpoint_name=\"\"\n", 160 | "new_endpoint_config_name=\"\"" 161 | ] 162 | }, 163 | { 164 | "cell_type": "code", 165 | "execution_count": null, 166 | "metadata": {}, 167 | "outputs": [], 168 | "source": [ 169 | "payload = {\n", 170 | " \"EndpointName\": new_endpoint_name,\n", 171 | " \"EndpointConfigName\": new_endpoint_config_name,\n", 172 | " \"minutes\": 30\n", 173 | "}\n", 174 | "response = requests.post(url=f\"{url}/endpoint-expiry\", headers=headers, json=payload)\n", 175 | "print(json.dumps(response.json(), indent=2))" 176 | ] 177 | }, 178 | { 179 | "attachments": {}, 180 | "cell_type": "markdown", 181 | "metadata": {}, 182 | "source": [ 183 | "### Interacting with your endpoint via API gateway\n", 184 | "\n", 185 | "With the deploy API Gateway and model lambda, you can interact with your Amazon SageMaker endpoint through the internet via API Gateway. Below is an example on how to send your payload request to the falcon model." 186 | ] 187 | }, 188 | { 189 | "cell_type": "code", 190 | "execution_count": null, 191 | "metadata": {}, 192 | "outputs": [], 193 | "source": [ 194 | "# Falcon example\n", 195 | "payload = {\n", 196 | " \"inputs\": \"Write a program to compute factorial in python:\",\n", 197 | " \"parameters\": {\"max_new_tokens\": 200}\n", 198 | "}\n", 199 | "\n", 200 | "# FLAN example\n", 201 | "# payload = {\n", 202 | "# 'text_inputs':'Write a program to compute factorial in python:', \n", 203 | "# 'max_length': 100, \n", 204 | "# 'temperature': 0.0, \n", 205 | "# 'seed': 321\n", 206 | "# }\n", 207 | "\n", 208 | "# open-llama example\n", 209 | "# payload = {\n", 210 | "# \"text_inputs\": \"Building a website can be done in 10 simple steps:\",\n", 211 | "# \"max_length\": 110,\n", 212 | "# \"no_repeat_ngram_size\": 3,\n", 213 | "# }\n", 214 | "\n", 215 | "# llama-2 example\n", 216 | "# payload = {\n", 217 | "# \"inputs\": \"Building a website can be done in 10 simple steps:\",\n", 218 | "# \"parameters\" :\n", 219 | "# {\n", 220 | "# \"max_new_tokens\": 110, \n", 221 | "# \"top_p\": 0.9, \n", 222 | "# \"temperature\" : 0.1\n", 223 | "# }\n", 224 | "# }\n", 225 | "\n", 226 | "response = requests.post(url=f\"{url}/falcon\", headers=headers, json=payload)\n", 227 | "print(json.dumps(response.json(), indent=2))" 228 | ] 229 | }, 230 | { 231 | "cell_type": "markdown", 232 | "metadata": {}, 233 | "source": [ 234 | "## Asynchronously interacting with your real-time endpoint via API Gateway\n", 235 | "\n", 236 | "In some instances, the real-time endpoint may take longer than 30 seconds to return a responses. Due to API gateway's 30 second timeout hard limit, an asynchronous approach will be required. The following code show you an example on how to asynchronously interactive with your real-time endpoint via two API calls." 237 | ] 238 | }, 239 | { 240 | "cell_type": "code", 241 | "execution_count": null, 242 | "metadata": {}, 243 | "outputs": [], 244 | "source": [ 245 | "# Falcon example\n", 246 | "payload = {\n", 247 | " \"endpointname\": endpoint_name,\n", 248 | " \"body\": {\"inputs\": \"Write a program to compute factorial in python:\", \"parameters\": {\"max_new_tokens\": 200}}\n", 249 | "}\n", 250 | "\n", 251 | "response = requests.post(url=f\"{url}/startexecution\", headers=headers, json=payload)\n", 252 | "print(json.dumps(response.json(), indent=2))\n", 253 | "\n", 254 | "# Get the execution arn\n", 255 | "executionArn = response.json().get('executionArn')" 256 | ] 257 | }, 258 | { 259 | "cell_type": "code", 260 | "execution_count": null, 261 | "metadata": {}, 262 | "outputs": [], 263 | "source": [ 264 | "payload ={\n", 265 | " \"executionArn\": executionArn\n", 266 | "}\n", 267 | "response = requests.post(url=f\"{url}/describeexecution\", headers=headers, json=payload)\n", 268 | "\n", 269 | "while 'RUNNING' in response.json().get('status'):\n", 270 | " time.sleep(1)\n", 271 | " response = requests.post(url=f\"{url}/describeexecution\", headers=headers, json=payload)\n", 272 | " print(\"Step is still running...\")\n", 273 | "\n", 274 | "# Return results\n", 275 | "output = response.json().get('output')\n", 276 | "output_json = json.loads(output)\n", 277 | "body = json.loads(output_json['Body'])\n", 278 | "body[0]['generated_text']" 279 | ] 280 | }, 281 | { 282 | "attachments": {}, 283 | "cell_type": "markdown", 284 | "metadata": {}, 285 | "source": [ 286 | "#### Interactive with your endpoint via Langchain/APIGateway\n", 287 | "\n", 288 | "The deploy API can be used with the [Amazon API Gateway/Langchain](https://python.langchain.com/docs/ecosystem/integrations/amazon_api_gateway) integration.\n", 289 | "\n", 290 | "The following example will walk you through on how to interact with the API Gateway backed by a Lambda authorizer." 291 | ] 292 | }, 293 | { 294 | "cell_type": "code", 295 | "execution_count": null, 296 | "metadata": {}, 297 | "outputs": [], 298 | "source": [ 299 | "!pip install langchain==0.0.238" 300 | ] 301 | }, 302 | { 303 | "cell_type": "code", 304 | "execution_count": null, 305 | "metadata": {}, 306 | "outputs": [], 307 | "source": [ 308 | "from langchain.llms import AmazonAPIGateway\n", 309 | "from langchain.agents import load_tools\n", 310 | "from langchain.agents import initialize_agent\n", 311 | "from langchain.agents import AgentType" 312 | ] 313 | }, 314 | { 315 | "cell_type": "code", 316 | "execution_count": null, 317 | "metadata": {}, 318 | "outputs": [], 319 | "source": [ 320 | "llm = AmazonAPIGateway(api_url=f\"{url}/falcon\", headers=headers)" 321 | ] 322 | }, 323 | { 324 | "attachments": {}, 325 | "cell_type": "markdown", 326 | "metadata": {}, 327 | "source": [ 328 | "### Langchain LLM example" 329 | ] 330 | }, 331 | { 332 | "cell_type": "code", 333 | "execution_count": null, 334 | "metadata": {}, 335 | "outputs": [], 336 | "source": [ 337 | "parameters = {\n", 338 | " \"max_new_tokens\": 100,\n", 339 | " \"num_return_sequences\": 1,\n", 340 | " \"top_k\": 50,\n", 341 | " \"top_p\": 0.95,\n", 342 | " \"do_sample\": False,\n", 343 | " \"return_full_text\": True,\n", 344 | " \"temperature\": 0.2,\n", 345 | "}\n", 346 | "\n", 347 | "prompt = \"what day comes after Friday?\"\n", 348 | "llm.model_kwargs = parameters\n", 349 | "llm(prompt)" 350 | ] 351 | }, 352 | { 353 | "attachments": {}, 354 | "cell_type": "markdown", 355 | "metadata": {}, 356 | "source": [ 357 | "### Langchain/APIGateway Agent Example" 358 | ] 359 | }, 360 | { 361 | "cell_type": "code", 362 | "execution_count": null, 363 | "metadata": {}, 364 | "outputs": [], 365 | "source": [ 366 | "parameters = {\n", 367 | " \"max_new_tokens\": 50,\n", 368 | " \"num_return_sequences\": 1,\n", 369 | " \"top_k\": 250,\n", 370 | " \"top_p\": 0.25,\n", 371 | " \"do_sample\": False,\n", 372 | " \"temperature\": 0.1,\n", 373 | "}\n", 374 | "\n", 375 | "llm.model_kwargs = parameters\n", 376 | "\n", 377 | "# Next, let's load some tools to use. Note that the `llm-math` tool uses an LLM, so we need to pass that in.\n", 378 | "tools = load_tools([\"python_repl\", \"llm-math\"], llm=llm)\n", 379 | "\n", 380 | "# Finally, let's initialize an agent with the tools, the language model, and the type of agent we want to use.\n", 381 | "agent = initialize_agent(\n", 382 | " tools,\n", 383 | " llm,\n", 384 | " agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION,\n", 385 | " verbose=True,\n", 386 | ")\n", 387 | "\n", 388 | "# Now let's test it out!\n", 389 | "agent.run(\"\"\"\n", 390 | "Write a Python script that prints \"Hello, world!\"\n", 391 | "\"\"\")" 392 | ] 393 | }, 394 | { 395 | "cell_type": "code", 396 | "execution_count": null, 397 | "metadata": {}, 398 | "outputs": [], 399 | "source": [] 400 | } 401 | ], 402 | "metadata": { 403 | "kernelspec": { 404 | "display_name": "Python 3", 405 | "language": "python", 406 | "name": "python3" 407 | }, 408 | "language_info": { 409 | "codemirror_mode": { 410 | "name": "ipython", 411 | "version": 3 412 | }, 413 | "file_extension": ".py", 414 | "mimetype": "text/x-python", 415 | "name": "python", 416 | "nbconvert_exporter": "python", 417 | "pygments_lexer": "ipython3", 418 | "version": "3.11.3" 419 | }, 420 | "orig_nbformat": 4 421 | }, 422 | "nbformat": 4, 423 | "nbformat_minor": 2 424 | } 425 | -------------------------------------------------------------------------------- /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 2023 🤖 ANZ ML 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 | # Amazon SageMaker Endpoint Manager 3 | 4 | A solution that will allow you to deploy Amazon SageMaker Foundation Model endpoint backed by a API Gateway/Lambda with automation to start and stop your endpoints. 5 | 6 | The Amazon SageMaker Endpoint manager solution will allow you to expose your Amazon SageMaker foundation models through the Amazon API Gateway with a dynamodb authorizer using CDK. Amazon SageMaker Endpoint manager also features a mechanism to manage your real-time endpoint which will automatically start and stop your Amazon SageMaker endpoint through an expiry datetime configuration for each endpoint. Similar to a parking meter whereby you top up credits to ensure that your parking does not expire, in this case, you keep renewing the endpoint expiry date time to keep it running. 7 | 8 | This solution was designed to solve a recurring problem with users leaving their Amazon SageMaker endpoint on and forgetting to delete them after usage. The approach taken to solve this in the first iteration is to enforce users to renew their endpoint expiry times based on how much time need it up for. By doing so, it raises the awareness of the cost of the endpoint (particularly for LLM endpoint) and also ensure that the user is intentional as to how time they actually need to use the endpoint for testing and development. 9 | 10 | --- 11 | ## What's New 12 | 13 | 17/08/2023 14 | - Added the ability to asynchronously invoke the Amazon SageMaker real-time endpoint via API gateway 15 | - Collapsed stacks into a single root stack for a simplified deployment 16 | 17 | 01/08/2023 18 | - Added support for loading jumpstart models which uses a Model Package (i.e. Marketplace subscription) instead of a Docker image 19 | - Added the ability to send custom attributes via API Gateway/AWS integration when invoking the Amazon SageMaker endpoint by specifying the `X-Amzn-SageMaker-Custom-Attributes` in the request header. 20 | 21 | 27/07/2023 22 | - Added lambda exception handling 23 | - Added AWS Gateway direct AWS integration with Amazon SageMaker. To use AWS integration, set the `type` in the `integration` property to `api`. 24 | 25 | 20/07/2023 26 | - Added support for multiple endpoints and apis in a configuration file - `config/configs.json` file. 27 | - Consolidated realtime and async stack to simplify deployment. 28 | 29 | --- 30 | 31 | ## Table of contents 32 | - [Amazon SageMaker Endpoint Manager](#amazon-sagemaker-endpoint-manager) 33 | - [What's New](#whats-new) 34 | - [Table of contents](#table-of-contents) 35 | - [Demo Overview](#demo-overview) 36 | - [How to deploy the stack](#how-to-deploy-the-stack) 37 | - [Real-time Endpoint Management Functions - Querying your real-time endpoint expiry time](#real-time-endpoint-management-functions---querying-your-real-time-endpoint-expiry-time) 38 | - [Real-time Endpoint Management Functions - Extending your real-time endpoint expiry time](#real-time-endpoint-management-functions---extending-your-real-time-endpoint-expiry-time) 39 | - [Real-time Endpoint Management Functions - Adding a new real-time endpoint](#real-time-endpoint-management-functions---adding-a-new-real-time-endpoint) 40 | - [Interacting with your real-time endpoint via API](#interacting-with-your-real-time-endpoint-via-api) 41 | - [Asynchronously interacting with your real-time endpoint via API](#asynchronously-interacting-with-your-real-time-endpoint-via-api) 42 | - [Example Notebook](#example-notebook) 43 | - [Endpoint Manager Configurations](#endpoint-manager-configurations) 44 | - [**Jumpstart model**](#jumpstart-model) 45 | - [**Schedule Configuration**](#schedule-configuration) 46 | - [**Integration Configuration**](#integration-configuration) 47 | - [**Integration Properties**](#integration-properties) 48 | - [How does the endpoint manager work?](#how-does-the-endpoint-manager-work) 49 | - [To Do](#to-do) 50 | - [References](#references) 51 | ## Demo Overview 52 | 53 | ![Architecture Diagram](docs/diagram.png) 54 | 55 | --- 56 | 57 | ## How to deploy the stack 58 | 59 | 1. Create a python virtualenv 60 | 61 | ``` 62 | $ python3 -m venv .venv 63 | ``` 64 | 65 | 2. Activate your virtual environment 66 | 67 | For Mac/Linux platform: 68 | ``` 69 | $ source .venv/bin/activate 70 | ``` 71 | 72 | If you are a Windows platform, you would activate the virtualenv like this: 73 | 74 | ``` 75 | % .venv\Scripts\activate.bat 76 | ``` 77 | 3. Install required dependencies 78 | 79 | ``` 80 | $ pip install -r requirements.txt 81 | ``` 82 | 83 | 4. Bootstrap your environment (if required) 84 | 85 | If you have not previously used CDK, bootstrap your environment 86 | 87 | ``` 88 | $ cdk bootstrap 89 | ``` 90 | 91 | 5. Define your configuration 92 | 93 | Setup your Amazon SageMaker Endpoint Manager and configure the models that you'd like to deploy by opening the [`config/config.json`](config/configs.json) file with a text editor. Configure the project settings such as your `project_prefix`, `region_name` - region to deploy the stack and `ddb_auth_table_name`. For more information on the configuration, refer to the [Endpoint manager Configuration section](#endpoint-manager-configurations). 94 | 95 | Next define the jumpstart models you'd like to deploy. For more information on the jumpstart model configuration, refer to [jumpstart model configuration section](#example-jumpstart-model-configuration). Below, you can find an example of how to deploy a real-time falcon40b and flan jumpstart model. You will also find additional examples in the [`config/example-configs.json`](config/example-configs.json) file. 96 | 97 | ### Example Jumpstart model configuration 98 | 99 | **Falcon 40B - Realtime *publicly accessible* Endpoint configuration using apigateway/lambda integration** 100 | ``` 101 | { 102 | "name" : "Falcon40BPublic", 103 | "model_id" : "huggingface-llm-falcon-40b-instruct-bf16", 104 | "inference_instance_count": 2, 105 | "inference_instance_type" : "ml.g5.12xlarge", 106 | "inference_type": "realtime", 107 | "public": true, 108 | "schedule": { 109 | "initial_provision_minutes": 90 110 | }, 111 | "integration": { 112 | "type": "lambda", 113 | "properties": { 114 | "lambda_src": "functions/falcon", 115 | "api_resource_name": "falcon" 116 | } 117 | } 118 | } 119 | ``` 120 | 121 | **FLAN T5 - Realtime Endpoint configuration using apigateway/lambda integration** 122 | ``` 123 | { 124 | "name" : "FlanT5", 125 | "model_id" : "huggingface-text2text-flan-t5-xxl", 126 | "inference_instance_type" : "ml.g5.12xlarge", 127 | "inference_type": "realtime", 128 | "schedule": { 129 | "initial_provision_minutes": 0 130 | }, 131 | "integration": { 132 | "type": "lambda", 133 | "properties": { 134 | "lambda_src": "functions/flan", 135 | "api_resource_name": "flan" 136 | } 137 | } 138 | } 139 | ``` 140 | 141 | **FLAN T5 - Realtime Endpoint configuration using API Gateway/AWS Integration** 142 | ``` 143 | { 144 | "name" : "FlanT5", 145 | "model_id" : "huggingface-text2text-flan-t5-xxl", 146 | "inference_instance_type" : "ml.g5.12xlarge", 147 | "inference_type": "realtime", 148 | "schedule": { 149 | "initial_provision_minutes": 0 150 | }, 151 | "integration": { 152 | "type": "api", 153 | "properties": { 154 | "api_resource_name": "flan" 155 | } 156 | } 157 | } 158 | ``` 159 | 160 | **FLAT T5 - Asynchronous Endpoint configuration** 161 | ``` 162 | { 163 | "name" : "FlanT5Async", 164 | "model_id" : "huggingface-text2text-flan-t5-xxl", 165 | "inference_instance_type" : "ml.g5.8xlarge", 166 | "inference_type": "async" 167 | } 168 | ``` 169 | 170 | 6. Deploy the SageMaker Endpoint Manager solution stack 171 | 172 | **Note** If you're upgrading from a previous version of Amazon SageMaker Endpoint Manager, you may need to delete the existing stacks. Please refer to the following instructions [upgrade instructions](#upgrade-instructions). 173 | 174 | 175 | Deploy the end-to-end SageMaker Endpoint manager stack. This stack will deploy several nested stacks including: 176 | 1. API gateway stack: The API Gateway which will provide us with an internet facing API to interact with our Amazon SageMaker Endpoint and manage our Amazon SageMaker endpoint. The API Gateway is backed by a basic lambda authorizer with the authorization tokens stored in an Amazon DynamoDB database. 177 | 2. Endpoint Manager Stack: The stack includes several lambda functions that will be responsible for the automatic creation and deletion of your Amazon SageMaker real-time endpoints. 178 | 3. Model Stack: Deploys the predefined Amazon SageMaker endpoints and passthrough lambda (if configured). This stack will deploy all models in the list of jumpstart models. 179 | 4. Step function Stack: Stack to support asynchronous invocation of the Amazon SageMaker real-time endpoint fronted by the API Gateway 180 | 181 | ``` 182 | cdk deploy SagemakerEndpointManagerStack 183 | ``` 184 | 185 | ### Upgrade instructions 186 | If you're using an older version of Amazon SageMaker Endpoint Manager with the 3 separate stacks, you need to delete this stacks before deploying the new version. To do so, refer to the following instructions: 187 | 188 | 1. Checkout the older Amazon SageMaker version 189 | 190 | ``` 191 | git checkout 049e21e 192 | ``` 193 | 2. Delete the stacks. 194 | ``` 195 | cdk destroy --all 196 | ``` 197 | If you have any existing endpoints, make sure you manually delete the endpoints. 198 | 3. Switch back to the main branch 199 | ``` 200 | git checkout main 201 | ``` 202 | 4. Deploy the end-to-end SageMaker Endpoint manager stack. 203 | 204 | ``` 205 | cdk deploy SagemakerEndpointManagerStack 206 | ``` 207 | 208 | 7. Setup your auth 209 | 210 | In your AWS account, you will find a Dynamodb table `auth` which stores a token (or pass code) which you will use to as an authorization token to access the APIs. Create an item in the `auth` table with an attribute `token` and set the value to your pass code which you will use when calling the API. 211 | 212 | Now that you have setup your environment with a real-time endpoint, let's take a look at some of the functionality this solutions has to offer. 213 | 214 | --- 215 | ## Real-time Endpoint Management Functions - Querying your real-time endpoint expiry time 216 | 217 | When you create your endpoint for the first time, it will initialize it with the default provision time in minutes. You can check the available time left on your endpoint by either querying a specific endpoint or get a list of endpoint. 218 | 219 | To check the time left for a specific endpoint run the following: 220 | 221 | ``` 222 | curl --location 'https://xxxxxxxxxx.execute-api.us-east-1.amazonaws.com/prod/endpoint-expiry?EndpointName=' \ 223 | --header 'Authorization: ' 224 | ``` 225 | 226 | Example Request: 227 | ``` 228 | curl --location 'https://xxxxxxxxxx.execute-api.us-east-1.amazonaws.com/prod/endpoint-expiry?EndpointName=demo-Falcon40B-Endpoint' \ 229 | --header 'Authorization: ' 230 | ``` 231 | 232 | Example Response: 233 | ``` 234 | { 235 | "EndpointName": "demo-Falcon40B-Endpoint", 236 | "EndpointExpiry ": "22-06-2023-08-24-12", 237 | "TimeLeft": "00:00:10.21130" 238 | } 239 | ``` 240 | 241 | To check the time left for all endpoints configured, run the following: 242 | ``` 243 | curl --location 'https://xxxxxxxxxx.execute-api.us-east-1.amazonaws.com/prod/endpoint-expiry' \ 244 | --header 'Authorization: ' 245 | ``` 246 | 247 | Example Response 248 | ``` 249 | [ 250 | { 251 | "EndpointName": "demo-Falcon40B-Endpoint", 252 | "EndpointExpiry ": "26-06-2023-12-39-47", 253 | "TimeLeft": "0:24:05.157431" 254 | }, 255 | { 256 | "EndpointName": "another-ml-Endpoint", 257 | "EndpointExpiry ": "26-06-2023-13-15-27", 258 | "TimeLeft": "0:59:45.157396" 259 | } 260 | ] 261 | ``` 262 | --- 263 | ## Real-time Endpoint Management Functions - Extending your real-time endpoint expiry time 264 | 265 | To extend the amount of time your endpoint will be kept alive, run the following: 266 | 267 | ``` 268 | curl --location 'https://xxxxxxxxxx.execute-api.us-east-1.amazonaws.com/prod/endpoint-expiry' \ 269 | --header 'Authorization: ' \ 270 | --header 'Content-Type: application/json' \ 271 | --data '{ 272 | "EndpointName": "", 273 | "minutes": 274 | }' 275 | ``` 276 | 277 | The following example request will extend the endpoint uptime by 10 minutes: 278 | ``` 279 | curl --location 'https://xxxxxxxxxx.execute-api.us-east-1.amazonaws.com/prod/endpoint-expiry' \ 280 | --header 'Authorization: ' \ 281 | --header 'Content-Type: application/json' \ 282 | --data '{ 283 | "EndpointName": "demo-Falcon40B-Endpoint", 284 | "minutes": 10 285 | }' 286 | ``` 287 | 288 | Expected Response: 289 | ``` 290 | { 291 | "EndpointName": "demo-Falcon40B-Endpoint", 292 | "EndpointExpiry ": "26-06-2023-12-39-47", 293 | "TimeLeft": "0:30:46.596924" 294 | } 295 | ``` 296 | --- 297 | 298 | ## Real-time Endpoint Management Functions - Adding a new real-time endpoint 299 | 300 | With the endpoint management API, you can add a new real-time endpoint with pre-existing Amazon SageMaker endpoint configurations. 301 | 302 | **Note:** You can use the endpoint manager for any model regardless if it is jumpstart or not. 303 | 304 | Run the following API call to create a new real-time endpoint: 305 | 306 | ``` 307 | curl --location 'https://xxxxxxxxxx.execute-api.us-east-1.amazonaws.com/prod/endpoint-expiry' \ 308 | --header 'Authorization: ' \ 309 | --header 'Content-Type: application/json' \ 310 | --data '{ 311 | "EndpointName": "", 312 | "EndpointConfigName": "", 313 | "minutes": 314 | }' 315 | ``` 316 | 317 | The following API call will create a new endpoint with the name `test-inpainting-Endpoint` using the endpoint configuration `jumpstart-example-model-inpainting-cfg` with an initial uptime of 30 minutes. 318 | ``` 319 | curl --location 'https://xxxxxxxxxx.execute-api.us-east-1.amazonaws.com/prod/endpoint-expiry' \ 320 | --header 'Authorization: ' \ 321 | --header 'Content-Type: application/json' \ 322 | --data '{ 323 | "EndpointName": "test-inpainting-Endpoint", 324 | "EndpointConfigName": "jumpstart-example-model-inpainting-cfg", 325 | "minutes": 30 326 | }' 327 | ``` 328 | 329 | Example Response: 330 | ``` 331 | { 332 | "EndpointName": "test-inpainting-Endpoint", 333 | "EndpointExpiry ": "26-06-2023-13-15-27", 334 | "TimeLeft": 30 335 | } 336 | ``` 337 | 338 | --- 339 | ## Interacting with your real-time endpoint via API 340 | With the deploy API Gateway and model lambda, you can interact with your Amazon SageMaker endpoint through the internet. Below are examples of how you can interact with the falcon and flan api. 341 | 342 | **Falcon API** 343 | 344 | Sample request to interact with the **Falcon API**: 345 | ``` 346 | curl --location 'https://xxxxxxxxxx.execute-api.us-east-1.amazonaws.com/prod/falcon' \ 347 | --header 'Authorization: ' \ 348 | --header 'Content-Type: application/json' \ 349 | --data '{ 350 | "inputs": "Write a program to compute factorial in python:", 351 | "parameters": {"max_new_tokens": 200} 352 | }' 353 | ``` 354 | 355 | Sample Response: 356 | ``` 357 | [ 358 | { 359 | "generated_text": "\nYou can compute factorial in Python using the built-in function `math.factorial()`. Here's an example:\n\n```python\nimport math\n\nn = 5\nfactorial = math.factorial(n)\nprint(factorial)\n```\n\nThis will output `120`, which is the factorial of 5." 360 | } 361 | ] 362 | ``` 363 | **Flan API** 364 | 365 | Sample request to interact with the **Flan API**: 366 | 367 | ``` 368 | curl --location 'https://xxxxxxxxxx.execute-api.us-east-1.amazonaws.com/prod/flan' \ 369 | --header 'Authorization: ' \ 370 | --header 'Content-Type: application/json' \ 371 | --data '{ 372 | "text_inputs":"write a story about beautiful weather on a topical island.", 373 | "max_length": 50, 374 | "temperature": 0.0, 375 | "seed": 321 376 | }' 377 | ``` 378 | 379 | Expected response 380 | ``` 381 | { 382 | "generated_texts": [ 383 | "..." 384 | ] 385 | } 386 | ``` 387 | --- 388 | ## Asynchronously interacting with your real-time endpoint via API 389 | 390 | In some cases, the inference may take more than 30 seconds which exceeds the API gateway timeout limit. As such an alternative approach to invoking the real-time Amazon SageMaker endpoint is required. This solution provide you with a mechanism to asynchronously invoke the endpoint and retrieve the response when the invocation has been completed. To run inference asynchronously, you will call the API in two step. The first to send your prompt `https://xxxxxxxxxx.execute-api.us-east-1.amazonaws.com/prod/startexecution` and the second to retrieve the result `https://xxxxxxxxxx.execute-api.us-east-1.amazonaws.com/prod/describeexecution`. 391 | 392 | 393 | Send prompt to API request 394 | ``` 395 | curl --location 'https://xxxxxxxxxx.execute-api.us-east-1.amazonaws.com/prod/startexecution' \ 396 | --header 'Authorization: ' \ 397 | --header 'Content-Type: application/json' \ 398 | --data '{ 399 | "endpointname": "demo-Falcon40B-Endpoint", 400 | "body": {"inputs": "Write a program to compute factorial in python:", "parameters": {"max_new_tokens": 200}} 401 | }' 402 | ``` 403 | 404 | Example Send prompt response 405 | ``` 406 | { 407 | "executionArn": "arn:aws:states:us-east-1:xxxxxxxxxxxxx:execution:SageMakerInvokeStepfunctionD7692275-BlnWWEoa6OY7:d7bde7bb-084a-4a29-b025-98" 408 | } 409 | ``` 410 | 411 | Once you've sent a prompt request, you will be provided with an executionARN. You will then use this response and send it to the retrieval API. Refer to the example below. 412 | 413 | Retrieve an invocation API request 414 | ``` 415 | curl --location 'https://xxxxxxxxxx.execute-api.us-east-1.amazonaws.com/prod/describeexecution' \ 416 | --header 'Authorization: ' \ 417 | --header 'Content-Type: application/json' \ 418 | --data '{ 419 | "executionArn": "arn:aws:states:us-east-1:xxxxxxxxxxxxx:execution:SageMakerInvokeStepfunctionD7692275-BlnWWEoa6OY7:d7bde7bb-084a-4a29-b025-98d9da47ce44" 420 | }' 421 | ``` 422 | 423 | If successful, you will get a response with a the status parameter as `SUCCEEDED`. If the invocation has a status of `RUNNING`, run the request again until you get a `SUCCEEDED` state. The output of the response can be found in the `output` parameter. 424 | 425 | Example retrieval response 426 | ``` 427 | { 428 | "executionArn": "arn:aws:states:us-east-1:xxxxxxxxxxxxx:execution:SageMakerInvokeStepfunctionD7692275-BlnWWEoa6OY7:d7bde7bb-084a-4a29-b025-98d9da47ce44", 429 | "input": "{\"endpointname\":\"demo-Falcon40B-Endpoint\",\"body\":{\"inputs\":\"Write a program to compute factorial in python:\",\"parameters\":{\"max_new_tokens\":200}}}", 430 | "inputDetails": { 431 | "__type": "com.amazonaws.swf.base.model#CloudWatchEventsExecutionDataDetails", 432 | "included": true 433 | }, 434 | "name": "d7bde7bb-084a-4a29-b025-98d9da47ce44", 435 | "output": "{\"Body\":\"[{\\\"generated_text\\\":\\\"\\\\nYou can compute factorial in Python using the built-in function `math.factorial()`. Here's an example:\\\\n\\\\n```python\\\\nimport math\\\\n\\\\nn = 5\\\\nfactorial = math.factorial(n)\\\\nprint(factorial)\\\\n```\\\\n\\\\nThis will output `120`, which is the factorial of 5.\\\"}]\",\"ContentType\":\"application/json\",\"InvokedProductionVariant\":\"AllTraffic\"}", 436 | ... 437 | "startDate": 1.691411436575E9, 438 | "stateMachineArn": "arn:aws:states:us-east-1:xxxxxxxxxxxxx:stateMachine:SageMakerInvokeStepfunctionD7692275-BlnWWEoa6OY7", 439 | "status": "SUCCEEDED", 440 | ... 441 | } 442 | ``` 443 | 444 | --- 445 | ## Example Notebook 446 | 447 | You can also interact with the API gateway via notebook. To do so, clone this repository or copy `00-api_gateway_managed_endpoint.ipynb` to your notebook environment (i.e. Amazon SageMaker Studio) and run through the instructions in the notebook. 448 | 449 | The notebook will show you how to manage your endpoint, interact with your SageMaker endpoint API And how to use Langchain with APIGateway. 450 | 451 | --- 452 | 453 | ## Endpoint Manager Configurations 454 | Endpoint manager configurations: 455 | - `project_prefix` 456 | - Description: Project prefix name to use for all resources 457 | - Type: String 458 | - Required: Yes 459 | - `region_name` 460 | - Description: AWS region to deploy the CDK solution and endpoint 461 | - Type: String 462 | - Example values: `us-east-1` | `us-west-1` 463 | - `ddb_auth_table_name` 464 | - Description: Name of the dynamodb table to store your auth token for your API Gateway 465 | - Type: String 466 | - `jumpstart_models` 467 | - Description: List of jumpstart models configurations 468 | - Type: Array of [Jumpstart model](#jumpstart-model) 469 | 470 | ### **Jumpstart model** 471 | Jumpstart model configurations 472 | - `name` 473 | - Description: Name of model 474 | - Type: String 475 | - Required: Yes 476 | - `model_id` 477 | - Description: Jumpstart model ID (A list of model id can be found [here](https://sagemaker.readthedocs.io/en/stable/doc_utils/pretrainedmodels.html)) 478 | - Type: String 479 | - Required: Yes 480 | - `inference_instance_count` 481 | - Description: Number of instances to use for inference 482 | - Type: Integer 483 | - Required: No 484 | - Default: 1 485 | - `inference_instance_type` 486 | - Description: Size of the instance type to use 487 | - Type: String 488 | - Required: Yes 489 | - `inference_type` 490 | - Description: Type of inference endpoint to be deployed - Real-time or asynchronous 491 | - Type: String 492 | - Required: Yes 493 | - Valid Options: `realtime` | `async` 494 | - `public` 495 | - Description: Whether to accept un-authenticated inference requests (without an API token) for this model 496 | - Type: Boolean 497 | - Required: No 498 | - Default: false 499 | - `schedule` 500 | - Description: Schedule configuration for the endpoint 501 | - Type: [Schedule Configuration](#schedule-config) object 502 | - `integration` 503 | - Description: Endpoint integration configurations. 504 | - Type: [Integration](#integration-configuration) object. 505 | 506 | 507 | ### **Schedule Configuration** 508 | SageMaker Endpoint Schedule configuration (Currently supports expiring endpoints). 509 | - `initial_provision_minutes` 510 | - Description: Initial time the endpoint will be provisioned for when the CDK stack is deployed in minutes. 511 | - Type: Integer 512 | 513 | 514 | ### **Integration Configuration** 515 | Endpoint integration configurations 516 | - `type` 517 | - Description: Indicates the type of API Gateway integration with the endpoint. If using lambda integration, ensure that you specify the `lambda_src` configuration in the integration properties. 518 | - Type: String 519 | - Required: Yes 520 | - Valid Options: `lambda` | `api` 521 | - `properties` 522 | - Description: Integration properties 523 | - Type: [Integration Properties](#integration-properties) 524 | 525 | ### **Integration Properties** 526 | Integration specific configurations 527 | - `lambda_src` 528 | - Description: Path to the lambda handler for the API Gateway/Endpoint integration. 529 | - Type: String 530 | - Required: Yes for lambda integration type. 531 | - `api_resource_name` 532 | - Description: API gateway resource name. For example, setting it to `falcon` will result in the API gateway path as `https://.execute-api.us-east-1.amazonaws.com/prod/falcon` 533 | - Type: String 534 | - Required: Yes 535 | 536 | --- 537 | ## How does the endpoint manager work? 538 | 539 | 1. When the stack is provisioned for the first time, the user defined the initial required endpoint provision time in minutes (`initial_provision_time_minutes`) in the `app.py` 540 | 2. Once provisioned, a start/stop lambda will poll a list of Amazon SageMaker Parameter store parameter with the prefix `/sagemaker/endpoint/expiry/*` to check the expiry date/time for each endpoint. If the date/time is not expired and an endpoint has not been created, the lambda will create the model endpoint. 541 | 3. If the expiry datetime is less than the current time, the lambda will automatically delete the endpoint. 542 | 4. Users can check the time left on their endpoint by querying the `endpoint-expiry` API. For more information refer to [Real-time Endpoint Management Functions - Querying your real-time endpoint expiry time](#real-time-endpoint-management-functions---querying-your-real-time-endpoint-expiry-time). 543 | 5. Users can also extend the endpoint uptime by sending a request to the `endpoint-expiry` API by providing the time in minutes the request body. For more information, refer to [Real-time Endpoint Management Functions - Extending your real-time endpoint expiry](#real-time-endpoint-management-functions---extending-your-real-time-endpoint-expiry-time). 544 | 6. You can also add a new endpoint to be managed by the endpoint manager for pre-existing Amazon SageMaker endpoint configurations. For more information, refer to [Real-time Endpoint Management Functions - Adding a new real-time endpoint](#real-time-endpoint-management-functions---adding-a-new-real-time-endpoint). 545 | --- 546 | ## To Do 547 | - [x] Bug - if time is expired, extending the time will need to be greater than the different of current time + time required. Will need to add a check to see if time is expired, add time from now + time required. 548 | - [x] Add support for multiple endpoints 549 | - [x] Add support for managing existing endpoints 550 | - [x] Add support for adding new endpoints via API 551 | - [x] Improve lambda error handling 552 | - [x] Add API gateway/AWS integration 553 | - [x] Add support for asynchronous invocation of Amazon SageMaker real-time endpoint 554 | - [ ] Add support for scheduled endpoints (i.e. M-F 9-5) 555 | - [ ] Add support for cognito users 556 | - [ ] Add support for expiry notifications 557 | - [ ] Add UI to manage endpoint expiry 558 | - [ ] Automatic shutdown of endpoint based on endpoint activity (i.e. None: 30 | super().__init__(scope, construct_id) 31 | 32 | if model_package_arn is not None: 33 | # Deploy model using model package arn 34 | container = [ 35 | sagemaker.CfnModel.ContainerDefinitionProperty( 36 | model_package_name=model_package_arn 37 | ) 38 | ] 39 | else: 40 | # Deploy model using docker image 41 | container = [ 42 | sagemaker.CfnModel.ContainerDefinitionProperty( 43 | image= model_docker_image, 44 | model_data_url= f"s3://{model_bucket_name}/{model_bucket_key}", 45 | environment= environment 46 | ) 47 | ] 48 | 49 | model = sagemaker.CfnModel(self, f"{model_name}-Model", 50 | execution_role_arn= role_arn, 51 | containers=container, 52 | enable_network_isolation=enable_network_isolation 53 | ) 54 | 55 | config = sagemaker.CfnEndpointConfig(self, f"{model_name}-Config", 56 | production_variants=[ 57 | sagemaker.CfnEndpointConfig.ProductionVariantProperty( 58 | model_name= model.attr_model_name, 59 | variant_name= variant_name, 60 | initial_variant_weight= variant_weight, 61 | initial_instance_count= instance_count, 62 | instance_type= instance_type 63 | ) 64 | ], 65 | async_inference_config=sagemaker.CfnEndpointConfig.AsyncInferenceConfigProperty( 66 | output_config=sagemaker.CfnEndpointConfig.AsyncInferenceOutputConfigProperty( 67 | notification_config=sagemaker.CfnEndpointConfig.AsyncInferenceNotificationConfigProperty( 68 | error_topic=error_topic, 69 | success_topic=success_topic 70 | ), 71 | s3_output_path=f"s3://{s3_async_bucket}/async_inference_output", 72 | s3_failure_path=f"s3://{s3_async_bucket}/async_inference_failure" 73 | ), 74 | # the properties below are optional 75 | client_config=sagemaker.CfnEndpointConfig.AsyncInferenceClientConfigProperty( 76 | max_concurrent_invocations_per_instance=4 77 | ) 78 | ) 79 | ) 80 | 81 | self.deploy_enable = deploy_enable 82 | if deploy_enable: 83 | self.endpoint = sagemaker.CfnEndpoint(self, f"{model_name}-Endpoint", 84 | endpoint_name= f"{project_prefix}-{model_name}-Endpoint", 85 | endpoint_config_name= config.attr_endpoint_config_name 86 | ) 87 | 88 | CfnOutput(scope=self,id=f"{model_name}EndpointName", value=self.endpoint.endpoint_name) 89 | 90 | @property 91 | def endpoint_name(self) -> str: 92 | """Return endpoint name""" 93 | return self.endpoint.attr_endpoint_name if self.deploy_enable else "not_yet_deployed" 94 | -------------------------------------------------------------------------------- /construct/sagemaker_endpoint_construct.py: -------------------------------------------------------------------------------- 1 | """SageMaker Endpoint Construct""" 2 | from typing import Optional 3 | from aws_cdk import ( 4 | aws_sagemaker as sagemaker, 5 | CfnOutput 6 | ) 7 | from constructs import Construct 8 | 9 | class SageMakerEndpointConstruct(Construct): 10 | """Class representing a real-time SageMaker Endpoint Construct""" 11 | 12 | def __init__(self, scope: Construct, construct_id: str, 13 | project_prefix: str, 14 | role_arn: str, 15 | model_name: str, 16 | model_bucket_name: Optional[str], 17 | model_bucket_key: Optional[str], 18 | model_docker_image: Optional[str], 19 | variant_name: str, 20 | variant_weight: int, 21 | instance_count: int, 22 | instance_type: str, 23 | environment: dict, 24 | deploy_enable: bool, 25 | model_package_arn: Optional[str], 26 | enable_network_isolation: Optional[bool]) -> None: 27 | super().__init__(scope, construct_id) 28 | 29 | # Do not use a custom named resource for models as these get replaced 30 | if model_package_arn is not None: 31 | # Deploy model using model package arn 32 | container = [ 33 | sagemaker.CfnModel.ContainerDefinitionProperty( 34 | model_package_name=model_package_arn 35 | ) 36 | ] 37 | else: 38 | # Deploy model using docker image 39 | container = [ 40 | sagemaker.CfnModel.ContainerDefinitionProperty( 41 | image= model_docker_image, 42 | model_data_url= f"s3://{model_bucket_name}/{model_bucket_key}", 43 | environment= environment 44 | ) 45 | ] 46 | 47 | model = sagemaker.CfnModel(self, f"{model_name}-Model", 48 | execution_role_arn= role_arn, 49 | containers=container, 50 | enable_network_isolation=enable_network_isolation 51 | ) 52 | 53 | self.config = sagemaker.CfnEndpointConfig(self, f"{model_name}-Config", 54 | production_variants=[ 55 | sagemaker.CfnEndpointConfig.ProductionVariantProperty( 56 | model_name= model.attr_model_name, 57 | variant_name= variant_name, 58 | initial_variant_weight= variant_weight, 59 | initial_instance_count= instance_count, 60 | instance_type= instance_type 61 | ) 62 | ] 63 | ) 64 | 65 | self.deploy_enable = deploy_enable 66 | if deploy_enable: 67 | self.endpoint = sagemaker.CfnEndpoint(self, f"{model_name}-Endpoint", 68 | endpoint_name= f"{project_prefix}-{model_name}-Endpoint", 69 | endpoint_config_name= self.config.attr_endpoint_config_name 70 | ) 71 | 72 | CfnOutput(scope=self,id=f"{model_name}EndpointName", value=self.endpoint.endpoint_name) 73 | 74 | @property 75 | def endpoint_name(self) -> str: 76 | """Return endpoint name""" 77 | return self.endpoint.attr_endpoint_name if self.deploy_enable else "not_yet_deployed" 78 | -------------------------------------------------------------------------------- /docs/diagram.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/dalacan/sagemaker-endpoint-manager/eaefa6c702bf7c1633bcb69e41862bba04de0f44/docs/diagram.png -------------------------------------------------------------------------------- /functions/auth/auth.py: -------------------------------------------------------------------------------- 1 | """ 2 | Copyright 2015-2016 Amazon.com, Inc. or its affiliates. All Rights Reserved. 3 | 4 | Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with the License. A copy of the License is located at 5 | 6 | http://aws.amazon.com/apache2.0/ 7 | 8 | or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. 9 | """ 10 | from __future__ import print_function 11 | 12 | import os 13 | import re 14 | import boto3 15 | import json 16 | 17 | dynamodb = boto3.resource('dynamodb') 18 | 19 | 20 | def handler(event, context): 21 | table = os.environ.get("TABLE_NAME") 22 | """Do not print the auth token unless absolutely necessary """ 23 | #print("Client token: " + event['authorizationToken']) 24 | print("Method ARN: " + event['methodArn']) 25 | """validate the incoming token""" 26 | """and produce the principal user identifier associated with the token""" 27 | 28 | """this could be accomplished in a number of ways:""" 29 | """1. Call out to OAuth provider""" 30 | """2. Decode a JWT token inline""" 31 | """3. Lookup in a self-managed DB""" 32 | principalId = "user" 33 | 34 | """you can send a 401 Unauthorized response to the client by failing like so:""" 35 | """raise Exception('Unauthorized')""" 36 | 37 | """if the token is valid, a policy must be generated which will allow or deny access to the client""" 38 | 39 | """if access is denied, the client will recieve a 403 Access Denied response""" 40 | """if access is allowed, API Gateway will proceed with the backend integration configured on the method that was called""" 41 | 42 | """this function must generate a policy that is associated with the recognized principal user identifier.""" 43 | """depending on your use case, you might store policies in a DB, or generate them on the fly""" 44 | 45 | """keep in mind, the policy is cached for 5 minutes by default (TTL is configurable in the authorizer)""" 46 | """and will apply to subsequent calls to any method/resource in the RestApi""" 47 | """made with the same token""" 48 | 49 | """the example policy below denies access to all resources in the RestApi""" 50 | tmp = event['methodArn'].split(':') 51 | apiGatewayArnTmp = tmp[5].split('/') 52 | awsAccountId = tmp[4] 53 | 54 | policy = AuthPolicy(principalId, awsAccountId) 55 | policy.restApiId = apiGatewayArnTmp[0] 56 | policy.region = tmp[3] 57 | policy.stage = apiGatewayArnTmp[1] 58 | 59 | # Check here 60 | token = event['headers']['Authorization'] 61 | 62 | try: 63 | auth_table = dynamodb.Table(table) 64 | response = auth_table.get_item( 65 | Key={"token": token} 66 | ) 67 | except Exception as e: 68 | print("Exception") 69 | policy.denyAllMethods() 70 | else: 71 | if 'Item' in response: 72 | print("Allowing access") 73 | policy.allowAllMethods() 74 | else: 75 | print("Not found, access denied.") 76 | policy.denyAllMethods() 77 | 78 | # Finally, build the policy 79 | authResponse = policy.build() 80 | 81 | # return authResponse 82 | return json.loads(json.dumps(authResponse, default=str)) 83 | 84 | class HttpVerb: 85 | GET = "GET" 86 | POST = "POST" 87 | PUT = "PUT" 88 | PATCH = "PATCH" 89 | HEAD = "HEAD" 90 | DELETE = "DELETE" 91 | OPTIONS = "OPTIONS" 92 | ALL = "*" 93 | 94 | class AuthPolicy(object): 95 | awsAccountId = "" 96 | """The AWS account id the policy will be generated for. This is used to create the method ARNs.""" 97 | principalId = "" 98 | """The principal used for the policy, this should be a unique identifier for the end user.""" 99 | version = "2012-10-17" 100 | """The policy version used for the evaluation. This should always be '2012-10-17'""" 101 | pathRegex = "^[/.a-zA-Z0-9-\*]+$" 102 | """The regular expression used to validate resource paths for the policy""" 103 | 104 | """these are the internal lists of allowed and denied methods. These are lists 105 | of objects and each object has 2 properties: A resource ARN and a nullable 106 | conditions statement. 107 | the build method processes these lists and generates the approriate 108 | statements for the final policy""" 109 | allowMethods = [] 110 | denyMethods = [] 111 | 112 | restApiId = "<>" 113 | """ Replace the placeholder value with a default API Gateway API id to be used in the policy. 114 | Beware of using '*' since it will not simply mean any API Gateway API id, because stars will greedily expand over '/' or other separators. 115 | See https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_resource.html for more details. """ 116 | 117 | region = "<>" 118 | """ Replace the placeholder value with a default region to be used in the policy. 119 | Beware of using '*' since it will not simply mean any region, because stars will greedily expand over '/' or other separators. 120 | See https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_resource.html for more details. """ 121 | 122 | stage = "<>" 123 | """ Replace the placeholder value with a default stage to be used in the policy. 124 | Beware of using '*' since it will not simply mean any stage, because stars will greedily expand over '/' or other separators. 125 | See https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_resource.html for more details. """ 126 | 127 | def __init__(self, principal, awsAccountId): 128 | self.awsAccountId = awsAccountId 129 | self.principalId = principal 130 | self.allowMethods = [] 131 | self.denyMethods = [] 132 | 133 | def _addMethod(self, effect, verb, resource, conditions): 134 | """Adds a method to the internal lists of allowed or denied methods. Each object in 135 | the internal list contains a resource ARN and a condition statement. The condition 136 | statement can be null.""" 137 | if verb != "*" and not hasattr(HttpVerb, verb): 138 | raise NameError("Invalid HTTP verb " + verb + ". Allowed verbs in HttpVerb class") 139 | resourcePattern = re.compile(self.pathRegex) 140 | if not resourcePattern.match(resource): 141 | raise NameError("Invalid resource path: " + resource + ". Path should match " + self.pathRegex) 142 | 143 | if resource[:1] == "/": 144 | resource = resource[1:] 145 | 146 | resourceArn = ("arn:aws:execute-api:" + 147 | self.region + ":" + 148 | self.awsAccountId + ":" + 149 | self.restApiId + "/" + 150 | self.stage + "/" + 151 | verb + "/" + 152 | resource) 153 | 154 | if effect.lower() == "allow": 155 | self.allowMethods.append({ 156 | 'resourceArn' : resourceArn, 157 | 'conditions' : conditions 158 | }) 159 | elif effect.lower() == "deny": 160 | self.denyMethods.append({ 161 | 'resourceArn' : resourceArn, 162 | 'conditions' : conditions 163 | }) 164 | 165 | def _getEmptyStatement(self, effect): 166 | """Returns an empty statement object prepopulated with the correct action and the 167 | desired effect.""" 168 | statement = { 169 | 'Action': 'execute-api:Invoke', 170 | 'Effect': effect[:1].upper() + effect[1:].lower(), 171 | 'Resource': [] 172 | } 173 | 174 | return statement 175 | 176 | def _getStatementForEffect(self, effect, methods): 177 | """This function loops over an array of objects containing a resourceArn and 178 | conditions statement and generates the array of statements for the policy.""" 179 | statements = [] 180 | 181 | if len(methods) > 0: 182 | statement = self._getEmptyStatement(effect) 183 | 184 | for curMethod in methods: 185 | if curMethod['conditions'] is None or len(curMethod['conditions']) == 0: 186 | statement['Resource'].append(curMethod['resourceArn']) 187 | else: 188 | conditionalStatement = self._getEmptyStatement(effect) 189 | conditionalStatement['Resource'].append(curMethod['resourceArn']) 190 | conditionalStatement['Condition'] = curMethod['conditions'] 191 | statements.append(conditionalStatement) 192 | 193 | statements.append(statement) 194 | 195 | return statements 196 | 197 | def allowAllMethods(self): 198 | """Adds a '*' allow to the policy to authorize access to all methods of an API""" 199 | self._addMethod("Allow", HttpVerb.ALL, "*", []) 200 | 201 | def denyAllMethods(self): 202 | """Adds a '*' allow to the policy to deny access to all methods of an API""" 203 | self._addMethod("Deny", HttpVerb.ALL, "*", []) 204 | 205 | def allowMethod(self, verb, resource): 206 | """Adds an API Gateway method (Http verb + Resource path) to the list of allowed 207 | methods for the policy""" 208 | self._addMethod("Allow", verb, resource, []) 209 | 210 | def denyMethod(self, verb, resource): 211 | """Adds an API Gateway method (Http verb + Resource path) to the list of denied 212 | methods for the policy""" 213 | self._addMethod("Deny", verb, resource, []) 214 | 215 | def allowMethodWithConditions(self, verb, resource, conditions): 216 | """Adds an API Gateway method (Http verb + Resource path) to the list of allowed 217 | methods and includes a condition for the policy statement. More on AWS policy 218 | conditions here: http://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements.html#Condition""" 219 | self._addMethod("Allow", verb, resource, conditions) 220 | 221 | def denyMethodWithConditions(self, verb, resource, conditions): 222 | """Adds an API Gateway method (Http verb + Resource path) to the list of denied 223 | methods and includes a condition for the policy statement. More on AWS policy 224 | conditions here: http://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements.html#Condition""" 225 | self._addMethod("Deny", verb, resource, conditions) 226 | 227 | def build(self): 228 | """Generates the policy document based on the internal lists of allowed and denied 229 | conditions. This will generate a policy with two main statements for the effect: 230 | one statement for Allow and one statement for Deny. 231 | Methods that includes conditions will have their own statement in the policy.""" 232 | if ((self.allowMethods is None or len(self.allowMethods) == 0) and 233 | (self.denyMethods is None or len(self.denyMethods) == 0)): 234 | raise NameError("No statements defined for the policy") 235 | 236 | policy = { 237 | 'principalId' : self.principalId, 238 | 'policyDocument' : { 239 | 'Version' : self.version, 240 | 'Statement' : [] 241 | } 242 | } 243 | 244 | policy['policyDocument']['Statement'].extend(self._getStatementForEffect("Allow", self.allowMethods)) 245 | policy['policyDocument']['Statement'].extend(self._getStatementForEffect("Deny", self.denyMethods)) 246 | 247 | return policy 248 | -------------------------------------------------------------------------------- /functions/falcon/app.py: -------------------------------------------------------------------------------- 1 | import os 2 | import boto3 3 | 4 | # grab environment variables 5 | ENDPOINT_NAME = os.environ['ENDPOINT_NAME'] 6 | client = boto3.client('runtime.sagemaker') 7 | 8 | def handler(event, context): 9 | 10 | payload = event['body'] 11 | 12 | try: 13 | response = client.invoke_endpoint( 14 | EndpointName=ENDPOINT_NAME, 15 | ContentType='application/json', 16 | Accept='application/json', 17 | Body=payload 18 | ) 19 | 20 | result = { 21 | "statusCode": 200, 22 | "headers": { 23 | 'Content-Type': 'text/json' 24 | }, 25 | "body": response["Body"].read() 26 | } 27 | except Exception as e: 28 | result = { 29 | "statusCode": 500, 30 | "headers": { 31 | 'Content-Type': 'text/json' 32 | }, 33 | "body": str(e) 34 | } 35 | 36 | return result 37 | -------------------------------------------------------------------------------- /functions/flan/app.py: -------------------------------------------------------------------------------- 1 | import os 2 | import json 3 | import boto3 4 | 5 | # grab environment variables 6 | ENDPOINT_NAME = os.environ['ENDPOINT_NAME'] 7 | runtime= boto3.client('runtime.sagemaker') 8 | 9 | def handler(event, context): 10 | payload = {'text_inputs':'write a sentence to suggest providing a custom input for the model inference', 'max_length': 50, 'temperature': 0.0, 'seed': 321} 11 | if event['body'] is not None : 12 | body = event['body'] 13 | else: 14 | body = json.dumps(payload) 15 | 16 | try: 17 | response = runtime.invoke_endpoint( 18 | EndpointName=ENDPOINT_NAME, 19 | Body=body, 20 | ContentType='application/json', 21 | Accept='application/json' ) 22 | 23 | response = response["Body"].read().decode('utf-8') 24 | 25 | result = { 26 | "statusCode": 200, 27 | "headers": { 28 | 'Content-Type': 'text/json' 29 | }, 30 | "body": response 31 | } 32 | except Exception as e: 33 | result = { 34 | "statusCode": 500, 35 | "headers": { 36 | 'Content-Type': 'text/json' 37 | }, 38 | "body": str(e) 39 | } 40 | 41 | return result 42 | -------------------------------------------------------------------------------- /functions/start_stop_endpoint/app.py: -------------------------------------------------------------------------------- 1 | import boto3 2 | import botocore 3 | from datetime import datetime 4 | import json 5 | 6 | sagemaker_client = boto3.client('sagemaker') 7 | ssm_client = boto3.client("ssm") 8 | 9 | def start_stop_endpoint(expiry_parameter_values): 10 | expiry = datetime.strptime(expiry_parameter_values['expiry'], '%d-%m-%Y-%H-%M-%S') 11 | now = datetime.utcnow() 12 | 13 | # Expired, delete endpoint 14 | if expiry < now: 15 | # Delete endpoint 16 | print("Endpoint has expired, deleting endpoint") 17 | try: 18 | sagemaker_client.delete_endpoint(EndpointName=expiry_parameter_values['endpoint_name']) 19 | except botocore.exceptions.ClientError as error: 20 | print("Error deleting endpoint") 21 | print(error) 22 | else: 23 | # Check if endpoint is expiring 24 | print("Endpoint is not expiring") 25 | try: 26 | print("Checking if endpoint exists") 27 | # Check endpoint exist 28 | describe_response = sagemaker_client.describe_endpoint( 29 | EndpointName=expiry_parameter_values['endpoint_name'] 30 | ) 31 | 32 | # Check if endpoint creation failed, it it has, delete it so that it can be created 33 | if describe_response['EndpointStatus'] == 'Failed': 34 | print("Endpoint creation failed, deleting endpoint") 35 | sagemaker_client.delete_endpoint(EndpointName=expiry_parameter_values['endpoint_name']) 36 | except botocore.exceptions.ClientError as error: 37 | # Endpoint does not exist, create endpoint 38 | if error.response['Error']['Code'] == 'ValidationException': 39 | print("Creating endpoint") 40 | try: 41 | create_endpoint_response = create_endpoint(expiry_parameter_values['endpoint_name'], expiry_parameter_values['endpoint_config_name']) 42 | except botocore.exceptions.ClientError as error: 43 | print("Error creating endpoint") 44 | else: 45 | print("Error describing endpoint") 46 | print(error) 47 | 48 | def create_endpoint(endpoint_name, endpoint_config_name): 49 | return sagemaker_client.create_endpoint( 50 | EndpointName=endpoint_name, 51 | EndpointConfigName=endpoint_config_name) 52 | 53 | def handler(event, context): 54 | # Get a list of endpoint expiry parameters 55 | response = ssm_client.get_parameters_by_path( 56 | Path="/sagemaker/endpoint/expiry/", 57 | Recursive=True) 58 | result = response["Parameters"] 59 | 60 | 61 | while "NextToken" in response: 62 | response = ssm_client.get_parameters_by_path( 63 | Path="/sagemaker/endpoint/expiry/", 64 | Recursive=True, 65 | NextToken=result["NextToken"]) 66 | result.extend(response["Parameters"]) 67 | 68 | # Process each endpoint expiry configuration 69 | for parameter in result: 70 | print("Processing endpoint") 71 | # endpoint_name = parameter['Name'].split("/")[-1] 72 | parameter_values = json.loads(parameter['Value']) 73 | start_stop_endpoint(parameter_values) -------------------------------------------------------------------------------- /functions/update_expiry/app.py: -------------------------------------------------------------------------------- 1 | import boto3 2 | import botocore 3 | import json 4 | 5 | from datetime import datetime, timedelta 6 | 7 | ssm_client = boto3.client("ssm") 8 | 9 | def get_expiry(expiry_parameter_values): 10 | expiry = datetime.strptime(expiry_parameter_values['expiry'], '%d-%m-%Y-%H-%M-%S') 11 | now = datetime.utcnow() 12 | time_left = expiry - now 13 | 14 | 15 | endpoint_expiry_info = { 16 | "EndpointName": expiry_parameter_values['endpoint_name'], 17 | "EndpointExpiry ": expiry_parameter_values['expiry'], 18 | "TimeLeft": str(time_left) 19 | } 20 | 21 | return endpoint_expiry_info 22 | 23 | def get_endpoint_expiry_info(event): 24 | if event['queryStringParameters'] is not None and 'EndpointName' in event['queryStringParameters']: 25 | print("Getting specific endpoint") 26 | # Get expiry 27 | expiry_parameter = ssm_client.get_parameter( 28 | Name=f"/sagemaker/endpoint/expiry/{event['queryStringParameters']['EndpointName']}", 29 | WithDecryption=False) 30 | expiry_parameter_values = json.loads(expiry_parameter['Parameter']['Value']) 31 | 32 | endpoint_expiry_info = get_expiry(expiry_parameter_values) 33 | 34 | response = { 35 | "statusCode": 200, 36 | "headers": { 37 | "Content-Type": "application/json" 38 | }, 39 | "body": json.dumps(endpoint_expiry_info) 40 | } 41 | else: 42 | print("Getting list of endpoint expiry") 43 | # Get a list of endpoint expiry parameters 44 | ssm_response = ssm_client.get_parameters_by_path( 45 | Path="/sagemaker/endpoint/expiry/", 46 | Recursive=True) 47 | result = ssm_response["Parameters"] 48 | 49 | 50 | while "NextToken" in ssm_response: 51 | ssm_response = ssm_client.get_parameters_by_path( 52 | Path="/sagemaker/endpoint/expiry/", 53 | Recursive=True, 54 | NextToken=result["NextToken"]) 55 | result.extend(ssm_response["Parameters"]) 56 | 57 | # Process each endpoint expiry configuration 58 | endpoint_expiry_info = [] 59 | for parameter in result: 60 | print("Processing endpoint") 61 | parameter_values = json.loads(parameter['Value']) 62 | endpoint_expiry_info.append(get_expiry(parameter_values)) 63 | 64 | response = { 65 | "statusCode": 200, 66 | "headers": { 67 | "Content-Type": "application/json" 68 | }, 69 | "body": json.dumps(endpoint_expiry_info) 70 | } 71 | 72 | return response 73 | 74 | def create_endpoint_config(endpoint_name, endpoint_config_name, provision_minutes): 75 | now = datetime.utcnow() 76 | expiry = now + timedelta(minutes=provision_minutes) 77 | expiry_str = expiry.strftime("%d-%m-%Y-%H-%M-%S") 78 | 79 | expiry_ssm_value = { 80 | "expiry": expiry_str, 81 | "endpoint_name": endpoint_name, 82 | "endpoint_config_name": endpoint_config_name 83 | } 84 | 85 | # Add new parameter 86 | ssm_response = ssm_client.put_parameter( 87 | Name=f"/sagemaker/endpoint/expiry/{endpoint_name}", 88 | Type="String", 89 | Overwrite=True, 90 | Value=json.dumps(expiry_ssm_value) 91 | ) 92 | 93 | return provision_minutes, expiry_str 94 | 95 | def update_endpoint_config(endpoint_name, provision_minutes, expiry_parameter_values): 96 | current_expiry = datetime.strptime(expiry_parameter_values['expiry'], '%d-%m-%Y-%H-%M-%S') 97 | 98 | # Check if current expiry is in the past 99 | now = datetime.utcnow() 100 | if current_expiry < now: 101 | current_expiry = now 102 | 103 | expiry = current_expiry + timedelta(minutes=provision_minutes) 104 | expiry_str = expiry.strftime("%d-%m-%Y-%H-%M-%S") 105 | 106 | time_left = expiry - now 107 | 108 | expiry_parameter_values['expiry'] = expiry_str 109 | 110 | # Update parameter 111 | ssm_response = ssm_client.put_parameter( 112 | Name=f"/sagemaker/endpoint/expiry/{endpoint_name}", 113 | Overwrite=True, 114 | Value=json.dumps(expiry_parameter_values) 115 | ) 116 | 117 | return time_left, expiry_str 118 | 119 | def create_update_endpoint_expiry(event): 120 | if event['body'] is not None : 121 | # Update expiry 122 | body = json.loads(event["body"]) 123 | 124 | if 'EndpointName' not in body: 125 | response = { 126 | "statusCode": 400, 127 | "body": json.dumps({"error": "EndpointName required"}) 128 | } 129 | return response 130 | 131 | try: 132 | endpoint_name = body['EndpointName'] 133 | expiry_parameter = ssm_client.get_parameter( 134 | Name=f"/sagemaker/endpoint/expiry/{endpoint_name}", 135 | WithDecryption=False) 136 | 137 | expiry_parameter_values = json.loads(expiry_parameter['Parameter']['Value']) 138 | 139 | print("Updating endpoint") 140 | time_left, expiry_str = update_endpoint_config(endpoint_name, body['minutes'], expiry_parameter_values) 141 | 142 | response = { 143 | "statusCode": 200, 144 | "headers": { 145 | "Content-Type": "application/json" 146 | }, 147 | "body": json.dumps({ 148 | "EndpointName": endpoint_name, 149 | "EndpointExpiry ": expiry_str, 150 | "TimeLeft": str(time_left) 151 | }) 152 | } 153 | except botocore.exceptions.ClientError as error: 154 | if error.response['Error']['Code'] == 'ParameterNotFound': 155 | if 'EndpointConfigName' in body: 156 | print("Creating new endpoint config") 157 | time_left, expiry_str = create_endpoint_config(endpoint_name, body['EndpointConfigName'], body['minutes']) 158 | 159 | response = { 160 | "statusCode": 200, 161 | "headers": { 162 | "Content-Type": "application/json" 163 | }, 164 | "body": json.dumps({ 165 | "EndpointName": endpoint_name, 166 | "EndpointExpiry ": expiry_str, 167 | "TimeLeft": str(time_left) 168 | }) 169 | } 170 | else: 171 | response = { 172 | "statusCode": 400, 173 | "body": json.dumps({"error": "EndpointName not found/Endpoint config name required"}) 174 | } 175 | else: 176 | response = { 177 | "statusCode": 400, 178 | "body": json.dumps({"error": "Error retrieving endpoint"}) 179 | } 180 | else: 181 | response = { 182 | "statusCode": 400, 183 | "body": json.dumps({"error": "Body required"}) 184 | } 185 | 186 | return response 187 | 188 | def handler(event, context): 189 | http_method = event['httpMethod'] 190 | 191 | if http_method == "GET": 192 | response = get_endpoint_expiry_info(event) 193 | elif http_method == "POST": 194 | response = create_update_endpoint_expiry(event) 195 | else: 196 | # Return an error message for unsupported methods 197 | response = { 198 | "statusCode": 405, 199 | "body": json.dumps({"error": "Method not allowed"}) 200 | } 201 | return response -------------------------------------------------------------------------------- /requirements-dev.txt: -------------------------------------------------------------------------------- 1 | pytest==6.2.5 2 | -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | aws-cdk-lib==2.90.0 2 | constructs>=10.0.0,<11.0.0 3 | 4 | sagemaker>=2.173.0 5 | boto3 -------------------------------------------------------------------------------- /source.bat: -------------------------------------------------------------------------------- 1 | @echo off 2 | 3 | rem The sole purpose of this script is to make the command 4 | rem 5 | rem source .venv/bin/activate 6 | rem 7 | rem (which activates a Python virtualenv on Linux or Mac OS X) work on Windows. 8 | rem On Windows, this command just runs this batch file (the argument is ignored). 9 | rem 10 | rem Now we don't need to document a Windows command for activating a virtualenv. 11 | 12 | echo Executing .venv\Scripts\activate.bat for you 13 | .venv\Scripts\activate.bat 14 | -------------------------------------------------------------------------------- /stack/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/dalacan/sagemaker-endpoint-manager/eaefa6c702bf7c1633bcb69e41862bba04de0f44/stack/__init__.py -------------------------------------------------------------------------------- /stack/api_stack.py: -------------------------------------------------------------------------------- 1 | from aws_cdk import ( 2 | RemovalPolicy, 3 | NestedStack, 4 | aws_lambda as _lambda, 5 | aws_apigateway as apigateway, 6 | aws_dynamodb as dynamodb, 7 | aws_iam as iam 8 | ) 9 | 10 | from constructs import Construct 11 | 12 | class APIStack(NestedStack): 13 | 14 | def __init__(self, scope: Construct, construct_id: str, configs, **kwargs) -> None: 15 | super().__init__(scope, construct_id, **kwargs) 16 | 17 | # DynamoDB table for authentication 18 | table_name = configs.get("ddb_auth_table_name", "AuthTable") 19 | 20 | auth_db = dynamodb.Table(self, "AuthTable", 21 | table_name=table_name, 22 | partition_key=dynamodb.Attribute(name="token", type=dynamodb.AttributeType.STRING), 23 | removal_policy=RemovalPolicy.DESTROY) 24 | 25 | # Auth handler function 26 | auth_handler = _lambda.Function(self, "AuthHandler", 27 | code=_lambda.Code.from_asset('functions/auth'), 28 | runtime=_lambda.Runtime.PYTHON_3_9, 29 | handler='auth.handler', 30 | environment={ 31 | "TABLE_NAME": table_name 32 | }) 33 | 34 | auth_db.grant_read_data(auth_handler) 35 | 36 | self.api_authorizer = apigateway.RequestAuthorizer(self, "APIAuthorizer", 37 | handler=auth_handler, 38 | identity_sources=[apigateway.IdentitySource.header("Authorization")] 39 | ) 40 | 41 | self.api = apigateway.RestApi(self, "FoundationModelAPI", 42 | rest_api_name="Foundation Model API Service", 43 | description="This service serves all the foundation models.") 44 | 45 | self.api_gateway_role = iam.Role( 46 | self, 47 | "ApiGatewayRole", 48 | assumed_by=iam.ServicePrincipal("apigateway.amazonaws.com"), 49 | ) 50 | -------------------------------------------------------------------------------- /stack/endpoint_manager_stack.py: -------------------------------------------------------------------------------- 1 | from aws_cdk import ( 2 | NestedStack, 3 | Duration, 4 | aws_iam as iam, 5 | aws_ssm as ssm, 6 | aws_lambda as _lambda, 7 | aws_events as events, 8 | aws_events_targets as targets, 9 | aws_apigateway as apigateway 10 | ) 11 | 12 | from constructs import Construct 13 | 14 | class EndpointManagerStack(NestedStack): 15 | 16 | def __init__(self, scope: Construct, construct_id: str, api_stack, **kwargs) -> None: 17 | super().__init__(scope, construct_id, **kwargs) 18 | 19 | # Create endpoint manager lambdas 20 | start_endpoint_handler = _lambda.Function(self, f"StartEndpointHandler", 21 | runtime=_lambda.Runtime.PYTHON_3_9, 22 | code=_lambda.Code.from_asset("functions/start_stop_endpoint"), 23 | handler="app.handler", 24 | timeout=Duration.seconds(30)) 25 | 26 | # Add policy to lambda to create endpoint 27 | start_endpoint_handler.add_to_role_policy(iam.PolicyStatement( 28 | effect=iam.Effect.ALLOW, 29 | actions=["sagemaker:CreateEndpoint", "sagemaker:DeleteEndpoint", "sagemaker:DescribeEndpoint"], 30 | resources=[ 31 | "*" 32 | ], 33 | )) 34 | 35 | ssm_arn = f"arn:aws:ssm:{self.region}:{self.account}:parameter/sagemaker/endpoint/expiry/*" 36 | 37 | # Add SSM read access 38 | start_endpoint_handler.add_to_role_policy(iam.PolicyStatement( 39 | effect=iam.Effect.ALLOW, 40 | actions=["ssm:DescribeParameters", "ssm:GetParameter", "ssm:GetParameterHistory", "ssm:GetParameters", "ssm:GetParametersByPath"], 41 | resources=[ 42 | ssm_arn 43 | ], 44 | )) 45 | 46 | start_stop_endpoint_rule = events.Rule(self, 'eventStartStopLambdaRule', 47 | description='Start/Stop Endpoint Lambda Rule', 48 | schedule=events.Schedule.rate(Duration.minutes(1)), 49 | targets=[targets.LambdaFunction(handler=start_endpoint_handler)]) 50 | 51 | update_expiry_handler = _lambda.Function(self, f"UpdateExpiryHandler", 52 | runtime=_lambda.Runtime.PYTHON_3_9, 53 | code=_lambda.Code.from_asset("functions/update_expiry"), 54 | handler="app.handler", 55 | timeout=Duration.seconds(30)) 56 | 57 | # Add SSM read/write policy 58 | update_expiry_handler.add_to_role_policy(iam.PolicyStatement( 59 | effect=iam.Effect.ALLOW, 60 | actions=["ssm:DescribeParameters", "ssm:GetParameter", "ssm:GetParameterHistory", "ssm:GetParameters", "ssm:PutParameter", "ssm:GetParametersByPath"], 61 | resources=[ 62 | ssm_arn 63 | ], 64 | )) 65 | 66 | # Add lambda to api gateway 67 | post_update_expiry_integration = apigateway.LambdaIntegration(update_expiry_handler, 68 | request_templates={"application/json": '{ "statusCode": "200" }'}) 69 | # Add lambda to api 70 | resource = api_stack.api.root.add_resource('endpoint-expiry') 71 | resource.add_method("POST", post_update_expiry_integration, authorizer=api_stack.api_authorizer) 72 | resource.add_method("GET", post_update_expiry_integration, authorizer=api_stack.api_authorizer) -------------------------------------------------------------------------------- /stack/foundation_model_stack.py: -------------------------------------------------------------------------------- 1 | from aws_cdk import ( 2 | NestedStack, 3 | Duration, 4 | aws_iam as iam, 5 | aws_ssm as ssm, 6 | aws_lambda as _lambda, 7 | aws_apigateway as apigateway, 8 | aws_sns as sns, 9 | aws_s3 as s3 10 | ) 11 | 12 | from constructs import Construct 13 | from construct.sagemaker_endpoint_construct import SageMakerEndpointConstruct 14 | from construct.sagemaker_async_endpoint_construct import SageMakerAsyncEndpointConstruct 15 | 16 | import json 17 | from datetime import datetime, timedelta 18 | from stack.util import merge_env 19 | 20 | from utils.sagemaker_helper import ( 21 | get_sagemaker_uris, 22 | sagemaker_env, 23 | get_model_spec, 24 | get_model_package_arn, 25 | enable_network_isolation 26 | ) 27 | 28 | from stack.stepfunction_stack import StepFunctionStack 29 | 30 | class FoundationModelStack(NestedStack): 31 | 32 | def __init__(self, scope: Construct, construct_id: str, configs, api_stack, **kwargs) -> None: 33 | super().__init__(scope, construct_id, **kwargs) 34 | 35 | step_function_enabled_endpoints = [] 36 | 37 | # Create policies for model 38 | role = iam.Role(self, "Gen-AI-SageMaker-Policy", assumed_by=iam.ServicePrincipal("sagemaker.amazonaws.com")) 39 | role.add_managed_policy(iam.ManagedPolicy.from_aws_managed_policy_name("AmazonS3FullAccess")) 40 | 41 | sts_policy = iam.Policy(self, "sm-deploy-policy-sts", 42 | statements=[iam.PolicyStatement( 43 | effect=iam.Effect.ALLOW, 44 | actions=[ 45 | "sts:AssumeRole" 46 | ], 47 | resources=["*"] 48 | )] 49 | ) 50 | 51 | logs_policy = iam.Policy(self, "sm-deploy-policy-logs", 52 | statements=[iam.PolicyStatement( 53 | effect=iam.Effect.ALLOW, 54 | actions=[ 55 | "cloudwatch:PutMetricData", 56 | "logs:CreateLogStream", 57 | "logs:PutLogEvents", 58 | "logs:CreateLogGroup", 59 | "logs:DescribeLogStreams", 60 | "ecr:GetAuthorizationToken" 61 | ], 62 | resources=["*"] 63 | )] 64 | ) 65 | 66 | ecr_policy = iam.Policy(self, "sm-deploy-policy-ecr", 67 | statements=[iam.PolicyStatement( 68 | effect=iam.Effect.ALLOW, 69 | actions=[ 70 | "ecr:*", 71 | ], 72 | resources=["*"] 73 | )] 74 | ) 75 | 76 | role.attach_inline_policy(sts_policy) 77 | role.attach_inline_policy(logs_policy) 78 | role.attach_inline_policy(ecr_policy) 79 | 80 | # Deploy jumpstart models 81 | for model in configs.get("jumpstart_models", []): 82 | # Get model info 83 | model_info = get_sagemaker_uris(model_id=model["model_id"], 84 | instance_type=model["inference_instance_type"], 85 | region_name=configs["region_name"]) 86 | 87 | # Get model default environment parameters 88 | model_env = sagemaker_env(model_id=model["model_id"], 89 | region=configs["region_name"], 90 | model_version="*") 91 | 92 | # Get jumpstart model package arn if available 93 | model_specs = get_model_spec( 94 | model_id=model["model_id"], 95 | model_version="*", 96 | region=configs["region_name"] 97 | ) 98 | 99 | model_package_arn = get_model_package_arn( 100 | model_specs=model_specs, 101 | region=configs["region_name"] 102 | ) 103 | 104 | is_network_isolation_enabled = enable_network_isolation(model_specs=model_specs) 105 | 106 | if model["inference_type"] == "realtime": 107 | # Create real-time endpoint 108 | # environment = { 109 | # "MODEL_CACHE_ROOT": "/opt/ml/model", 110 | # "SAGEMAKER_ENV": "1", 111 | # "SAGEMAKER_MODEL_SERVER_TIMEOUT": "3600", 112 | # "SAGEMAKER_MODEL_SERVER_WORKERS": "1", 113 | # "SAGEMAKER_CONTAINER_LOG_LEVEL": "20", 114 | # "SAGEMAKER_PROGRAM": "inference.py", 115 | # "SAGEMAKER_REGION": model_info["region_name"], 116 | # "SAGEMAKER_SUBMIT_DIRECTORY": "/opt/ml/model/code", 117 | # } 118 | environment = { 119 | "MODEL_CACHE_ROOT": "/opt/ml/model", 120 | "SAGEMAKER_ENV": "1", 121 | "SAGEMAKER_MODEL_SERVER_TIMEOUT": "3600", 122 | "SAGEMAKER_CONTAINER_LOG_LEVEL": "20", 123 | "SAGEMAKER_PROGRAM": "inference.py", 124 | "SAGEMAKER_REGION": model_info["region_name"], 125 | "SAGEMAKER_SUBMIT_DIRECTORY": "/opt/ml/model/code", 126 | } 127 | 128 | environment = merge_env(environment, model_env) 129 | 130 | endpoint = SageMakerEndpointConstruct(self, f'FoundationModelEndpoint-{model["name"]}', 131 | project_prefix = configs["project_prefix"], 132 | 133 | role_arn= role.role_arn, 134 | 135 | model_name = model["name"], 136 | model_bucket_name = model_info["model_bucket_name"], 137 | model_bucket_key = model_info["model_bucket_key"], 138 | model_docker_image = model_info["model_docker_image"], 139 | 140 | variant_name = "AllTraffic", 141 | variant_weight = 1, 142 | instance_count = model.get("inference_instance_count", 1), 143 | instance_type = model_info["instance_type"], 144 | 145 | environment = environment, 146 | deploy_enable = False, 147 | model_package_arn=model_package_arn, 148 | enable_network_isolation=is_network_isolation_enabled 149 | ) 150 | 151 | endpoint.node.add_dependency(role) 152 | endpoint.node.add_dependency(sts_policy) 153 | endpoint.node.add_dependency(logs_policy) 154 | endpoint.node.add_dependency(ecr_policy) 155 | 156 | endpoint_name = f'{configs["project_prefix"]}-{model["name"]}-Endpoint' 157 | 158 | # Set endpoint expiry 159 | now = datetime.utcnow() 160 | expiry = now + timedelta(minutes=model["schedule"]["initial_provision_minutes"]) 161 | 162 | expiry_ssm_value = { 163 | "expiry": expiry.strftime("%d-%m-%Y-%H-%M-%S"), 164 | "endpoint_name": endpoint_name, 165 | "endpoint_config_name": endpoint.config.attr_endpoint_config_name 166 | } 167 | 168 | # Create default SSM parameter to manage endpoint 169 | expiry_ssm = ssm.StringParameter(self, 170 | f"{endpoint_name}-expiry", 171 | parameter_name=f"/sagemaker/endpoint/expiry/{endpoint_name}", 172 | string_value=json.dumps(expiry_ssm_value)) 173 | 174 | endpoint_arn = f'arn:aws:sagemaker:{self.region}:{self.account}:endpoint/{endpoint_name.lower()}' 175 | resource_name = model["integration"]["properties"]["api_resource_name"] 176 | 177 | if model.get("async_api_enabled", False): 178 | step_function_enabled_endpoints.append(endpoint_arn) 179 | 180 | # Check integration type 181 | if model["integration"]["type"] == "lambda": 182 | # Add lambda/api integration 183 | app_handler = _lambda.Function(self, f"{resource_name}Handler", 184 | runtime=_lambda.Runtime.PYTHON_3_9, 185 | code=_lambda.Code.from_asset(model["integration"]["properties"]["lambda_src"]), 186 | handler="app.handler", 187 | timeout=Duration.seconds(180), 188 | environment={ 189 | "ENDPOINT_NAME": endpoint_name, 190 | }) 191 | 192 | # Add sagemaker invoke permissions 193 | app_handler.add_to_role_policy(iam.PolicyStatement( 194 | effect=iam.Effect.ALLOW, 195 | actions=["sagemaker:InvokeEndpoint"], 196 | resources=[endpoint_arn], 197 | )) 198 | 199 | post_model_integration = apigateway.LambdaIntegration(app_handler, 200 | request_templates={"application/json": '{ "statusCode": "200" }'}) 201 | # Add lambda to api 202 | resource = api_stack.api.root.add_resource(resource_name) 203 | resource.add_method( 204 | "POST", 205 | post_model_integration, 206 | authorizer=None if model.get("public") else api_stack.api_authorizer, 207 | ) 208 | elif model["integration"]["type"] == "api": 209 | # Add permission to invoke endpoint 210 | api_stack.api_gateway_role.add_to_policy(iam.PolicyStatement( 211 | effect=iam.Effect.ALLOW, 212 | actions=["sagemaker:InvokeEndpoint"], 213 | resources=[endpoint_arn], 214 | ) 215 | ) 216 | 217 | # Add api integration/aws integration 218 | resource = api_stack.api.root.add_resource(resource_name) 219 | post_model_integration = apigateway.AwsIntegration( 220 | service="runtime.sagemaker", 221 | integration_http_method="POST", 222 | path=f"endpoints/{endpoint_name}/invocations", 223 | options=apigateway.IntegrationOptions( 224 | request_parameters={ 225 | "integration.request.header.Content-Type": "method.request.header.Content-Type", 226 | "integration.request.header.Accept": "method.request.header.Accept", 227 | "integration.request.header.X-Amzn-SageMaker-Custom-Attributes": "method.request.header.X-Amzn-SageMaker-Custom-Attributes" 228 | }, 229 | credentials_role=api_stack.api_gateway_role, 230 | integration_responses=[ 231 | apigateway.IntegrationResponse( 232 | status_code="200", 233 | response_templates={ 234 | "application/json": "$input.json('$')" 235 | }, 236 | ), 237 | apigateway.IntegrationResponse( 238 | status_code="400", 239 | selection_pattern="4\d{2}", 240 | response_templates={ 241 | "application/json": '{ "error": $input.path("$.OriginalMessage") }' 242 | }, 243 | ), 244 | apigateway.IntegrationResponse( 245 | status_code="500", 246 | selection_pattern="5\d{2}", 247 | response_templates={ 248 | "application/json": '{ "error": $input.path("$.OriginalMessage") }' 249 | }, 250 | ), 251 | ], 252 | ), 253 | ) 254 | resource.add_method("POST", 255 | post_model_integration, 256 | authorizer=None if model.get("public") else api_stack.api_authorizer, 257 | request_parameters={ 258 | "method.request.header.Content-Type": True, 259 | "method.request.header.Accept": True, 260 | "method.request.header.X-Amzn-SageMaker-Custom-Attributes": False 261 | }, 262 | method_responses=[ 263 | apigateway.MethodResponse(status_code="200"), 264 | apigateway.MethodResponse( 265 | status_code="400", 266 | response_models={ 267 | "application/json": apigateway.Model.ERROR_MODEL 268 | }, 269 | ), 270 | apigateway.MethodResponse( 271 | status_code="500", 272 | response_models={ 273 | "application/json": apigateway.Model.ERROR_MODEL 274 | }, 275 | ), 276 | ] 277 | ) 278 | 279 | elif model["inference_type"] == "async": 280 | # Create async endpoint 281 | 282 | # Create sns success and error topic 283 | success_topic = sns.Topic(self, f'{model["name"]}-SuccessTopic', 284 | display_name=f'{model["name"]}-SuccessTopic') 285 | 286 | error_topic = sns.Topic(self, f'{model["name"]}-ErrorTopic', 287 | display_name=f'{model["name"]}-ErrorTopic') 288 | 289 | sns_policy = iam.Policy(self, "sm-deploy-policy-sns", 290 | statements=[iam.PolicyStatement( 291 | effect=iam.Effect.ALLOW, 292 | actions=["sns:Publish"], 293 | resources=[success_topic.topic_arn, error_topic.topic_arn] 294 | )] 295 | ) 296 | 297 | # Create async output bucket 298 | s3_async = s3.Bucket(self, f'{model["name"]}-S3Async') 299 | 300 | s3_policy = iam.Policy(self, "sm-deploy-policy-s3", 301 | statements=[iam.PolicyStatement( 302 | effect=iam.Effect.ALLOW, 303 | actions=["s3:*"], 304 | resources=[s3_async.bucket_arn] 305 | )] 306 | ) 307 | 308 | role.attach_inline_policy(sns_policy) 309 | role.attach_inline_policy(s3_policy) 310 | 311 | environment = { 312 | "MODEL_CACHE_ROOT": "/opt/ml/model", 313 | "SAGEMAKER_ENV": "1", 314 | "SAGEMAKER_MODEL_SERVER_TIMEOUT": "3600", 315 | "SAGEMAKER_CONTAINER_LOG_LEVEL": "20", 316 | "SAGEMAKER_PROGRAM": "inference.py", 317 | "SAGEMAKER_REGION": model_info["region_name"], 318 | "SAGEMAKER_SUBMIT_DIRECTORY": "/opt/ml/model/code", 319 | } 320 | 321 | environment = merge_env(environment, model_env) 322 | 323 | endpoint = SageMakerAsyncEndpointConstruct(self, "FoundationModelEndpoint", 324 | project_prefix = configs["project_prefix"], 325 | 326 | role_arn= role.role_arn, 327 | 328 | model_name = model["name"], 329 | model_bucket_name = model_info["model_bucket_name"], 330 | model_bucket_key = model_info["model_bucket_key"], 331 | model_docker_image = model_info["model_docker_image"], 332 | 333 | variant_name = "AllTraffic", 334 | variant_weight = 1, 335 | instance_count = model.get("inference_instance_count", 1), 336 | instance_type = model_info["instance_type"], 337 | 338 | environment = environment, 339 | deploy_enable = True, 340 | 341 | success_topic=success_topic.topic_arn, 342 | error_topic=error_topic.topic_arn, 343 | s3_async_bucket=s3_async.bucket_name, 344 | model_package_arn=model_package_arn, 345 | enable_network_isolation=is_network_isolation_enabled 346 | ) 347 | endpoint.node.add_dependency(role) 348 | endpoint.node.add_dependency(sts_policy) 349 | endpoint.node.add_dependency(logs_policy) 350 | endpoint.node.add_dependency(ecr_policy) 351 | 352 | if len(step_function_enabled_endpoints) > 0: 353 | stepfunction_stack = StepFunctionStack(self, "StepFunctionStack", 354 | api_stack = api_stack, 355 | step_function_enabled_endpoints=step_function_enabled_endpoints) -------------------------------------------------------------------------------- /stack/lambda_stack.py: -------------------------------------------------------------------------------- 1 | from aws_cdk import ( 2 | Duration, 3 | Stack, 4 | aws_lambda as _lambda, 5 | aws_iam as iam 6 | ) 7 | 8 | from constructs import Construct 9 | 10 | class LambdaStack(Stack): 11 | 12 | def __init__(self, scope: Construct, construct_id: str, resource_name, asset_dir, endpoint_name, **kwargs) -> None: 13 | super().__init__(scope, construct_id, **kwargs) 14 | 15 | # Create lambda 16 | self.app_handler = _lambda.Function(self, f"{resource_name}Handler", 17 | runtime=_lambda.Runtime.PYTHON_3_9, 18 | code=_lambda.Code.from_asset(asset_dir), 19 | handler="app.handler", 20 | timeout=Duration.seconds(180), 21 | environment={ 22 | "ENDPOINT_NAME": endpoint_name, 23 | }) 24 | 25 | # 26 | endpoint_arn = f'arn:aws:sagemaker:{self.region}:{self.account}:endpoint/{endpoint_name.lower()}' 27 | 28 | self.app_handler.add_to_role_policy(iam.PolicyStatement( 29 | effect=iam.Effect.ALLOW, 30 | actions=["sagemaker:InvokeEndpoint"], 31 | resources=[endpoint_arn], 32 | )) 33 | 34 | self.resource_name = resource_name 35 | 36 | -------------------------------------------------------------------------------- /stack/sagemaker_endpoint_manager_stack.py: -------------------------------------------------------------------------------- 1 | from aws_cdk import ( 2 | Stack, 3 | CfnOutput 4 | ) 5 | 6 | from constructs import Construct 7 | 8 | from stack.api_stack import APIStack 9 | from stack.foundation_model_stack import FoundationModelStack 10 | from stack.endpoint_manager_stack import EndpointManagerStack 11 | from stack.stepfunction_stack import StepFunctionStack 12 | 13 | class SagemakerEndpointManagerStack(Stack): 14 | def __init__(self, scope: Construct, construct_id: str, configs, **kwargs) -> None: 15 | super().__init__(scope, construct_id, **kwargs) 16 | 17 | # Deploy api stack 18 | api_stack = APIStack(self, "APIStack", 19 | configs=configs 20 | ) 21 | 22 | # Deploy endpoint manager stack 23 | endpoint_manager_stack = EndpointManagerStack(self, "EndpointManagerStack", 24 | api_stack = api_stack 25 | ) 26 | 27 | # Deploy model stack 28 | fm_stack = FoundationModelStack(self, "ModelStack", 29 | configs=configs, 30 | api_stack=api_stack 31 | ) 32 | 33 | CfnOutput(self, "APIURL", 34 | value=f"https://{api_stack.api.rest_api_id}.execute-api.{self.region}.amazonaws.com/prod" 35 | ) -------------------------------------------------------------------------------- /stack/stepfunction_stack.py: -------------------------------------------------------------------------------- 1 | from aws_cdk import ( 2 | NestedStack, 3 | aws_apigateway as apigateway, 4 | aws_stepfunctions as sfn, 5 | aws_iam as iam, 6 | ) 7 | 8 | from constructs import Construct 9 | 10 | class StepFunctionStack(NestedStack): 11 | def __init__(self, scope: Construct, construct_id: str, api_stack, step_function_enabled_endpoints, **kwargs) -> None: 12 | super().__init__(scope, construct_id, **kwargs) 13 | 14 | # Create a step function execution role 15 | role = iam.Role(self, "StepfunctionExecutionRole", assumed_by=iam.ServicePrincipal("states.amazonaws.com")) 16 | 17 | # Add permission to role to invoke Amazon SageMaker real time endpoint 18 | role.add_to_policy( 19 | iam.PolicyStatement( 20 | effect=iam.Effect.ALLOW, 21 | actions=["sagemaker:InvokeEndpoint"], 22 | resources=step_function_enabled_endpoints 23 | ) 24 | ) 25 | 26 | # Create an Amazon SageMaker invoke state machine 27 | sagemaker_invoke_fnc = sfn.StateMachine(self, "SageMakerInvokeStepfunction", 28 | definition_body=sfn.DefinitionBody.from_file("config/sagemaker-invoke.json"), 29 | role=role 30 | ) 31 | 32 | # Add permission to invoke step function 33 | api_stack.api_gateway_role.add_to_policy( 34 | iam.PolicyStatement( 35 | effect=iam.Effect.ALLOW, 36 | actions=["states:StartExecution"], 37 | resources=[sagemaker_invoke_fnc.state_machine_arn] 38 | ) 39 | ) 40 | 41 | # Add permission to get describe step function execution 42 | stepfunction_execution_arn = f'arn:aws:states:{self.region}:{self.account}:execution:{sagemaker_invoke_fnc.state_machine_name}:*' 43 | 44 | api_stack.api_gateway_role.add_to_policy( 45 | iam.PolicyStatement( 46 | effect=iam.Effect.ALLOW, 47 | actions=["states:DescribeExecution"], 48 | resources=[stepfunction_execution_arn] 49 | ) 50 | ) 51 | 52 | # Add api integration with step function 53 | start_execution_resource = api_stack.api.root.add_resource("startexecution") 54 | 55 | # Add apigateway integration with step function using with sagemaker_invoke_fnc state machine arn 56 | start_execution_integration = apigateway.AwsIntegration( 57 | service="states", 58 | integration_http_method="POST", 59 | action="StartExecution", 60 | options=apigateway.IntegrationOptions( 61 | credentials_role=api_stack.api_gateway_role, 62 | integration_responses=[ 63 | apigateway.IntegrationResponse( 64 | status_code="200", 65 | ) 66 | ], 67 | request_templates={"application/json": "{ \"stateMachineArn\": \""+sagemaker_invoke_fnc.state_machine_arn+"\", \"input\": \"$util.escapeJavaScript($input.json('$'))\" }" } 68 | ) 69 | ) 70 | 71 | start_execution_resource.add_method("POST", 72 | start_execution_integration, 73 | authorizer=api_stack.api_authorizer, 74 | method_responses=[ 75 | apigateway.MethodResponse( 76 | status_code="200", 77 | response_models={ 78 | "application/json": apigateway.Model.EMPTY_MODEL 79 | }, 80 | ), 81 | apigateway.MethodResponse( 82 | status_code="400", 83 | response_models={ 84 | "application/json": apigateway.Model.ERROR_MODEL 85 | }, 86 | ), 87 | apigateway.MethodResponse( 88 | status_code="500", 89 | response_models={ 90 | "application/json": apigateway.Model.ERROR_MODEL 91 | }, 92 | ), 93 | ] 94 | ) 95 | 96 | # Add api integration with step function to get step function execution status 97 | describe_execution_resource = api_stack.api.root.add_resource("describeexecution") 98 | 99 | # Add apigateway integration with step function to get step function execution status 100 | describe_execution_integration = apigateway.AwsIntegration( 101 | service="states", 102 | integration_http_method="POST", 103 | action="DescribeExecution", 104 | options=apigateway.IntegrationOptions( 105 | credentials_role=api_stack.api_gateway_role, 106 | integration_responses=[ 107 | apigateway.IntegrationResponse( 108 | status_code="200", 109 | ) 110 | ] 111 | ) 112 | ) 113 | 114 | describe_execution_resource.add_method("POST", 115 | describe_execution_integration, 116 | authorizer=api_stack.api_authorizer, 117 | method_responses=[ 118 | apigateway.MethodResponse( 119 | status_code="200", 120 | response_models={ 121 | "application/json": apigateway.Model.EMPTY_MODEL 122 | }, 123 | ), 124 | apigateway.MethodResponse( 125 | status_code="400", 126 | response_models={ 127 | "application/json": apigateway.Model.ERROR_MODEL 128 | }, 129 | ), 130 | apigateway.MethodResponse( 131 | status_code="500", 132 | response_models={ 133 | "application/json": apigateway.Model.ERROR_MODEL 134 | }, 135 | ), 136 | ] 137 | ) 138 | 139 | 140 | 141 | 142 | 143 | 144 | -------------------------------------------------------------------------------- /stack/util.py: -------------------------------------------------------------------------------- 1 | def merge_env(env, extra_env_vars): 2 | """Sets env based on default or override, returns envs.""" 3 | if env is None: 4 | env = {} 5 | 6 | for key, value in extra_env_vars.items(): 7 | 8 | if key not in env: 9 | env[key] = value 10 | 11 | if env == {}: 12 | env = None 13 | 14 | return env -------------------------------------------------------------------------------- /tests/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/dalacan/sagemaker-endpoint-manager/eaefa6c702bf7c1633bcb69e41862bba04de0f44/tests/__init__.py -------------------------------------------------------------------------------- /tests/unit/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/dalacan/sagemaker-endpoint-manager/eaefa6c702bf7c1633bcb69e41862bba04de0f44/tests/unit/__init__.py -------------------------------------------------------------------------------- /tests/unit/test_sagemaker_jumpstart_generative_ai_app_stack.py: -------------------------------------------------------------------------------- 1 | import aws_cdk as core 2 | import aws_cdk.assertions as assertions 3 | 4 | from sagemaker_jumpstart_generative_ai_app.sagemaker_jumpstart_generative_ai_app_stack import SagemakerJumpstartGenerativeAiAppStack 5 | 6 | # example tests. To run these tests, uncomment this file along with the example 7 | # resource in sagemaker_jumpstart_generative_ai_app/sagemaker_jumpstart_generative_ai_app_stack.py 8 | def test_sqs_queue_created(): 9 | app = core.App() 10 | stack = SagemakerJumpstartGenerativeAiAppStack(app, "sagemaker-jumpstart-generative-ai-app") 11 | template = assertions.Template.from_stack(stack) 12 | 13 | # template.has_resource_properties("AWS::SQS::Queue", { 14 | # "VisibilityTimeout": 300 15 | # }) 16 | -------------------------------------------------------------------------------- /utils/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/dalacan/sagemaker-endpoint-manager/eaefa6c702bf7c1633bcb69e41862bba04de0f44/utils/__init__.py -------------------------------------------------------------------------------- /utils/sagemaker_helper.py: -------------------------------------------------------------------------------- 1 | import sagemaker 2 | from sagemaker import script_uris 3 | from sagemaker import image_uris 4 | from sagemaker import model_uris 5 | from sagemaker.jumpstart.notebook_utils import list_jumpstart_models 6 | from sagemaker import environment_variables 7 | from sagemaker.jumpstart.utils import verify_model_region_and_return_specs 8 | from sagemaker.jumpstart.enums import JumpStartScriptScope 9 | from sagemaker.jumpstart.constants import ( 10 | JUMPSTART_DEFAULT_REGION_NAME, 11 | ) 12 | import boto3 13 | from typing import Optional 14 | 15 | # session = sagemaker.Session() 16 | 17 | def sagemaker_env(model_id, region, model_version="*"): 18 | extra_env_vars = environment_variables.retrieve_default( 19 | model_id=model_id, 20 | model_version=model_version, 21 | region=region, 22 | include_aws_sdk_env_vars=False 23 | ) 24 | 25 | return extra_env_vars 26 | 27 | def get_sagemaker_uris(model_id,instance_type,region_name): 28 | 29 | 30 | MODEL_VERSION = "*" # latest 31 | SCOPE = "inference" 32 | 33 | inference_image_uri = image_uris.retrieve(region=region_name, 34 | framework=None, 35 | model_id=model_id, 36 | model_version=MODEL_VERSION, 37 | image_scope=SCOPE, 38 | instance_type=instance_type) 39 | 40 | inference_model_uri = model_uris.retrieve( 41 | region=region_name, 42 | model_id=model_id, 43 | model_version=MODEL_VERSION, 44 | model_scope=SCOPE) 45 | 46 | inference_source_uri = script_uris.retrieve( 47 | region=region_name, 48 | model_id=model_id, 49 | model_version=MODEL_VERSION, 50 | script_scope=SCOPE) 51 | 52 | model_bucket_name = inference_model_uri.split("/")[2] 53 | model_bucket_key = "/".join(inference_model_uri.split("/")[3:]) 54 | model_docker_image = inference_image_uri 55 | 56 | return {"model_bucket_name":model_bucket_name, "model_bucket_key": model_bucket_key, \ 57 | "model_docker_image":model_docker_image, "instance_type":instance_type, \ 58 | "inference_source_uri":inference_source_uri, "region_name":region_name} 59 | 60 | def get_model_spec( 61 | model_id: str, 62 | model_version: str, 63 | region: Optional[str], 64 | scope: Optional[str] = None, 65 | ): 66 | if region is None: 67 | region = JUMPSTART_DEFAULT_REGION_NAME 68 | 69 | # Default to inference scope 70 | if scope is None: 71 | scope = JumpStartScriptScope.INFERENCE 72 | 73 | model_specs = verify_model_region_and_return_specs( 74 | model_id=model_id, 75 | version=model_version, 76 | scope=scope, 77 | region=region 78 | ) 79 | 80 | if model_specs is None: 81 | return None 82 | 83 | return model_specs 84 | 85 | def get_model_package_arn( 86 | model_specs, 87 | region: Optional[str]): 88 | if region is None: 89 | region = JUMPSTART_DEFAULT_REGION_NAME 90 | 91 | if model_specs.hosting_model_package_arns is None: 92 | return None 93 | 94 | # Return regional arn 95 | regional_arn = model_specs.hosting_model_package_arns.get(region) 96 | 97 | return regional_arn 98 | 99 | def enable_network_isolation(model_specs): 100 | if model_specs.inference_enable_network_isolation is None: 101 | return False 102 | 103 | # Return regional arn 104 | inference_enable_network_isolation = model_specs.inference_enable_network_isolation 105 | 106 | return inference_enable_network_isolation 107 | --------------------------------------------------------------------------------