├── .editorconfig ├── .github └── workflows │ └── deploy.yaml ├── .gitignore ├── .prettierrc ├── LICENSE ├── README.md ├── conf.json ├── docs ├── azure_openai.md ├── caching.md ├── deepseek.md ├── fallback.md ├── guards.md ├── logging.md ├── malacca.jpg ├── metrics.md ├── openai.md ├── rate-limiting.md └── virtual-key.md ├── eslint.config.mjs ├── package-lock.json ├── package.json ├── src ├── index.ts ├── middlewares │ ├── analytics.ts │ ├── buffer.ts │ ├── cache.ts │ ├── fallback.ts │ ├── guard.ts │ ├── index.ts │ ├── logging.ts │ ├── rateLimiter.ts │ └── virtualKey.ts ├── providers │ ├── azureOpenAI.ts │ ├── deepseek.ts │ ├── index.ts │ ├── openai.ts │ └── workersAI.ts └── types.ts ├── test ├── deepseek.test.ts ├── index.spec.ts ├── openai.test.ts └── tsconfig.json ├── tsconfig.json ├── vitest.config.mts ├── worker-configuration.d.ts ├── wrangler.test.toml └── wrangler.toml /.editorconfig: -------------------------------------------------------------------------------- 1 | # http://editorconfig.org 2 | root = true 3 | 4 | [*] 5 | indent_style = tab 6 | end_of_line = lf 7 | charset = utf-8 8 | trim_trailing_whitespace = true 9 | insert_final_newline = true 10 | 11 | [*.yml] 12 | indent_style = space 13 | -------------------------------------------------------------------------------- /.github/workflows/deploy.yaml: -------------------------------------------------------------------------------- 1 | name: Deploy 2 | 3 | on: 4 | push: 5 | branches: 6 | - master 7 | workflow_dispatch: 8 | repository_dispatch: 9 | 10 | 11 | jobs: 12 | deploy: 13 | runs-on: ubuntu-latest 14 | name: Deploy 15 | steps: 16 | - uses: actions/checkout@v4 17 | - name: Deploy 18 | uses: cloudflare/wrangler-action@v3 19 | with: 20 | apiToken: ${{ secrets.CLOUDFLARE_API_TOKEN }} 21 | wranglerVersion: "3.78.12" -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Logs 2 | 3 | logs 4 | _.log 5 | npm-debug.log_ 6 | yarn-debug.log* 7 | yarn-error.log* 8 | lerna-debug.log* 9 | .pnpm-debug.log* 10 | 11 | # Diagnostic reports (https://nodejs.org/api/report.html) 12 | 13 | report.[0-9]_.[0-9]_.[0-9]_.[0-9]_.json 14 | 15 | # Runtime data 16 | 17 | pids 18 | _.pid 19 | _.seed 20 | \*.pid.lock 21 | 22 | # Directory for instrumented libs generated by jscoverage/JSCover 23 | 24 | lib-cov 25 | 26 | # Coverage directory used by tools like istanbul 27 | 28 | coverage 29 | \*.lcov 30 | 31 | # nyc test coverage 32 | 33 | .nyc_output 34 | 35 | # Grunt intermediate storage (https://gruntjs.com/creating-plugins#storing-task-files) 36 | 37 | .grunt 38 | 39 | # Bower dependency directory (https://bower.io/) 40 | 41 | bower_components 42 | 43 | # node-waf configuration 44 | 45 | .lock-wscript 46 | 47 | # Compiled binary addons (https://nodejs.org/api/addons.html) 48 | 49 | build/Release 50 | 51 | # Dependency directories 52 | 53 | node_modules/ 54 | jspm_packages/ 55 | 56 | # Snowpack dependency directory (https://snowpack.dev/) 57 | 58 | web_modules/ 59 | 60 | # TypeScript cache 61 | 62 | \*.tsbuildinfo 63 | 64 | # Optional npm cache directory 65 | 66 | .npm 67 | 68 | # Optional eslint cache 69 | 70 | .eslintcache 71 | 72 | # Optional stylelint cache 73 | 74 | .stylelintcache 75 | 76 | # Microbundle cache 77 | 78 | .rpt2_cache/ 79 | .rts2_cache_cjs/ 80 | .rts2_cache_es/ 81 | .rts2_cache_umd/ 82 | 83 | # Optional REPL history 84 | 85 | .node_repl_history 86 | 87 | # Output of 'npm pack' 88 | 89 | \*.tgz 90 | 91 | # Yarn Integrity file 92 | 93 | .yarn-integrity 94 | 95 | # dotenv environment variable files 96 | 97 | .env 98 | .env.development.local 99 | .env.test.local 100 | .env.production.local 101 | .env.local 102 | 103 | # parcel-bundler cache (https://parceljs.org/) 104 | 105 | .cache 106 | .parcel-cache 107 | 108 | # Next.js build output 109 | 110 | .next 111 | out 112 | 113 | # Nuxt.js build / generate output 114 | 115 | .nuxt 116 | dist 117 | 118 | # Gatsby files 119 | 120 | .cache/ 121 | 122 | # Comment in the public line in if your project uses Gatsby and not Next.js 123 | 124 | # https://nextjs.org/blog/next-9-1#public-directory-support 125 | 126 | # public 127 | 128 | # vuepress build output 129 | 130 | .vuepress/dist 131 | 132 | # vuepress v2.x temp and cache directory 133 | 134 | .temp 135 | .cache 136 | 137 | # Docusaurus cache and generated files 138 | 139 | .docusaurus 140 | 141 | # Serverless directories 142 | 143 | .serverless/ 144 | 145 | # FuseBox cache 146 | 147 | .fusebox/ 148 | 149 | # DynamoDB Local files 150 | 151 | .dynamodb/ 152 | 153 | # TernJS port file 154 | 155 | .tern-port 156 | 157 | # Stores VSCode versions used for testing VSCode extensions 158 | 159 | .vscode-test 160 | 161 | # yarn v2 162 | 163 | .yarn/cache 164 | .yarn/unplugged 165 | .yarn/build-state.yml 166 | .yarn/install-state.gz 167 | .pnp.\* 168 | 169 | # wrangler project 170 | 171 | .dev.vars 172 | .wrangler/ 173 | 174 | .DS_Store -------------------------------------------------------------------------------- /.prettierrc: -------------------------------------------------------------------------------- 1 | { 2 | "printWidth": 140, 3 | "singleQuote": true, 4 | "semi": true, 5 | "useTabs": true 6 | } 7 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "{}" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright {yyyy} {name of copyright owner} 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Malacca 2 | 3 | ![Malacca Logo](./docs/malacca.jpg) 4 | 5 | **Malacca** is an open-source AI gateway designed to become the central hub in the world of AI. 6 | 7 | It is fully **CloudFlare Native**: allowing for global scale deployment without any maintenance overhead and free for 1M requests each day. 8 | 9 | It is written in **TypeScript**: ensuring adaptability to the rapidly evolving AI ecosystem and catering to the diverse needs of application developers. 10 | 11 | > Malacca is still an early-stage project, containing many experiments by the author. Currently, it only supports AzureOpenAI. While Malacca provides numerous features, its primary purpose is to offer a framework and examples to help users better implement their own custom functionalities. In fact, we encourage you to read the code and adapt it to your specific needs. We welcome contributions and ideas from the community to help expand and improve this project. 12 | 13 | ## Features 14 | 15 | - 🌍 **Global Scale, Zero Maintenance** 16 | - Built on Cloudflare Workers, Malacca offers seamless global deployment without the need to manage servers. 17 | 18 | - 🧩 **High Flexibility and Extensibility** 19 | - Written in TypeScript, which provides excellent readability and allows easy customization and expansion of features. 20 | 21 | - 🛠️ **Comprehensive Feature Set** 22 | - 🔑 **Virtual Key**: Manage access permissions using virtual keys, providing more granular control over API access. 23 | - ⚡ **Caching**: Reduce latency and costs by caching repeat requests. 24 | - 🛡️ **Guard**: Deny the request if the request or response has inappropriate content. 25 | - 📊 **Analytics**: Track the status, error, latency and usage of tokens, allowing you to understand and manage API costs. 26 | - 📋 **Logging**: Record requests and responses to further fine-tune or reinforcement learning. 27 | - 🚦 **Rate Limiting**: Protect upstream API resources by controlling request rates. 28 | - 🔄 **Fallback**: Fallback to CF Workers AI if the upstream API fails. 29 | 30 | ## Quick Start 31 | 32 | ### Prerequisites 33 | 34 | - A **Cloudflare** account. 35 | - **Wrangler CLI** installed (used to manage Cloudflare Workers). 36 | - Enable Workers Analytics Engine. (Head to the [Cloudflare Dashboard](https://dash.cloudflare.com/?to=/:account/workers/analytics-engine)). 37 | 38 | ### Deployment Steps 39 | 40 | 1. **Clone the Repository** 41 | 42 | ```bash 43 | git clone https://github.com/oilbeater/malacca.git 44 | cd malacca 45 | ``` 46 | 47 | 2. **Install Dependencies** 48 | 49 | ```bash 50 | npm install 51 | ``` 52 | 53 | 3. **Configure the Project** 54 | 55 | Create KV Namespace for LLM Cache and Virtual Key 56 | 57 | ```bash 58 | npx wrangler kv namespace create MALACCA_CACHE 59 | npx wrangler kv namespace create MALACCA_USER 60 | ``` 61 | 62 | Then edit the `wrangler.toml` configuration with the KV ids generated. 63 | 64 | 4. **Deploy to Cloudflare Workers** 65 | 66 | ```bash 67 | npm run deploy 68 | ``` 69 | 70 | Then you can visit Malacca with the Worker domain or custom domain. 71 | 72 | ### Supported LLM Providers 73 | 74 | - [OpenAI](./docs/openai.md) 75 | - [Azure OpenAI](./docs/azure_openai.md) 76 | - [DeepSeek](./docs/deepseek.md) 77 | 78 | ### How to use? 79 | 80 | - [Virtual Key](./docs/virtual-key.md) 81 | - [Caching](./docs/caching.md) 82 | - [Guard](./docs/guards.md) 83 | - [Logging](./docs/logging.md) 84 | - [Metrics](./docs/metrics.md) 85 | - [Rate Limiting](./docs/rate-limiting.md) 86 | - [Fallback](./docs/fallback.md) 87 | 88 | ## Customization and Extension 89 | 90 | Malacca offers a flexible architecture, allowing users to: 91 | 92 | - Add custom middleware to suit specific needs. 93 | - Extend or modify existing features. 94 | - Integrate additional upstream AI API services. 95 | 96 | You can just clone and modify the code then `wrangler deploy` to deploy your code globally. 97 | 98 | ## Contact 99 | 100 | If you have any questions or suggestions, feel free to reach out via email at [mengxin@alauda.io](mailto:mengxin@alauda.io). 101 | -------------------------------------------------------------------------------- /conf.json: -------------------------------------------------------------------------------- 1 | { 2 | "locations": [ 3 | { 4 | "path": "/", 5 | "auth": "static", 6 | "auth-token": "admin", 7 | "cache": "none", 8 | "upstream": "aoi" 9 | } 10 | ], 11 | "upstreams": [ 12 | { 13 | "name": "aoi", 14 | "algorithm": "random", 15 | "transform": "aoi", 16 | "server": [ 17 | { 18 | "type": "AzureOpenAI", 19 | "api-key": "api-key", 20 | "api-version": "2023-03-15-preview", 21 | "resource_name": "resource_name", 22 | "deployment_name": "deployment_name", 23 | "weight": 1, 24 | "timeout": 1000, 25 | "backup": false, 26 | "retry": 3 27 | }, 28 | { 29 | "type": "CloudflareAI", 30 | "model": "@deepseek", 31 | "backup": true 32 | } 33 | ] 34 | } 35 | ] 36 | } -------------------------------------------------------------------------------- /docs/azure_openai.md: -------------------------------------------------------------------------------- 1 | # Azure OpenAI 2 | 3 | To leverage the advanced features provided by Malacca while using the Azure OpenAI API, you only need to adjust the `base_url` configuration in the original SDK. This simple change allows you to benefit from Malacca's capabilities such as caching, virtual key management, rate limiting, logging and all other features. 4 | 5 | You need to get the following parameters: 6 | 7 | - `Worker_Domain`: The domain url where your Worker is accessible, you can find it in your worker Settings. 8 | - `Resource_Name`: The Azure OpenAI resource name. 9 | - `Deployment_Name`: The Azure OpenAI deployment name. 10 | - `Virtual_Key`: The virtual key that protect your real API key. 11 | 12 | ## Python Example 13 | 14 | ```python 15 | from openai import AzureOpenAI 16 | 17 | client = AzureOpenAI( 18 | api_key="{Virtual_Key}", 19 | base_url="https://{Worker_Domain}/azure-openai/{Resource_Name}", 20 | api_version="2024-07-01-preview" 21 | ) 22 | 23 | completion = client.chat.completions.create( 24 | model="{Deployment_Name}", 25 | messages=[ 26 | { 27 | "role": "user", 28 | "content": "Tell me a very short story about Malacca.", 29 | }, 30 | ], 31 | ) 32 | 33 | print(completion.to_json()) 34 | ``` 35 | 36 | ## Curl Example 37 | 38 | ```bash 39 | curl --request POST \ 40 | --url 'https://${Worker_Domain}/azure-openai/${Resource_Name}/deployments/${Deployment_Name}/chat/completions?api-version=2024-07-01-preview' \ 41 | --header 'Content-Type: application/json' \ 42 | --header 'api-key: ${Virtual_Key}' \ 43 | --header 'content-type: application/json' \ 44 | --data '{ 45 | "messages": [ 46 | { 47 | "role": "user", 48 | "content": [ 49 | { 50 | "type": "text", 51 | "text": "Tell a very short story about Malacca" 52 | } 53 | ] 54 | } 55 | ], 56 | "model": "", 57 | "temperature": 0.7, 58 | "top_p": 0.95, 59 | "max_tokens": 800, 60 | "stream": false 61 | }' 62 | ``` -------------------------------------------------------------------------------- /docs/caching.md: -------------------------------------------------------------------------------- 1 | # ⚡ Caching 2 | 3 | Malacca Caching can significantly enhance the performance and efficiency of your LLM (Large Language Model) applications. Here are some key benefits: 4 | 5 | - ⚡️ Reduced latency: By caching responses, Malacca can serve repeated queries instantly, dramatically reducing response times. 6 | - 💰 Cost savings: Cached responses eliminate the need for redundant API calls, potentially lowering your usage costs for LLM services. 7 | - 🔌 Offline capabilities: With caching, your application can provide responses even when the LLM API is temporarily unavailable. 8 | - 😊 Enhanced user experience: Faster response times due to caching lead to a smoother and more responsive user experience. 9 | 10 | By default Malacca will use the full request body as the cache key, which means only exactly same request will hit the cache. 11 | 12 | Malacca only cache the 200 response with 3600s ttl, you can add your own logical to achieve advanced cache by modifying the code logical. 13 | 14 | For cached response there will be a header in the response: 15 | 16 | ```bash 17 | malacca-cache-status: hit 18 | ``` 19 | 20 | You can customize the cache logic by modifying the cache middleware in `src/middlewares/cache.ts`. 21 | -------------------------------------------------------------------------------- /docs/deepseek.md: -------------------------------------------------------------------------------- 1 | # DeepSeek 2 | 3 | To leverage the advanced features provided by Malacca while using the DeepSeek API, you only need to adjust the `base_url` configuration in the original SDK. This simple change allows you to benefit from Malacca's capabilities such as caching, virtual key management, rate limiting, logging and all other features. 4 | 5 | You need to get the following parameters: 6 | 7 | - `Worker_Domain`: The domain url where your Worker is accessible, you can find it in your worker Settings. 8 | - `Virtual_Key`: The virtual key that protect your real API key. 9 | 10 | ## Python Example 11 | 12 | DeepSeek API is compatible with OpenAI API, so you can use [OpenAI Python SDK](https://github.com/openai/openai-python) to visit DeepSeek with Malacca endpoint. 13 | 14 | ```python 15 | from openai import OpenAI 16 | 17 | client = OpenAI(api_key="{Virtual_Key}", base_url="https://{Worker_Domain}/deepseek/") 18 | 19 | response = client.chat.completions.create( 20 | model="deepseek-chat", 21 | messages=[ 22 | {"role": "system", "content": "You are a helpful assistant"}, 23 | {"role": "user", "content": "Tell me a very short story about Malacca."}, 24 | ], 25 | stream=False 26 | ) 27 | 28 | print(response.choices[0].message.content) 29 | ``` -------------------------------------------------------------------------------- /docs/fallback.md: -------------------------------------------------------------------------------- 1 | # 🔄 Fallback 2 | 3 | Malacca's fallback is designed to protect your API from upstream API failures. When the upstream API fails, Malacca will automatically fallback to the CF Workers AI. By default it will fallback to the `@cf/meta/llama-3.1-8b-instruct` model. 4 | 5 | You can customize the fallback logical to fit your needs or change to another model by modifying the `src/middlewares/fallback.ts` file. 6 | 7 | -------------------------------------------------------------------------------- /docs/guards.md: -------------------------------------------------------------------------------- 1 | # 🛡️ Guard 2 | 3 | Malacca's guard is designed to protect your API from inappropriate content. It is a powerful tool that can be used to protect your API from a variety of attacks, including but not limited to: 4 | 5 | - **Content Filtering**: The guard can be used to filter out content that is inappropriate or offensive. 6 | - **Abuse Detection**: The guard can be used to detect and prevent abuse of your API by bad actors. 7 | 8 | You can customize the guards logic by modifying the guards middleware in `src/middlewares/guards.ts`. -------------------------------------------------------------------------------- /docs/logging.md: -------------------------------------------------------------------------------- 1 | # 📋Logging 2 | 3 | Malacca can record all the API request and response body for further fine-tune or reinforcement learning. 4 | 5 | It is built on the Cloudflare worker logging mechanism you can view streaming log through the [Real-time logs](https://developers.cloudflare.com/workers/observability/logs/real-time-logs/) or [Logpuh](https://developers.cloudflare.com/workers/observability/logs/logpush/) to a destination. 6 | 7 | The log entry looks like this: 8 | 9 | ```json 10 | { 11 | "truncated": false, 12 | "outcome": "ok", 13 | "scriptVersion": { 14 | "id": "4d9d8c51-8b2e-4396-8e6f-e328fa14f80e" 15 | }, 16 | "scriptName": "malacca", 17 | "diagnosticsChannelEvents": [], 18 | "exceptions": [], 19 | "logs": [ 20 | { 21 | "message": [ 22 | { 23 | "request_body": { 24 | "messages": [ 25 | { 26 | "role": "user", 27 | "content": [ 28 | { 29 | "type": "text", 30 | "text": "Tell me a short story about Malacca" 31 | } 32 | ] 33 | } 34 | ], 35 | "model": "", 36 | "temperature": 0.7, 37 | "top_p": 0.95, 38 | "max_tokens": 800, 39 | "stream": false 40 | } 41 | } 42 | ], 43 | "level": "log", 44 | "timestamp": 1727689534756 45 | }, 46 | { 47 | "message": [ 48 | { 49 | "response_body": "{\"choices\":[{\"content_filter_results\":{\"hate\":{\"filtered\":false,\"severity\":\"safe\"},\"protected_material_code\":{\"filtered\":false,\"detected\":false},\"protected_material_text\":{\"filtered\":false,\"detected\":false},\"self_harm\":{\"filtered\":false,\"severity\":\"safe\"},\"sexual\":{\"filtered\":false,\"severity\":\"safe\"},\"violence\":{\"filtered\":false,\"severity\":\"safe\"}},\"finish_reason\":\"stop\",\"index\":0,\"logprobs\":null,\"message\":{\"content\":\"Once upon a time in the historical port city of Malacca, there stood an ancient lighthouse on a hill, overlooking the Straits of Malacca. This lighthouse, known as the Light of Malacca, had guided sailors safely to shore for centuries.\\n\\nOne fateful evening, a fierce storm rolled in from the sea. Dark clouds swirled, and thunder roared as if the heavens themselves were at war. The waves crashed violently against the rocky shore, and the people of Malacca huddled in their homes, praying for safety.\\n\\nAmidst the chaos, young Aisha, the lighthouse keeper's daughter, noticed that the light in the lighthouse had gone out. The storm had knocked out the flames. Without the beacon, ships at sea would be lost to the treacherous waters.\\n\\nWith her father away on an urgent errand, Aisha knew she had to act quickly. Braving the howling winds and torrential rain, she climbed the steep hill to the lighthouse. Her heart pounded with each step, but her resolve never wavered.\\n\\nReaching the top, she battled the elements to relight the flame. She struck match after match, her hands trembling from the cold and wet. Finally, the wick caught fire, and the lighthouse blazed back to life. Its powerful beam cut through the storm, guiding the ships safely to harbor.\\n\\nThe next morning, as the storm subsided and the sun rose over the horizon, the townspeople gathered to thank Aisha. Her bravery had saved countless lives. From that day forward, the Light of Malacca was known not just as a beacon for sailors, but as a symbol of courage and hope, embodied by a young girl who dared to shine in the darkest of times.\",\"role\":\"assistant\"}}],\"created\":1727689535,\"id\":\"chatcmpl-AD7GBCrVx9zkg7j5r0auuLkQYjbk6\",\"model\":\"gpt-4o-2024-05-13\",\"object\":\"chat.completion\",\"prompt_filter_results\":[{\"prompt_index\":0,\"content_filter_results\":{\"hate\":{\"filtered\":false,\"severity\":\"safe\"},\"jailbreak\":{\"filtered\":false,\"detected\":false},\"self_harm\":{\"filtered\":false,\"severity\":\"safe\"},\"sexual\":{\"filtered\":false,\"severity\":\"safe\"},\"violence\":{\"filtered\":false,\"severity\":\"safe\"}}}],\"system_fingerprint\":\"fp_80a1bad4c7\",\"usage\":{\"completion_tokens\":354,\"prompt_tokens\":15,\"total_tokens\":369}}\n" 50 | } 51 | ], 52 | "level": "log", 53 | "timestamp": 1727689541328 54 | } 55 | ], 56 | "eventTimestamp": 1727689534741, 57 | "event": { 58 | "request": { 59 | "url": "http://malacca.oilbeater.com/azure-openai/malacca/deployments/gpt4o/chat/completions?api-version=2024-07-01-preview", 60 | "method": "POST", 61 | "headers": { 62 | "accept": "application/json, text/plain, */*", 63 | "accept-encoding": "gzip", 64 | "api-key": "REDACTED", 65 | "cf-connecting-ip": "106.39.34.146", 66 | "cf-ipcountry": "CN", 67 | "cf-ray": "8cb347e7f97794b7", 68 | "cf-visitor": "{\"scheme\":\"http\"}", 69 | "connection": "Keep-Alive", 70 | "content-length": "177", 71 | "content-type": "application/json", 72 | "host": "malacca.oilbeater.com", 73 | "request-start-time": "1727689533645", 74 | "user-agent": "axios/1.7.2", 75 | "x-forwarded-proto": "http", 76 | "x-real-ip": "106.39.34.146" 77 | }, 78 | "cf": { 79 | "clientTcpRtt": 144, 80 | "longitude": "116.39500", 81 | "latitude": "39.91100", 82 | "tlsCipher": "", 83 | "continent": "AS", 84 | "asn": 4847, 85 | "clientAcceptEncoding": "gzip, compress, deflate, br", 86 | "country": "CN", 87 | "tlsClientAuth": { 88 | "certIssuerDNLegacy": "", 89 | "certIssuerSKI": "", 90 | "certSubjectDNRFC2253": "", 91 | "certSubjectDNLegacy": "", 92 | "certFingerprintSHA256": "", 93 | "certNotBefore": "", 94 | "certSKI": "", 95 | "certSerial": "", 96 | "certIssuerDN": "", 97 | "certVerified": "NONE", 98 | "certNotAfter": "", 99 | "certSubjectDN": "", 100 | "certPresented": "0", 101 | "certRevoked": "0", 102 | "certIssuerSerial": "", 103 | "certIssuerDNRFC2253": "", 104 | "certFingerprintSHA1": "" 105 | }, 106 | "verifiedBotCategory": "", 107 | "tlsVersion": "", 108 | "colo": "LHR", 109 | "timezone": "Asia/Shanghai", 110 | "tlsClientHelloLength": "", 111 | "edgeRequestKeepAliveStatus": 1, 112 | "requestPriority": "", 113 | "tlsClientExtensionsSha1": "", 114 | "region": "Beijing", 115 | "city": "Beijing", 116 | "regionCode": "BJ", 117 | "asOrganization": "China Telecom", 118 | "tlsClientRandom": "", 119 | "httpProtocol": "HTTP/1.1" 120 | } 121 | }, 122 | "response": { 123 | "status": 200 124 | } 125 | }, 126 | "id": 0 127 | } 128 | ``` 129 | 130 | You can customize the logging logic by modifying the logging middleware in `src/middlewares/logging.ts`. 131 | -------------------------------------------------------------------------------- /docs/malacca.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/oilbeater/malacca/1e91cd9891405c757800501c42eca81bed510611/docs/malacca.jpg -------------------------------------------------------------------------------- /docs/metrics.md: -------------------------------------------------------------------------------- 1 | # 📊 Metrics 2 | 3 | Malacca use [Cloudflare Analytics Engine](https://developers.cloudflare.com/analytics/analytics-engine/) to manage metrics like token usage, errors, latency, cache hit rate and so on. 4 | 5 | You can query the analytics engine with [SQL API](https://developers.cloudflare.com/analytics/analytics-engine/sql-api/) to get the metrics to draw your own dashboard. 6 | 7 | ```SQL 8 | SELECT 9 | blob1 AS endpoint, 10 | blob2 as path, 11 | blob3 as status, 12 | double1 as latency, 13 | double2 as prompt_tokens, 14 | double3 as completion_tokens 15 | FROM MALACCA 16 | WHERE timestamp > NOW() - INTERVAL '30' MINUTE 17 | ``` 18 | 19 | Response: 20 | 21 | ```json 22 | { 23 | "meta": [ 24 | { 25 | "name": "endpoint", 26 | "type": "String" 27 | }, 28 | { 29 | "name": "path", 30 | "type": "String" 31 | }, 32 | { 33 | "name": "status", 34 | "type": "String" 35 | }, 36 | { 37 | "name": "latency", 38 | "type": "Float64" 39 | }, 40 | { 41 | "name": "prompt_tokens", 42 | "type": "Float64" 43 | }, 44 | { 45 | "name": "completion_tokens", 46 | "type": "Float64" 47 | } 48 | ], 49 | "data": [ 50 | { 51 | "endpoint": "azure-openai", 52 | "path": "/azure-openai/malacca/deployments/gpt4o/chat/completions", 53 | "status": "404", 54 | "latency": 0, 55 | "prompt_tokens": 16, 56 | "completion_tokens": 703 57 | } 58 | ], 59 | "rows": 1, 60 | "rows_before_limit_at_least": 1 61 | } 62 | ``` 63 | 64 | You can customize the metrics logic by modifying the metrics middleware in `src/middlewares/metrics.ts`. -------------------------------------------------------------------------------- /docs/openai.md: -------------------------------------------------------------------------------- 1 | # OpenAI 2 | 3 | To leverage the advanced features provided by Malacca while using the OpenAI API, you only need to adjust the `base_url` configuration in the original SDK. This simple change allows you to benefit from Malacca's capabilities such as caching, virtual key management, rate limiting, logging and all other features. 4 | 5 | You need to get the following parameters: 6 | 7 | - `Worker_Domain`: The domain url where your Worker is accessible, you can find it in your worker Settings. 8 | - `Virtual_Key`: The virtual key that protect your real API key. 9 | 10 | ## Python Example 11 | 12 | You can use [OpenAI Python SDK](https://github.com/openai/openai-python) to visit OpenAI with Malacca endpoint. 13 | 14 | ```python 15 | from openai import OpenAI 16 | 17 | client = OpenAI(api_key="{Virtual_Key}", base_url="https://{Worker_Domain}/openai/") 18 | 19 | response = client.chat.completions.create( 20 | model="gpt-4o", 21 | messages=[ 22 | {"role": "system", "content": "You are a helpful assistant"}, 23 | {"role": "user", "content": "Tell me a very short story about Malacca."}, 24 | ], 25 | stream=False 26 | ) 27 | 28 | print(response.choices[0].message.content) 29 | ``` -------------------------------------------------------------------------------- /docs/rate-limiting.md: -------------------------------------------------------------------------------- 1 | # 🚦 Rate Limiting 2 | 3 | Rate Rate limiting is a crucial feature that helps protect your application from potential abuse or unintended overuse. By implementing rate limits, you can: 4 | 5 | - 🛡️ Prevent excessive requests from a single user or IP address 6 | - 💰 Control costs by limiting the number of API calls 7 | - 🚀 Ensure fair usage and maintain service quality for all users 8 | - 🔒 Mitigate potential Denial of Service (DoS) attacks 9 | 10 | Malacca's rate limiting feature relies on the [Cloudflare Workers Rate Limiting](https://developers.cloudflare.com/workers/runtime-apis/bindings/rate-limit/) feature. It allows you to set limits on the number of requests a user can make within a specified time frame. 11 | 12 | By default it limit by the virtual key and allows 100 requests per minute. 13 | 14 | You can modify the limit tokens count in `wrangler.toml` file, for example: 15 | 16 | ```toml 17 | [[unsafe.bindings]] 18 | name = "MY_RATE_LIMITER" 19 | type = "ratelimit" 20 | namespace_id = "1001" 21 | simple = { limit = 100, period = 60 } 22 | ``` 23 | 24 | And uou can also modify the rate limiting logic by modifying the rate limiting middleware in `src/middlewares/rateLimiter.ts`. -------------------------------------------------------------------------------- /docs/virtual-key.md: -------------------------------------------------------------------------------- 1 | # 🔑 Virtual Key 2 | 3 | Virtual Key is a security feature that allows you to protect your real API key by providing a separate, temporary key for authentication. This feature enhances the security of your API usage in several ways: 4 | 5 | - 🎭 Masking: It hides your actual API key, reducing the risk of exposure. 6 | - 🔐 Access Control: You can create and manage multiple virtual keys with different permissions. 7 | - ❌ Revocation: Virtual keys can be easily revoked without affecting the main API key. 8 | - 📊 Usage Tracking: Each virtual key's usage can be monitored separately. 9 | 10 | > Virtual Key is enabled by default, so you need at least set up one key before invoke API calls. 11 | 12 | ## How to set Virtual Key 13 | 14 | Virtual Key is implemented by Cloudflare Worker KV, you can easily add a delete key by Wrangler CLI. 15 | 16 | 1. Add a Virtual Key 17 | 18 | ```bash 19 | VIRTUAL_KEY=malacca 20 | REAL_KEY=YOUR_REAL_API_KEY 21 | npx wrangler kv key put ${VIRTUAL_KEY} ${REAL_KEY} --binding MALACCA_USER 22 | ``` 23 | 24 | 2. Revoke a Virtual Key 25 | 26 | ```bash 27 | npx wrangler kv key delete ${VIRTUAL_KEY} --binding MALACCA_USER 28 | ``` 29 | 30 | You can also manage the KV pairs directly from Cloudflare Worker KV web console. 31 | 32 | You can customize the virtual key logic by modifying the virtual key middleware in `src/middlewares/virtualKey.ts`. -------------------------------------------------------------------------------- /eslint.config.mjs: -------------------------------------------------------------------------------- 1 | // @ts-check 2 | 3 | import eslint from '@eslint/js'; 4 | import tseslint from 'typescript-eslint'; 5 | 6 | export default tseslint.config( 7 | eslint.configs.recommended, 8 | ...tseslint.configs.strict, 9 | ...tseslint.configs.stylistic, 10 | { 11 | ignores: ['worker-configuration.d.ts', '.wrangler/**', 'node_modules/**', 'build/**'], 12 | }, 13 | ); 14 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "malacca", 3 | "version": "0.0.0", 4 | "private": true, 5 | "scripts": { 6 | "deploy": "wrangler deploy", 7 | "dev": "wrangler dev --remote", 8 | "start": "wrangler dev", 9 | "test": "vitest run", 10 | "cf-typegen": "wrangler types" 11 | }, 12 | "devDependencies": { 13 | "@cloudflare/vitest-pool-workers": "^0.5.18", 14 | "@cloudflare/workers-types": "^4.20241011.0", 15 | "@eslint/js": "^9.10.0", 16 | "@types/eslint__js": "^8.42.3", 17 | "eslint": "^9.12.0", 18 | "typescript": "^5.6.3", 19 | "typescript-eslint": "^8.8.1", 20 | "vitest": "^2.1.2", 21 | "wrangler": "^3.78.12" 22 | }, 23 | "dependencies": { 24 | "hono": "^4.6.4" 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /src/index.ts: -------------------------------------------------------------------------------- 1 | import { Hono } from 'hono'; 2 | import { providers } from './providers'; 3 | 4 | const app = new Hono<{ Bindings: Env }>(); 5 | 6 | app.get('/', (c) => c.text('Welcome to Malacca!')); 7 | 8 | Object.entries(providers).forEach(([_, provider]) => { 9 | app.route(provider.basePath, provider.route); 10 | }); 11 | 12 | app.onError((err, c) => c.text(err.message, 500)); 13 | 14 | export default app; -------------------------------------------------------------------------------- /src/middlewares/analytics.ts: -------------------------------------------------------------------------------- 1 | import { Context, MiddlewareHandler, Next } from 'hono'; 2 | import { AppContext, setMiddlewares } from '.'; 3 | 4 | export function recordAnalytics( 5 | c: Context, 6 | endpoint: string, 7 | duration: number, 8 | ) { 9 | 10 | const getModelName = c.get('getModelName'); 11 | const modelName = typeof getModelName === 'function' ? getModelName(c) : 'unknown'; 12 | 13 | const getTokenCount = c.get('getTokenCount'); 14 | const { input_tokens, output_tokens } = typeof getTokenCount === 'function' ? getTokenCount(c) : { input_tokens: 0, output_tokens: 0 }; 15 | 16 | console.log(endpoint, c.req.path, modelName, input_tokens, output_tokens, c.get('malacca-cache-status') || 'miss', c.res.status); 17 | 18 | if (c.env.MALACCA) { 19 | c.env.MALACCA.writeDataPoint({ 20 | 'blobs': [endpoint, c.req.path, c.res.status.toString(), c.get('malacca-cache-status') || 'miss', modelName], 21 | 'doubles': [duration, input_tokens, output_tokens], 22 | 'indexes': [endpoint], 23 | }); 24 | } 25 | } 26 | 27 | export const metricsMiddleware: MiddlewareHandler = async (c: Context, next: Next) => { 28 | setMiddlewares(c, 'metrics'); 29 | const startTime = Date.now(); 30 | await next(); 31 | 32 | c.executionCtx.waitUntil((async () => { 33 | await c.get('bufferPromise'); 34 | const endTime = Date.now(); 35 | const duration = endTime - startTime; 36 | const endpoint = c.get('endpoint') || 'unknown'; 37 | recordAnalytics(c, endpoint, duration); 38 | })()); 39 | }; 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | -------------------------------------------------------------------------------- /src/middlewares/buffer.ts: -------------------------------------------------------------------------------- 1 | import { Context, MiddlewareHandler, Next } from 'hono' 2 | import { AppContext, setMiddlewares } from '.'; 3 | 4 | export const bufferMiddleware: MiddlewareHandler = async (c: Context, next: Next) => { 5 | setMiddlewares(c, 'buffer'); 6 | let buffer = '' 7 | let resolveBuffer!: () => void 8 | const bufferPromise = new Promise((resolve) => { 9 | resolveBuffer = resolve 10 | }) 11 | c.set('bufferPromise', bufferPromise) 12 | 13 | const reqBuffer: string = await c.req.text() || '' 14 | c.set('reqBuffer', reqBuffer) 15 | 16 | await next() 17 | 18 | const originalResponse = c.res 19 | const { readable, writable } = new TransformStream(); 20 | const writer = writable.getWriter(); 21 | c.executionCtx.waitUntil((async () => { 22 | const reader = originalResponse.body?.getReader(); 23 | if (!reader) { 24 | c.set('buffer', buffer); 25 | resolveBuffer(); 26 | return; 27 | } 28 | 29 | try { 30 | while (true) { 31 | const { done, value } = await reader.read(); 32 | if (done) break; 33 | const chunk = new TextDecoder('utf-8').decode(value) 34 | buffer += chunk 35 | await writer.write(value); 36 | } 37 | } finally { 38 | c.set('buffer', buffer); 39 | resolveBuffer(); 40 | await writer.close(); 41 | } 42 | })()); 43 | 44 | c.res = new Response(readable, { 45 | status: originalResponse.status, 46 | statusText: originalResponse.statusText, 47 | headers: originalResponse.headers 48 | }); 49 | 50 | } 51 | -------------------------------------------------------------------------------- /src/middlewares/cache.ts: -------------------------------------------------------------------------------- 1 | import { Context, MiddlewareHandler, Next } from "hono"; 2 | import { AppContext, setMiddlewares } from '.'; 3 | 4 | export async function generateCacheKey(urlWithQueryParams: string, body: string): Promise { 5 | const cacheKey = await crypto.subtle.digest( 6 | 'SHA-256', 7 | new TextEncoder().encode(urlWithQueryParams + JSON.stringify(body)) 8 | ); 9 | return Array.from(new Uint8Array(cacheKey)) 10 | .map(b => b.toString(16).padStart(2, '0')) 11 | .join(''); 12 | } 13 | 14 | export const cacheMiddleware: MiddlewareHandler = async (c: Context, next: Next) => { 15 | setMiddlewares(c, 'cache'); 16 | const cacheKeyHex = await generateCacheKey(c.req.url, await c.req.text()); 17 | const response = await c.env.MALACCA_CACHE.get(cacheKeyHex, "stream"); 18 | if (response) { 19 | const { value: _value, metadata } = await c.env.MALACCA_CACHE.getWithMetadata(cacheKeyHex, "stream"); 20 | const contentType = (metadata as Record)['contentType'] || 'application/octet-stream'; 21 | c.set('malacca-cache-status', 'hit'); 22 | return new Response(response, { headers: { 'malacca-cache-status': 'hit', 'content-type': contentType } }); 23 | } 24 | 25 | await next(); 26 | 27 | if (c.res.status === 200) { 28 | c.executionCtx.waitUntil((async () => { 29 | await c.get('bufferPromise'); 30 | const contentType = c.res.headers.get('content-type'); 31 | c.executionCtx.waitUntil(c.env.MALACCA_CACHE.put(cacheKeyHex, c.get('buffer'), { expirationTtl: 3600, metadata: { 'contentType': contentType } })); 32 | })()); 33 | } 34 | }; -------------------------------------------------------------------------------- /src/middlewares/fallback.ts: -------------------------------------------------------------------------------- 1 | import { Context, Next } from 'hono'; 2 | import { AppContext, setMiddlewares } from '.'; 3 | 4 | export const fallbackMiddleware = async (c: Context, next: Next) => { 5 | setMiddlewares(c, 'fallback'); 6 | try { 7 | await next(); 8 | 9 | // Check if the response status is in the 5xx range 10 | if (c.res && c.res.status >= 500 && c.res.status < 600) { 11 | throw new Error(`Upstream returned ${c.res.status} status`); 12 | } 13 | } catch (error) { 14 | try { 15 | // Call CF Workers AI as a fallback 16 | const fallbackResponse = await c.env.AI.run( 17 | "@cf/meta/llama-3.1-8b-instruct", 18 | await c.req.json() 19 | ); 20 | 21 | let response: Response; 22 | if (fallbackResponse instanceof ReadableStream) { 23 | response = new Response(fallbackResponse); 24 | } else { 25 | response = new Response(fallbackResponse.response); 26 | } 27 | 28 | // Add a header to indicate fallback was used 29 | response.headers.set('X-Fallback-Used', 'true'); 30 | return response; 31 | } catch (fallbackError) { 32 | return new Response('Both primary and fallback providers failed', { status: 500 }); 33 | } 34 | } 35 | }; 36 | -------------------------------------------------------------------------------- /src/middlewares/guard.ts: -------------------------------------------------------------------------------- 1 | import { Context, MiddlewareHandler, Next } from "hono"; 2 | import { AppContext, setMiddlewares } from "."; 3 | 4 | const denyRequestPatterns = [ 5 | 'password', 6 | ]; 7 | 8 | const denyResponsePatterns = [ 9 | 'password', 10 | ]; 11 | 12 | 13 | // The guard middleware is used to protect the API by checking if the request match the specific regex. 14 | // If so it returns message "Rejected due to inappropriate content" with 403 status code. 15 | export const guardMiddleware: MiddlewareHandler = async (c: Context, next: Next) => { 16 | setMiddlewares(c, 'guard'); 17 | const requestText = await c.req.text(); 18 | if (denyRequestPatterns.some(pattern => new RegExp(pattern, 'i').test(requestText))) { 19 | return c.text('Rejected due to inappropriate content', 403); 20 | } 21 | 22 | await next(); 23 | 24 | if (c.res.status === 200 && c.res.headers.get('Content-Type')?.includes('application/json')) { 25 | const responseText = await c.res.clone().text(); 26 | if (denyResponsePatterns.some(pattern => new RegExp(pattern, 'i').test(responseText))) { 27 | return c.text('Rejected due to inappropriate content', 403); 28 | } 29 | } 30 | } -------------------------------------------------------------------------------- /src/middlewares/index.ts: -------------------------------------------------------------------------------- 1 | import { Context } from 'hono'; 2 | 3 | export { cacheMiddleware } from './cache'; 4 | export { metricsMiddleware } from './analytics'; 5 | export { bufferMiddleware } from './buffer'; 6 | export { loggingMiddleware } from './logging'; 7 | export { virtualKeyMiddleware } from './virtualKey'; 8 | export { rateLimiterMiddleware } from './rateLimiter'; 9 | export { guardMiddleware } from './guard'; 10 | export { fallbackMiddleware } from './fallback'; 11 | export interface AppContext { 12 | Bindings: Env, 13 | Variables: { 14 | middlewares: string[], 15 | endpoint: string, 16 | 'malacca-cache-status': string, 17 | bufferPromise: Promise, 18 | buffer: string, 19 | reqBuffer: string, 20 | realKey: string, 21 | getModelName: (c: Context) => string, 22 | getTokenCount: (c: Context) => { input_tokens: number, output_tokens: number }, 23 | getVirtualKey: (c: Context) => string, 24 | } 25 | } 26 | 27 | export function setMiddlewares(c: Context, name: string) { 28 | if (!c.get('middlewares')) { 29 | c.set('middlewares', [name]); 30 | } else { 31 | c.set('middlewares', [...c.get('middlewares'), name]); 32 | } 33 | } -------------------------------------------------------------------------------- /src/middlewares/logging.ts: -------------------------------------------------------------------------------- 1 | import { Context, Next } from 'hono'; 2 | import { AppContext, setMiddlewares } from '.'; 3 | 4 | export const loggingMiddleware = async (c: Context, next: Next) => { 5 | setMiddlewares(c, 'logging'); 6 | await next(); 7 | 8 | // Log request and response 9 | c.executionCtx.waitUntil((async () => { 10 | const requestBody = c.get('reqBuffer') || ''; 11 | console.log('Request:', { 12 | body: requestBody, 13 | }); 14 | 15 | await c.get('bufferPromise') 16 | console.log('Response:', { 17 | body: c.get('buffer'), 18 | }); 19 | })()); 20 | }; 21 | -------------------------------------------------------------------------------- /src/middlewares/rateLimiter.ts: -------------------------------------------------------------------------------- 1 | import { Context, Next } from "hono"; 2 | import { AppContext, setMiddlewares } from '.'; 3 | 4 | export const rateLimiterMiddleware = async (c: Context, next: Next) => { 5 | setMiddlewares(c, 'rateLimiter'); 6 | const key = c.req.header('api-key') || ''; 7 | const { success } = await c.env.MY_RATE_LIMITER.limit({ key: key }) 8 | if (!success) { 9 | return new Response(`429 Failure – rate limit exceeded`, { status: 429 }) 10 | } 11 | 12 | await next(); 13 | }; -------------------------------------------------------------------------------- /src/middlewares/virtualKey.ts: -------------------------------------------------------------------------------- 1 | import { Context, Next } from "hono"; 2 | import { AppContext, setMiddlewares } from '.'; 3 | 4 | export const virtualKeyMiddleware = async (c: Context, next: Next) => { 5 | setMiddlewares(c, 'virtualKey'); 6 | const apiKey = c.get('getVirtualKey')(c); 7 | const realKey = await c.env.MALACCA_USER.get(apiKey); 8 | if (!realKey) { 9 | return c.text('Unauthorized', 401); 10 | } 11 | c.set('realKey', realKey); 12 | await next(); 13 | }; -------------------------------------------------------------------------------- /src/providers/azureOpenAI.ts: -------------------------------------------------------------------------------- 1 | import { Hono, Context, Next } from 'hono'; 2 | import { AIProvider } from '../types'; 3 | import { 4 | cacheMiddleware, 5 | metricsMiddleware, 6 | bufferMiddleware, 7 | loggingMiddleware, 8 | virtualKeyMiddleware, 9 | rateLimiterMiddleware, 10 | guardMiddleware, 11 | fallbackMiddleware 12 | } from '../middlewares'; 13 | 14 | const BasePath = '/azure-openai/:resource_name/deployments/:deployment_name'; 15 | const ProviderName = 'azure-openai'; 16 | const azureOpenAIRoute = new Hono(); 17 | 18 | const initMiddleware = async (c: Context, next: Next) => { 19 | if (!c.get('middlewares')) { 20 | c.set('middlewares', ['init']); 21 | } else { 22 | c.set('middlewares', [...c.get('middlewares'), 'init']); 23 | } 24 | c.set('endpoint', ProviderName); 25 | c.set('getModelName', getModelName); 26 | c.set('getTokenCount', getTokenCount); 27 | c.set('getVirtualKey', getVirtualKey); 28 | await next(); 29 | }; 30 | 31 | azureOpenAIRoute.use( 32 | initMiddleware, 33 | metricsMiddleware, 34 | loggingMiddleware, 35 | bufferMiddleware, 36 | virtualKeyMiddleware, 37 | rateLimiterMiddleware, 38 | guardMiddleware, 39 | cacheMiddleware, 40 | fallbackMiddleware 41 | ); 42 | 43 | azureOpenAIRoute.post('/*', async (c: Context) => { 44 | return azureOpenAIProvider.handleRequest(c); 45 | }); 46 | 47 | export const azureOpenAIProvider: AIProvider = { 48 | name: ProviderName, 49 | basePath: BasePath, 50 | route: azureOpenAIRoute, 51 | getModelName: getModelName, 52 | getTokenCount: getTokenCount, 53 | handleRequest: async (c: Context) => { 54 | const resourceName = c.req.param('resource_name') || ''; 55 | const deploymentName = c.req.param('deployment_name') || ''; 56 | const functionName = c.req.path.slice(`/azure-openai/${resourceName}/deployments/${deploymentName}/`.length); 57 | const azureEndpoint = `https://${resourceName}.openai.azure.com/openai/deployments/${deploymentName}/${functionName}`; 58 | const queryParams = new URLSearchParams(c.req.query()).toString(); 59 | const urlWithQueryParams = `${azureEndpoint}?${queryParams}`; 60 | 61 | const headers = new Headers(c.req.header()); 62 | if (c.get('middlewares')?.includes('virtualKey')) { 63 | const apiKey: string = c.get('realKey'); 64 | if (apiKey) { 65 | headers.set('api-key', apiKey); 66 | } 67 | } 68 | const response = await fetch(urlWithQueryParams, { 69 | method: c.req.method, 70 | body: JSON.stringify(await c.req.json()), 71 | headers: headers 72 | }); 73 | 74 | return response; 75 | } 76 | }; 77 | 78 | function getModelName(c: Context): string { 79 | if (c.res.status === 200) { 80 | const buf = c.get('buffer') || "" 81 | if (c.res.headers.get('content-type') === 'application/json') { 82 | const model = JSON.parse(buf)['model']; 83 | if (model) { 84 | return model 85 | } 86 | } else { 87 | const chunks = buf.split('\n\n'); 88 | for (const chunk of chunks) { 89 | if (chunk.startsWith('data: ')) { 90 | const jsonStr = chunk.slice(6); 91 | try { 92 | const jsonData = JSON.parse(jsonStr); 93 | if (jsonData.model != "") { 94 | return jsonData.model; 95 | } 96 | } catch { 97 | continue; 98 | } 99 | } 100 | } 101 | } 102 | } 103 | return "unknown" 104 | } 105 | 106 | function getTokenCount(c: Context): { input_tokens: number, output_tokens: number } { 107 | const buf = c.get('buffer') || "" 108 | if (c.res.status === 200) { 109 | if (c.res.headers.get('content-type') === 'application/json') { 110 | const usage = JSON.parse(buf)['usage']; 111 | if (usage) { 112 | const input_tokens = usage['prompt_tokens'] || 0; 113 | const output_tokens = usage['completion_tokens'] || 0; 114 | return { input_tokens, output_tokens } 115 | } 116 | } else { 117 | // For streaming response, azure openai does not return usage in the response body, so we count the words and multiply by 4/3 to get the number of input tokens 118 | const requestBody = c.get('reqBuffer') || '{}' 119 | const messages = JSON.stringify(JSON.parse(requestBody).messages); 120 | const input_tokens = Math.ceil(messages.split(/\s+/).length * 4 / 3); 121 | 122 | // For streaming responses, we count the number of '\n\n' as the number of output tokens 123 | const output_tokens = buf.split('\n\n').length - 1; 124 | return { input_tokens: input_tokens, output_tokens: output_tokens } 125 | } 126 | } 127 | return { input_tokens: 0, output_tokens: 0 } 128 | } 129 | 130 | function getVirtualKey(c: Context): string { 131 | return c.req.header('api-key') || ''; 132 | } -------------------------------------------------------------------------------- /src/providers/deepseek.ts: -------------------------------------------------------------------------------- 1 | import { Hono, Context, Next } from 'hono'; 2 | import { AIProvider } from '../types'; 3 | import { 4 | cacheMiddleware, 5 | metricsMiddleware, 6 | bufferMiddleware, 7 | loggingMiddleware, 8 | virtualKeyMiddleware, 9 | rateLimiterMiddleware, 10 | guardMiddleware, 11 | fallbackMiddleware 12 | } from '../middlewares'; 13 | 14 | const BasePath = '/deepseek'; 15 | const ProviderName = 'deepseek'; 16 | const deepseekRoute = new Hono(); 17 | 18 | const initMiddleware = async (c: Context, next: Next) => { 19 | c.set('endpoint', ProviderName); 20 | c.set('getModelName', getModelName); 21 | c.set('getTokenCount', getTokenCount); 22 | c.set('getVirtualKey', getVirtualKey); 23 | await next(); 24 | }; 25 | 26 | deepseekRoute.use( 27 | initMiddleware, 28 | metricsMiddleware, 29 | loggingMiddleware, 30 | bufferMiddleware, 31 | virtualKeyMiddleware, 32 | rateLimiterMiddleware, 33 | guardMiddleware, 34 | cacheMiddleware, 35 | fallbackMiddleware 36 | ); 37 | 38 | deepseekRoute.post('/*', async (c: Context) => { 39 | return deepseekProvider.handleRequest(c); 40 | }); 41 | 42 | deepseekRoute.get('/*', async (c: Context) => { 43 | return c.text('DeepSeek endpoint on Malacca.', 200, { 'Content-Type': 'text/plain' }); 44 | }); 45 | 46 | export const deepseekProvider: AIProvider = { 47 | name: ProviderName, 48 | basePath: BasePath, 49 | route: deepseekRoute, 50 | getModelName: getModelName, 51 | getTokenCount: getTokenCount, 52 | handleRequest: async (c: Context) => { 53 | const functionName = c.req.path.slice(`/deepseek/`.length); 54 | const deepseekEndpoint = `https://api.deepseek.com/${functionName}`; 55 | 56 | const headers = new Headers(c.req.header()); 57 | if (c.get('middlewares')?.includes('virtualKey')) { 58 | const apiKey: string = c.get('realKey'); 59 | if (apiKey) { 60 | headers.set('Authorization', `Bearer ${apiKey}`); 61 | } 62 | } 63 | 64 | const response = await fetch(deepseekEndpoint, { 65 | method: c.req.method, 66 | body: JSON.stringify(await c.req.json()), 67 | headers: headers 68 | }); 69 | 70 | return response; 71 | } 72 | }; 73 | 74 | function getModelName(c: Context): string { 75 | const body = c.get('reqBuffer') || '{}'; 76 | const model = JSON.parse(body).model; 77 | return model || "unknown"; 78 | } 79 | 80 | function getTokenCount(c: Context): { input_tokens: number, output_tokens: number } { 81 | const buf = c.get('buffer') || ""; 82 | if (c.res.status === 200) { 83 | if (c.res.headers.get('content-type') === 'application/json') { 84 | try { 85 | const jsonResponse = JSON.parse(buf); 86 | const usage = jsonResponse.usage; 87 | if (usage) { 88 | return { 89 | input_tokens: usage.prompt_tokens || 0, 90 | output_tokens: usage.completion_tokens || 0 91 | }; 92 | } 93 | } catch (error) { 94 | console.error("Error parsing response:", error); 95 | } 96 | } 97 | else { 98 | const output = buf.trim().split('\n\n').at(-2); 99 | if (output && output.startsWith('data: ')) { 100 | const usage_message = JSON.parse(output.slice('data: '.length)); 101 | if ('usage' in usage_message) { 102 | return { 103 | input_tokens: usage_message.usage.prompt_tokens || 0, 104 | output_tokens: usage_message.usage.completion_tokens || 0 105 | }; 106 | } 107 | return { input_tokens: 0, output_tokens: 0 }; 108 | } 109 | } 110 | } 111 | return { input_tokens: 0, output_tokens: 0 }; 112 | } 113 | 114 | function getVirtualKey(c: Context): string { 115 | const authHeader = c.req.header('Authorization') || ''; 116 | return authHeader.startsWith('Bearer ') ? authHeader.slice(7) : ''; 117 | } 118 | 119 | -------------------------------------------------------------------------------- /src/providers/index.ts: -------------------------------------------------------------------------------- 1 | import { azureOpenAIProvider } from './azureOpenAI'; 2 | import { workersAIProvider } from './workersAI'; 3 | import { deepseekProvider } from './deepseek'; 4 | import { openaiProvider } from './openai'; 5 | export const providers = { 6 | 'azure-openai': azureOpenAIProvider, 7 | 'workers-ai': workersAIProvider, 8 | 'deepseek': deepseekProvider, 9 | 'openai': openaiProvider, 10 | }; 11 | -------------------------------------------------------------------------------- /src/providers/openai.ts: -------------------------------------------------------------------------------- 1 | import { Hono, Context, Next } from 'hono'; 2 | import { AIProvider } from '../types'; 3 | import { 4 | cacheMiddleware, 5 | metricsMiddleware, 6 | bufferMiddleware, 7 | loggingMiddleware, 8 | virtualKeyMiddleware, 9 | rateLimiterMiddleware, 10 | guardMiddleware, 11 | fallbackMiddleware 12 | } from '../middlewares'; 13 | 14 | const BasePath = '/openai'; 15 | const ProviderName = 'openai'; 16 | const openaiRoute = new Hono(); 17 | 18 | const initMiddleware = async (c: Context, next: Next) => { 19 | c.set('endpoint', ProviderName); 20 | c.set('getModelName', getModelName); 21 | c.set('getTokenCount', getTokenCount); 22 | c.set('getVirtualKey', getVirtualKey); 23 | await next(); 24 | }; 25 | 26 | openaiRoute.use( 27 | initMiddleware, 28 | metricsMiddleware, 29 | loggingMiddleware, 30 | bufferMiddleware, 31 | virtualKeyMiddleware, 32 | rateLimiterMiddleware, 33 | guardMiddleware, 34 | cacheMiddleware, 35 | fallbackMiddleware 36 | ); 37 | 38 | openaiRoute.post('/*', async (c: Context) => { 39 | return openaiProvider.handleRequest(c); 40 | }); 41 | 42 | openaiRoute.get('/*', async (c: Context) => { 43 | return c.text('OpenAI endpoint on Malacca.', 200, { 'Content-Type': 'text/plain' }); 44 | }); 45 | 46 | export const openaiProvider: AIProvider = { 47 | name: ProviderName, 48 | basePath: BasePath, 49 | route: openaiRoute, 50 | getModelName: getModelName, 51 | getTokenCount: getTokenCount, 52 | handleRequest: async (c: Context) => { 53 | const functionName = c.req.path.slice(`/openai/`.length); 54 | const openaiEndpoint = `https://api.openai.com/${functionName}`; 55 | console.log('openaiEndpoint', openaiEndpoint); 56 | const headers = new Headers(c.req.header()); 57 | if (c.get('middlewares')?.includes('virtualKey')) { 58 | const apiKey: string = c.get('realKey'); 59 | if (apiKey) { 60 | headers.set('Authorization', `Bearer ${apiKey}`); 61 | } 62 | } 63 | 64 | const response = await fetch(openaiEndpoint, { 65 | method: c.req.method, 66 | body: JSON.stringify(await c.req.json()), 67 | headers: headers 68 | }); 69 | 70 | return response; 71 | } 72 | }; 73 | 74 | function getModelName(c: Context): string { 75 | const body = c.get('reqBuffer') || '{}'; 76 | const model = JSON.parse(body).model; 77 | return model || "unknown"; 78 | } 79 | 80 | function getTokenCount(c: Context): { input_tokens: number, output_tokens: number } { 81 | const buf = c.get('buffer') || ""; 82 | if (c.res.status === 200) { 83 | if (c.res.headers.get('content-type') === 'application/json') { 84 | try { 85 | const jsonResponse = JSON.parse(buf); 86 | const usage = jsonResponse.usage; 87 | if (usage) { 88 | return { 89 | input_tokens: usage.prompt_tokens || 0, 90 | output_tokens: usage.completion_tokens || 0 91 | }; 92 | } 93 | } catch (error) { 94 | console.error("Error parsing response:", error); 95 | } 96 | } 97 | else { 98 | const output = buf.trim().split('\n\n').at(-2); 99 | if (output && output.startsWith('data: ')) { 100 | const usage_message = JSON.parse(output.slice('data: '.length)); 101 | if ('usage' in usage_message) { 102 | return { 103 | input_tokens: usage_message.usage.prompt_tokens || 0, 104 | output_tokens: usage_message.usage.completion_tokens || 0 105 | }; 106 | } 107 | return { input_tokens: 0, output_tokens: 0 }; 108 | } 109 | } 110 | } 111 | return { input_tokens: 0, output_tokens: 0 }; 112 | } 113 | 114 | function getVirtualKey(c: Context): string { 115 | const authHeader = c.req.header('Authorization') || ''; 116 | return authHeader.startsWith('Bearer ') ? authHeader.slice(7) : ''; 117 | } 118 | 119 | -------------------------------------------------------------------------------- /src/providers/workersAI.ts: -------------------------------------------------------------------------------- 1 | import { Context, Hono } from 'hono'; 2 | import { AIProvider } from '../types'; 3 | 4 | const ProviderName = 'workers-ai'; 5 | const BasePath = '/workers-ai'; 6 | const workersAIRoute = new Hono(); 7 | workersAIRoute.post('/:provider/:repo/:model', async (c) => { 8 | return workersAIProvider.handleRequest(c); 9 | }); 10 | 11 | export const workersAIProvider: AIProvider = { 12 | name: ProviderName, 13 | basePath: BasePath, 14 | route: workersAIRoute, 15 | getModelName: getModelName, 16 | getTokenCount: getTokenCount, 17 | handleRequest: async (c: Context<{ Bindings: Env }>) => { 18 | const model = getModelName(c); 19 | const response = await c.env.AI.run(`${model}`, 20 | await c.req.json()); 21 | 22 | if (response instanceof ReadableStream) { 23 | return new Response(response); 24 | } 25 | 26 | return new Response(JSON.stringify(response)); 27 | } 28 | }; 29 | 30 | function getModelName(c: Context) { 31 | const provider = c.req.param('provider'); 32 | const repo = c.req.param('repo'); 33 | const model = c.req.param('model'); 34 | return `${provider}/${repo}/${model}`; 35 | } 36 | 37 | function getTokenCount(c: Context) { 38 | return { input_tokens: 0, output_tokens: 0 }; 39 | } 40 | 41 | function getVirtualKey(c: Context) { 42 | return ''; 43 | } -------------------------------------------------------------------------------- /src/types.ts: -------------------------------------------------------------------------------- 1 | import { Context, Hono } from 'hono'; 2 | export interface AIProvider { 3 | name: string; 4 | handleRequest: (c: Context) => Promise; 5 | getModelName: (c: Context) => string; 6 | getTokenCount: (c: Context) => {input_tokens: number, output_tokens: number}; 7 | basePath: string; 8 | route: Hono; 9 | } 10 | -------------------------------------------------------------------------------- /test/deepseek.test.ts: -------------------------------------------------------------------------------- 1 | /// 2 | /// 3 | import { env, SELF } from 'cloudflare:test'; 4 | import { beforeAll, describe, it, expect } from 'vitest'; 5 | 6 | declare module "cloudflare:test" { 7 | interface ProvidedEnv extends Env { } 8 | } 9 | 10 | beforeAll(async () => { 11 | await env.MALACCA_USER.put('deepseek', import.meta.env.VITE_DEEPSEEK_API_KEY); 12 | }); 13 | 14 | const url = `https://example.com/deepseek/chat/completions`; 15 | 16 | const createRequestBody = (stream: boolean, placeholder: string) => ` 17 | { 18 | "model": "deepseek-chat", 19 | "messages": [ 20 | { 21 | "role": "system", 22 | "content": "You are an AI assistant that helps people find information." 23 | }, 24 | { 25 | "role": "user", 26 | "content": "Tell me a very short story about ${placeholder}" 27 | } 28 | ], 29 | "temperature": 0.7, 30 | "top_p": 0.95, 31 | "max_tokens": 100, 32 | "stream": ${stream} 33 | }`; 34 | 35 | describe('Test Virtual Key', () => { 36 | it('should return 401 for invalid api key', async () => { 37 | const response = await SELF.fetch(url, { 38 | method: 'POST', 39 | body: createRequestBody(true, 'Malacca'), 40 | headers: { 'Content-Type': 'application/json', 'Authorization': 'Bearer invalid-key' } 41 | }); 42 | 43 | expect(response.status).toBe(401); 44 | }); 45 | }); 46 | 47 | describe('Test Guard', () => { 48 | it('should return 403 for deny request', async () => { 49 | const response = await SELF.fetch(url, { 50 | method: 'POST', 51 | body: createRequestBody(true, 'password'), 52 | headers: { 'Content-Type': 'application/json', 'Authorization': `Bearer deepseek` } 53 | }); 54 | 55 | expect(response.status).toBe(403); 56 | }); 57 | }); 58 | 59 | describe('Test Cache', () => { 60 | it('with cache first response should with no header malacca-cache-status and following response with hit', async () => { 61 | const body = createRequestBody(false, 'Malacca'); 62 | let start = Date.now(); 63 | let response = await SELF.fetch(url, { method: 'POST', body: body, headers: { 'Content-Type': 'application/json', 'Authorization': `Bearer deepseek` } }); 64 | const value = await response.json() 65 | const duration = Date.now() - start 66 | 67 | expect(response.status).toBe(200); 68 | expect(response.headers.get('content-type')).toContain('application/json'); 69 | expect(response.headers.get('malacca-cache-status')).toBeNull(); 70 | 71 | start = Date.now(); 72 | response = await SELF.fetch(url, { method: 'POST', body: body, headers: { 'Content-Type': 'application/json', 'Authorization': `Bearer deepseek` } }); 73 | const cacheValue = await response.json() 74 | const cacheDuration = Date.now() - start 75 | 76 | expect(response.status).toBe(200); 77 | expect(response.headers.get('malacca-cache-status')).toBe('hit'); 78 | expect(response.headers.get('content-type')).toBe('application/json'); 79 | expect(value).toEqual(cacheValue) 80 | expect(duration / 2).toBeGreaterThan(cacheDuration) 81 | }); 82 | 83 | it('Test stream with cache', async () => { 84 | const body = createRequestBody(true, 'Malacca'); 85 | let start = Date.now(); 86 | let response = await SELF.fetch(url, { method: 'POST', body: body, headers: { 'Content-Type': 'application/json', 'Authorization': `Bearer deepseek` } }); 87 | const value = await response.text() 88 | const duration = Date.now() - start 89 | 90 | expect(response.status).toBe(200); 91 | expect(response.headers.get('content-type')).toContain('text/event-stream'); 92 | expect(response.headers.get('malacca-cache-status')).toBeNull(); 93 | 94 | start = Date.now(); 95 | response = await SELF.fetch(url, { method: 'POST', body: body, headers: { 'Content-Type': 'application/json', 'Authorization': `Bearer deepseek` } }); 96 | const cacheValue = await response.text() 97 | const cacheDuration = Date.now() - start 98 | 99 | expect(response.status).toBe(200); 100 | expect(response.headers.get('malacca-cache-status')).toBe('hit'); 101 | expect(response.headers.get('content-type')).toContain('text/event-stream'); 102 | expect(value).toEqual(cacheValue) 103 | expect(duration / 2).toBeGreaterThan(cacheDuration) 104 | }); 105 | 106 | it('should not cache non-200 responses', async () => { 107 | const invalidBody = JSON.stringify({ 108 | messages: [{ role: "user", content: "This is an invalid request" }], 109 | stream: "invalid-model", 110 | temperature: 0.7, 111 | top_p: 0.95, 112 | max_tokens: 800, 113 | }); 114 | 115 | // First request - should return a non-200 response 116 | let response = await SELF.fetch(url, { 117 | method: 'POST', 118 | body: invalidBody, 119 | headers: { 'Content-Type': 'application/json', 'Authorization': `Bearer deepseek` } 120 | }); 121 | 122 | expect(response.status).not.toBe(200); 123 | expect(response.headers.get('malacca-cache-status')).toBeNull(); 124 | 125 | // Second request with the same invalid body 126 | response = await SELF.fetch(url, { 127 | method: 'POST', 128 | body: invalidBody, 129 | headers: { 'Content-Type': 'application/json', 'Authorization': `Bearer deepseek` } 130 | }); 131 | 132 | expect(response.status).not.toBe(200); 133 | // Should still be a cache miss, as non-200 responses are not cached 134 | expect(response.headers.get('malacca-cache-status')).toBeNull(); 135 | }); 136 | }); -------------------------------------------------------------------------------- /test/index.spec.ts: -------------------------------------------------------------------------------- 1 | /// 2 | /// 3 | import { env, SELF } from 'cloudflare:test'; 4 | import { beforeAll, describe, it, expect } from 'vitest'; 5 | 6 | declare module "cloudflare:test" { 7 | interface ProvidedEnv extends Env { } 8 | } 9 | 10 | beforeAll(async () => { 11 | // Set up Cloudflare KV 12 | await env.MALACCA_USER.put('oilbeater', import.meta.env.VITE_AZURE_API_KEY, { metadata: { 'contentType': 'application/json' } }); 13 | }); 14 | 15 | describe('Welcome to Malacca worker', () => { 16 | it('responds with Welcome to Malacca!', async () => { 17 | const response = await SELF.fetch('https://example.com'); 18 | expect(await response.text()).toMatchInlineSnapshot(`"Welcome to Malacca!"`); 19 | }); 20 | }); 21 | 22 | const url = `https://example.com/azure-openai/${import.meta.env.VITE_AZURE_RESOURCE_NAME}/deployments/${import.meta.env.VITE_AZURE_DEPLOYMENT_NAME}/chat/completions?api-version=2024-07-01-preview`; 23 | const createRequestBody = (stream: boolean, placeholder: string) => ` 24 | { 25 | "messages": [ 26 | { 27 | "role": "system", 28 | "content": [ 29 | { 30 | "type": "text", 31 | "text": "You are an AI assistant that helps people find information." 32 | } 33 | ] 34 | }, 35 | { 36 | "role": "user", 37 | "content": [ 38 | { 39 | "type": "text", 40 | "text": "Tell me a very short story about ${placeholder}" 41 | } 42 | ] 43 | } 44 | ], 45 | "temperature": 0.7, 46 | "top_p": 0.95, 47 | "max_tokens": 800, 48 | "stream": ${stream} 49 | }`; 50 | 51 | describe('Test Cache', () => { 52 | it('with cache first response should with no header malacca-cache-status and following response with hit', async () => { 53 | const body = createRequestBody(false, 'Malacca'); 54 | let start = Date.now(); 55 | let response = await SELF.fetch(url, { method: 'POST', body: body, headers: { 'Content-Type': 'application/json', 'api-key': 'oilbeater' } }); 56 | const value = await response.json() 57 | const duration = Date.now() - start 58 | 59 | expect(response.status).toBe(200); 60 | expect(response.headers.get('content-type')).toContain('application/json'); 61 | expect(response.headers.get('malacca-cache-status')).toBeNull(); 62 | 63 | start = Date.now(); 64 | response = await SELF.fetch(url, { method: 'POST', body: body, headers: { 'Content-Type': 'application/json', 'api-key': 'oilbeater' } }); 65 | const cacheValue = await response.json() 66 | const cacheDuration = Date.now() - start 67 | 68 | expect(response.status).toBe(200); 69 | expect(response.headers.get('malacca-cache-status')).toBe('hit'); 70 | expect(response.headers.get('content-type')).toBe('application/json'); 71 | expect(value).toEqual(cacheValue) 72 | expect(duration / 2).toBeGreaterThan(cacheDuration) 73 | }); 74 | 75 | it('Test stream with cache', async () => { 76 | const body = createRequestBody(true, 'Malacca'); 77 | let start = Date.now(); 78 | let response = await SELF.fetch(url, { method: 'POST', body: body, headers: { 'Content-Type': 'application/json', 'api-key': 'oilbeater' } }); 79 | const value = await response.text() 80 | const duration = Date.now() - start 81 | 82 | expect(response.status).toBe(200); 83 | expect(response.headers.get('content-type')).toContain('text/event-stream'); 84 | expect(response.headers.get('malacca-cache-status')).toBeNull(); 85 | 86 | start = Date.now(); 87 | response = await SELF.fetch(url, { method: 'POST', body: body, headers: { 'Content-Type': 'application/json', 'api-key': 'oilbeater' } }); 88 | const cacheValue = await response.text() 89 | const cacheDuration = Date.now() - start 90 | 91 | expect(response.status).toBe(200); 92 | expect(response.headers.get('malacca-cache-status')).toBe('hit'); 93 | expect(response.headers.get('content-type')).toContain('text/event-stream'); 94 | expect(value).toEqual(cacheValue) 95 | expect(duration / 2).toBeGreaterThan(cacheDuration) 96 | }); 97 | 98 | it('should not cache non-200 responses', async () => { 99 | const invalidBody = JSON.stringify({ 100 | messages: [{ role: "user", content: "This is an invalid request" }], 101 | stream: "invalid-model", 102 | temperature: 0.7, 103 | top_p: 0.95, 104 | max_tokens: 800, 105 | }); 106 | 107 | // First request - should return a non-200 response 108 | let response = await SELF.fetch(url, { 109 | method: 'POST', 110 | body: invalidBody, 111 | headers: { 'Content-Type': 'application/json', 'api-key': 'oilbeater' } 112 | }); 113 | 114 | expect(response.status).not.toBe(200); 115 | expect(response.headers.get('malacca-cache-status')).toBeNull(); 116 | 117 | // Second request with the same invalid body 118 | response = await SELF.fetch(url, { 119 | method: 'POST', 120 | body: invalidBody, 121 | headers: { 'Content-Type': 'application/json', 'api-key': 'oilbeater' } 122 | }); 123 | 124 | expect(response.status).not.toBe(200); 125 | // Should still be a cache miss, as non-200 responses are not cached 126 | expect(response.headers.get('malacca-cache-status')).toBeNull(); 127 | }); 128 | }); 129 | 130 | describe('Test Virtual Key', () => { 131 | it('should return 401 for invalid api key', async () => { 132 | const response = await SELF.fetch(url, { 133 | method: 'POST', 134 | body: createRequestBody(true, 'Malacca'), 135 | headers: { 'Content-Type': 'application/json', 'api-key': 'invalid-key' } 136 | }); 137 | 138 | expect(response.status).toBe(401); 139 | }); 140 | }); 141 | 142 | describe('Test Guard', () => { 143 | it('should return 403 for deny request', async () => { 144 | const response = await SELF.fetch(url, { 145 | method: 'POST', 146 | body: createRequestBody(true, 'password'), 147 | headers: { 'Content-Type': 'application/json', 'api-key': 'oilbeater' } 148 | }); 149 | 150 | expect(response.status).toBe(403); 151 | }); 152 | }); 153 | -------------------------------------------------------------------------------- /test/openai.test.ts: -------------------------------------------------------------------------------- 1 | /// 2 | /// 3 | import { env, SELF } from 'cloudflare:test'; 4 | import { beforeAll, describe, it, expect } from 'vitest'; 5 | 6 | declare module "cloudflare:test" { 7 | interface ProvidedEnv extends Env { } 8 | } 9 | 10 | beforeAll(async () => { 11 | await env.MALACCA_USER.put('openai', import.meta.env.VITE_OPENAI_API_KEY); 12 | }); 13 | 14 | const url = `https://example.com/openai/v1/chat/completions`; 15 | 16 | const createRequestBody = (stream: boolean, placeholder: string) => ` 17 | { 18 | "model": "gpt-4o-mini", 19 | "messages": [ 20 | { 21 | "role": "system", 22 | "content": "You are an AI assistant that helps people find information." 23 | }, 24 | { 25 | "role": "user", 26 | "content": "Tell me a very short story about ${placeholder}" 27 | } 28 | ], 29 | "temperature": 0.7, 30 | "top_p": 0.95, 31 | "max_tokens": 100, 32 | "stream": ${stream} 33 | }`; 34 | 35 | describe('Test Virtual Key', () => { 36 | it('should return 401 for invalid api key', async () => { 37 | const response = await SELF.fetch(url, { 38 | method: 'POST', 39 | body: createRequestBody(true, 'Malacca'), 40 | headers: { 'Content-Type': 'application/json', 'Authorization': 'Bearer invalid-key' } 41 | }); 42 | 43 | expect(response.status).toBe(401); 44 | }); 45 | }); 46 | 47 | describe('Test Guard', () => { 48 | it('should return 403 for deny request', async () => { 49 | const response = await SELF.fetch(url, { 50 | method: 'POST', 51 | body: createRequestBody(true, 'password'), 52 | headers: { 'Content-Type': 'application/json', 'Authorization': `Bearer openai` } 53 | }); 54 | 55 | expect(response.status).toBe(403); 56 | }); 57 | }); 58 | 59 | describe('Test Cache', () => { 60 | it('with cache first response should with no header malacca-cache-status and following response with hit', async () => { 61 | const body = createRequestBody(false, 'Malacca'); 62 | let start = Date.now(); 63 | let response = await SELF.fetch(url, { method: 'POST', body: body, headers: { 'Content-Type': 'application/json', 'Authorization': `Bearer openai` } }); 64 | const value = await response.json() 65 | const duration = Date.now() - start 66 | 67 | expect(response.status).toBe(200); 68 | expect(response.headers.get('content-type')).toContain('application/json'); 69 | expect(response.headers.get('malacca-cache-status')).toBeNull(); 70 | 71 | start = Date.now(); 72 | response = await SELF.fetch(url, { method: 'POST', body: body, headers: { 'Content-Type': 'application/json', 'Authorization': `Bearer openai` } }); 73 | const cacheValue = await response.json() 74 | const cacheDuration = Date.now() - start 75 | 76 | expect(response.status).toBe(200); 77 | expect(response.headers.get('malacca-cache-status')).toBe('hit'); 78 | expect(response.headers.get('content-type')).toBe('application/json'); 79 | expect(value).toEqual(cacheValue) 80 | expect(duration / 2).toBeGreaterThan(cacheDuration) 81 | }); 82 | 83 | it('Test stream with cache', async () => { 84 | const body = createRequestBody(true, 'Malacca'); 85 | let start = Date.now(); 86 | let response = await SELF.fetch(url, { method: 'POST', body: body, headers: { 'Content-Type': 'application/json', 'Authorization': `Bearer openai` } }); 87 | const value = await response.text() 88 | const duration = Date.now() - start 89 | 90 | expect(response.status).toBe(200); 91 | expect(response.headers.get('content-type')).toContain('text/event-stream'); 92 | expect(response.headers.get('malacca-cache-status')).toBeNull(); 93 | 94 | start = Date.now(); 95 | response = await SELF.fetch(url, { method: 'POST', body: body, headers: { 'Content-Type': 'application/json', 'Authorization': `Bearer openai` } }); 96 | const cacheValue = await response.text() 97 | const cacheDuration = Date.now() - start 98 | 99 | expect(response.status).toBe(200); 100 | expect(response.headers.get('malacca-cache-status')).toBe('hit'); 101 | expect(response.headers.get('content-type')).toContain('text/event-stream'); 102 | expect(value).toEqual(cacheValue) 103 | expect(duration / 2).toBeGreaterThan(cacheDuration) 104 | }); 105 | 106 | it('should not cache non-200 responses', async () => { 107 | const invalidBody = JSON.stringify({ 108 | messages: [{ role: "user", content: "This is an invalid request" }], 109 | stream: "invalid-model", 110 | temperature: 0.7, 111 | top_p: 0.95, 112 | max_tokens: 800, 113 | }); 114 | 115 | // First request - should return a non-200 response 116 | let response = await SELF.fetch(url, { 117 | method: 'POST', 118 | body: invalidBody, 119 | headers: { 'Content-Type': 'application/json', 'Authorization': `Bearer openai` } 120 | }); 121 | 122 | expect(response.status).not.toBe(200); 123 | expect(response.headers.get('malacca-cache-status')).toBeNull(); 124 | 125 | // Second request with the same invalid body 126 | response = await SELF.fetch(url, { 127 | method: 'POST', 128 | body: invalidBody, 129 | headers: { 'Content-Type': 'application/json', 'Authorization': `Bearer openai` } 130 | }); 131 | 132 | expect(response.status).not.toBe(200); 133 | // Should still be a cache miss, as non-200 responses are not cached 134 | expect(response.headers.get('malacca-cache-status')).toBeNull(); 135 | }); 136 | }); -------------------------------------------------------------------------------- /test/tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": "../tsconfig.json", 3 | "compilerOptions": { 4 | "types": ["@cloudflare/workers-types/experimental", "@cloudflare/vitest-pool-workers"] 5 | }, 6 | "include": ["./**/*.ts", "../src/env.d.ts"], 7 | "exclude": [] 8 | } 9 | -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | /* Visit https://aka.ms/tsconfig.json to read more about this file */ 4 | 5 | /* Projects */ 6 | // "incremental": true, /* Enable incremental compilation */ 7 | // "composite": true, /* Enable constraints that allow a TypeScript project to be used with project references. */ 8 | // "tsBuildInfoFile": "./", /* Specify the folder for .tsbuildinfo incremental compilation files. */ 9 | // "disableSourceOfProjectReferenceRedirect": true, /* Disable preferring source files instead of declaration files when referencing composite projects */ 10 | // "disableSolutionSearching": true, /* Opt a project out of multi-project reference checking when editing. */ 11 | // "disableReferencedProjectLoad": true, /* Reduce the number of projects loaded automatically by TypeScript. */ 12 | 13 | /* Language and Environment */ 14 | "target": "es2021" /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */, 15 | "lib": ["es2021"] /* Specify a set of bundled library declaration files that describe the target runtime environment. */, 16 | "jsx": "react-jsx" /* Specify what JSX code is generated. */, 17 | // "experimentalDecorators": true, /* Enable experimental support for TC39 stage 2 draft decorators. */ 18 | // "emitDecoratorMetadata": true, /* Emit design-type metadata for decorated declarations in source files. */ 19 | // "jsxFactory": "", /* Specify the JSX factory function used when targeting React JSX emit, e.g. 'React.createElement' or 'h' */ 20 | // "jsxFragmentFactory": "", /* Specify the JSX Fragment reference used for fragments when targeting React JSX emit e.g. 'React.Fragment' or 'Fragment'. */ 21 | // "jsxImportSource": "", /* Specify module specifier used to import the JSX factory functions when using `jsx: react-jsx*`.` */ 22 | // "reactNamespace": "", /* Specify the object invoked for `createElement`. This only applies when targeting `react` JSX emit. */ 23 | // "noLib": true, /* Disable including any library files, including the default lib.d.ts. */ 24 | // "useDefineForClassFields": true, /* Emit ECMAScript-standard-compliant class fields. */ 25 | 26 | /* Modules */ 27 | "module": "es2022" /* Specify what module code is generated. */, 28 | // "rootDir": "./", /* Specify the root folder within your source files. */ 29 | "moduleResolution": "Bundler" /* Specify how TypeScript looks up a file from a given module specifier. */, 30 | // "baseUrl": "./", /* Specify the base directory to resolve non-relative module names. */ 31 | // "paths": {}, /* Specify a set of entries that re-map imports to additional lookup locations. */ 32 | // "rootDirs": [], /* Allow multiple folders to be treated as one when resolving modules. */ 33 | // "typeRoots": [], /* Specify multiple folders that act like `./node_modules/@types`. */ 34 | "types": [ 35 | "@cloudflare/workers-types/2023-07-01" 36 | ] /* Specify type package names to be included without being referenced in a source file. */, 37 | // "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */ 38 | "resolveJsonModule": true /* Enable importing .json files */, 39 | // "noResolve": true, /* Disallow `import`s, `require`s or ``s from expanding the number of files TypeScript should add to a project. */ 40 | 41 | /* JavaScript Support */ 42 | "allowJs": true /* Allow JavaScript files to be a part of your program. Use the `checkJS` option to get errors from these files. */, 43 | "checkJs": false /* Enable error reporting in type-checked JavaScript files. */, 44 | // "maxNodeModuleJsDepth": 1, /* Specify the maximum folder depth used for checking JavaScript files from `node_modules`. Only applicable with `allowJs`. */ 45 | 46 | /* Emit */ 47 | // "declaration": true, /* Generate .d.ts files from TypeScript and JavaScript files in your project. */ 48 | // "declarationMap": true, /* Create sourcemaps for d.ts files. */ 49 | // "emitDeclarationOnly": true, /* Only output d.ts files and not JavaScript files. */ 50 | // "sourceMap": true, /* Create source map files for emitted JavaScript files. */ 51 | // "outFile": "./", /* Specify a file that bundles all outputs into one JavaScript file. If `declaration` is true, also designates a file that bundles all .d.ts output. */ 52 | // "outDir": "./", /* Specify an output folder for all emitted files. */ 53 | // "removeComments": true, /* Disable emitting comments. */ 54 | "noEmit": true /* Disable emitting files from a compilation. */, 55 | // "importHelpers": true, /* Allow importing helper functions from tslib once per project, instead of including them per-file. */ 56 | // "importsNotUsedAsValues": "remove", /* Specify emit/checking behavior for imports that are only used for types */ 57 | // "downlevelIteration": true, /* Emit more compliant, but verbose and less performant JavaScript for iteration. */ 58 | // "sourceRoot": "", /* Specify the root path for debuggers to find the reference source code. */ 59 | // "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */ 60 | // "inlineSourceMap": true, /* Include sourcemap files inside the emitted JavaScript. */ 61 | // "inlineSources": true, /* Include source code in the sourcemaps inside the emitted JavaScript. */ 62 | // "emitBOM": true, /* Emit a UTF-8 Byte Order Mark (BOM) in the beginning of output files. */ 63 | // "newLine": "crlf", /* Set the newline character for emitting files. */ 64 | // "stripInternal": true, /* Disable emitting declarations that have `@internal` in their JSDoc comments. */ 65 | // "noEmitHelpers": true, /* Disable generating custom helper functions like `__extends` in compiled output. */ 66 | // "noEmitOnError": true, /* Disable emitting files if any type checking errors are reported. */ 67 | // "preserveConstEnums": true, /* Disable erasing `const enum` declarations in generated code. */ 68 | // "declarationDir": "./", /* Specify the output directory for generated declaration files. */ 69 | // "preserveValueImports": true, /* Preserve unused imported values in the JavaScript output that would otherwise be removed. */ 70 | 71 | /* Interop Constraints */ 72 | "isolatedModules": true /* Ensure that each file can be safely transpiled without relying on other imports. */, 73 | "allowSyntheticDefaultImports": true /* Allow 'import x from y' when a module doesn't have a default export. */, 74 | // "esModuleInterop": true /* Emit additional JavaScript to ease support for importing CommonJS modules. This enables `allowSyntheticDefaultImports` for type compatibility. */, 75 | // "preserveSymlinks": true, /* Disable resolving symlinks to their realpath. This correlates to the same flag in node. */ 76 | "forceConsistentCasingInFileNames": true /* Ensure that casing is correct in imports. */, 77 | 78 | /* Type Checking */ 79 | "strict": true /* Enable all strict type-checking options. */, 80 | // "noImplicitAny": true, /* Enable error reporting for expressions and declarations with an implied `any` type.. */ 81 | // "strictNullChecks": true, /* When type checking, take into account `null` and `undefined`. */ 82 | // "strictFunctionTypes": true, /* When assigning functions, check to ensure parameters and the return values are subtype-compatible. */ 83 | // "strictBindCallApply": true, /* Check that the arguments for `bind`, `call`, and `apply` methods match the original function. */ 84 | // "strictPropertyInitialization": true, /* Check for class properties that are declared but not set in the constructor. */ 85 | // "noImplicitThis": true, /* Enable error reporting when `this` is given the type `any`. */ 86 | // "useUnknownInCatchVariables": true, /* Type catch clause variables as 'unknown' instead of 'any'. */ 87 | // "alwaysStrict": true, /* Ensure 'use strict' is always emitted. */ 88 | // "noUnusedLocals": true, /* Enable error reporting when a local variables aren't read. */ 89 | // "noUnusedParameters": true, /* Raise an error when a function parameter isn't read */ 90 | // "exactOptionalPropertyTypes": true, /* Interpret optional property types as written, rather than adding 'undefined'. */ 91 | // "noImplicitReturns": true, /* Enable error reporting for codepaths that do not explicitly return in a function. */ 92 | // "noFallthroughCasesInSwitch": true, /* Enable error reporting for fallthrough cases in switch statements. */ 93 | // "noUncheckedIndexedAccess": true, /* Include 'undefined' in index signature results */ 94 | // "noImplicitOverride": true, /* Ensure overriding members in derived classes are marked with an override modifier. */ 95 | // "noPropertyAccessFromIndexSignature": true, /* Enforces using indexed accessors for keys declared using an indexed type */ 96 | // "allowUnusedLabels": true, /* Disable error reporting for unused labels. */ 97 | // "allowUnreachableCode": true, /* Disable error reporting for unreachable code. */ 98 | 99 | /* Completeness */ 100 | // "skipDefaultLibCheck": true, /* Skip type checking .d.ts files that are included with TypeScript. */ 101 | "skipLibCheck": true /* Skip type checking all .d.ts files. */ 102 | }, 103 | "exclude": ["test"], 104 | "include": ["worker-configuration.d.ts", "src/**/*.ts"] 105 | } 106 | -------------------------------------------------------------------------------- /vitest.config.mts: -------------------------------------------------------------------------------- 1 | import { defineWorkersConfig } from '@cloudflare/vitest-pool-workers/config'; 2 | 3 | export default defineWorkersConfig({ 4 | test: { 5 | testTimeout: 100000, 6 | poolOptions: { 7 | workers: { 8 | wrangler: { configPath: './wrangler.test.toml' }, 9 | }, 10 | }, 11 | }, 12 | }); 13 | -------------------------------------------------------------------------------- /worker-configuration.d.ts: -------------------------------------------------------------------------------- 1 | // Generated by Wrangler by running `wrangler types` 2 | 3 | interface Env { 4 | MALACCA_USER: KVNamespace; 5 | MALACCA_CACHE: KVNamespace; 6 | MALACCA: AnalyticsEngineDataset; 7 | MY_RATE_LIMITER: RateLimit; 8 | AI: Ai; 9 | } 10 | -------------------------------------------------------------------------------- /wrangler.test.toml: -------------------------------------------------------------------------------- 1 | #:schema node_modules/wrangler/config-schema.json 2 | name = "malacca" 3 | main = "src/index.ts" 4 | compatibility_date = "2024-09-02" 5 | compatibility_flags = ["nodejs_compat"] 6 | minify = true 7 | logpush = false 8 | 9 | # Bind an Analytics Engine dataset. Use Analytics Engine to write analytics within your Pages Function. 10 | # Docs: https://developers.cloudflare.com/workers/wrangler/configuration/#analytics-engine-datasets 11 | [[analytics_engine_datasets]] 12 | binding = "MALACCA" 13 | 14 | # Bind a KV Namespace. Use KV as persistent storage for small key-value pairs. 15 | # Docs: https://developers.cloudflare.com/workers/wrangler/configuration/#kv-namespaces 16 | [[kv_namespaces]] 17 | binding = "MALACCA_USER" 18 | id = "172f036565724816a51f04789deeecd0" 19 | 20 | [[kv_namespaces]] 21 | binding = "MALACCA_CACHE" 22 | id = "8ef9a507dca94b21b4f64e40952c0dfd" 23 | 24 | [observability] 25 | enabled = true 26 | 27 | [[unsafe.bindings]] 28 | name = "MY_RATE_LIMITER" 29 | type = "ratelimit" 30 | # An identifier you define, that is unique to your Cloudflare account. 31 | # Must be an integer. 32 | namespace_id = "1001" 33 | 34 | # Limit: the number of tokens allowed within a given period in a single 35 | # Cloudflare location 36 | # Period: the duration of the period, in seconds. Must be either 10 or 60 37 | simple = { limit = 100, period = 60 } -------------------------------------------------------------------------------- /wrangler.toml: -------------------------------------------------------------------------------- 1 | #:schema node_modules/wrangler/config-schema.json 2 | name = "malacca" 3 | main = "src/index.ts" 4 | compatibility_date = "2024-09-02" 5 | compatibility_flags = ["nodejs_compat"] 6 | minify = true 7 | logpush = false 8 | 9 | # Bind an Analytics Engine dataset. Use Analytics Engine to write analytics within your Pages Function. 10 | # Docs: https://developers.cloudflare.com/workers/wrangler/configuration/#analytics-engine-datasets 11 | [[analytics_engine_datasets]] 12 | binding = "MALACCA" 13 | 14 | # Bind a KV Namespace. Use KV as persistent storage for small key-value pairs. 15 | # Docs: https://developers.cloudflare.com/workers/wrangler/configuration/#kv-namespaces 16 | [[kv_namespaces]] 17 | binding = "MALACCA_USER" 18 | id = "172f036565724816a51f04789deeecd0" 19 | 20 | [[kv_namespaces]] 21 | binding = "MALACCA_CACHE" 22 | id = "8ef9a507dca94b21b4f64e40952c0dfd" 23 | 24 | [observability] 25 | enabled = true 26 | 27 | [[unsafe.bindings]] 28 | name = "MY_RATE_LIMITER" 29 | type = "ratelimit" 30 | # An identifier you define, that is unique to your Cloudflare account. 31 | # Must be an integer. 32 | namespace_id = "1001" 33 | 34 | # Limit: the number of tokens allowed within a given period in a single 35 | # Cloudflare location 36 | # Period: the duration of the period, in seconds. Must be either 10 or 60 37 | simple = { limit = 100, period = 60 } 38 | 39 | [ai] 40 | binding = "AI" --------------------------------------------------------------------------------