Compare commits
35 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 15f697aa6e | |||
| a59b6555e7 | |||
| 2d82e55d72 | |||
| 6352df5d5a | |||
| 7d517a4c5f | |||
| 0418951928 | |||
| 3012aa651e | |||
| 1b68ad7c6f | |||
| 68b48428de | |||
| b76db652e0 | |||
| 63ab1a7685 | |||
| a3462e21bc | |||
| 8d2ed23522 | |||
| 205ffa69ce | |||
| 930bac0072 | |||
| 3ad826851c | |||
| 6dabc82bcf | |||
| d3e7ef3c14 | |||
| b1062dc9b3 | |||
| 32b623d6bc | |||
| 0a27345c29 | |||
| c15f07c0d8 | |||
| db28e90c51 | |||
| c0cd2c7549 | |||
| 9445110727 | |||
| 34a673a80a | |||
| 8cb960e174 | |||
| 32fea30c91 | |||
| 3f9fd25004 | |||
| e068edcf48 | |||
| 2098948b7a | |||
| 7705ee58a0 | |||
| 7c64d9209e | |||
| 59107af3d6 | |||
| 435280fa04 |
+15
-2
@@ -40,12 +40,14 @@ NODE_ENV=production
|
|||||||
|
|
||||||
# Which model types users are allowed to access.
|
# Which model types users are allowed to access.
|
||||||
# The following model families are recognized:
|
# The following model families are recognized:
|
||||||
# turbo | gpt4 | gpt4-32k | gpt4-turbo | dall-e | claude | claude-opus | gemini-pro | mistral-tiny | mistral-small | mistral-medium | mistral-large | aws-claude | azure-turbo | azure-gpt4 | azure-gpt4-32k | azure-gpt4-turbo | azure-dall-e
|
# turbo | gpt4 | gpt4-32k | gpt4-turbo | gpt4o | dall-e | claude | claude-opus | gemini-pro | mistral-tiny | mistral-small | mistral-medium | mistral-large | aws-claude | aws-claude-opus | azure-turbo | azure-gpt4 | azure-gpt4-32k | azure-gpt4-turbo | azure-gpt4o | azure-dall-e
|
||||||
# By default, all models are allowed except for 'dall-e' / 'azure-dall-e'.
|
# By default, all models are allowed except for 'dall-e' / 'azure-dall-e'.
|
||||||
# To allow DALL-E image generation, uncomment the line below and add 'dall-e' or
|
# To allow DALL-E image generation, uncomment the line below and add 'dall-e' or
|
||||||
# 'azure-dall-e' to the list of allowed model families.
|
# 'azure-dall-e' to the list of allowed model families.
|
||||||
# ALLOWED_MODEL_FAMILIES=turbo,gpt4,gpt4-32k,gpt4-turbo,claude,claude-opus,gemini-pro,mistral-tiny,mistral-small,mistral-medium,mistral-large,aws-claude,azure-turbo,azure-gpt4,azure-gpt4-32k,azure-gpt4-turbo
|
# ALLOWED_MODEL_FAMILIES=turbo,gpt4,gpt4-32k,gpt4-turbo,gpt4o,claude,claude-opus,gemini-pro,mistral-tiny,mistral-small,mistral-medium,mistral-large,aws-claude,aws-claude-opus,azure-turbo,azure-gpt4,azure-gpt4-32k,azure-gpt4-turbo,azure-gpt4o
|
||||||
|
|
||||||
|
# IP addresses or CIDR blocks from which requests will be blocked.
|
||||||
|
# IP_BLACKLIST=10.0.0.1/24
|
||||||
# URLs from which requests will be blocked.
|
# URLs from which requests will be blocked.
|
||||||
# BLOCKED_ORIGINS=reddit.com,9gag.com
|
# BLOCKED_ORIGINS=reddit.com,9gag.com
|
||||||
# Message to show when requests are blocked.
|
# Message to show when requests are blocked.
|
||||||
@@ -74,6 +76,13 @@ NODE_ENV=production
|
|||||||
# Detail level of logging. (trace | debug | info | warn | error)
|
# Detail level of logging. (trace | debug | info | warn | error)
|
||||||
# LOG_LEVEL=info
|
# LOG_LEVEL=info
|
||||||
|
|
||||||
|
# Captcha verification settings. Refer to docs/pow-captcha.md for guidance.
|
||||||
|
# CAPTCHA_MODE=none
|
||||||
|
# POW_TOKEN_HOURS=24
|
||||||
|
# POW_TOKEN_MAX_IPS=2
|
||||||
|
# POW_DIFFICULTY_LEVEL=low
|
||||||
|
# POW_CHALLENGE_TIMEOUT=30
|
||||||
|
|
||||||
# ------------------------------------------------------------------------------
|
# ------------------------------------------------------------------------------
|
||||||
# Optional settings for user management, access control, and quota enforcement:
|
# Optional settings for user management, access control, and quota enforcement:
|
||||||
# See `docs/user-management.md` for more information and setup instructions.
|
# See `docs/user-management.md` for more information and setup instructions.
|
||||||
@@ -136,6 +145,10 @@ AZURE_CREDENTIALS=azure-resource-name:deployment-id:api-key,another-azure-resour
|
|||||||
|
|
||||||
# With user_token gatekeeper, the admin password used to manage users.
|
# With user_token gatekeeper, the admin password used to manage users.
|
||||||
# ADMIN_KEY=your-very-secret-key
|
# ADMIN_KEY=your-very-secret-key
|
||||||
|
# To restrict access to the admin interface to specific IP addresses, set the
|
||||||
|
# ADMIN_WHITELIST environment variable to a comma-separated list of CIDR blocks.
|
||||||
|
# ADMIN_WHITELIST=0.0.0.0/0
|
||||||
|
|
||||||
|
|
||||||
# With firebase_rtdb gatekeeper storage, the Firebase project credentials.
|
# With firebase_rtdb gatekeeper storage, the Firebase project credentials.
|
||||||
# FIREBASE_KEY=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
|
# FIREBASE_KEY=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
|
||||||
|
|||||||
+3
-4
@@ -1,11 +1,10 @@
|
|||||||
{
|
{
|
||||||
|
"plugins": ["prettier-plugin-ejs"],
|
||||||
"overrides": [
|
"overrides": [
|
||||||
{
|
{
|
||||||
"files": [
|
"files": "*.ejs",
|
||||||
"*.ejs"
|
|
||||||
],
|
|
||||||
"options": {
|
"options": {
|
||||||
"printWidth": 160,
|
"printWidth": 120,
|
||||||
"bracketSameLine": true
|
"bracketSameLine": true
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,135 @@
|
|||||||
|
# Proof-of-work Verification
|
||||||
|
|
||||||
|
You can require users to complete a proof-of-work before they can access the
|
||||||
|
proxy. This can increase the cost of denial of service attacks and slow down
|
||||||
|
automated abuse.
|
||||||
|
|
||||||
|
When configured, users access the challenge UI and request a token. The server
|
||||||
|
sends a challenge to the client, which asks the user's browser to find a
|
||||||
|
solution to the challenge that meets a certain constraint (the difficulty
|
||||||
|
level). Once the user has found a solution, they can submit it to the server
|
||||||
|
and get a user token valid for a period you specify.
|
||||||
|
|
||||||
|
The proof-of-work challenge uses the argon2id hash function.
|
||||||
|
|
||||||
|
## Configuration
|
||||||
|
|
||||||
|
To enable proof-of-work verification, set the following environment variables:
|
||||||
|
|
||||||
|
```
|
||||||
|
GATEKEEPER=user_token
|
||||||
|
CAPTCHA_MODE=proof_of_work
|
||||||
|
# Validity of the token in hours
|
||||||
|
POW_TOKEN_HOURS=24
|
||||||
|
# Max number of IPs that can use a user_token issued via proof-of-work
|
||||||
|
POW_TOKEN_MAX_IPS=2
|
||||||
|
# The difficulty level of the proof-of-work challenge. You can use one of the
|
||||||
|
# predefined levels specified below, or you can specify a custom number of
|
||||||
|
# expected hash iterations.
|
||||||
|
POW_DIFFICULTY_LEVEL=low
|
||||||
|
# The time limit for solving the challenge, in minutes
|
||||||
|
POW_CHALLENGE_TIMEOUT=30
|
||||||
|
```
|
||||||
|
|
||||||
|
## Difficulty Levels
|
||||||
|
|
||||||
|
The difficulty level controls how long, on average, it will take for a user to
|
||||||
|
solve the proof-of-work challenge. Due to randomness, the actual time can very
|
||||||
|
significantly; lucky users may solve the challenge in a fraction of the average
|
||||||
|
time, while unlucky users may take much longer.
|
||||||
|
|
||||||
|
The difficulty level doesn't affect the speed of the hash function itself, only
|
||||||
|
the number of hashes that will need to be computed. Therefore, the time required
|
||||||
|
to complete the challenge scales linearly with the difficulty level's iteration
|
||||||
|
count.
|
||||||
|
|
||||||
|
You can adjust the difficulty level while the proxy is running from the admin
|
||||||
|
interface.
|
||||||
|
|
||||||
|
Be aware that there is a time limit for solving the challenge, by default set to
|
||||||
|
30 minutes. Above 'high' difficulty, you will probably need to increase the time
|
||||||
|
limit or it will be very hard for users with slow devices to find a solution
|
||||||
|
within the time limit.
|
||||||
|
|
||||||
|
### Low
|
||||||
|
|
||||||
|
- Average of 200 iterations required
|
||||||
|
- Default setting.
|
||||||
|
|
||||||
|
### Medium
|
||||||
|
|
||||||
|
- Average of 900 iterations required
|
||||||
|
|
||||||
|
### High
|
||||||
|
|
||||||
|
- Average of 1900 iterations required
|
||||||
|
|
||||||
|
### Extreme
|
||||||
|
|
||||||
|
- Average of 4000 iterations required
|
||||||
|
- Not recommended unless you are expecting very high levels of abuse
|
||||||
|
- May require increasing `POW_CHALLENGE_TIMEOUT`
|
||||||
|
|
||||||
|
### Custom
|
||||||
|
|
||||||
|
Setting `POW_DIFFICULTY_LEVEL` to an integer will use that number of iterations
|
||||||
|
as the difficulty level.
|
||||||
|
|
||||||
|
## Other challenge settings
|
||||||
|
|
||||||
|
- `POW_CHALLENGE_TIMEOUT`: The time limit for solving the challenge, in minutes.
|
||||||
|
Default is 30.
|
||||||
|
- `POW_TOKEN_HOURS`: The period of time for which a user token issued via proof-
|
||||||
|
of-work can be used. Default is 24 hours. Starts when the challenge is solved.
|
||||||
|
- `POW_TOKEN_MAX_IPS`: The maximum number of unique IPs that can use a single
|
||||||
|
user token issued via proof-of-work. Default is 2.
|
||||||
|
- `POW_TOKEN_PURGE_HOURS`: The period of time after which an expired user token
|
||||||
|
issued via proof-of-work will be removed from the database. Until it is
|
||||||
|
purged, users can refresh expired tokens by completing a half-difficulty
|
||||||
|
challenge. Default is 48 hours.
|
||||||
|
- `POW_MAX_TOKENS_PER_IP`: The maximum number of active user tokens that can
|
||||||
|
be associated with a single IP address. After this limit is reached, the
|
||||||
|
oldest token will be forcibly expired when a new token is issued. Set to 0
|
||||||
|
to disable this feature. Default is 0.
|
||||||
|
|
||||||
|
## Custom argon2id parameters
|
||||||
|
|
||||||
|
You can set custom argon2id parameters for the proof-of-work challenge.
|
||||||
|
Generally, you should not need to change these unless you have a specific
|
||||||
|
reason to do so.
|
||||||
|
|
||||||
|
The listed values are the defaults.
|
||||||
|
|
||||||
|
```
|
||||||
|
ARGON2_TIME_COST=8
|
||||||
|
ARGON2_MEMORY_KB=65536
|
||||||
|
ARGON2_PARALLELISM=1
|
||||||
|
ARGON2_HASH_LENGTH=32
|
||||||
|
```
|
||||||
|
|
||||||
|
Increasing parallelism will not do much except increase memory consumption for
|
||||||
|
both the client and server, because browser proof-of-work implementations are
|
||||||
|
single-threaded. It's better to increase the time cost if you want to increase
|
||||||
|
the difficulty.
|
||||||
|
|
||||||
|
Increasing memory too much may cause memory exhaustion on some mobile devices,
|
||||||
|
particularly on iOS due to the way Safari handles WebAssembly memory allocation.
|
||||||
|
|
||||||
|
## Tested hash rates
|
||||||
|
|
||||||
|
These were measured with the default argon2id parameters listed above. These
|
||||||
|
tests were not at all scientific so take them with a grain of salt.
|
||||||
|
|
||||||
|
Safari does not like large WASM memory usage, so concurrency is limited to 4 to
|
||||||
|
avoid overallocating memory on mobile WebKit browsers. Thermal throttling can
|
||||||
|
also significantly reduce hash rates on mobile devices.
|
||||||
|
|
||||||
|
- Intel Core i9-13900K (Chrome): 33-35 H/s
|
||||||
|
- Intel Core i9-13900K (Firefox): 29-32 H/s
|
||||||
|
- Intel Core i9-13900K (Chrome, in VM limited to 4 cores): 12.2 - 13.0 H/s
|
||||||
|
- iPad Pro (M2) (Safari, 6 workers): 8.0 - 10 H/s
|
||||||
|
- Thermal throttles early. 8 cores is normal concurrency, but unstable.
|
||||||
|
- iPhone 13 Pro (Safari): 4.0 - 4.6 H/s
|
||||||
|
- Samsung Galaxy S10e (Chrome): 3.6 - 3.8 H/s
|
||||||
|
- This is a 2019 phone almost matching an iPhone five years newer because of
|
||||||
|
bad Safari performance.
|
||||||
@@ -12,6 +12,7 @@ Several of these features require you to set secrets in your environment. If usi
|
|||||||
- [Memory](#memory)
|
- [Memory](#memory)
|
||||||
- [Firebase Realtime Database](#firebase-realtime-database)
|
- [Firebase Realtime Database](#firebase-realtime-database)
|
||||||
- [Firebase setup instructions](#firebase-setup-instructions)
|
- [Firebase setup instructions](#firebase-setup-instructions)
|
||||||
|
- [Whitelisting admin IP addresses](#whitelisting-admin-ip-addresses)
|
||||||
|
|
||||||
## No user management (`GATEKEEPER=none`)
|
## No user management (`GATEKEEPER=none`)
|
||||||
|
|
||||||
@@ -61,3 +62,12 @@ To use Firebase Realtime Database to persist user data, set the following enviro
|
|||||||
8. Set `GATEKEEPER_STORE` to `firebase_rtdb` in your environment if you haven't already.
|
8. Set `GATEKEEPER_STORE` to `firebase_rtdb` in your environment if you haven't already.
|
||||||
|
|
||||||
The proxy server will attempt to connect to your Firebase Realtime Database at startup and will throw an error if it cannot connect. If you see this error, check that your `FIREBASE_RTDB_URL` and `FIREBASE_KEY` secrets are set correctly.
|
The proxy server will attempt to connect to your Firebase Realtime Database at startup and will throw an error if it cannot connect. If you see this error, check that your `FIREBASE_RTDB_URL` and `FIREBASE_KEY` secrets are set correctly.
|
||||||
|
|
||||||
|
## Whitelisting admin IP addresses
|
||||||
|
You can add your own IP ranges to the `ADMIN_WHITELIST` environment variable for additional security.
|
||||||
|
|
||||||
|
You can provide a comma-separated list containing individual IPv4 or IPv6 addresses, or CIDR ranges.
|
||||||
|
|
||||||
|
To whitelist an entire IP range, use CIDR notation. For example, `192.168.0.1/24` would whitelist all addresses from `192.168.0.0` to `192.168.0.255`.
|
||||||
|
|
||||||
|
To disable the whitelist, set `ADMIN_WHITELIST=0.0.0.0/0`, which will allow access from any IP address. This is the default behavior.
|
||||||
|
|||||||
Generated
+1156
-711
File diff suppressed because it is too large
Load Diff
+9
-3
@@ -4,6 +4,7 @@
|
|||||||
"description": "Reverse proxy for the OpenAI API",
|
"description": "Reverse proxy for the OpenAI API",
|
||||||
"scripts": {
|
"scripts": {
|
||||||
"build": "tsc && copyfiles -u 1 src/**/*.ejs build",
|
"build": "tsc && copyfiles -u 1 src/**/*.ejs build",
|
||||||
|
"database:migrate": "ts-node scripts/migrate.ts",
|
||||||
"prepare": "husky install",
|
"prepare": "husky install",
|
||||||
"start": "node build/server.js",
|
"start": "node build/server.js",
|
||||||
"start:dev": "nodemon --watch src --exec ts-node --transpile-only src/server.ts",
|
"start:dev": "nodemon --watch src --exec ts-node --transpile-only src/server.ts",
|
||||||
@@ -19,6 +20,7 @@
|
|||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@anthropic-ai/tokenizer": "^0.0.4",
|
"@anthropic-ai/tokenizer": "^0.0.4",
|
||||||
"@aws-crypto/sha256-js": "^5.2.0",
|
"@aws-crypto/sha256-js": "^5.2.0",
|
||||||
|
"@node-rs/argon2": "^1.8.3",
|
||||||
"@smithy/eventstream-codec": "^2.1.3",
|
"@smithy/eventstream-codec": "^2.1.3",
|
||||||
"@smithy/eventstream-serde-node": "^2.1.3",
|
"@smithy/eventstream-serde-node": "^2.1.3",
|
||||||
"@smithy/protocol-http": "^3.2.1",
|
"@smithy/protocol-http": "^3.2.1",
|
||||||
@@ -26,18 +28,21 @@
|
|||||||
"@smithy/types": "^2.10.1",
|
"@smithy/types": "^2.10.1",
|
||||||
"@smithy/util-utf8": "^2.1.1",
|
"@smithy/util-utf8": "^2.1.1",
|
||||||
"axios": "^1.3.5",
|
"axios": "^1.3.5",
|
||||||
|
"better-sqlite3": "^10.0.0",
|
||||||
"check-disk-space": "^3.4.0",
|
"check-disk-space": "^3.4.0",
|
||||||
"cookie-parser": "^1.4.6",
|
"cookie-parser": "^1.4.6",
|
||||||
"copyfiles": "^2.4.1",
|
"copyfiles": "^2.4.1",
|
||||||
"cors": "^2.8.5",
|
"cors": "^2.8.5",
|
||||||
"csrf-csrf": "^2.3.0",
|
"csrf-csrf": "^2.3.0",
|
||||||
"dotenv": "^16.3.1",
|
"dotenv": "^16.3.1",
|
||||||
"ejs": "^3.1.9",
|
"ejs": "^3.1.10",
|
||||||
"express": "^4.18.2",
|
"express": "^4.18.2",
|
||||||
"express-session": "^1.17.3",
|
"express-session": "^1.17.3",
|
||||||
"firebase-admin": "^11.10.1",
|
"firebase-admin": "^12.1.0",
|
||||||
|
"glob": "^10.3.12",
|
||||||
"googleapis": "^122.0.0",
|
"googleapis": "^122.0.0",
|
||||||
"http-proxy-middleware": "^3.0.0-beta.1",
|
"http-proxy-middleware": "^3.0.0-beta.1",
|
||||||
|
"ipaddr.js": "^2.1.0",
|
||||||
"memorystore": "^1.6.7",
|
"memorystore": "^1.6.7",
|
||||||
"multer": "^1.4.5-lts.1",
|
"multer": "^1.4.5-lts.1",
|
||||||
"node-schedule": "^2.1.1",
|
"node-schedule": "^2.1.1",
|
||||||
@@ -55,6 +60,7 @@
|
|||||||
"zod-error": "^1.5.0"
|
"zod-error": "^1.5.0"
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
|
"@types/better-sqlite3": "^7.6.10",
|
||||||
"@types/cookie-parser": "^1.4.3",
|
"@types/cookie-parser": "^1.4.3",
|
||||||
"@types/cors": "^2.8.13",
|
"@types/cors": "^2.8.13",
|
||||||
"@types/express": "^4.17.17",
|
"@types/express": "^4.17.17",
|
||||||
@@ -72,11 +78,11 @@
|
|||||||
"nodemon": "^3.0.1",
|
"nodemon": "^3.0.1",
|
||||||
"pino-pretty": "^10.2.3",
|
"pino-pretty": "^10.2.3",
|
||||||
"prettier": "^3.0.3",
|
"prettier": "^3.0.3",
|
||||||
|
"prettier-plugin-ejs": "^1.0.3",
|
||||||
"ts-node": "^10.9.1",
|
"ts-node": "^10.9.1",
|
||||||
"typescript": "^5.4.2"
|
"typescript": "^5.4.2"
|
||||||
},
|
},
|
||||||
"overrides": {
|
"overrides": {
|
||||||
"google-gax": "^3.6.1",
|
|
||||||
"postcss": "^8.4.31",
|
"postcss": "^8.4.31",
|
||||||
"follow-redirects": "^1.15.4"
|
"follow-redirects": "^1.15.4"
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,349 @@
|
|||||||
|
/*! normalize.css v8.0.1 | MIT License | github.com/necolas/normalize.css */
|
||||||
|
|
||||||
|
/* Document
|
||||||
|
========================================================================== */
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 1. Correct the line height in all browsers.
|
||||||
|
* 2. Prevent adjustments of font size after orientation changes in iOS.
|
||||||
|
*/
|
||||||
|
|
||||||
|
html {
|
||||||
|
line-height: 1.15; /* 1 */
|
||||||
|
-webkit-text-size-adjust: 100%; /* 2 */
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Sections
|
||||||
|
========================================================================== */
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Remove the margin in all browsers.
|
||||||
|
*/
|
||||||
|
|
||||||
|
body {
|
||||||
|
margin: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Render the `main` element consistently in IE.
|
||||||
|
*/
|
||||||
|
|
||||||
|
main {
|
||||||
|
display: block;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Correct the font size and margin on `h1` elements within `section` and
|
||||||
|
* `article` contexts in Chrome, Firefox, and Safari.
|
||||||
|
*/
|
||||||
|
|
||||||
|
h1 {
|
||||||
|
font-size: 2em;
|
||||||
|
margin: 0.67em 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Grouping content
|
||||||
|
========================================================================== */
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 1. Add the correct box sizing in Firefox.
|
||||||
|
* 2. Show the overflow in Edge and IE.
|
||||||
|
*/
|
||||||
|
|
||||||
|
hr {
|
||||||
|
box-sizing: content-box; /* 1 */
|
||||||
|
height: 0; /* 1 */
|
||||||
|
overflow: visible; /* 2 */
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 1. Correct the inheritance and scaling of font size in all browsers.
|
||||||
|
* 2. Correct the odd `em` font sizing in all browsers.
|
||||||
|
*/
|
||||||
|
|
||||||
|
pre {
|
||||||
|
font-family: monospace, monospace; /* 1 */
|
||||||
|
font-size: 1em; /* 2 */
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Text-level semantics
|
||||||
|
========================================================================== */
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Remove the gray background on active links in IE 10.
|
||||||
|
*/
|
||||||
|
|
||||||
|
a {
|
||||||
|
background-color: transparent;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 1. Remove the bottom border in Chrome 57-
|
||||||
|
* 2. Add the correct text decoration in Chrome, Edge, IE, Opera, and Safari.
|
||||||
|
*/
|
||||||
|
|
||||||
|
abbr[title] {
|
||||||
|
border-bottom: none; /* 1 */
|
||||||
|
text-decoration: underline; /* 2 */
|
||||||
|
text-decoration: underline dotted; /* 2 */
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Add the correct font weight in Chrome, Edge, and Safari.
|
||||||
|
*/
|
||||||
|
|
||||||
|
b,
|
||||||
|
strong {
|
||||||
|
font-weight: bolder;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 1. Correct the inheritance and scaling of font size in all browsers.
|
||||||
|
* 2. Correct the odd `em` font sizing in all browsers.
|
||||||
|
*/
|
||||||
|
|
||||||
|
code,
|
||||||
|
kbd,
|
||||||
|
samp {
|
||||||
|
font-family: monospace, monospace; /* 1 */
|
||||||
|
font-size: 1em; /* 2 */
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Add the correct font size in all browsers.
|
||||||
|
*/
|
||||||
|
|
||||||
|
small {
|
||||||
|
font-size: 80%;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Prevent `sub` and `sup` elements from affecting the line height in
|
||||||
|
* all browsers.
|
||||||
|
*/
|
||||||
|
|
||||||
|
sub,
|
||||||
|
sup {
|
||||||
|
font-size: 75%;
|
||||||
|
line-height: 0;
|
||||||
|
position: relative;
|
||||||
|
vertical-align: baseline;
|
||||||
|
}
|
||||||
|
|
||||||
|
sub {
|
||||||
|
bottom: -0.25em;
|
||||||
|
}
|
||||||
|
|
||||||
|
sup {
|
||||||
|
top: -0.5em;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Embedded content
|
||||||
|
========================================================================== */
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Remove the border on images inside links in IE 10.
|
||||||
|
*/
|
||||||
|
|
||||||
|
img {
|
||||||
|
border-style: none;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Forms
|
||||||
|
========================================================================== */
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 1. Change the font styles in all browsers.
|
||||||
|
* 2. Remove the margin in Firefox and Safari.
|
||||||
|
*/
|
||||||
|
|
||||||
|
button,
|
||||||
|
input,
|
||||||
|
optgroup,
|
||||||
|
select,
|
||||||
|
textarea {
|
||||||
|
font-family: inherit; /* 1 */
|
||||||
|
font-size: 100%; /* 1 */
|
||||||
|
line-height: 1.15; /* 1 */
|
||||||
|
margin: 0; /* 2 */
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Show the overflow in IE.
|
||||||
|
* 1. Show the overflow in Edge.
|
||||||
|
*/
|
||||||
|
|
||||||
|
button,
|
||||||
|
input { /* 1 */
|
||||||
|
overflow: visible;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Remove the inheritance of text transform in Edge, Firefox, and IE.
|
||||||
|
* 1. Remove the inheritance of text transform in Firefox.
|
||||||
|
*/
|
||||||
|
|
||||||
|
button,
|
||||||
|
select { /* 1 */
|
||||||
|
text-transform: none;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Correct the inability to style clickable types in iOS and Safari.
|
||||||
|
*/
|
||||||
|
|
||||||
|
button,
|
||||||
|
[type="button"],
|
||||||
|
[type="reset"],
|
||||||
|
[type="submit"] {
|
||||||
|
-webkit-appearance: button;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Remove the inner border and padding in Firefox.
|
||||||
|
*/
|
||||||
|
|
||||||
|
button::-moz-focus-inner,
|
||||||
|
[type="button"]::-moz-focus-inner,
|
||||||
|
[type="reset"]::-moz-focus-inner,
|
||||||
|
[type="submit"]::-moz-focus-inner {
|
||||||
|
border-style: none;
|
||||||
|
padding: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Restore the focus styles unset by the previous rule.
|
||||||
|
*/
|
||||||
|
|
||||||
|
button:-moz-focusring,
|
||||||
|
[type="button"]:-moz-focusring,
|
||||||
|
[type="reset"]:-moz-focusring,
|
||||||
|
[type="submit"]:-moz-focusring {
|
||||||
|
outline: 1px dotted ButtonText;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Correct the padding in Firefox.
|
||||||
|
*/
|
||||||
|
|
||||||
|
fieldset {
|
||||||
|
padding: 0.35em 0.75em 0.625em;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 1. Correct the text wrapping in Edge and IE.
|
||||||
|
* 2. Correct the color inheritance from `fieldset` elements in IE.
|
||||||
|
* 3. Remove the padding so developers are not caught out when they zero out
|
||||||
|
* `fieldset` elements in all browsers.
|
||||||
|
*/
|
||||||
|
|
||||||
|
legend {
|
||||||
|
box-sizing: border-box; /* 1 */
|
||||||
|
color: inherit; /* 2 */
|
||||||
|
display: table; /* 1 */
|
||||||
|
max-width: 100%; /* 1 */
|
||||||
|
padding: 0; /* 3 */
|
||||||
|
white-space: normal; /* 1 */
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Add the correct vertical alignment in Chrome, Firefox, and Opera.
|
||||||
|
*/
|
||||||
|
|
||||||
|
progress {
|
||||||
|
vertical-align: baseline;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Remove the default vertical scrollbar in IE 10+.
|
||||||
|
*/
|
||||||
|
|
||||||
|
textarea {
|
||||||
|
overflow: auto;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 1. Add the correct box sizing in IE 10.
|
||||||
|
* 2. Remove the padding in IE 10.
|
||||||
|
*/
|
||||||
|
|
||||||
|
[type="checkbox"],
|
||||||
|
[type="radio"] {
|
||||||
|
box-sizing: border-box; /* 1 */
|
||||||
|
padding: 0; /* 2 */
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Correct the cursor style of increment and decrement buttons in Chrome.
|
||||||
|
*/
|
||||||
|
|
||||||
|
[type="number"]::-webkit-inner-spin-button,
|
||||||
|
[type="number"]::-webkit-outer-spin-button {
|
||||||
|
height: auto;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 1. Correct the odd appearance in Chrome and Safari.
|
||||||
|
* 2. Correct the outline style in Safari.
|
||||||
|
*/
|
||||||
|
|
||||||
|
[type="search"] {
|
||||||
|
-webkit-appearance: textfield; /* 1 */
|
||||||
|
outline-offset: -2px; /* 2 */
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Remove the inner padding in Chrome and Safari on macOS.
|
||||||
|
*/
|
||||||
|
|
||||||
|
[type="search"]::-webkit-search-decoration {
|
||||||
|
-webkit-appearance: none;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 1. Correct the inability to style clickable types in iOS and Safari.
|
||||||
|
* 2. Change font properties to `inherit` in Safari.
|
||||||
|
*/
|
||||||
|
|
||||||
|
::-webkit-file-upload-button {
|
||||||
|
-webkit-appearance: button; /* 1 */
|
||||||
|
font: inherit; /* 2 */
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Interactive
|
||||||
|
========================================================================== */
|
||||||
|
|
||||||
|
/*
|
||||||
|
* Add the correct display in Edge, IE 10+, and Firefox.
|
||||||
|
*/
|
||||||
|
|
||||||
|
details {
|
||||||
|
display: block;
|
||||||
|
}
|
||||||
|
|
||||||
|
/*
|
||||||
|
* Add the correct display in all browsers.
|
||||||
|
*/
|
||||||
|
|
||||||
|
summary {
|
||||||
|
display: list-item;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Misc
|
||||||
|
========================================================================== */
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Add the correct display in IE 10+.
|
||||||
|
*/
|
||||||
|
|
||||||
|
template {
|
||||||
|
display: none;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Add the correct display in IE 10.
|
||||||
|
*/
|
||||||
|
|
||||||
|
[hidden] {
|
||||||
|
display: none;
|
||||||
|
}
|
||||||
@@ -0,0 +1,231 @@
|
|||||||
|
/* modified https://github.com/oxalorg/sakura */
|
||||||
|
html {
|
||||||
|
font-size: 62.5%;
|
||||||
|
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto,
|
||||||
|
"Helvetica Neue", Arial, "Noto Sans", sans-serif;
|
||||||
|
}
|
||||||
|
body {
|
||||||
|
font-size: 1.8rem;
|
||||||
|
line-height: 1.618;
|
||||||
|
max-width: 38em;
|
||||||
|
margin: auto;
|
||||||
|
color: #c9c9c9;
|
||||||
|
background-color: #222222;
|
||||||
|
padding: 13px;
|
||||||
|
}
|
||||||
|
@media (max-width: 684px) {
|
||||||
|
body {
|
||||||
|
font-size: 1.53rem;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
@media (max-width: 382px) {
|
||||||
|
body {
|
||||||
|
font-size: 1.35rem;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
h1,
|
||||||
|
h2,
|
||||||
|
h3,
|
||||||
|
h4,
|
||||||
|
h5,
|
||||||
|
h6 {
|
||||||
|
line-height: 1.1;
|
||||||
|
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto,
|
||||||
|
"Helvetica Neue", Arial, "Noto Sans", sans-serif;
|
||||||
|
font-weight: 700;
|
||||||
|
margin-top: 3rem;
|
||||||
|
margin-bottom: 1.5rem;
|
||||||
|
overflow-wrap: break-word;
|
||||||
|
word-wrap: break-word;
|
||||||
|
-ms-word-break: break-all;
|
||||||
|
word-break: break-word;
|
||||||
|
}
|
||||||
|
h1 {
|
||||||
|
font-size: 2.35em;
|
||||||
|
}
|
||||||
|
h2 {
|
||||||
|
font-size: 2em;
|
||||||
|
}
|
||||||
|
h3 {
|
||||||
|
font-size: 1.75em;
|
||||||
|
}
|
||||||
|
h4 {
|
||||||
|
font-size: 1.5em;
|
||||||
|
}
|
||||||
|
h5 {
|
||||||
|
font-size: 1.25em;
|
||||||
|
}
|
||||||
|
h6 {
|
||||||
|
font-size: 1em;
|
||||||
|
}
|
||||||
|
p {
|
||||||
|
margin-top: 0px;
|
||||||
|
margin-bottom: 2.5rem;
|
||||||
|
}
|
||||||
|
small,
|
||||||
|
sub,
|
||||||
|
sup {
|
||||||
|
font-size: 75%;
|
||||||
|
}
|
||||||
|
hr {
|
||||||
|
border-color: #ffffff;
|
||||||
|
}
|
||||||
|
a {
|
||||||
|
text-decoration: none;
|
||||||
|
color: #ffffff;
|
||||||
|
}
|
||||||
|
a:visited {
|
||||||
|
color: #e6e6e6;
|
||||||
|
}
|
||||||
|
a:hover {
|
||||||
|
color: #c9c9c9;
|
||||||
|
text-decoration: underline;
|
||||||
|
}
|
||||||
|
ul {
|
||||||
|
padding-left: 1.4em;
|
||||||
|
margin-top: 0px;
|
||||||
|
margin-bottom: 2.5rem;
|
||||||
|
}
|
||||||
|
li {
|
||||||
|
margin-bottom: 0.4em;
|
||||||
|
}
|
||||||
|
blockquote {
|
||||||
|
margin-left: 0px;
|
||||||
|
margin-right: 0px;
|
||||||
|
padding-left: 1em;
|
||||||
|
padding-top: 0.8em;
|
||||||
|
padding-bottom: 0.8em;
|
||||||
|
padding-right: 0.8em;
|
||||||
|
border-left: 5px solid #ffffff;
|
||||||
|
margin-bottom: 2.5rem;
|
||||||
|
background-color: #4a4a4a;
|
||||||
|
}
|
||||||
|
blockquote p {
|
||||||
|
margin-bottom: 0;
|
||||||
|
}
|
||||||
|
img,
|
||||||
|
video {
|
||||||
|
height: auto;
|
||||||
|
max-width: 100%;
|
||||||
|
margin-top: 0px;
|
||||||
|
margin-bottom: 2.5rem;
|
||||||
|
}
|
||||||
|
pre {
|
||||||
|
background-color: #4a4a4a;
|
||||||
|
display: block;
|
||||||
|
padding: 1em;
|
||||||
|
overflow-x: auto;
|
||||||
|
margin-top: 0px;
|
||||||
|
margin-bottom: 2.5rem;
|
||||||
|
font-size: 0.9em;
|
||||||
|
}
|
||||||
|
code,
|
||||||
|
kbd,
|
||||||
|
samp {
|
||||||
|
font-size: 0.9em;
|
||||||
|
padding: 0 0.5em;
|
||||||
|
background-color: #4a4a4a;
|
||||||
|
white-space: pre-wrap;
|
||||||
|
}
|
||||||
|
pre > code {
|
||||||
|
padding: 0;
|
||||||
|
background-color: transparent;
|
||||||
|
white-space: pre;
|
||||||
|
font-size: 1em;
|
||||||
|
}
|
||||||
|
table {
|
||||||
|
text-align: justify;
|
||||||
|
width: 100%;
|
||||||
|
border-collapse: collapse;
|
||||||
|
margin-bottom: 2rem;
|
||||||
|
}
|
||||||
|
td,
|
||||||
|
th {
|
||||||
|
padding: 0.5em;
|
||||||
|
border-bottom: 1px solid #4a4a4a;
|
||||||
|
}
|
||||||
|
input,
|
||||||
|
textarea {
|
||||||
|
border: 1px solid #c9c9c9;
|
||||||
|
}
|
||||||
|
input:focus,
|
||||||
|
textarea:focus {
|
||||||
|
border: 1px solid #ffffff;
|
||||||
|
}
|
||||||
|
textarea {
|
||||||
|
width: 100%;
|
||||||
|
}
|
||||||
|
.button,
|
||||||
|
button,
|
||||||
|
input[type="submit"],
|
||||||
|
input[type="reset"],
|
||||||
|
input[type="button"],
|
||||||
|
input[type="file"]::file-selector-button {
|
||||||
|
display: inline-block;
|
||||||
|
padding: 5px 10px;
|
||||||
|
text-align: center;
|
||||||
|
text-decoration: none;
|
||||||
|
white-space: nowrap;
|
||||||
|
background-color: #ffffff;
|
||||||
|
color: #222222;
|
||||||
|
border-radius: 1px;
|
||||||
|
border: 1px solid #ffffff;
|
||||||
|
cursor: pointer;
|
||||||
|
box-sizing: border-box;
|
||||||
|
}
|
||||||
|
.button[disabled],
|
||||||
|
button[disabled],
|
||||||
|
input[type="submit"][disabled],
|
||||||
|
input[type="reset"][disabled],
|
||||||
|
input[type="button"][disabled],
|
||||||
|
input[type="file"][disabled] {
|
||||||
|
cursor: default;
|
||||||
|
opacity: 0.5;
|
||||||
|
}
|
||||||
|
.button:hover,
|
||||||
|
button:hover,
|
||||||
|
input[type="submit"]:hover,
|
||||||
|
input[type="reset"]:hover,
|
||||||
|
input[type="button"]:hover,
|
||||||
|
input[type="file"]::file-selector-button:hover {
|
||||||
|
background-color: #c9c9c9;
|
||||||
|
color: #222222;
|
||||||
|
outline: 0;
|
||||||
|
}
|
||||||
|
.button:focus-visible,
|
||||||
|
button:focus-visible,
|
||||||
|
input[type="submit"]:focus-visible,
|
||||||
|
input[type="reset"]:focus-visible,
|
||||||
|
input[type="button"]:focus-visible,
|
||||||
|
input[type="file"]::file-selector-button:focus-visible {
|
||||||
|
outline-style: solid;
|
||||||
|
outline-width: 2px;
|
||||||
|
}
|
||||||
|
textarea,
|
||||||
|
select,
|
||||||
|
input {
|
||||||
|
color: #c9c9c9;
|
||||||
|
padding: 6px 10px;
|
||||||
|
margin-bottom: 10px;
|
||||||
|
background-color: #4a4a4a;
|
||||||
|
border: 1px solid #4a4a4a;
|
||||||
|
border-radius: 4px;
|
||||||
|
box-shadow: none;
|
||||||
|
box-sizing: border-box;
|
||||||
|
}
|
||||||
|
textarea:focus,
|
||||||
|
select:focus,
|
||||||
|
input:focus {
|
||||||
|
border: 1px solid #ffffff;
|
||||||
|
outline: 0;
|
||||||
|
}
|
||||||
|
input[type="checkbox"]:focus {
|
||||||
|
outline: 1px dotted #ffffff;
|
||||||
|
}
|
||||||
|
label,
|
||||||
|
legend,
|
||||||
|
fieldset {
|
||||||
|
display: block;
|
||||||
|
margin-bottom: 0.5rem;
|
||||||
|
font-weight: 600;
|
||||||
|
}
|
||||||
@@ -0,0 +1,237 @@
|
|||||||
|
/* modified https://github.com/oxalorg/sakura */
|
||||||
|
:root {
|
||||||
|
--accent-color: #4a4a4a;
|
||||||
|
--accent-color-hover: #5a5a5a;
|
||||||
|
--link-color: #58739c;
|
||||||
|
--link-visted-color: #6f5e6f;
|
||||||
|
}
|
||||||
|
html {
|
||||||
|
font-size: 62.5%;
|
||||||
|
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto,
|
||||||
|
"Helvetica Neue", Arial, "Noto Sans", sans-serif;
|
||||||
|
}
|
||||||
|
body {
|
||||||
|
font-size: 1.8rem;
|
||||||
|
line-height: 1.618;
|
||||||
|
max-width: 38em;
|
||||||
|
margin: auto;
|
||||||
|
color: #4a4a4a;
|
||||||
|
background-color: #f9f9f9;
|
||||||
|
padding: 13px;
|
||||||
|
}
|
||||||
|
@media (max-width: 684px) {
|
||||||
|
body {
|
||||||
|
font-size: 1.53rem;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
@media (max-width: 382px) {
|
||||||
|
body {
|
||||||
|
font-size: 1.35rem;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
h1,
|
||||||
|
h2,
|
||||||
|
h3,
|
||||||
|
h4,
|
||||||
|
h5,
|
||||||
|
h6 {
|
||||||
|
line-height: 1.1;
|
||||||
|
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto,
|
||||||
|
"Helvetica Neue", Arial, "Noto Sans", sans-serif;
|
||||||
|
font-weight: 700;
|
||||||
|
margin-top: 3rem;
|
||||||
|
margin-bottom: 1.5rem;
|
||||||
|
overflow-wrap: break-word;
|
||||||
|
word-wrap: break-word;
|
||||||
|
-ms-word-break: break-all;
|
||||||
|
word-break: break-word;
|
||||||
|
}
|
||||||
|
h1 {
|
||||||
|
font-size: 2.35em;
|
||||||
|
}
|
||||||
|
h2 {
|
||||||
|
font-size: 2em;
|
||||||
|
}
|
||||||
|
h3 {
|
||||||
|
font-size: 1.75em;
|
||||||
|
}
|
||||||
|
h4 {
|
||||||
|
font-size: 1.5em;
|
||||||
|
}
|
||||||
|
h5 {
|
||||||
|
font-size: 1.25em;
|
||||||
|
}
|
||||||
|
h6 {
|
||||||
|
font-size: 1em;
|
||||||
|
}
|
||||||
|
p {
|
||||||
|
margin-top: 0;
|
||||||
|
margin-bottom: 2.5rem;
|
||||||
|
}
|
||||||
|
small,
|
||||||
|
sub,
|
||||||
|
sup {
|
||||||
|
font-size: 75%;
|
||||||
|
}
|
||||||
|
hr {
|
||||||
|
border-color: var(--accent-color);
|
||||||
|
}
|
||||||
|
a {
|
||||||
|
text-decoration: none;
|
||||||
|
color: var(--link-color);
|
||||||
|
}
|
||||||
|
a:visited {
|
||||||
|
color: var(--link-visted-color);
|
||||||
|
}
|
||||||
|
a:hover {
|
||||||
|
color: var(--accent-color-hover);
|
||||||
|
text-decoration: underline;
|
||||||
|
}
|
||||||
|
ul {
|
||||||
|
padding-left: 1.4em;
|
||||||
|
margin-top: 0;
|
||||||
|
margin-bottom: 2.5rem;
|
||||||
|
}
|
||||||
|
li {
|
||||||
|
margin-bottom: 0.4em;
|
||||||
|
}
|
||||||
|
blockquote {
|
||||||
|
margin-left: 0;
|
||||||
|
margin-right: 0;
|
||||||
|
padding-left: 1em;
|
||||||
|
padding-top: 0.8em;
|
||||||
|
padding-bottom: 0.8em;
|
||||||
|
padding-right: 0.8em;
|
||||||
|
border-left: 5px solid var(--accent-color);
|
||||||
|
margin-bottom: 2.5rem;
|
||||||
|
background-color: #f1f1f1;
|
||||||
|
}
|
||||||
|
blockquote p {
|
||||||
|
margin-bottom: 0;
|
||||||
|
}
|
||||||
|
img,
|
||||||
|
video {
|
||||||
|
height: auto;
|
||||||
|
max-width: 100%;
|
||||||
|
margin-top: 0;
|
||||||
|
margin-bottom: 2.5rem;
|
||||||
|
}
|
||||||
|
pre {
|
||||||
|
background-color: #f1f1f1;
|
||||||
|
display: block;
|
||||||
|
padding: 1em;
|
||||||
|
overflow-x: auto;
|
||||||
|
margin-top: 0;
|
||||||
|
margin-bottom: 2.5rem;
|
||||||
|
font-size: 0.9em;
|
||||||
|
}
|
||||||
|
code,
|
||||||
|
kbd,
|
||||||
|
samp {
|
||||||
|
font-size: 0.9em;
|
||||||
|
padding: 0 0.5em;
|
||||||
|
background-color: #f1f1f1;
|
||||||
|
white-space: pre-wrap;
|
||||||
|
}
|
||||||
|
pre > code {
|
||||||
|
padding: 0;
|
||||||
|
background-color: transparent;
|
||||||
|
white-space: pre;
|
||||||
|
font-size: 1em;
|
||||||
|
}
|
||||||
|
table {
|
||||||
|
text-align: justify;
|
||||||
|
width: 100%;
|
||||||
|
border-collapse: collapse;
|
||||||
|
margin-bottom: 2rem;
|
||||||
|
}
|
||||||
|
td,
|
||||||
|
th {
|
||||||
|
padding: 0.5em;
|
||||||
|
border-bottom: 1px solid #f1f1f1;
|
||||||
|
}
|
||||||
|
input,
|
||||||
|
textarea {
|
||||||
|
border: 1px solid #4a4a4a;
|
||||||
|
}
|
||||||
|
input:focus,
|
||||||
|
textarea:focus {
|
||||||
|
border: 1px solid var(--accent-color);
|
||||||
|
}
|
||||||
|
textarea {
|
||||||
|
width: 100%;
|
||||||
|
}
|
||||||
|
.button,
|
||||||
|
button,
|
||||||
|
input[type="submit"],
|
||||||
|
input[type="reset"],
|
||||||
|
input[type="button"],
|
||||||
|
input[type="file"]::file-selector-button {
|
||||||
|
display: inline-block;
|
||||||
|
padding: 5px 10px;
|
||||||
|
text-align: center;
|
||||||
|
text-decoration: none;
|
||||||
|
white-space: nowrap;
|
||||||
|
background-color: var(--accent-color);
|
||||||
|
color: #f9f9f9;
|
||||||
|
border-radius: 2px;
|
||||||
|
border: 1px solid var(--accent-color);
|
||||||
|
cursor: pointer;
|
||||||
|
box-sizing: border-box;
|
||||||
|
}
|
||||||
|
.button[disabled],
|
||||||
|
button[disabled],
|
||||||
|
input[type="submit"][disabled],
|
||||||
|
input[type="reset"][disabled],
|
||||||
|
input[type="button"][disabled],
|
||||||
|
input[type="file"][disabled] {
|
||||||
|
cursor: default;
|
||||||
|
opacity: 0.5;
|
||||||
|
}
|
||||||
|
.button:hover,
|
||||||
|
button:hover,
|
||||||
|
input[type="submit"]:hover,
|
||||||
|
input[type="reset"]:hover,
|
||||||
|
input[type="button"]:hover,
|
||||||
|
input[type="file"]::file-selector-button:hover {
|
||||||
|
background-color: var(--accent-color-hover);
|
||||||
|
color: #f9f9f9;
|
||||||
|
outline: 0;
|
||||||
|
}
|
||||||
|
.button:focus-visible,
|
||||||
|
button:focus-visible,
|
||||||
|
input[type="submit"]:focus-visible,
|
||||||
|
input[type="reset"]:focus-visible,
|
||||||
|
input[type="button"]:focus-visible,
|
||||||
|
input[type="file"]::file-selector-button:focus-visible {
|
||||||
|
outline-style: solid;
|
||||||
|
outline-width: 2px;
|
||||||
|
}
|
||||||
|
textarea,
|
||||||
|
select,
|
||||||
|
input {
|
||||||
|
color: #4a4a4a;
|
||||||
|
padding: 6px 10px;
|
||||||
|
margin-bottom: 10px;
|
||||||
|
background-color: #f1f1f1;
|
||||||
|
border: 1px solid #f1f1f1;
|
||||||
|
border-radius: 4px;
|
||||||
|
box-shadow: none;
|
||||||
|
box-sizing: border-box;
|
||||||
|
}
|
||||||
|
textarea:focus,
|
||||||
|
select:focus,
|
||||||
|
input:focus {
|
||||||
|
border: 1px solid var(--accent-color);
|
||||||
|
outline: 0;
|
||||||
|
}
|
||||||
|
input[type="checkbox"]:focus {
|
||||||
|
outline: 1px dotted var(--accent-color);
|
||||||
|
}
|
||||||
|
label,
|
||||||
|
legend,
|
||||||
|
fieldset {
|
||||||
|
display: block;
|
||||||
|
margin-bottom: 0.5rem;
|
||||||
|
font-weight: 600;
|
||||||
|
}
|
||||||
@@ -0,0 +1,121 @@
|
|||||||
|
importScripts(
|
||||||
|
"https://cdn.jsdelivr.net/npm/hash-wasm@4.11.0/dist/argon2.umd.min.js"
|
||||||
|
);
|
||||||
|
|
||||||
|
let active = false;
|
||||||
|
let nonce = 0;
|
||||||
|
let signature = "";
|
||||||
|
let lastNotify = 0;
|
||||||
|
let hashesSinceLastNotify = 0;
|
||||||
|
let params = {
|
||||||
|
salt: null,
|
||||||
|
hashLength: 0,
|
||||||
|
iterations: 0,
|
||||||
|
memorySize: 0,
|
||||||
|
parallelism: 0,
|
||||||
|
targetValue: BigInt(0),
|
||||||
|
safariFix: false,
|
||||||
|
};
|
||||||
|
|
||||||
|
self.onmessage = async (event) => {
|
||||||
|
const { data } = event;
|
||||||
|
switch (data.type) {
|
||||||
|
case "stop":
|
||||||
|
active = false;
|
||||||
|
self.postMessage({ type: "paused", hashes: hashesSinceLastNotify });
|
||||||
|
return;
|
||||||
|
case "start":
|
||||||
|
active = true;
|
||||||
|
signature = data.signature;
|
||||||
|
nonce = data.nonce;
|
||||||
|
|
||||||
|
const c = data.challenge;
|
||||||
|
// decode salt to Uint8Array
|
||||||
|
const salt = new Uint8Array(c.s.length / 2);
|
||||||
|
for (let i = 0; i < c.s.length; i += 2) {
|
||||||
|
salt[i / 2] = parseInt(c.s.slice(i, i + 2), 16);
|
||||||
|
}
|
||||||
|
|
||||||
|
params = {
|
||||||
|
salt: salt,
|
||||||
|
hashLength: c.hl,
|
||||||
|
iterations: c.t,
|
||||||
|
memorySize: c.m,
|
||||||
|
parallelism: c.p,
|
||||||
|
targetValue: BigInt(c.d.slice(0, -1)),
|
||||||
|
safariFix: data.isMobileWebkit,
|
||||||
|
};
|
||||||
|
|
||||||
|
console.log("Started", params);
|
||||||
|
self.postMessage({ type: "started" });
|
||||||
|
setTimeout(solve, 0);
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const doHash = async (password) => {
|
||||||
|
const { salt, hashLength, iterations, memorySize, parallelism } = params;
|
||||||
|
return await self.hashwasm.argon2id({
|
||||||
|
password,
|
||||||
|
salt,
|
||||||
|
hashLength,
|
||||||
|
iterations,
|
||||||
|
memorySize,
|
||||||
|
parallelism,
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
|
const checkHash = (hash) => {
|
||||||
|
const { targetValue } = params;
|
||||||
|
const hashValue = BigInt(`0x${hash}`);
|
||||||
|
return hashValue <= targetValue;
|
||||||
|
};
|
||||||
|
|
||||||
|
const solve = async () => {
|
||||||
|
if (!active) {
|
||||||
|
console.log("Stopped solver", nonce);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Safari WASM doesn't like multiple calls in one worker
|
||||||
|
const batchSize = 1;
|
||||||
|
const batch = [];
|
||||||
|
for (let i = 0; i < batchSize; i++) {
|
||||||
|
batch.push(nonce++);
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
const results = await Promise.all(
|
||||||
|
batch.map(async (nonce) => {
|
||||||
|
const hash = await doHash(String(nonce));
|
||||||
|
return { hash, nonce };
|
||||||
|
})
|
||||||
|
);
|
||||||
|
hashesSinceLastNotify += batchSize;
|
||||||
|
|
||||||
|
const solution = results.find(({ hash }) => checkHash(hash));
|
||||||
|
if (solution) {
|
||||||
|
console.log("Solution found", solution, params.salt);
|
||||||
|
self.postMessage({ type: "solved", nonce: solution.nonce });
|
||||||
|
active = false;
|
||||||
|
} else {
|
||||||
|
if (Date.now() - lastNotify > 1000) {
|
||||||
|
console.log("Last nonce", nonce, "Hashes", hashesSinceLastNotify);
|
||||||
|
self.postMessage({ type: "progress", hashes: hashesSinceLastNotify });
|
||||||
|
lastNotify = Date.now();
|
||||||
|
hashesSinceLastNotify = 0;
|
||||||
|
}
|
||||||
|
setTimeout(solve, 10);
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
console.error("Error", error);
|
||||||
|
const stack = error.stack;
|
||||||
|
const debug = {
|
||||||
|
stack,
|
||||||
|
lastNonce: nonce,
|
||||||
|
targetValue: params.targetValue,
|
||||||
|
};
|
||||||
|
self.postMessage({ type: "error", error: error.message, debug });
|
||||||
|
active = false;
|
||||||
|
}
|
||||||
|
};
|
||||||
@@ -0,0 +1,39 @@
|
|||||||
|
import Database from "better-sqlite3";
|
||||||
|
import { DATABASE_VERSION, migrateDatabase } from "../src/shared/database";
|
||||||
|
import { logger } from "../src/logger";
|
||||||
|
import { config } from "../src/config";
|
||||||
|
|
||||||
|
const log = logger.child({ module: "scripts/migrate" });
|
||||||
|
|
||||||
|
async function runMigration() {
|
||||||
|
let targetVersion = Number(process.argv[2]) || undefined;
|
||||||
|
|
||||||
|
if (!targetVersion) {
|
||||||
|
log.info("Enter target version or leave empty to use the latest version.");
|
||||||
|
process.stdin.resume();
|
||||||
|
process.stdin.setEncoding("utf8");
|
||||||
|
const input = await new Promise<string>((resolve) => {
|
||||||
|
process.stdin.on("data", (text) => {
|
||||||
|
resolve((String(text) || "").trim());
|
||||||
|
});
|
||||||
|
});
|
||||||
|
process.stdin.pause();
|
||||||
|
targetVersion = Number(input);
|
||||||
|
if (!targetVersion) {
|
||||||
|
targetVersion = DATABASE_VERSION;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const db = new Database(config.sqliteDataPath, {
|
||||||
|
verbose: (msg, ...args) => log.debug({ args }, String(msg)),
|
||||||
|
});
|
||||||
|
|
||||||
|
const currentVersion = db.pragma("user_version", { simple: true });
|
||||||
|
log.info({ currentVersion, targetVersion }, "Running migrations.");
|
||||||
|
migrateDatabase(targetVersion, db);
|
||||||
|
}
|
||||||
|
|
||||||
|
runMigration().catch((error) => {
|
||||||
|
log.error(error, "Migration failed.");
|
||||||
|
process.exit(1);
|
||||||
|
});
|
||||||
@@ -0,0 +1,100 @@
|
|||||||
|
import Database from "better-sqlite3";
|
||||||
|
import { v4 as uuidv4 } from "uuid";
|
||||||
|
import { config } from "../src/config";
|
||||||
|
|
||||||
|
function generateRandomIP() {
|
||||||
|
return (
|
||||||
|
Math.floor(Math.random() * 255) +
|
||||||
|
"." +
|
||||||
|
Math.floor(Math.random() * 255) +
|
||||||
|
"." +
|
||||||
|
Math.floor(Math.random() * 255) +
|
||||||
|
"." +
|
||||||
|
Math.floor(Math.random() * 255)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function generateRandomDate() {
|
||||||
|
const end = new Date();
|
||||||
|
const start = new Date(end);
|
||||||
|
start.setDate(end.getDate() - 90);
|
||||||
|
const randomDate = new Date(
|
||||||
|
start.getTime() + Math.random() * (end.getTime() - start.getTime())
|
||||||
|
);
|
||||||
|
return randomDate.toISOString();
|
||||||
|
}
|
||||||
|
|
||||||
|
function generateMockSHA256() {
|
||||||
|
const characters = 'abcdef0123456789';
|
||||||
|
let hash = '';
|
||||||
|
|
||||||
|
for (let i = 0; i < 64; i++) {
|
||||||
|
const randomIndex = Math.floor(Math.random() * characters.length);
|
||||||
|
hash += characters[randomIndex];
|
||||||
|
}
|
||||||
|
|
||||||
|
return hash;
|
||||||
|
}
|
||||||
|
|
||||||
|
function getRandomModelFamily() {
|
||||||
|
const modelFamilies = [
|
||||||
|
"turbo",
|
||||||
|
"gpt4",
|
||||||
|
"gpt4-32k",
|
||||||
|
"gpt4-turbo",
|
||||||
|
"claude",
|
||||||
|
"claude-opus",
|
||||||
|
"gemini-pro",
|
||||||
|
"mistral-tiny",
|
||||||
|
"mistral-small",
|
||||||
|
"mistral-medium",
|
||||||
|
"mistral-large",
|
||||||
|
"aws-claude",
|
||||||
|
"aws-claude-opus",
|
||||||
|
"azure-turbo",
|
||||||
|
"azure-gpt4",
|
||||||
|
"azure-gpt4-32k",
|
||||||
|
"azure-gpt4-turbo",
|
||||||
|
"dall-e",
|
||||||
|
"azure-dall-e",
|
||||||
|
];
|
||||||
|
return modelFamilies[Math.floor(Math.random() * modelFamilies.length)];
|
||||||
|
}
|
||||||
|
|
||||||
|
(async () => {
|
||||||
|
const db = new Database(config.sqliteDataPath);
|
||||||
|
const numRows = 100;
|
||||||
|
const insertStatement = db.prepare(`
|
||||||
|
INSERT INTO events (type, ip, date, model, family, hashes, userToken, inputTokens, outputTokens)
|
||||||
|
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
|
||||||
|
`);
|
||||||
|
|
||||||
|
const users = Array.from({ length: 10 }, () => uuidv4());
|
||||||
|
function getRandomUser() {
|
||||||
|
return users[Math.floor(Math.random() * users.length)];
|
||||||
|
}
|
||||||
|
|
||||||
|
const transaction = db.transaction(() => {
|
||||||
|
for (let i = 0; i < numRows; i++) {
|
||||||
|
insertStatement.run(
|
||||||
|
"chat_completion",
|
||||||
|
generateRandomIP(),
|
||||||
|
generateRandomDate(),
|
||||||
|
getRandomModelFamily() + "-" + Math.floor(Math.random() * 100),
|
||||||
|
getRandomModelFamily(),
|
||||||
|
Array.from(
|
||||||
|
{ length: Math.floor(Math.random() * 10) },
|
||||||
|
generateMockSHA256
|
||||||
|
).join(","),
|
||||||
|
getRandomUser(),
|
||||||
|
Math.floor(Math.random() * 500),
|
||||||
|
Math.floor(Math.random() * 6000)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
transaction();
|
||||||
|
|
||||||
|
console.log(`Inserted ${numRows} rows into the events table.`);
|
||||||
|
db.close();
|
||||||
|
})();
|
||||||
@@ -0,0 +1,49 @@
|
|||||||
|
import { Router } from "express";
|
||||||
|
import { z } from "zod";
|
||||||
|
import { encodeCursor, decodeCursor } from "../../shared/utils";
|
||||||
|
import { eventsRepo } from "../../shared/database/repos/events";
|
||||||
|
|
||||||
|
const router = Router();
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Returns events for the given user token.
|
||||||
|
* GET /admin/events/:token
|
||||||
|
* @query first - The number of events to return.
|
||||||
|
* @query after - The cursor to start returning events from (exclusive).
|
||||||
|
*/
|
||||||
|
router.get("/:token", (req, res) => {
|
||||||
|
const schema = z.object({
|
||||||
|
token: z.string(),
|
||||||
|
first: z.coerce.number().int().positive().max(200).default(25),
|
||||||
|
after: z
|
||||||
|
.string()
|
||||||
|
.optional()
|
||||||
|
.transform((v) => {
|
||||||
|
try {
|
||||||
|
return decodeCursor(v);
|
||||||
|
} catch {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
})
|
||||||
|
.nullable(),
|
||||||
|
sort: z.string().optional(),
|
||||||
|
});
|
||||||
|
const args = schema.safeParse({ ...req.params, ...req.query });
|
||||||
|
if (!args.success) {
|
||||||
|
return res.status(400).json({ error: args.error });
|
||||||
|
}
|
||||||
|
|
||||||
|
const data = eventsRepo
|
||||||
|
.getUserEvents(args.data.token, {
|
||||||
|
limit: args.data.first,
|
||||||
|
cursor: args.data.after,
|
||||||
|
})
|
||||||
|
.map((e) => ({ node: e, cursor: encodeCursor(e.date) }));
|
||||||
|
|
||||||
|
res.json({
|
||||||
|
data,
|
||||||
|
endCursor: data[data.length - 1]?.cursor,
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
export { router as eventsApiRouter };
|
||||||
@@ -2,7 +2,7 @@ import { Router } from "express";
|
|||||||
import { z } from "zod";
|
import { z } from "zod";
|
||||||
import * as userStore from "../../shared/users/user-store";
|
import * as userStore from "../../shared/users/user-store";
|
||||||
import { parseSort, sortBy } from "../../shared/utils";
|
import { parseSort, sortBy } from "../../shared/utils";
|
||||||
import { UserPartialSchema, UserSchema } from "../../shared/users/schema";
|
import { UserPartialSchema, UserSchema } from "../../shared/database/repos/users";
|
||||||
|
|
||||||
const router = Router();
|
const router = Router();
|
||||||
|
|
||||||
|
|||||||
+19
-4
@@ -1,17 +1,31 @@
|
|||||||
import express, { Router } from "express";
|
import express, { Router } from "express";
|
||||||
import { authorize } from "./auth";
|
import { createWhitelistMiddleware } from "../shared/cidr";
|
||||||
import { HttpError } from "../shared/errors";
|
import { HttpError } from "../shared/errors";
|
||||||
|
import { injectCsrfToken, checkCsrfToken } from "../shared/inject-csrf";
|
||||||
import { injectLocals } from "../shared/inject-locals";
|
import { injectLocals } from "../shared/inject-locals";
|
||||||
import { withSession } from "../shared/with-session";
|
import { withSession } from "../shared/with-session";
|
||||||
import { injectCsrfToken, checkCsrfToken } from "../shared/inject-csrf";
|
import { config } from "../config";
|
||||||
import { renderPage } from "../info-page";
|
import { renderPage } from "../info-page";
|
||||||
import { buildInfo } from "../service-info";
|
import { buildInfo } from "../service-info";
|
||||||
|
import { authorize } from "./auth";
|
||||||
import { loginRouter } from "./login";
|
import { loginRouter } from "./login";
|
||||||
import { usersApiRouter as apiRouter } from "./api/users";
|
import { eventsApiRouter } from "./api/events";
|
||||||
|
import { usersApiRouter } from "./api/users";
|
||||||
import { usersWebRouter as webRouter } from "./web/manage";
|
import { usersWebRouter as webRouter } from "./web/manage";
|
||||||
|
import { logger } from "../logger";
|
||||||
|
|
||||||
const adminRouter = Router();
|
const adminRouter = Router();
|
||||||
|
|
||||||
|
const whitelist = createWhitelistMiddleware(
|
||||||
|
"ADMIN_WHITELIST",
|
||||||
|
config.adminWhitelist
|
||||||
|
);
|
||||||
|
|
||||||
|
if (!whitelist.ranges.length && config.adminKey?.length) {
|
||||||
|
logger.error("ADMIN_WHITELIST is empty. No admin requests will be allowed. Set 0.0.0.0/0 to allow all.");
|
||||||
|
}
|
||||||
|
|
||||||
|
adminRouter.use(whitelist);
|
||||||
adminRouter.use(
|
adminRouter.use(
|
||||||
express.json({ limit: "20mb" }),
|
express.json({ limit: "20mb" }),
|
||||||
express.urlencoded({ extended: true, limit: "20mb" })
|
express.urlencoded({ extended: true, limit: "20mb" })
|
||||||
@@ -19,7 +33,8 @@ adminRouter.use(
|
|||||||
adminRouter.use(withSession);
|
adminRouter.use(withSession);
|
||||||
adminRouter.use(injectCsrfToken);
|
adminRouter.use(injectCsrfToken);
|
||||||
|
|
||||||
adminRouter.use("/users", authorize({ via: "header" }), apiRouter);
|
adminRouter.use("/users", authorize({ via: "header" }), usersApiRouter);
|
||||||
|
adminRouter.use("/events", authorize({ via: "header" }), eventsApiRouter);
|
||||||
|
|
||||||
adminRouter.use(checkCsrfToken);
|
adminRouter.use(checkCsrfToken);
|
||||||
adminRouter.use(injectLocals);
|
adminRouter.use(injectLocals);
|
||||||
|
|||||||
+194
-11
@@ -1,4 +1,5 @@
|
|||||||
import { Router } from "express";
|
import { Router } from "express";
|
||||||
|
import ipaddr from "ipaddr.js";
|
||||||
import multer from "multer";
|
import multer from "multer";
|
||||||
import { z } from "zod";
|
import { z } from "zod";
|
||||||
import { config } from "../../config";
|
import { config } from "../../config";
|
||||||
@@ -8,13 +9,10 @@ import { parseSort, sortBy, paginate } from "../../shared/utils";
|
|||||||
import { keyPool } from "../../shared/key-management";
|
import { keyPool } from "../../shared/key-management";
|
||||||
import { LLMService, MODEL_FAMILIES } from "../../shared/models";
|
import { LLMService, MODEL_FAMILIES } from "../../shared/models";
|
||||||
import { getTokenCostUsd, prettyTokens } from "../../shared/stats";
|
import { getTokenCostUsd, prettyTokens } from "../../shared/stats";
|
||||||
import {
|
|
||||||
User,
|
|
||||||
UserPartialSchema,
|
|
||||||
UserSchema,
|
|
||||||
UserTokenCounts,
|
|
||||||
} from "../../shared/users/schema";
|
|
||||||
import { getLastNImages } from "../../shared/file-storage/image-history";
|
import { getLastNImages } from "../../shared/file-storage/image-history";
|
||||||
|
import { blacklists, parseCidrs, whitelists } from "../../shared/cidr";
|
||||||
|
import { invalidatePowHmacKey } from "../../user/web/pow-captcha";
|
||||||
|
import { User, UserPartialSchema, UserSchema, UserTokenCounts } from "../../shared/database/repos/users";
|
||||||
|
|
||||||
const router = Router();
|
const router = Router();
|
||||||
|
|
||||||
@@ -40,6 +38,74 @@ router.get("/create-user", (req, res) => {
|
|||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
router.get("/anti-abuse", (_req, res) => {
|
||||||
|
const wl = [...whitelists.entries()];
|
||||||
|
const bl = [...blacklists.entries()];
|
||||||
|
|
||||||
|
res.render("admin_anti-abuse", {
|
||||||
|
captchaMode: config.captchaMode,
|
||||||
|
difficulty: config.powDifficultyLevel,
|
||||||
|
whitelists: wl.map((w) => ({
|
||||||
|
name: w[0],
|
||||||
|
mode: "whitelist",
|
||||||
|
ranges: w[1].ranges,
|
||||||
|
})),
|
||||||
|
blacklists: bl.map((b) => ({
|
||||||
|
name: b[0],
|
||||||
|
mode: "blacklist",
|
||||||
|
ranges: b[1].ranges,
|
||||||
|
})),
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
router.post("/cidr", (req, res) => {
|
||||||
|
const body = req.body;
|
||||||
|
const valid = z
|
||||||
|
.object({
|
||||||
|
action: z.enum(["add", "remove"]),
|
||||||
|
mode: z.enum(["whitelist", "blacklist"]),
|
||||||
|
name: z.string().min(1),
|
||||||
|
mask: z.string().min(1),
|
||||||
|
})
|
||||||
|
.safeParse(body);
|
||||||
|
|
||||||
|
if (!valid.success) {
|
||||||
|
throw new HttpError(
|
||||||
|
400,
|
||||||
|
valid.error.issues.flatMap((issue) => issue.message).join(", ")
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
const { mode, name, mask } = valid.data;
|
||||||
|
const list = (mode === "whitelist" ? whitelists : blacklists).get(name);
|
||||||
|
if (!list) {
|
||||||
|
throw new HttpError(404, "List not found");
|
||||||
|
}
|
||||||
|
if (valid.data.action === "remove") {
|
||||||
|
const newRanges = new Set(list.ranges);
|
||||||
|
newRanges.delete(mask);
|
||||||
|
list.updateRanges([...newRanges]);
|
||||||
|
req.session.flash = {
|
||||||
|
type: "success",
|
||||||
|
message: `${mode} ${name} updated`,
|
||||||
|
};
|
||||||
|
return res.redirect("/admin/manage/anti-abuse");
|
||||||
|
} else if (valid.data.action === "add") {
|
||||||
|
const result = parseCidrs(mask);
|
||||||
|
if (result.length === 0) {
|
||||||
|
throw new HttpError(400, "Invalid CIDR mask");
|
||||||
|
}
|
||||||
|
|
||||||
|
const newRanges = new Set([...list.ranges, mask]);
|
||||||
|
list.updateRanges([...newRanges]);
|
||||||
|
req.session.flash = {
|
||||||
|
type: "success",
|
||||||
|
message: `${mode} ${name} updated`,
|
||||||
|
};
|
||||||
|
return res.redirect("/admin/manage/anti-abuse");
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
router.post("/create-user", (req, res) => {
|
router.post("/create-user", (req, res) => {
|
||||||
const body = req.body;
|
const body = req.body;
|
||||||
|
|
||||||
@@ -223,10 +289,14 @@ router.post("/maintenance", (req, res) => {
|
|||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
case "downloadImageMetadata": {
|
case "downloadImageMetadata": {
|
||||||
const data = JSON.stringify({
|
const data = JSON.stringify(
|
||||||
exportedAt: new Date().toISOString(),
|
{
|
||||||
generations: getLastNImages()
|
exportedAt: new Date().toISOString(),
|
||||||
}, null, 2);
|
generations: getLastNImages(),
|
||||||
|
},
|
||||||
|
null,
|
||||||
|
2
|
||||||
|
);
|
||||||
res.setHeader(
|
res.setHeader(
|
||||||
"Content-Disposition",
|
"Content-Disposition",
|
||||||
`attachment; filename=image-metadata-${new Date().toISOString()}.json`
|
`attachment; filename=image-metadata-${new Date().toISOString()}.json`
|
||||||
@@ -234,14 +304,127 @@ router.post("/maintenance", (req, res) => {
|
|||||||
res.setHeader("Content-Type", "application/json");
|
res.setHeader("Content-Type", "application/json");
|
||||||
return res.send(data);
|
return res.send(data);
|
||||||
}
|
}
|
||||||
|
case "expireTempTokens": {
|
||||||
|
const users = userStore.getUsers();
|
||||||
|
const temps = users.filter((u) => u.type === "temporary");
|
||||||
|
temps.forEach((user) => {
|
||||||
|
user.expiresAt = Date.now();
|
||||||
|
user.disabledReason = "Admin forced expiration.";
|
||||||
|
userStore.upsertUser(user);
|
||||||
|
});
|
||||||
|
invalidatePowHmacKey();
|
||||||
|
flash.type = "success";
|
||||||
|
flash.message = `${temps.length} temporary users marked for expiration.`;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
case "cleanTempTokens": {
|
||||||
|
const users = userStore.getUsers();
|
||||||
|
const disabledTempUsers = users.filter(
|
||||||
|
(u) => u.type === "temporary" && u.expiresAt && u.expiresAt < Date.now()
|
||||||
|
);
|
||||||
|
disabledTempUsers.forEach((user) => {
|
||||||
|
user.disabledAt = 1; //will be cleaned up by the next cron job
|
||||||
|
userStore.upsertUser(user);
|
||||||
|
});
|
||||||
|
flash.type = "success";
|
||||||
|
flash.message = `${disabledTempUsers.length} disabled temporary users marked for cleanup.`;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
case "setDifficulty": {
|
||||||
|
const selected = req.body["pow-difficulty"];
|
||||||
|
const valid = ["low", "medium", "high", "extreme"];
|
||||||
|
if (!selected || !valid.includes(selected)) {
|
||||||
|
throw new HttpError(400, "Invalid difficulty" + selected);
|
||||||
|
}
|
||||||
|
config.powDifficultyLevel = selected;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
case "generateTempIpReport": {
|
||||||
|
const tempUsers = userStore
|
||||||
|
.getUsers()
|
||||||
|
.filter((u) => u.type === "temporary");
|
||||||
|
const ipv4RangeMap: Map<string, Set<string>> = new Map<
|
||||||
|
string,
|
||||||
|
Set<string>
|
||||||
|
>();
|
||||||
|
const ipv6RangeMap: Map<string, Set<string>> = new Map<
|
||||||
|
string,
|
||||||
|
Set<string>
|
||||||
|
>();
|
||||||
|
|
||||||
|
tempUsers.forEach((u) => {
|
||||||
|
u.ip.forEach((ip) => {
|
||||||
|
try {
|
||||||
|
const parsed = ipaddr.parse(ip);
|
||||||
|
if (parsed.kind() === "ipv4") {
|
||||||
|
const subnet =
|
||||||
|
parsed.toNormalizedString().split(".").slice(0, 3).join(".") +
|
||||||
|
".0/24";
|
||||||
|
const userSet = ipv4RangeMap.get(subnet) || new Set<string>();
|
||||||
|
userSet.add(u.token);
|
||||||
|
ipv4RangeMap.set(subnet, userSet);
|
||||||
|
} else if (parsed.kind() === "ipv6") {
|
||||||
|
const subnet =
|
||||||
|
parsed.toNormalizedString().split(":").slice(0, 4).join(":") +
|
||||||
|
"::/48";
|
||||||
|
const userSet = ipv6RangeMap.get(subnet) || new Set<string>();
|
||||||
|
userSet.add(u.token);
|
||||||
|
ipv6RangeMap.set(subnet, userSet);
|
||||||
|
}
|
||||||
|
} catch (e) {
|
||||||
|
req.log.warn(
|
||||||
|
{ ip, error: e.message },
|
||||||
|
"Invalid IP address; skipping"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
const ipv4Ranges = Array.from(ipv4RangeMap.entries())
|
||||||
|
.map(([subnet, userSet]) => ({
|
||||||
|
subnet,
|
||||||
|
distinctTokens: userSet.size,
|
||||||
|
}))
|
||||||
|
.sort((a, b) => b.distinctTokens - a.distinctTokens);
|
||||||
|
|
||||||
|
const ipv6Ranges = Array.from(ipv6RangeMap.entries())
|
||||||
|
.map(([subnet, userSet]) => ({
|
||||||
|
subnet,
|
||||||
|
distinctTokens: userSet.size,
|
||||||
|
}))
|
||||||
|
.sort((a, b) => {
|
||||||
|
if (a.distinctTokens === b.distinctTokens) {
|
||||||
|
return a.subnet.localeCompare(b.subnet);
|
||||||
|
}
|
||||||
|
return b.distinctTokens - a.distinctTokens;
|
||||||
|
});
|
||||||
|
|
||||||
|
const data = JSON.stringify(
|
||||||
|
{
|
||||||
|
exportedAt: new Date().toISOString(),
|
||||||
|
ipv4Ranges,
|
||||||
|
ipv6Ranges,
|
||||||
|
},
|
||||||
|
null,
|
||||||
|
2
|
||||||
|
);
|
||||||
|
|
||||||
|
res.setHeader(
|
||||||
|
"Content-Disposition",
|
||||||
|
`attachment; filename=temp-ip-report-${new Date().toISOString()}.json`
|
||||||
|
);
|
||||||
|
res.setHeader("Content-Type", "application/json");
|
||||||
|
return res.send(data);
|
||||||
|
}
|
||||||
default: {
|
default: {
|
||||||
throw new HttpError(400, "Invalid action");
|
throw new HttpError(400, "Invalid action");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
req.session.flash = flash;
|
req.session.flash = flash;
|
||||||
|
const referer = req.get("referer");
|
||||||
|
|
||||||
return res.redirect(`/admin/manage`);
|
return res.redirect(referer || "/admin/manage");
|
||||||
});
|
});
|
||||||
|
|
||||||
router.get("/download-stats", (_req, res) => {
|
router.get("/download-stats", (_req, res) => {
|
||||||
|
|||||||
@@ -0,0 +1,140 @@
|
|||||||
|
<%- include("partials/shared_header", { title: "Proof of Work Verification Settings - OAI Reverse Proxy Admin" }) %>
|
||||||
|
<style>
|
||||||
|
details {
|
||||||
|
margin-top: 1em;
|
||||||
|
}
|
||||||
|
details summary {
|
||||||
|
font-weight: bold;
|
||||||
|
cursor: pointer;
|
||||||
|
}
|
||||||
|
details p {
|
||||||
|
margin-left: 1em;
|
||||||
|
}
|
||||||
|
|
||||||
|
#token-manage {
|
||||||
|
display: flex;
|
||||||
|
width: 100%;
|
||||||
|
}
|
||||||
|
#token-manage button {
|
||||||
|
flex-grow: 1;
|
||||||
|
margin: 0 0.5em;
|
||||||
|
}
|
||||||
|
</style>
|
||||||
|
|
||||||
|
<h1>Abuse Mitigation Settings</h1>
|
||||||
|
<div>
|
||||||
|
<h2>Proof-of-Work Verification</h2>
|
||||||
|
<p>
|
||||||
|
The Proof-of-Work difficulty level is used to determine how much work a client must perform to earn a temporary user
|
||||||
|
token. Higher difficulty levels require more work, which can help mitigate abuse by making it more expensive for
|
||||||
|
attackers to generate tokens. However, higher difficulty levels can also make it more difficult for legitimate users
|
||||||
|
to generate tokens. Refer to documentation for guidance.
|
||||||
|
</p>
|
||||||
|
<%if (captchaMode === "none") { %>
|
||||||
|
<p>
|
||||||
|
<strong>PoW verification is not enabled. Set <code>CAPTCHA_MODE=proof_of_work</code> to enable.</strong>
|
||||||
|
</p>
|
||||||
|
<% } else { %>
|
||||||
|
<h3>Difficulty Level</h3>
|
||||||
|
<div>
|
||||||
|
<label for="difficulty">Difficulty Level:</label>
|
||||||
|
<span id="currentDifficulty">Current: <%= difficulty %></span>
|
||||||
|
<select name="difficulty" id="difficulty">
|
||||||
|
<option value="low">Low</option>
|
||||||
|
<option value="medium">Medium</option>
|
||||||
|
<option value="high">High</option>
|
||||||
|
<option value="extreme">Extreme</option>
|
||||||
|
</select>
|
||||||
|
<button onclick='doAction("setDifficulty")'>Update Difficulty</button>
|
||||||
|
</div>
|
||||||
|
<% } %>
|
||||||
|
<form id="maintenanceForm" action="/admin/manage/maintenance" method="post">
|
||||||
|
<input id="_csrf" type="hidden" name="_csrf" value="<%= csrfToken %>" />
|
||||||
|
<input id="hiddenAction" type="hidden" name="action" value="" />
|
||||||
|
<input id="hiddenDifficulty" type="hidden" name="pow-difficulty" value="" />
|
||||||
|
</form>
|
||||||
|
<h3>Manage Temporary User Tokens</h3>
|
||||||
|
<div id="token-manage">
|
||||||
|
<p><button onclick='doAction("expireTempTokens")'>🕒 Expire All Temp Tokens</button></p>
|
||||||
|
<p><button onclick='doAction("cleanTempTokens")'>🧹 Delete Expired Temp Tokens</button></p>
|
||||||
|
<p><button onclick='doAction("generateTempIpReport")'>📊 Generate Temp Token IP Report</button></p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<h2>IP Whitelists and Blacklists</h2>
|
||||||
|
<p>
|
||||||
|
You can specify IP ranges to whitelist or blacklist from accessing the proxy. Note that changes here are not
|
||||||
|
persisted across server restarts. If you want to make changes permanent, you can copy the values to your deployment
|
||||||
|
configuration.
|
||||||
|
</p>
|
||||||
|
<p>
|
||||||
|
Entries can be specified as single addresses or
|
||||||
|
<a href="https://en.wikipedia.org/wiki/Classless_Inter-Domain_Routing#CIDR_notation">CIDR notation</a>. IPv6 is
|
||||||
|
supported but not recommended for use with the current version of the proxy.
|
||||||
|
</p>
|
||||||
|
<% for (let i = 0; i < whitelists.length; i++) { %>
|
||||||
|
<%- include("partials/admin-cidr-widget", { list: whitelists[i] }) %>
|
||||||
|
<% } %>
|
||||||
|
<% for (let i = 0; i < blacklists.length; i++) { %>
|
||||||
|
<%- include("partials/admin-cidr-widget", { list: blacklists[i] }) %>
|
||||||
|
<% } %>
|
||||||
|
<form action="/admin/manage/cidr" method="post" id="cidrForm">
|
||||||
|
<input id="_csrf" type="hidden" name="_csrf" value="<%= csrfToken %>" />
|
||||||
|
<input type="hidden" name="action" value="add" />
|
||||||
|
<input type="hidden" name="name" value="" />
|
||||||
|
<input type="hidden" name="mode" value="" />
|
||||||
|
<input type="hidden" name="mask" value="" />
|
||||||
|
</form>
|
||||||
|
<details>
|
||||||
|
<summary>Copy environment variables</summary>
|
||||||
|
<p>
|
||||||
|
If you have made changes with the UI, you can copy the values below to your deployment configuration to persist
|
||||||
|
them across server restarts.
|
||||||
|
</p>
|
||||||
|
<pre>
|
||||||
|
<% for (let i = 0; i < whitelists.length; i++) { %><%= whitelists[i].name %>=<%= whitelists[i].ranges.join(",") %><% } %>
|
||||||
|
<% for (let i = 0; i < blacklists.length; i++) { %><%= blacklists[i].name %>=<%= blacklists[i].ranges.join(",") %><% } %>
|
||||||
|
</pre>
|
||||||
|
</details>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<script>
|
||||||
|
function doAction(action) {
|
||||||
|
document.getElementById("hiddenAction").value = action;
|
||||||
|
if (action === "setDifficulty") {
|
||||||
|
document.getElementById("hiddenDifficulty").value = document.getElementById("difficulty").value;
|
||||||
|
}
|
||||||
|
document.getElementById("maintenanceForm").submit();
|
||||||
|
}
|
||||||
|
|
||||||
|
function onAddCidr(event) {
|
||||||
|
const list = event.target.dataset;
|
||||||
|
const newMask = prompt("Enter the IP or CIDR range to add to the list:");
|
||||||
|
if (!newMask) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const form = document.getElementById("cidrForm");
|
||||||
|
form["action"].value = "add";
|
||||||
|
form["name"].value = list.name;
|
||||||
|
form["mode"].value = list.mode;
|
||||||
|
form["mask"].value = newMask;
|
||||||
|
form.submit();
|
||||||
|
}
|
||||||
|
|
||||||
|
function onRemoveCidr(event) {
|
||||||
|
const list = event.target.dataset;
|
||||||
|
const removeMask = event.target.dataset.mask;
|
||||||
|
if (!removeMask) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const form = document.getElementById("cidrForm");
|
||||||
|
form["action"].value = "remove";
|
||||||
|
form["name"].value = list.name;
|
||||||
|
form["mode"].value = list.mode;
|
||||||
|
form["mask"].value = removeMask;
|
||||||
|
form.submit();
|
||||||
|
}
|
||||||
|
</script>
|
||||||
|
<%- include("partials/admin-footer") %>
|
||||||
@@ -51,9 +51,8 @@
|
|||||||
<legend>Temporary User Options</legend>
|
<legend>Temporary User Options</legend>
|
||||||
<div class="temporary-user-fieldset">
|
<div class="temporary-user-fieldset">
|
||||||
<p class="full-width">
|
<p class="full-width">
|
||||||
Temporary users will be disabled after the specified duration, and their records will be deleted 72 hours after that.
|
Temporary users will be disabled after the specified duration, and their records will be permanently deleted after some time.
|
||||||
These options apply only to new
|
These options apply only to new temporary users; existing ones use whatever options were in effect when they were created.
|
||||||
temporary users; existing ones use whatever options were in effect when they were created.
|
|
||||||
</p>
|
</p>
|
||||||
<label for="temporaryUserDuration" class="full-width">Access duration (in minutes)</label>
|
<label for="temporaryUserDuration" class="full-width">Access duration (in minutes)</label>
|
||||||
<input type="number" name="temporaryUserDuration" id="temporaryUserDuration" value="60" class="full-width" />
|
<input type="number" name="temporaryUserDuration" id="temporaryUserDuration" value="60" class="full-width" />
|
||||||
|
|||||||
@@ -5,18 +5,6 @@
|
|||||||
flex-direction: column;
|
flex-direction: column;
|
||||||
}
|
}
|
||||||
|
|
||||||
#statsForm div {
|
|
||||||
display: flex;
|
|
||||||
flex-direction: row;
|
|
||||||
margin-bottom: 0.5em;
|
|
||||||
}
|
|
||||||
|
|
||||||
#statsForm div label {
|
|
||||||
width: 6em;
|
|
||||||
text-align: right;
|
|
||||||
margin-right: 1em;
|
|
||||||
}
|
|
||||||
|
|
||||||
#statsForm ul {
|
#statsForm ul {
|
||||||
margin: 0;
|
margin: 0;
|
||||||
padding-left: 2em;
|
padding-left: 2em;
|
||||||
@@ -33,17 +21,17 @@
|
|||||||
}
|
}
|
||||||
</style>
|
</style>
|
||||||
<h1>Download Stats</h1>
|
<h1>Download Stats</h1>
|
||||||
<p>
|
<p>Download usage statistics to a Markdown document. You can paste this into a service like Rentry.org to share it.</p>
|
||||||
Download usage statistics to a Markdown document. You can paste this into a service like Rentry.org to share it.
|
|
||||||
</p>
|
|
||||||
<div>
|
<div>
|
||||||
<h3>Options</h3>
|
<h3>Options</h3>
|
||||||
<form id="statsForm" action="/admin/manage/generate-stats" method="post"
|
<form
|
||||||
style="display: flex; flex-direction: column;">
|
id="statsForm"
|
||||||
|
action="/admin/manage/generate-stats"
|
||||||
|
method="post"
|
||||||
|
style="display: flex; flex-direction: column">
|
||||||
<input id="_csrf" type="hidden" name="_csrf" value="<%= csrfToken %>" />
|
<input id="_csrf" type="hidden" name="_csrf" value="<%= csrfToken %>" />
|
||||||
<div>
|
<div>
|
||||||
<label for="anon">Anonymize</label>
|
<label for="anon"><input id="anon" type="checkbox" name="anon" value="true" /> <span>Anonymize</span></label>
|
||||||
<input id="anon" type="checkbox" name="anon" value="true" />
|
|
||||||
</div>
|
</div>
|
||||||
<div>
|
<div>
|
||||||
<label for="sort">Sort</label>
|
<label for="sort">Sort</label>
|
||||||
@@ -64,11 +52,12 @@
|
|||||||
</select>
|
</select>
|
||||||
</div>
|
</div>
|
||||||
<div>
|
<div>
|
||||||
<label for="format">Custom Format <ul>
|
<label for="format">Custom Format</label>
|
||||||
<li><code>{{header}}</code></li>
|
<ul>
|
||||||
<li><code>{{stats}}</code></li>
|
<li><code>{{header}}</code></li>
|
||||||
<li><code>{{time}}</code></li>
|
<li><code>{{stats}}</code></li>
|
||||||
</ul></label>
|
<li><code>{{time}}</code></li>
|
||||||
|
</ul>
|
||||||
<textarea id="format" name="format" rows="10" cols="50" placeholder="{{stats}}">
|
<textarea id="format" name="format" rows="10" cols="50" placeholder="{{stats}}">
|
||||||
# Stats
|
# Stats
|
||||||
{{header}}
|
{{header}}
|
||||||
@@ -115,33 +104,35 @@
|
|||||||
loadDefaults();
|
loadDefaults();
|
||||||
|
|
||||||
async function fetchAndCopy() {
|
async function fetchAndCopy() {
|
||||||
const form = document.getElementById('statsForm');
|
const form = document.getElementById("statsForm");
|
||||||
const formData = new FormData(form);
|
const formData = new FormData(form);
|
||||||
|
|
||||||
const response = await fetch(form.action, {
|
const response = await fetch(form.action, {
|
||||||
method: 'POST',
|
method: "POST",
|
||||||
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
|
headers: { "Content-Type": "application/x-www-form-urlencoded" },
|
||||||
credentials: 'same-origin',
|
credentials: "same-origin",
|
||||||
body: new URLSearchParams(formData),
|
body: new URLSearchParams(formData),
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|
||||||
if (response.ok) {
|
if (response.ok) {
|
||||||
const content = await response.text();
|
const content = await response.text();
|
||||||
copyToClipboard(content);
|
copyToClipboard(content);
|
||||||
} else {
|
} else {
|
||||||
throw new Error('Failed to fetch generated stats. Try reloading the page.');
|
throw new Error("Failed to fetch generated stats. Try reloading the page.");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
function copyToClipboard(text) {
|
function copyToClipboard(text) {
|
||||||
navigator.clipboard.writeText(text).then(() => {
|
navigator.clipboard
|
||||||
alert('Copied to clipboard');
|
.writeText(text)
|
||||||
}).catch(err => {
|
.then(() => {
|
||||||
alert('Failed to copy to clipboard. Try downloading the file instead.');
|
alert("Copied to clipboard");
|
||||||
});
|
})
|
||||||
|
.catch((err) => {
|
||||||
|
alert("Failed to copy to clipboard. Try downloading the file instead.");
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
document.getElementById('copyButton').addEventListener('click', fetchAndCopy);
|
document.getElementById("copyButton").addEventListener("click", fetchAndCopy);
|
||||||
</script>
|
</script>
|
||||||
<%- include("partials/admin-footer") %>
|
<%- include("partials/admin-footer") %>
|
||||||
|
|||||||
@@ -25,13 +25,14 @@
|
|||||||
<li><a href="/admin/manage/import-users">Import Users</a></li>
|
<li><a href="/admin/manage/import-users">Import Users</a></li>
|
||||||
<li><a href="/admin/manage/export-users">Export Users</a></li>
|
<li><a href="/admin/manage/export-users">Export Users</a></li>
|
||||||
<li><a href="/admin/manage/download-stats">Download Rentry Stats</a>
|
<li><a href="/admin/manage/download-stats">Download Rentry Stats</a>
|
||||||
|
<li><a href="/admin/manage/anti-abuse">Abuse Mitigation Settings</a></li>
|
||||||
<li><a href="/admin/service-info">Service Info</a></li>
|
<li><a href="/admin/service-info">Service Info</a></li>
|
||||||
</ul>
|
</ul>
|
||||||
<h3>Maintenance</h3>
|
<h3>Maintenance</h3>
|
||||||
<form id="maintenanceForm" action="/admin/manage/maintenance" method="post">
|
<form id="maintenanceForm" action="/admin/manage/maintenance" method="post">
|
||||||
<input id="_csrf" type="hidden" name="_csrf" value="<%= csrfToken %>" />
|
<input id="_csrf" type="hidden" name="_csrf" value="<%= csrfToken %>" />
|
||||||
<input id="hiddenAction" type="hidden" name="action" value="" />
|
<input id="hiddenAction" type="hidden" name="action" value="" />
|
||||||
<div display="flex" flex-direction="column">
|
<div>
|
||||||
<fieldset>
|
<fieldset>
|
||||||
<legend>Key Recheck</legend>
|
<legend>Key Recheck</legend>
|
||||||
<button id="recheck-keys" type="button" onclick="submitForm('recheck')">Force Key Recheck</button>
|
<button id="recheck-keys" type="button" onclick="submitForm('recheck')">Force Key Recheck</button>
|
||||||
|
|||||||
@@ -4,9 +4,8 @@
|
|||||||
<% if (users.length === 0) { %>
|
<% if (users.length === 0) { %>
|
||||||
<p>No users found.</p>
|
<p>No users found.</p>
|
||||||
<% } else { %>
|
<% } else { %>
|
||||||
<input type="checkbox" id="toggle-nicknames" onchange="toggleNicknames()" />
|
<label for="toggle-nicknames"><input type="checkbox" id="toggle-nicknames" onchange="toggleNicknames()" /> Show Nicknames</label>
|
||||||
<label for="toggle-nicknames">Show Nicknames</label>
|
<table class="striped full-width">
|
||||||
<table class="striped">
|
|
||||||
<thead>
|
<thead>
|
||||||
<tr>
|
<tr>
|
||||||
<th>User</th>
|
<th>User</th>
|
||||||
|
|||||||
@@ -55,8 +55,9 @@
|
|||||||
<td><%- user.disabledReason %></td>
|
<td><%- user.disabledReason %></td>
|
||||||
<% if (user.disabledAt) { %>
|
<% if (user.disabledAt) { %>
|
||||||
<td class="actions">
|
<td class="actions">
|
||||||
<a title="Edit" id="edit-disabledReason" href="#" data-field="disabledReason"
|
<a title="Edit" id="edit-disabledReason" href="#" data-field="disabledReason" data-token="<%= user.token %>"
|
||||||
data-token="<%= user.token %>">✏️</a>
|
>✏️</a
|
||||||
|
>
|
||||||
</td>
|
</td>
|
||||||
<% } %>
|
<% } %>
|
||||||
</tr>
|
</tr>
|
||||||
@@ -72,7 +73,8 @@
|
|||||||
<td colspan="2"><%- include("partials/shared_user_ip_list", { user, shouldRedact: false }) %></td>
|
<td colspan="2"><%- include("partials/shared_user_ip_list", { user, shouldRedact: false }) %></td>
|
||||||
</tr>
|
</tr>
|
||||||
<tr>
|
<tr>
|
||||||
<th scope="row">Admin Note <span title="Unlike nickname, this is not visible to or editable by the user">🔒</span>
|
<th scope="row">
|
||||||
|
Admin Note <span title="Unlike nickname, this is not visible to or editable by the user">🔒</span>
|
||||||
</th>
|
</th>
|
||||||
<td><%- user.adminNote ?? "none" %></td>
|
<td><%- user.adminNote ?? "none" %></td>
|
||||||
<td class="actions">
|
<td class="actions">
|
||||||
@@ -85,10 +87,16 @@
|
|||||||
<td colspan="2"><%- user.expiresAt %></td>
|
<td colspan="2"><%- user.expiresAt %></td>
|
||||||
</tr>
|
</tr>
|
||||||
<% } %>
|
<% } %>
|
||||||
|
<% if (user.meta) { %>
|
||||||
|
<tr>
|
||||||
|
<th scope="row">Meta</th>
|
||||||
|
<td colspan="2"><%- JSON.stringify(user.meta) %></td>
|
||||||
|
</tr>
|
||||||
|
<% } %>
|
||||||
</tbody>
|
</tbody>
|
||||||
</table>
|
</table>
|
||||||
|
|
||||||
<form style="display:none" id="current-values">
|
<form style="display: none" id="current-values">
|
||||||
<input type="hidden" name="token" value="<%- user.token %>" />
|
<input type="hidden" name="token" value="<%- user.token %>" />
|
||||||
<% ["nickname", "type", "disabledAt", "disabledReason", "maxIps", "adminNote"].forEach(function (key) { %>
|
<% ["nickname", "type", "disabledAt", "disabledReason", "maxIps", "adminNote"].forEach(function (key) { %>
|
||||||
<input type="hidden" name="<%- key %>" value="<%- user[key] %>" />
|
<input type="hidden" name="<%- key %>" value="<%- user[key] %>" />
|
||||||
@@ -102,7 +110,8 @@
|
|||||||
<input type="hidden" name="_csrf" value="<%- csrfToken %>" />
|
<input type="hidden" name="_csrf" value="<%- csrfToken %>" />
|
||||||
<button type="submit" class="btn btn-primary">Refresh Quotas for User</button>
|
<button type="submit" class="btn btn-primary">Refresh Quotas for User</button>
|
||||||
</form>
|
</form>
|
||||||
<% } %> <%- include("partials/shared_quota-info", { quota, user }) %>
|
<% } %>
|
||||||
|
<%- include("partials/shared_quota-info", { quota, user }) %>
|
||||||
|
|
||||||
<p><a href="/admin/manage/list-users">Back to User List</a></p>
|
<p><a href="/admin/manage/list-users">Back to User List</a></p>
|
||||||
|
|
||||||
@@ -144,4 +153,5 @@
|
|||||||
});
|
});
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
<%- include("partials/admin-ban-xhr-script") %> <%- include("partials/admin-footer") %>
|
<%- include("partials/admin-ban-xhr-script") %>
|
||||||
|
<%- include("partials/admin-footer") %>
|
||||||
|
|||||||
@@ -0,0 +1,13 @@
|
|||||||
|
<h3>
|
||||||
|
<%= list.name %>
|
||||||
|
(<%= list.mode %>)
|
||||||
|
</h3>
|
||||||
|
<ul>
|
||||||
|
<% list.ranges.forEach(function(mask) { %>
|
||||||
|
<li>
|
||||||
|
<%= mask %>
|
||||||
|
<button class="remove" data-mode="<%= list.mode %>" data-name="<%= list.name %>" data-mask="<%= mask %>" onclick="onRemoveCidr(event)">Remove</button>
|
||||||
|
</li>
|
||||||
|
<% }); %>
|
||||||
|
</ul>
|
||||||
|
<button class="add" data-mode="<%= list.mode %>" data-name="<%= list.name %>" onclick="onAddCidr(event)">Add</button>
|
||||||
+200
-13
@@ -1,3 +1,4 @@
|
|||||||
|
import crypto from "crypto";
|
||||||
import dotenv from "dotenv";
|
import dotenv from "dotenv";
|
||||||
import type firebase from "firebase-admin";
|
import type firebase from "firebase-admin";
|
||||||
import path from "path";
|
import path from "path";
|
||||||
@@ -107,9 +108,70 @@ type Config = {
|
|||||||
* `maxIpsPerUser` limit, or if only connections from new IPs are be rejected.
|
* `maxIpsPerUser` limit, or if only connections from new IPs are be rejected.
|
||||||
*/
|
*/
|
||||||
maxIpsAutoBan: boolean;
|
maxIpsAutoBan: boolean;
|
||||||
/** Per-IP limit for requests per minute to text and chat models. */
|
/**
|
||||||
|
* Which captcha verification mode to use. Requires `user_token` gatekeeper.
|
||||||
|
* Allows users to automatically obtain a token by solving a captcha.
|
||||||
|
* - `none`: No captcha verification; tokens are issued manually.
|
||||||
|
* - `proof_of_work`: Users must solve an Argon2 proof of work to obtain a
|
||||||
|
* temporary usertoken valid for a limited period.
|
||||||
|
*/
|
||||||
|
captchaMode: "none" | "proof_of_work";
|
||||||
|
/**
|
||||||
|
* Duration (in hours) for which a PoW-issued temporary user token is valid.
|
||||||
|
*/
|
||||||
|
powTokenHours: number;
|
||||||
|
/**
|
||||||
|
* The maximum number of IPs from which a single temporary user token can be
|
||||||
|
* used. Upon reaching the limit, the `maxIpsAutoBan` behavior is triggered.
|
||||||
|
*/
|
||||||
|
powTokenMaxIps: number;
|
||||||
|
/**
|
||||||
|
* Difficulty level for the proof-of-work challenge.
|
||||||
|
* - `low`: 200 iterations
|
||||||
|
* - `medium`: 900 iterations
|
||||||
|
* - `high`: 1900 iterations
|
||||||
|
* - `extreme`: 4000 iterations
|
||||||
|
* - `number`: A custom number of iterations to use.
|
||||||
|
*
|
||||||
|
* Difficulty level only affects the number of iterations used in the PoW,
|
||||||
|
* not the complexity of the hash itself. Therefore, the average time-to-solve
|
||||||
|
* will scale linearly with the number of iterations.
|
||||||
|
*
|
||||||
|
* Refer to docs/proof-of-work.md for guidance and hashrate benchmarks.
|
||||||
|
*/
|
||||||
|
powDifficultyLevel: "low" | "medium" | "high" | "extreme" | number;
|
||||||
|
/**
|
||||||
|
* Duration (in minutes) before a PoW challenge expires. Users' browsers must
|
||||||
|
* solve the challenge within this time frame or it will be rejected. Should
|
||||||
|
* be kept somewhat low to prevent abusive clients from working on many
|
||||||
|
* challenges in parallel, but you may need to increase this value for higher
|
||||||
|
* difficulty levels or older devices will not be able to solve the challenge
|
||||||
|
* in time.
|
||||||
|
*
|
||||||
|
* Defaults to 30 minutes.
|
||||||
|
*/
|
||||||
|
powChallengeTimeout: number;
|
||||||
|
/**
|
||||||
|
* Duration (in hours) before expired temporary user tokens are purged from
|
||||||
|
* the user database. Users can refresh expired tokens by solving a faster PoW
|
||||||
|
* challenge as long as the original token has not been purged. Once purged,
|
||||||
|
* the user must solve a full PoW challenge to obtain a new token.
|
||||||
|
*
|
||||||
|
* Defaults to 48 hours. At 0, tokens are purged immediately upon expiry.
|
||||||
|
*/
|
||||||
|
powTokenPurgeHours: number;
|
||||||
|
/**
|
||||||
|
* Maximum number of active temporary user tokens that can be associated with
|
||||||
|
* a single IP address. Note that this may impact users sending requests from
|
||||||
|
* hosted AI chat clients such as Agnaistic or RisuAI, as they may share IPs.
|
||||||
|
*
|
||||||
|
* When the limit is reached, the oldest token with the same IP will be
|
||||||
|
* expired. At 0, no limit is enforced. Defaults to 0.
|
||||||
|
*/
|
||||||
|
// powMaxTokensPerIp: number;
|
||||||
|
/** Per-user limit for requests per minute to text and chat models. */
|
||||||
textModelRateLimit: number;
|
textModelRateLimit: number;
|
||||||
/** Per-IP limit for requests per minute to image generation models. */
|
/** Per-user limit for requests per minute to image generation models. */
|
||||||
imageModelRateLimit: number;
|
imageModelRateLimit: number;
|
||||||
/**
|
/**
|
||||||
* For OpenAI, the maximum number of context tokens (prompt + max output) a
|
* For OpenAI, the maximum number of context tokens (prompt + max output) a
|
||||||
@@ -146,10 +208,38 @@ type Config = {
|
|||||||
* key and can't attach the policy, you can set this to true.
|
* key and can't attach the policy, you can set this to true.
|
||||||
*/
|
*/
|
||||||
allowAwsLogging?: boolean;
|
allowAwsLogging?: boolean;
|
||||||
|
/**
|
||||||
|
* Path to the SQLite database file for storing data such as event logs. By
|
||||||
|
* default, the database will be stored at `data/database.sqlite`.
|
||||||
|
*
|
||||||
|
* Ensure target is writable by the server process, and be careful not to
|
||||||
|
* select a path that is served publicly. The default path is safe.
|
||||||
|
*/
|
||||||
|
sqliteDataPath?: string;
|
||||||
|
/**
|
||||||
|
* Whether to log events, such as generated completions, to the database.
|
||||||
|
* Events are associated with IP+user token pairs. If user_token mode is
|
||||||
|
* disabled, no events will be logged.
|
||||||
|
*
|
||||||
|
* Currently there is no pruning mechanism for the events table, so it will
|
||||||
|
* grow indefinitely. You may want to periodically prune the table manually.
|
||||||
|
*/
|
||||||
|
eventLogging?: boolean;
|
||||||
|
/**
|
||||||
|
* When hashing prompt histories, how many messages to trim from the end.
|
||||||
|
* If zero, only the full prompt hash will be stored.
|
||||||
|
* If greater than zero, for each number N, a hash of the prompt with the
|
||||||
|
* last N messages removed will be stored.
|
||||||
|
*
|
||||||
|
* Experimental function, config may change in future versions.
|
||||||
|
*/
|
||||||
|
eventLoggingTrim?: number;
|
||||||
/** Whether prompts and responses should be logged to persistent storage. */
|
/** Whether prompts and responses should be logged to persistent storage. */
|
||||||
promptLogging?: boolean;
|
promptLogging?: boolean;
|
||||||
/** Which prompt logging backend to use. */
|
/** Which prompt logging backend to use. */
|
||||||
promptLoggingBackend?: "google_sheets";
|
promptLoggingBackend?: "google_sheets" | "file";
|
||||||
|
/** Prefix for prompt logging files when using the file backend. */
|
||||||
|
promptLoggingFilePrefix?: string;
|
||||||
/** Base64-encoded Google Sheets API key. */
|
/** Base64-encoded Google Sheets API key. */
|
||||||
googleSheetsKey?: string;
|
googleSheetsKey?: string;
|
||||||
/** Google Sheets spreadsheet ID. */
|
/** Google Sheets spreadsheet ID. */
|
||||||
@@ -249,11 +339,33 @@ type Config = {
|
|||||||
* risk.
|
* risk.
|
||||||
*/
|
*/
|
||||||
allowOpenAIToolUsage?: boolean;
|
allowOpenAIToolUsage?: boolean;
|
||||||
|
/**
|
||||||
|
* Whether to allow prompts containing images, for use with multimodal models.
|
||||||
|
* Avoid giving this to untrusted users, as they can submit illegal content.
|
||||||
|
*
|
||||||
|
* Applies to GPT-4 Vision and Claude Vision. Users with `special` role are
|
||||||
|
* exempt from this restriction.
|
||||||
|
*/
|
||||||
|
allowImagePrompts?: boolean;
|
||||||
/**
|
/**
|
||||||
* Allows overriding the default proxy endpoint route. Defaults to /proxy.
|
* Allows overriding the default proxy endpoint route. Defaults to /proxy.
|
||||||
* A leading slash is required.
|
* A leading slash is required.
|
||||||
*/
|
*/
|
||||||
proxyEndpointRoute: string;
|
proxyEndpointRoute: string;
|
||||||
|
/**
|
||||||
|
* If set, only requests from these IP addresses will be permitted to use the
|
||||||
|
* admin API and UI. Provide a comma-separated list of IP addresses or CIDR
|
||||||
|
* ranges. If not set, the admin API and UI will be open to all requests.
|
||||||
|
*/
|
||||||
|
adminWhitelist: string[];
|
||||||
|
/**
|
||||||
|
* If set, requests from these IP addresses will be blocked from using the
|
||||||
|
* application. Provide a comma-separated list of IP addresses or CIDR ranges.
|
||||||
|
* If not set, no IP addresses will be blocked.
|
||||||
|
*
|
||||||
|
* Takes precedence over the adminWhitelist.
|
||||||
|
*/
|
||||||
|
ipBlacklist: string[];
|
||||||
};
|
};
|
||||||
|
|
||||||
// To change configs, create a file called .env in the root directory.
|
// To change configs, create a file called .env in the root directory.
|
||||||
@@ -270,10 +382,22 @@ export const config: Config = {
|
|||||||
proxyKey: getEnvWithDefault("PROXY_KEY", ""),
|
proxyKey: getEnvWithDefault("PROXY_KEY", ""),
|
||||||
adminKey: getEnvWithDefault("ADMIN_KEY", ""),
|
adminKey: getEnvWithDefault("ADMIN_KEY", ""),
|
||||||
serviceInfoPassword: getEnvWithDefault("SERVICE_INFO_PASSWORD", ""),
|
serviceInfoPassword: getEnvWithDefault("SERVICE_INFO_PASSWORD", ""),
|
||||||
|
sqliteDataPath: getEnvWithDefault(
|
||||||
|
"SQLITE_DATA_PATH",
|
||||||
|
path.join(DATA_DIR, "database.sqlite")
|
||||||
|
),
|
||||||
|
eventLogging: getEnvWithDefault("EVENT_LOGGING", false),
|
||||||
|
eventLoggingTrim: getEnvWithDefault("EVENT_LOGGING_TRIM", 5),
|
||||||
gatekeeper: getEnvWithDefault("GATEKEEPER", "none"),
|
gatekeeper: getEnvWithDefault("GATEKEEPER", "none"),
|
||||||
gatekeeperStore: getEnvWithDefault("GATEKEEPER_STORE", "memory"),
|
gatekeeperStore: getEnvWithDefault("GATEKEEPER_STORE", "memory"),
|
||||||
maxIpsPerUser: getEnvWithDefault("MAX_IPS_PER_USER", 0),
|
maxIpsPerUser: getEnvWithDefault("MAX_IPS_PER_USER", 0),
|
||||||
maxIpsAutoBan: getEnvWithDefault("MAX_IPS_AUTO_BAN", true),
|
maxIpsAutoBan: getEnvWithDefault("MAX_IPS_AUTO_BAN", false),
|
||||||
|
captchaMode: getEnvWithDefault("CAPTCHA_MODE", "none"),
|
||||||
|
powTokenHours: getEnvWithDefault("POW_TOKEN_HOURS", 24),
|
||||||
|
powTokenMaxIps: getEnvWithDefault("POW_TOKEN_MAX_IPS", 2),
|
||||||
|
powDifficultyLevel: getEnvWithDefault("POW_DIFFICULTY_LEVEL", "low"),
|
||||||
|
powChallengeTimeout: getEnvWithDefault("POW_CHALLENGE_TIMEOUT", 30),
|
||||||
|
powTokenPurgeHours: getEnvWithDefault("POW_TOKEN_PURGE_HOURS", 48),
|
||||||
firebaseRtdbUrl: getEnvWithDefault("FIREBASE_RTDB_URL", undefined),
|
firebaseRtdbUrl: getEnvWithDefault("FIREBASE_RTDB_URL", undefined),
|
||||||
firebaseKey: getEnvWithDefault("FIREBASE_KEY", undefined),
|
firebaseKey: getEnvWithDefault("FIREBASE_KEY", undefined),
|
||||||
textModelRateLimit: getEnvWithDefault("TEXT_MODEL_RATE_LIMIT", 4),
|
textModelRateLimit: getEnvWithDefault("TEXT_MODEL_RATE_LIMIT", 4),
|
||||||
@@ -296,6 +420,7 @@ export const config: Config = {
|
|||||||
"gpt4",
|
"gpt4",
|
||||||
"gpt4-32k",
|
"gpt4-32k",
|
||||||
"gpt4-turbo",
|
"gpt4-turbo",
|
||||||
|
"gpt4o",
|
||||||
"claude",
|
"claude",
|
||||||
"claude-opus",
|
"claude-opus",
|
||||||
"gemini-pro",
|
"gemini-pro",
|
||||||
@@ -304,10 +429,12 @@ export const config: Config = {
|
|||||||
"mistral-medium",
|
"mistral-medium",
|
||||||
"mistral-large",
|
"mistral-large",
|
||||||
"aws-claude",
|
"aws-claude",
|
||||||
|
"aws-claude-opus",
|
||||||
"azure-turbo",
|
"azure-turbo",
|
||||||
"azure-gpt4",
|
"azure-gpt4",
|
||||||
"azure-gpt4-turbo",
|
|
||||||
"azure-gpt4-32k",
|
"azure-gpt4-32k",
|
||||||
|
"azure-gpt4-turbo",
|
||||||
|
"azure-gpt4o",
|
||||||
]),
|
]),
|
||||||
rejectPhrases: parseCsv(getEnvWithDefault("REJECT_PHRASES", "")),
|
rejectPhrases: parseCsv(getEnvWithDefault("REJECT_PHRASES", "")),
|
||||||
rejectMessage: getEnvWithDefault(
|
rejectMessage: getEnvWithDefault(
|
||||||
@@ -320,6 +447,10 @@ export const config: Config = {
|
|||||||
allowAwsLogging: getEnvWithDefault("ALLOW_AWS_LOGGING", false),
|
allowAwsLogging: getEnvWithDefault("ALLOW_AWS_LOGGING", false),
|
||||||
promptLogging: getEnvWithDefault("PROMPT_LOGGING", false),
|
promptLogging: getEnvWithDefault("PROMPT_LOGGING", false),
|
||||||
promptLoggingBackend: getEnvWithDefault("PROMPT_LOGGING_BACKEND", undefined),
|
promptLoggingBackend: getEnvWithDefault("PROMPT_LOGGING_BACKEND", undefined),
|
||||||
|
promptLoggingFilePrefix: getEnvWithDefault(
|
||||||
|
"PROMPT_LOGGING_FILE_PREFIX",
|
||||||
|
"prompt-logs"
|
||||||
|
),
|
||||||
googleSheetsKey: getEnvWithDefault("GOOGLE_SHEETS_KEY", undefined),
|
googleSheetsKey: getEnvWithDefault("GOOGLE_SHEETS_KEY", undefined),
|
||||||
googleSheetsSpreadsheetId: getEnvWithDefault(
|
googleSheetsSpreadsheetId: getEnvWithDefault(
|
||||||
"GOOGLE_SHEETS_SPREADSHEET_ID",
|
"GOOGLE_SHEETS_SPREADSHEET_ID",
|
||||||
@@ -348,20 +479,46 @@ export const config: Config = {
|
|||||||
staticServiceInfo: getEnvWithDefault("STATIC_SERVICE_INFO", false),
|
staticServiceInfo: getEnvWithDefault("STATIC_SERVICE_INFO", false),
|
||||||
trustedProxies: getEnvWithDefault("TRUSTED_PROXIES", 1),
|
trustedProxies: getEnvWithDefault("TRUSTED_PROXIES", 1),
|
||||||
allowOpenAIToolUsage: getEnvWithDefault("ALLOW_OPENAI_TOOL_USAGE", false),
|
allowOpenAIToolUsage: getEnvWithDefault("ALLOW_OPENAI_TOOL_USAGE", false),
|
||||||
|
allowImagePrompts: getEnvWithDefault("ALLOW_IMAGE_PROMPTS", false),
|
||||||
proxyEndpointRoute: getEnvWithDefault("PROXY_ENDPOINT_ROUTE", "/proxy"),
|
proxyEndpointRoute: getEnvWithDefault("PROXY_ENDPOINT_ROUTE", "/proxy"),
|
||||||
|
adminWhitelist: parseCsv(getEnvWithDefault("ADMIN_WHITELIST", "0.0.0.0/0")),
|
||||||
|
ipBlacklist: parseCsv(getEnvWithDefault("IP_BLACKLIST", "")),
|
||||||
} as const;
|
} as const;
|
||||||
|
|
||||||
function generateCookieSecret() {
|
function generateSigningKey() {
|
||||||
if (process.env.COOKIE_SECRET !== undefined) {
|
if (process.env.COOKIE_SECRET !== undefined) {
|
||||||
|
// legacy, replaced by SIGNING_KEY
|
||||||
return process.env.COOKIE_SECRET;
|
return process.env.COOKIE_SECRET;
|
||||||
|
} else if (process.env.SIGNING_KEY !== undefined) {
|
||||||
|
return process.env.SIGNING_KEY;
|
||||||
}
|
}
|
||||||
|
|
||||||
const seed = "" + config.adminKey + config.openaiKey + config.anthropicKey;
|
const secrets = [
|
||||||
const crypto = require("crypto");
|
config.adminKey,
|
||||||
|
config.openaiKey,
|
||||||
|
config.anthropicKey,
|
||||||
|
config.googleAIKey,
|
||||||
|
config.mistralAIKey,
|
||||||
|
config.awsCredentials,
|
||||||
|
config.azureCredentials,
|
||||||
|
];
|
||||||
|
if (secrets.filter((s) => s).length === 0) {
|
||||||
|
startupLogger.warn(
|
||||||
|
"No SIGNING_KEY or secrets are set. All sessions, cookies, and proofs of work will be invalidated on restart."
|
||||||
|
);
|
||||||
|
return crypto.randomBytes(32).toString("hex");
|
||||||
|
}
|
||||||
|
|
||||||
|
startupLogger.info("No SIGNING_KEY set; one will be generated from secrets.");
|
||||||
|
startupLogger.info(
|
||||||
|
"It's recommended to set SIGNING_KEY explicitly to ensure users' sessions and cookies always persist across restarts."
|
||||||
|
);
|
||||||
|
const seed = secrets.map((s) => s || "n/a").join("");
|
||||||
return crypto.createHash("sha256").update(seed).digest("hex");
|
return crypto.createHash("sha256").update(seed).digest("hex");
|
||||||
}
|
}
|
||||||
|
|
||||||
export const COOKIE_SECRET = generateCookieSecret();
|
const signingKey = generateSigningKey();
|
||||||
|
export const COOKIE_SECRET = signingKey;
|
||||||
|
|
||||||
export async function assertConfigIsValid() {
|
export async function assertConfigIsValid() {
|
||||||
if (process.env.MODEL_RATE_LIMIT !== undefined) {
|
if (process.env.MODEL_RATE_LIMIT !== undefined) {
|
||||||
@@ -377,6 +534,12 @@ export async function assertConfigIsValid() {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (config.promptLogging && !config.promptLoggingBackend) {
|
||||||
|
throw new Error(
|
||||||
|
"Prompt logging is enabled but no backend is configured. Set PROMPT_LOGGING_BACKEND to 'google_sheets' or 'file'."
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
if (!["none", "proxy_key", "user_token"].includes(config.gatekeeper)) {
|
if (!["none", "proxy_key", "user_token"].includes(config.gatekeeper)) {
|
||||||
throw new Error(
|
throw new Error(
|
||||||
`Invalid gatekeeper mode: ${config.gatekeeper}. Must be one of: none, proxy_key, user_token.`
|
`Invalid gatekeeper mode: ${config.gatekeeper}. Must be one of: none, proxy_key, user_token.`
|
||||||
@@ -389,15 +552,32 @@ export async function assertConfigIsValid() {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
if (config.gatekeeper === "proxy_key" && !config.proxyKey) {
|
if (
|
||||||
|
config.captchaMode === "proof_of_work" &&
|
||||||
|
config.gatekeeper !== "user_token"
|
||||||
|
) {
|
||||||
throw new Error(
|
throw new Error(
|
||||||
"`proxy_key` gatekeeper mode requires a `PROXY_KEY` to be set."
|
"Captcha mode 'proof_of_work' requires gatekeeper mode 'user_token'."
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
if (config.gatekeeper !== "proxy_key" && config.proxyKey) {
|
if (config.captchaMode === "proof_of_work") {
|
||||||
|
const val = config.powDifficultyLevel;
|
||||||
|
const isDifficulty =
|
||||||
|
typeof val === "string" &&
|
||||||
|
["low", "medium", "high", "extreme"].includes(val);
|
||||||
|
const isIterations =
|
||||||
|
typeof val === "number" && Number.isInteger(val) && val > 0;
|
||||||
|
if (!isDifficulty && !isIterations) {
|
||||||
|
throw new Error(
|
||||||
|
"Invalid POW_DIFFICULTY_LEVEL. Must be one of: low, medium, high, extreme, or a positive integer."
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (config.gatekeeper === "proxy_key" && !config.proxyKey) {
|
||||||
throw new Error(
|
throw new Error(
|
||||||
"`PROXY_KEY` is set, but gatekeeper mode is not `proxy_key`. Make sure to set `GATEKEEPER=proxy_key`."
|
"`proxy_key` gatekeeper mode requires a `PROXY_KEY` to be set."
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -453,9 +633,13 @@ export const OMITTED_KEYS = [
|
|||||||
"rejectPhrases",
|
"rejectPhrases",
|
||||||
"rejectMessage",
|
"rejectMessage",
|
||||||
"showTokenCosts",
|
"showTokenCosts",
|
||||||
|
"promptLoggingFilePrefix",
|
||||||
"googleSheetsKey",
|
"googleSheetsKey",
|
||||||
"firebaseKey",
|
"firebaseKey",
|
||||||
"firebaseRtdbUrl",
|
"firebaseRtdbUrl",
|
||||||
|
"sqliteDataPath",
|
||||||
|
"eventLogging",
|
||||||
|
"eventLoggingTrim",
|
||||||
"gatekeeperStore",
|
"gatekeeperStore",
|
||||||
"maxIpsPerUser",
|
"maxIpsPerUser",
|
||||||
"blockedOrigins",
|
"blockedOrigins",
|
||||||
@@ -469,6 +653,9 @@ export const OMITTED_KEYS = [
|
|||||||
"allowedModelFamilies",
|
"allowedModelFamilies",
|
||||||
"trustedProxies",
|
"trustedProxies",
|
||||||
"proxyEndpointRoute",
|
"proxyEndpointRoute",
|
||||||
|
"adminWhitelist",
|
||||||
|
"ipBlacklist",
|
||||||
|
"powTokenPurgeHours",
|
||||||
] satisfies (keyof Config)[];
|
] satisfies (keyof Config)[];
|
||||||
type OmitKeys = (typeof OMITTED_KEYS)[number];
|
type OmitKeys = (typeof OMITTED_KEYS)[number];
|
||||||
|
|
||||||
|
|||||||
+34
-15
@@ -16,6 +16,7 @@ const MODEL_FAMILY_FRIENDLY_NAME: { [f in ModelFamily]: string } = {
|
|||||||
gpt4: "GPT-4",
|
gpt4: "GPT-4",
|
||||||
"gpt4-32k": "GPT-4 32k",
|
"gpt4-32k": "GPT-4 32k",
|
||||||
"gpt4-turbo": "GPT-4 Turbo",
|
"gpt4-turbo": "GPT-4 Turbo",
|
||||||
|
gpt4o: "GPT-4o",
|
||||||
"dall-e": "DALL-E",
|
"dall-e": "DALL-E",
|
||||||
claude: "Claude (Sonnet)",
|
claude: "Claude (Sonnet)",
|
||||||
"claude-opus": "Claude (Opus)",
|
"claude-opus": "Claude (Opus)",
|
||||||
@@ -25,10 +26,12 @@ const MODEL_FAMILY_FRIENDLY_NAME: { [f in ModelFamily]: string } = {
|
|||||||
"mistral-medium": "Mistral Medium",
|
"mistral-medium": "Mistral Medium",
|
||||||
"mistral-large": "Mistral Large",
|
"mistral-large": "Mistral Large",
|
||||||
"aws-claude": "AWS Claude (Sonnet)",
|
"aws-claude": "AWS Claude (Sonnet)",
|
||||||
|
"aws-claude-opus": "AWS Claude (Opus)",
|
||||||
"azure-turbo": "Azure GPT-3.5 Turbo",
|
"azure-turbo": "Azure GPT-3.5 Turbo",
|
||||||
"azure-gpt4": "Azure GPT-4",
|
"azure-gpt4": "Azure GPT-4",
|
||||||
"azure-gpt4-32k": "Azure GPT-4 32k",
|
"azure-gpt4-32k": "Azure GPT-4 32k",
|
||||||
"azure-gpt4-turbo": "Azure GPT-4 Turbo",
|
"azure-gpt4-turbo": "Azure GPT-4 Turbo",
|
||||||
|
"azure-gpt4o": "Azure GPT-4o",
|
||||||
"azure-dall-e": "Azure DALL-E",
|
"azure-dall-e": "Azure DALL-E",
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -60,36 +63,42 @@ export function renderPage(info: ServiceInfo) {
|
|||||||
const title = getServerTitle();
|
const title = getServerTitle();
|
||||||
const headerHtml = buildInfoPageHeader(info);
|
const headerHtml = buildInfoPageHeader(info);
|
||||||
|
|
||||||
return `<!DOCTYPE html>
|
return `<!doctype html>
|
||||||
<html lang="en">
|
<html lang="en">
|
||||||
<head>
|
<head>
|
||||||
<meta charset="utf-8" />
|
<meta charset="utf-8" />
|
||||||
<meta name="robots" content="noindex" />
|
<meta name="robots" content="noindex" />
|
||||||
<title>${title}</title>
|
<title>${title}</title>
|
||||||
|
<link rel="stylesheet" href="/res/css/reset.css" media="screen" />
|
||||||
|
<link rel="stylesheet" href="/res/css/sakura.css" media="screen" />
|
||||||
|
<link rel="stylesheet" href="/res/css/sakura-dark.css" media="screen and (prefers-color-scheme: dark)" />
|
||||||
<style>
|
<style>
|
||||||
body {
|
body {
|
||||||
font-family: sans-serif;
|
font-family: sans-serif;
|
||||||
background-color: #f0f0f0;
|
|
||||||
padding: 1em;
|
padding: 1em;
|
||||||
|
max-width: 900px;
|
||||||
|
margin: 0;
|
||||||
}
|
}
|
||||||
@media (prefers-color-scheme: dark) {
|
|
||||||
body {
|
.self-service-links {
|
||||||
background-color: #222;
|
display: flex;
|
||||||
color: #eee;
|
justify-content: center;
|
||||||
}
|
margin-bottom: 1em;
|
||||||
|
padding: 0.5em;
|
||||||
a:link, a:visited {
|
font-size: 0.8em;
|
||||||
color: #bbe;
|
}
|
||||||
}
|
|
||||||
|
.self-service-links a {
|
||||||
|
margin: 0 0.5em;
|
||||||
}
|
}
|
||||||
</style>
|
</style>
|
||||||
</head>
|
</head>
|
||||||
<body>
|
<body>
|
||||||
${headerHtml}
|
${headerHtml}
|
||||||
<hr />
|
<hr />
|
||||||
|
${getSelfServiceLinks()}
|
||||||
<h2>Service Info</h2>
|
<h2>Service Info</h2>
|
||||||
<pre>${JSON.stringify(info, null, 2)}</pre>
|
<pre>${JSON.stringify(info, null, 2)}</pre>
|
||||||
${getSelfServiceLinks()}
|
|
||||||
</body>
|
</body>
|
||||||
</html>`;
|
</html>`;
|
||||||
}
|
}
|
||||||
@@ -143,7 +152,15 @@ This proxy keeps full logs of all prompts and AI responses. Prompt logs are anon
|
|||||||
|
|
||||||
function getSelfServiceLinks() {
|
function getSelfServiceLinks() {
|
||||||
if (config.gatekeeper !== "user_token") return "";
|
if (config.gatekeeper !== "user_token") return "";
|
||||||
return `<footer style="font-size: 0.8em;"><hr /><a target="_blank" href="/user/lookup">Check your user token info</a></footer>`;
|
|
||||||
|
const links = [["Check your user token", "/user/lookup"]];
|
||||||
|
if (config.captchaMode !== "none") {
|
||||||
|
links.unshift(["Request a user token", "/user/captcha"]);
|
||||||
|
}
|
||||||
|
|
||||||
|
return `<div class="self-service-links">${links
|
||||||
|
.map(([text, link]) => `<a target="_blank" href="${link}">${text}</a>`)
|
||||||
|
.join(" | ")}</div>`;
|
||||||
}
|
}
|
||||||
|
|
||||||
function getServerTitle() {
|
function getServerTitle() {
|
||||||
@@ -190,7 +207,7 @@ function buildRecentImageSection() {
|
|||||||
</div>`;
|
</div>`;
|
||||||
}
|
}
|
||||||
html += `</div>`;
|
html += `</div>`;
|
||||||
html += `<p style="clear: both; text-align: center;"><a href="/user/image-history">View all recent images</a></p>`
|
html += `<p style="clear: both; text-align: center;"><a href="/user/image-history">View all recent images</a></p>`;
|
||||||
|
|
||||||
return html;
|
return html;
|
||||||
}
|
}
|
||||||
@@ -201,7 +218,9 @@ function escapeHtml(unsafe: string) {
|
|||||||
.replace(/</g, "<")
|
.replace(/</g, "<")
|
||||||
.replace(/>/g, ">")
|
.replace(/>/g, ">")
|
||||||
.replace(/"/g, """)
|
.replace(/"/g, """)
|
||||||
.replace(/'/g, "'");
|
.replace(/'/g, "'")
|
||||||
|
.replace(/\[/g, "[")
|
||||||
|
.replace(/]/g, "]");
|
||||||
}
|
}
|
||||||
|
|
||||||
function getExternalUrlForHuggingfaceSpaceId(spaceId: string) {
|
function getExternalUrlForHuggingfaceSpaceId(spaceId: string) {
|
||||||
|
|||||||
@@ -156,7 +156,7 @@ function transformAnthropicTextResponseToOpenAI(
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
function transformAnthropicChatResponseToOpenAI(
|
export function transformAnthropicChatResponseToOpenAI(
|
||||||
anthropicBody: Record<string, any>
|
anthropicBody: Record<string, any>
|
||||||
): Record<string, any> {
|
): Record<string, any> {
|
||||||
return {
|
return {
|
||||||
|
|||||||
+40
-12
@@ -16,7 +16,7 @@ import {
|
|||||||
ProxyResHandlerWithBody,
|
ProxyResHandlerWithBody,
|
||||||
createOnProxyResHandler,
|
createOnProxyResHandler,
|
||||||
} from "./middleware/response";
|
} from "./middleware/response";
|
||||||
import { transformAnthropicChatResponseToAnthropicText } from "./anthropic";
|
import { transformAnthropicChatResponseToAnthropicText, transformAnthropicChatResponseToOpenAI } from "./anthropic";
|
||||||
import { sendErrorToClient } from "./middleware/response/error-generator";
|
import { sendErrorToClient } from "./middleware/response/error-generator";
|
||||||
|
|
||||||
const LATEST_AWS_V2_MINOR_VERSION = "1";
|
const LATEST_AWS_V2_MINOR_VERSION = "1";
|
||||||
@@ -37,6 +37,7 @@ const getModelsResponse = () => {
|
|||||||
"anthropic.claude-v2:1",
|
"anthropic.claude-v2:1",
|
||||||
"anthropic.claude-3-haiku-20240307-v1:0",
|
"anthropic.claude-3-haiku-20240307-v1:0",
|
||||||
"anthropic.claude-3-sonnet-20240229-v1:0",
|
"anthropic.claude-3-sonnet-20240229-v1:0",
|
||||||
|
"anthropic.claude-3-opus-20240229-v1:0",
|
||||||
];
|
];
|
||||||
|
|
||||||
const models = variants.map((id) => ({
|
const models = variants.map((id) => ({
|
||||||
@@ -76,8 +77,10 @@ const awsResponseHandler: ProxyResHandlerWithBody = async (
|
|||||||
req.log.info("Transforming Anthropic Text back to OpenAI format");
|
req.log.info("Transforming Anthropic Text back to OpenAI format");
|
||||||
newBody = transformAwsTextResponseToOpenAI(body, req);
|
newBody = transformAwsTextResponseToOpenAI(body, req);
|
||||||
break;
|
break;
|
||||||
// case "openai<-anthropic-chat":
|
case "openai<-anthropic-chat":
|
||||||
// todo: implement this
|
req.log.info("Transforming AWS Anthropic Chat back to OpenAI format");
|
||||||
|
newBody = transformAnthropicChatResponseToOpenAI(body);
|
||||||
|
break;
|
||||||
case "anthropic-text<-anthropic-chat":
|
case "anthropic-text<-anthropic-chat":
|
||||||
req.log.info("Transforming AWS Anthropic Chat back to Text format");
|
req.log.info("Transforming AWS Anthropic Chat back to Text format");
|
||||||
newBody = transformAnthropicChatResponseToAnthropicText(body);
|
newBody = transformAnthropicChatResponseToAnthropicText(body);
|
||||||
@@ -159,7 +162,7 @@ const textToChatPreprocessor = createPreprocessorMiddleware(
|
|||||||
* Routes text completion prompts to aws anthropic-chat if they need translation
|
* Routes text completion prompts to aws anthropic-chat if they need translation
|
||||||
* (claude-3 based models do not support the old text completion endpoint).
|
* (claude-3 based models do not support the old text completion endpoint).
|
||||||
*/
|
*/
|
||||||
const awsTextCompletionRouter: RequestHandler = (req, res, next) => {
|
const preprocessAwsTextRequest: RequestHandler = (req, res, next) => {
|
||||||
if (req.body.model?.includes("claude-3")) {
|
if (req.body.model?.includes("claude-3")) {
|
||||||
textToChatPreprocessor(req, res, next);
|
textToChatPreprocessor(req, res, next);
|
||||||
} else {
|
} else {
|
||||||
@@ -167,10 +170,32 @@ const awsTextCompletionRouter: RequestHandler = (req, res, next) => {
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
|
const oaiToAwsTextPreprocessor = createPreprocessorMiddleware(
|
||||||
|
{ inApi: "openai", outApi: "anthropic-text", service: "aws" },
|
||||||
|
{ afterTransform: [maybeReassignModel] }
|
||||||
|
);
|
||||||
|
|
||||||
|
const oaiToAwsChatPreprocessor = createPreprocessorMiddleware(
|
||||||
|
{ inApi: "openai", outApi: "anthropic-chat", service: "aws" },
|
||||||
|
{ afterTransform: [maybeReassignModel] }
|
||||||
|
);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Routes an OpenAI prompt to either the legacy Claude text completion endpoint
|
||||||
|
* or the new Claude chat completion endpoint, based on the requested model.
|
||||||
|
*/
|
||||||
|
const preprocessOpenAICompatRequest: RequestHandler = (req, res, next) => {
|
||||||
|
if (req.body.model?.includes("claude-3")) {
|
||||||
|
oaiToAwsChatPreprocessor(req, res, next);
|
||||||
|
} else {
|
||||||
|
oaiToAwsTextPreprocessor(req, res, next);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
const awsRouter = Router();
|
const awsRouter = Router();
|
||||||
awsRouter.get("/v1/models", handleModelRequest);
|
awsRouter.get("/v1/models", handleModelRequest);
|
||||||
// Native(ish) Anthropic text completion endpoint.
|
// Native(ish) Anthropic text completion endpoint.
|
||||||
awsRouter.post("/v1/complete", ipLimiter, awsTextCompletionRouter, awsProxy);
|
awsRouter.post("/v1/complete", ipLimiter, preprocessAwsTextRequest, awsProxy);
|
||||||
// Native Anthropic chat completion endpoint.
|
// Native Anthropic chat completion endpoint.
|
||||||
awsRouter.post(
|
awsRouter.post(
|
||||||
"/v1/messages",
|
"/v1/messages",
|
||||||
@@ -198,10 +223,7 @@ awsRouter.post(
|
|||||||
awsRouter.post(
|
awsRouter.post(
|
||||||
"/v1/chat/completions",
|
"/v1/chat/completions",
|
||||||
ipLimiter,
|
ipLimiter,
|
||||||
createPreprocessorMiddleware(
|
preprocessOpenAICompatRequest,
|
||||||
{ inApi: "openai", outApi: "anthropic-text", service: "aws" },
|
|
||||||
{ afterTransform: [maybeReassignModel] }
|
|
||||||
),
|
|
||||||
awsProxy
|
awsProxy
|
||||||
);
|
);
|
||||||
|
|
||||||
@@ -222,7 +244,7 @@ function maybeReassignModel(req: Request) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
const pattern =
|
const pattern =
|
||||||
/^(claude-)?(instant-)?(v)?(\d+)(\.(\d+))?(-\d+k)?(-sonnet-?|-opus-?)(\d*)/i;
|
/^(claude-)?(instant-)?(v)?(\d+)(\.(\d+))?(-\d+k)?(-sonnet-?|-opus-?|-haiku-?)(\d*)/i;
|
||||||
const match = model.match(pattern);
|
const match = model.match(pattern);
|
||||||
|
|
||||||
// If there's no match, return the latest v2 model
|
// If there's no match, return the latest v2 model
|
||||||
@@ -257,10 +279,16 @@ function maybeReassignModel(req: Request) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// AWS currently only supports one v3 model.
|
// AWS currently only supports one v3 model.
|
||||||
const variant = match[8]; // sonnet or opus
|
const variant = match[8]; // sonnet, opus, or haiku
|
||||||
const variantVersion = match[9];
|
const variantVersion = match[9];
|
||||||
if (major === "3") {
|
if (major === "3") {
|
||||||
req.body.model = "anthropic.claude-3-sonnet-20240229-v1:0";
|
if (variant.includes("opus")) {
|
||||||
|
req.body.model = "anthropic.claude-3-opus-20240229-v1:0";
|
||||||
|
} else if (variant.includes("haiku")) {
|
||||||
|
req.body.model = "anthropic.claude-3-haiku-20240307-v1:0";
|
||||||
|
} else {
|
||||||
|
req.body.model = "anthropic.claude-3-sonnet-20240229-v1:0";
|
||||||
|
}
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
+41
-10
@@ -1,6 +1,7 @@
|
|||||||
import type { Request, RequestHandler } from "express";
|
import type { Request, Response, RequestHandler } from "express";
|
||||||
import { config } from "../config";
|
import { config } from "../config";
|
||||||
import { authenticate, getUser } from "../shared/users/user-store";
|
import { authenticate, getUser } from "../shared/users/user-store";
|
||||||
|
import { sendErrorToClient } from "./middleware/response/error-generator";
|
||||||
|
|
||||||
const GATEKEEPER = config.gatekeeper;
|
const GATEKEEPER = config.gatekeeper;
|
||||||
const PROXY_KEY = config.proxyKey;
|
const PROXY_KEY = config.proxyKey;
|
||||||
@@ -50,9 +51,9 @@ export const gatekeeper: RequestHandler = (req, res, next) => {
|
|||||||
// IP alone to distinguish between them and prevent usertoken sharing.
|
// IP alone to distinguish between them and prevent usertoken sharing.
|
||||||
// Risu sends a signed token in the request headers with an anonymous user
|
// Risu sends a signed token in the request headers with an anonymous user
|
||||||
// ID that we can instead use to associate requests with an individual.
|
// ID that we can instead use to associate requests with an individual.
|
||||||
const ip = req.risuToken?.length ?
|
const ip = req.risuToken?.length
|
||||||
`risu${req.risuToken}-${req.ip}` :
|
? `risu${req.risuToken}-${req.ip}`
|
||||||
req.ip;
|
: req.ip;
|
||||||
|
|
||||||
const { user, result } = authenticate(token, ip);
|
const { user, result } = authenticate(token, ip);
|
||||||
|
|
||||||
@@ -61,17 +62,47 @@ export const gatekeeper: RequestHandler = (req, res, next) => {
|
|||||||
req.user = user;
|
req.user = user;
|
||||||
return next();
|
return next();
|
||||||
case "limited":
|
case "limited":
|
||||||
return res.status(403).json({
|
return sendError(
|
||||||
error: `Forbidden: no more IPs can authenticate with this token`,
|
req,
|
||||||
});
|
res,
|
||||||
|
403,
|
||||||
|
"Forbidden: no more IPs can authenticate with this user token"
|
||||||
|
);
|
||||||
case "disabled":
|
case "disabled":
|
||||||
const bannedUser = getUser(token);
|
const bannedUser = getUser(token);
|
||||||
if (bannedUser?.disabledAt) {
|
if (bannedUser?.disabledAt) {
|
||||||
const reason = bannedUser.disabledReason || "Token disabled";
|
const reason = bannedUser.disabledReason || "User token disabled";
|
||||||
return res.status(403).json({ error: `Forbidden: ${reason}` });
|
return sendError(req, res, 403, `Forbidden: ${reason}`);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
res.status(401).json({ error: "Unauthorized" });
|
sendError(req, res, 401, "Unauthorized");
|
||||||
};
|
};
|
||||||
|
|
||||||
|
function sendError(
|
||||||
|
req: Request,
|
||||||
|
res: Response,
|
||||||
|
status: number,
|
||||||
|
message: string
|
||||||
|
) {
|
||||||
|
const isPost = req.method === "POST";
|
||||||
|
const hasBody = isPost && req.body;
|
||||||
|
const hasModel = hasBody && req.body.model;
|
||||||
|
|
||||||
|
if (!hasModel) {
|
||||||
|
return res.status(status).json({ error: message });
|
||||||
|
}
|
||||||
|
|
||||||
|
sendErrorToClient({
|
||||||
|
req,
|
||||||
|
res,
|
||||||
|
options: {
|
||||||
|
title: `Proxy gatekeeper error (HTTP ${status})`,
|
||||||
|
message,
|
||||||
|
format: "unknown",
|
||||||
|
statusCode: status,
|
||||||
|
reqId: req.id,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|||||||
@@ -3,10 +3,10 @@ import http from "http";
|
|||||||
import httpProxy from "http-proxy";
|
import httpProxy from "http-proxy";
|
||||||
import { ZodError } from "zod";
|
import { ZodError } from "zod";
|
||||||
import { generateErrorMessage } from "zod-error";
|
import { generateErrorMessage } from "zod-error";
|
||||||
|
import { HttpError } from "../../shared/errors";
|
||||||
import { assertNever } from "../../shared/utils";
|
import { assertNever } from "../../shared/utils";
|
||||||
import { QuotaExceededError } from "./request/preprocessors/apply-quota-limits";
|
import { QuotaExceededError } from "./request/preprocessors/apply-quota-limits";
|
||||||
import { sendErrorToClient } from "./response/error-generator";
|
import { sendErrorToClient } from "./response/error-generator";
|
||||||
import { HttpError } from "../../shared/errors";
|
|
||||||
|
|
||||||
const OPENAI_CHAT_COMPLETION_ENDPOINT = "/v1/chat/completions";
|
const OPENAI_CHAT_COMPLETION_ENDPOINT = "/v1/chat/completions";
|
||||||
const OPENAI_TEXT_COMPLETION_ENDPOINT = "/v1/completions";
|
const OPENAI_TEXT_COMPLETION_ENDPOINT = "/v1/completions";
|
||||||
@@ -54,13 +54,13 @@ export function sendProxyError(
|
|||||||
const msg =
|
const msg =
|
||||||
statusCode === 500
|
statusCode === 500
|
||||||
? `The proxy encountered an error while trying to process your prompt.`
|
? `The proxy encountered an error while trying to process your prompt.`
|
||||||
: `The proxy encountered an error while trying to send your prompt to the upstream service.`;
|
: `The proxy encountered an error while trying to send your prompt to the API.`;
|
||||||
|
|
||||||
sendErrorToClient({
|
sendErrorToClient({
|
||||||
options: {
|
options: {
|
||||||
format: req.inboundApi,
|
format: req.inboundApi,
|
||||||
title: `Proxy error (HTTP ${statusCode} ${statusMessage})`,
|
title: `Proxy error (HTTP ${statusCode} ${statusMessage})`,
|
||||||
message: `${msg} Further technical details are provided below.`,
|
message: `${msg} Further details are provided below.`,
|
||||||
obj: errorPayload,
|
obj: errorPayload,
|
||||||
reqId: req.id,
|
reqId: req.id,
|
||||||
model: req.body?.model,
|
model: req.body?.model,
|
||||||
|
|||||||
@@ -11,16 +11,17 @@ export {
|
|||||||
// Express middleware (runs before http-proxy-middleware, can be async)
|
// Express middleware (runs before http-proxy-middleware, can be async)
|
||||||
export { addAzureKey } from "./preprocessors/add-azure-key";
|
export { addAzureKey } from "./preprocessors/add-azure-key";
|
||||||
export { applyQuotaLimits } from "./preprocessors/apply-quota-limits";
|
export { applyQuotaLimits } from "./preprocessors/apply-quota-limits";
|
||||||
export { validateContextSize } from "./preprocessors/validate-context-size";
|
|
||||||
export { countPromptTokens } from "./preprocessors/count-prompt-tokens";
|
export { countPromptTokens } from "./preprocessors/count-prompt-tokens";
|
||||||
export { languageFilter } from "./preprocessors/language-filter";
|
export { languageFilter } from "./preprocessors/language-filter";
|
||||||
export { setApiFormat } from "./preprocessors/set-api-format";
|
export { setApiFormat } from "./preprocessors/set-api-format";
|
||||||
export { signAwsRequest } from "./preprocessors/sign-aws-request";
|
export { signAwsRequest } from "./preprocessors/sign-aws-request";
|
||||||
export { transformOutboundPayload } from "./preprocessors/transform-outbound-payload";
|
export { transformOutboundPayload } from "./preprocessors/transform-outbound-payload";
|
||||||
|
export { validateContextSize } from "./preprocessors/validate-context-size";
|
||||||
|
export { validateVision } from "./preprocessors/validate-vision";
|
||||||
|
|
||||||
// http-proxy-middleware callbacks (runs on onProxyReq, cannot be async)
|
// http-proxy-middleware callbacks (runs on onProxyReq, cannot be async)
|
||||||
export { addKey, addKeyForEmbeddingsRequest } from "./onproxyreq/add-key";
|
|
||||||
export { addAnthropicPreamble } from "./onproxyreq/add-anthropic-preamble";
|
export { addAnthropicPreamble } from "./onproxyreq/add-anthropic-preamble";
|
||||||
|
export { addKey, addKeyForEmbeddingsRequest } from "./onproxyreq/add-key";
|
||||||
export { blockZoomerOrigins } from "./onproxyreq/block-zoomer-origins";
|
export { blockZoomerOrigins } from "./onproxyreq/block-zoomer-origins";
|
||||||
export { checkModelFamily } from "./onproxyreq/check-model-family";
|
export { checkModelFamily } from "./onproxyreq/check-model-family";
|
||||||
export { finalizeBody } from "./onproxyreq/finalize-body";
|
export { finalizeBody } from "./onproxyreq/finalize-body";
|
||||||
|
|||||||
@@ -1,3 +1,5 @@
|
|||||||
|
import { AnthropicChatMessage } from "../../../../shared/api-schemas";
|
||||||
|
import { containsImageContent } from "../../../../shared/api-schemas/anthropic";
|
||||||
import { Key, OpenAIKey, keyPool } from "../../../../shared/key-management";
|
import { Key, OpenAIKey, keyPool } from "../../../../shared/key-management";
|
||||||
import { isEmbeddingsRequest } from "../../common";
|
import { isEmbeddingsRequest } from "../../common";
|
||||||
import { HPMRequestCallback } from "../index";
|
import { HPMRequestCallback } from "../index";
|
||||||
@@ -19,17 +21,24 @@ export const addKey: HPMRequestCallback = (proxyReq, req) => {
|
|||||||
throw new Error("You must specify a model with your request.");
|
throw new Error("You must specify a model with your request.");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
let needsMultimodal = false;
|
||||||
|
if (outboundApi === "anthropic-chat") {
|
||||||
|
needsMultimodal = containsImageContent(
|
||||||
|
body.messages as AnthropicChatMessage[]
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
if (inboundApi === outboundApi) {
|
if (inboundApi === outboundApi) {
|
||||||
assignedKey = keyPool.get(body.model, service);
|
assignedKey = keyPool.get(body.model, service, needsMultimodal);
|
||||||
} else {
|
} else {
|
||||||
switch (outboundApi) {
|
switch (outboundApi) {
|
||||||
// If we are translating between API formats we may need to select a model
|
// If we are translating between API formats we may need to select a model
|
||||||
// for the user, because the provided model is for the inbound API.
|
// for the user, because the provided model is for the inbound API.
|
||||||
// TODO: This whole else condition is probably no longer needed since API
|
// TODO: This whole else condition is probably no longer needed since API
|
||||||
// translation now reassigns the model earlier in the request pipeline.
|
// translation now reassigns the model earlier in the request pipeline.
|
||||||
case "anthropic-chat":
|
|
||||||
case "anthropic-text":
|
case "anthropic-text":
|
||||||
assignedKey = keyPool.get("claude-v1", service);
|
case "anthropic-chat":
|
||||||
|
assignedKey = keyPool.get("claude-v1", service, needsMultimodal);
|
||||||
break;
|
break;
|
||||||
case "openai-text":
|
case "openai-text":
|
||||||
assignedKey = keyPool.get("gpt-3.5-turbo-instruct", service);
|
assignedKey = keyPool.get("gpt-3.5-turbo-instruct", service);
|
||||||
|
|||||||
@@ -7,10 +7,15 @@ import { HPMRequestCallback } from "../index";
|
|||||||
export const stripHeaders: HPMRequestCallback = (proxyReq) => {
|
export const stripHeaders: HPMRequestCallback = (proxyReq) => {
|
||||||
proxyReq.setHeader("origin", "");
|
proxyReq.setHeader("origin", "");
|
||||||
proxyReq.setHeader("referer", "");
|
proxyReq.setHeader("referer", "");
|
||||||
|
proxyReq.removeHeader("tailscale-user-login");
|
||||||
|
proxyReq.removeHeader("tailscale-user-name");
|
||||||
|
proxyReq.removeHeader("tailscale-headers-info");
|
||||||
|
proxyReq.removeHeader("tailscale-user-profile-pic")
|
||||||
proxyReq.removeHeader("cf-connecting-ip");
|
proxyReq.removeHeader("cf-connecting-ip");
|
||||||
proxyReq.removeHeader("forwarded");
|
proxyReq.removeHeader("forwarded");
|
||||||
proxyReq.removeHeader("true-client-ip");
|
proxyReq.removeHeader("true-client-ip");
|
||||||
proxyReq.removeHeader("x-forwarded-for");
|
proxyReq.removeHeader("x-forwarded-for");
|
||||||
|
proxyReq.removeHeader("x-forwarded-host");
|
||||||
|
proxyReq.removeHeader("x-forwarded-proto");
|
||||||
proxyReq.removeHeader("x-real-ip");
|
proxyReq.removeHeader("x-real-ip");
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -4,11 +4,12 @@ import { initializeSseStream } from "../../../shared/streaming";
|
|||||||
import { classifyErrorAndSend } from "../common";
|
import { classifyErrorAndSend } from "../common";
|
||||||
import {
|
import {
|
||||||
RequestPreprocessor,
|
RequestPreprocessor,
|
||||||
validateContextSize,
|
|
||||||
countPromptTokens,
|
countPromptTokens,
|
||||||
|
languageFilter,
|
||||||
setApiFormat,
|
setApiFormat,
|
||||||
transformOutboundPayload,
|
transformOutboundPayload,
|
||||||
languageFilter,
|
validateContextSize,
|
||||||
|
validateVision,
|
||||||
} from ".";
|
} from ".";
|
||||||
|
|
||||||
type RequestPreprocessorOptions = {
|
type RequestPreprocessorOptions = {
|
||||||
@@ -50,6 +51,7 @@ export const createPreprocessorMiddleware = (
|
|||||||
languageFilter,
|
languageFilter,
|
||||||
...(afterTransform ?? []),
|
...(afterTransform ?? []),
|
||||||
validateContextSize,
|
validateContextSize,
|
||||||
|
validateVision,
|
||||||
];
|
];
|
||||||
return async (...args) => executePreprocessors(preprocessors, args);
|
return async (...args) => executePreprocessors(preprocessors, args);
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -6,7 +6,7 @@ import {
|
|||||||
GoogleAIChatMessage,
|
GoogleAIChatMessage,
|
||||||
MistralAIChatMessage,
|
MistralAIChatMessage,
|
||||||
OpenAIChatMessage,
|
OpenAIChatMessage,
|
||||||
} from "../../../../shared/api-support";
|
} from "../../../../shared/api-schemas";
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Given a request with an already-transformed body, counts the number of
|
* Given a request with an already-transformed body, counts the number of
|
||||||
@@ -31,7 +31,10 @@ export const countPromptTokens: RequestPreprocessor = async (req) => {
|
|||||||
}
|
}
|
||||||
case "anthropic-chat": {
|
case "anthropic-chat": {
|
||||||
req.outputTokens = req.body.max_tokens;
|
req.outputTokens = req.body.max_tokens;
|
||||||
const prompt: AnthropicChatMessage[] = req.body.messages;
|
const prompt = {
|
||||||
|
system: req.body.system ?? "",
|
||||||
|
messages: req.body.messages,
|
||||||
|
};
|
||||||
result = await countTokens({ req, prompt, service });
|
result = await countTokens({ req, prompt, service });
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -7,7 +7,7 @@ import {
|
|||||||
MistralAIChatMessage,
|
MistralAIChatMessage,
|
||||||
OpenAIChatMessage,
|
OpenAIChatMessage,
|
||||||
flattenAnthropicMessages,
|
flattenAnthropicMessages,
|
||||||
} from "../../../../shared/api-support";
|
} from "../../../../shared/api-schemas";
|
||||||
|
|
||||||
const rejectedClients = new Map<string, number>();
|
const rejectedClients = new Map<string, number>();
|
||||||
|
|
||||||
|
|||||||
@@ -5,7 +5,7 @@ import { HttpRequest } from "@smithy/protocol-http";
|
|||||||
import {
|
import {
|
||||||
AnthropicV1TextSchema,
|
AnthropicV1TextSchema,
|
||||||
AnthropicV1MessagesSchema,
|
AnthropicV1MessagesSchema,
|
||||||
} from "../../../../shared/api-support";
|
} from "../../../../shared/api-schemas";
|
||||||
import { keyPool } from "../../../../shared/key-management";
|
import { keyPool } from "../../../../shared/key-management";
|
||||||
import { RequestPreprocessor } from "../index";
|
import { RequestPreprocessor } from "../index";
|
||||||
|
|
||||||
@@ -38,6 +38,7 @@ export const signAwsRequest: RequestPreprocessor = async (req) => {
|
|||||||
if (req.outboundApi === "anthropic-chat") {
|
if (req.outboundApi === "anthropic-chat") {
|
||||||
strippedParams = AnthropicV1MessagesSchema.pick({
|
strippedParams = AnthropicV1MessagesSchema.pick({
|
||||||
messages: true,
|
messages: true,
|
||||||
|
system: true,
|
||||||
max_tokens: true,
|
max_tokens: true,
|
||||||
stop_sequences: true,
|
stop_sequences: true,
|
||||||
temperature: true,
|
temperature: true,
|
||||||
|
|||||||
@@ -1,14 +1,14 @@
|
|||||||
import {
|
import {
|
||||||
API_REQUEST_VALIDATORS,
|
API_REQUEST_VALIDATORS,
|
||||||
API_REQUEST_TRANSFORMERS,
|
API_REQUEST_TRANSFORMERS,
|
||||||
} from "../../../../shared/api-support";
|
} from "../../../../shared/api-schemas";
|
||||||
import { BadRequestError } from "../../../../shared/errors";
|
import { BadRequestError } from "../../../../shared/errors";
|
||||||
|
import { fixMistralPrompt } from "../../../../shared/api-schemas/mistral-ai";
|
||||||
import {
|
import {
|
||||||
isImageGenerationRequest,
|
isImageGenerationRequest,
|
||||||
isTextGenerationRequest,
|
isTextGenerationRequest,
|
||||||
} from "../../common";
|
} from "../../common";
|
||||||
import { RequestPreprocessor } from "../index";
|
import { RequestPreprocessor } from "../index";
|
||||||
import { fixMistralPrompt } from "../../../../shared/api-support/kits/mistral-ai/request-transformers";
|
|
||||||
|
|
||||||
/** Transforms an incoming request body to one that matches the target API. */
|
/** Transforms an incoming request body to one that matches the target API. */
|
||||||
export const transformOutboundPayload: RequestPreprocessor = async (req) => {
|
export const transformOutboundPayload: RequestPreprocessor = async (req) => {
|
||||||
|
|||||||
@@ -46,9 +46,18 @@ export const validateContextSize: RequestPreprocessor = async (req) => {
|
|||||||
}
|
}
|
||||||
proxyMax ||= Number.MAX_SAFE_INTEGER;
|
proxyMax ||= Number.MAX_SAFE_INTEGER;
|
||||||
|
|
||||||
|
if (req.user?.type === "special") {
|
||||||
|
req.log.debug("Special user, not enforcing proxy context limit.");
|
||||||
|
proxyMax = Number.MAX_SAFE_INTEGER;
|
||||||
|
}
|
||||||
|
|
||||||
let modelMax: number;
|
let modelMax: number;
|
||||||
if (model.match(/gpt-3.5-turbo-16k/)) {
|
if (model.match(/gpt-3.5-turbo-16k/)) {
|
||||||
modelMax = 16384;
|
modelMax = 16384;
|
||||||
|
} else if (model.match(/^gpt-4o/)) {
|
||||||
|
modelMax = 128000;
|
||||||
|
} else if (model.match(/gpt-4-turbo(-\d{4}-\d{2}-\d{2})?$/)) {
|
||||||
|
modelMax = 131072;
|
||||||
} else if (model.match(/gpt-4-turbo(-preview)?$/)) {
|
} else if (model.match(/gpt-4-turbo(-preview)?$/)) {
|
||||||
modelMax = 131072;
|
modelMax = 131072;
|
||||||
} else if (model.match(/gpt-4-(0125|1106)(-preview)?$/)) {
|
} else if (model.match(/gpt-4-(0125|1106)(-preview)?$/)) {
|
||||||
@@ -56,7 +65,7 @@ export const validateContextSize: RequestPreprocessor = async (req) => {
|
|||||||
} else if (model.match(/^gpt-4(-\d{4})?-vision(-preview)?$/)) {
|
} else if (model.match(/^gpt-4(-\d{4})?-vision(-preview)?$/)) {
|
||||||
modelMax = 131072;
|
modelMax = 131072;
|
||||||
} else if (model.match(/gpt-3.5-turbo/)) {
|
} else if (model.match(/gpt-3.5-turbo/)) {
|
||||||
modelMax = 4096;
|
modelMax = 16384;
|
||||||
} else if (model.match(/gpt-4-32k/)) {
|
} else if (model.match(/gpt-4-32k/)) {
|
||||||
modelMax = 32768;
|
modelMax = 32768;
|
||||||
} else if (model.match(/gpt-4/)) {
|
} else if (model.match(/gpt-4/)) {
|
||||||
@@ -75,7 +84,7 @@ export const validateContextSize: RequestPreprocessor = async (req) => {
|
|||||||
modelMax = GOOGLE_AI_MAX_CONTEXT;
|
modelMax = GOOGLE_AI_MAX_CONTEXT;
|
||||||
} else if (model.match(/^mistral-(tiny|small|medium)$/)) {
|
} else if (model.match(/^mistral-(tiny|small|medium)$/)) {
|
||||||
modelMax = MISTRAL_AI_MAX_CONTENT;
|
modelMax = MISTRAL_AI_MAX_CONTENT;
|
||||||
} else if (model.match(/^anthropic\.claude-3-sonnet/)) {
|
} else if (model.match(/^anthropic\.claude-3/)) {
|
||||||
modelMax = 200000;
|
modelMax = 200000;
|
||||||
} else if (model.match(/^anthropic\.claude-v2:\d/)) {
|
} else if (model.match(/^anthropic\.claude-v2:\d/)) {
|
||||||
modelMax = 200000;
|
modelMax = 200000;
|
||||||
|
|||||||
@@ -0,0 +1,38 @@
|
|||||||
|
import { config } from "../../../../config";
|
||||||
|
import { assertNever } from "../../../../shared/utils";
|
||||||
|
import { RequestPreprocessor } from "../index";
|
||||||
|
import { containsImageContent as containsImageContentOpenAI } from "../../../../shared/api-schemas/openai";
|
||||||
|
import { containsImageContent as containsImageContentAnthropic } from "../../../../shared/api-schemas/anthropic";
|
||||||
|
import { ForbiddenError } from "../../../../shared/errors";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Rejects prompts containing images if multimodal prompts are disabled.
|
||||||
|
*/
|
||||||
|
export const validateVision: RequestPreprocessor = async (req) => {
|
||||||
|
if (config.allowImagePrompts) return;
|
||||||
|
if (req.user?.type === "special") return;
|
||||||
|
|
||||||
|
let hasImage = false;
|
||||||
|
switch (req.outboundApi) {
|
||||||
|
case "openai":
|
||||||
|
hasImage = containsImageContentOpenAI(req.body.messages);
|
||||||
|
break;
|
||||||
|
case "anthropic-chat":
|
||||||
|
hasImage = containsImageContentAnthropic(req.body.messages);
|
||||||
|
break;
|
||||||
|
case "anthropic-text":
|
||||||
|
case "google-ai":
|
||||||
|
case "mistral-ai":
|
||||||
|
case "openai-image":
|
||||||
|
case "openai-text":
|
||||||
|
return;
|
||||||
|
default:
|
||||||
|
assertNever(req.outboundApi);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (hasImage) {
|
||||||
|
throw new ForbiddenError(
|
||||||
|
"Prompts containing images are not permitted. Disable 'Send Inline Images' in your client and try again."
|
||||||
|
);
|
||||||
|
}
|
||||||
|
};
|
||||||
@@ -31,17 +31,28 @@ function getMessageContent({
|
|||||||
}
|
}
|
||||||
```
|
```
|
||||||
*/
|
*/
|
||||||
|
|
||||||
const note = obj?.proxy_note || obj?.error?.message || "";
|
const note = obj?.proxy_note || obj?.error?.message || "";
|
||||||
const friendlyMessage = note ? `${message}\n\n***\n\n*${note}*` : message;
|
const header = `### **${title}**`;
|
||||||
const details = JSON.parse(JSON.stringify(obj ?? {}));
|
const friendlyMessage = note ? `${message}\n\n----\n\n*${note}*` : message;
|
||||||
let stack = "";
|
|
||||||
if (details.stack) {
|
const serializedObj = obj
|
||||||
stack = `\n\nInclude this trace when reporting an issue.\n\`\`\`\n${details.stack}\n\`\`\``;
|
? ["```", JSON.stringify(obj, null, 2), "```"].join("\n")
|
||||||
delete details.stack;
|
: "";
|
||||||
|
|
||||||
|
const { stack } = JSON.parse(JSON.stringify(obj ?? {}));
|
||||||
|
let prettyTrace = "";
|
||||||
|
if (stack && obj) {
|
||||||
|
prettyTrace = [
|
||||||
|
"Include this trace when reporting an issue.",
|
||||||
|
"```",
|
||||||
|
stack,
|
||||||
|
"```",
|
||||||
|
].join("\n");
|
||||||
|
delete obj.stack;
|
||||||
}
|
}
|
||||||
return `\n\n**${title}**\n${friendlyMessage}${
|
|
||||||
obj ? `\n\`\`\`\n${JSON.stringify(obj, null, 2)}\n\`\`\`\n${stack}` : ""
|
return [header, friendlyMessage, serializedObj, prettyTrace].join("\n\n");
|
||||||
}`;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
type ErrorGeneratorOptions = {
|
type ErrorGeneratorOptions = {
|
||||||
|
|||||||
@@ -0,0 +1,76 @@
|
|||||||
|
import util from "util";
|
||||||
|
import zlib from "zlib";
|
||||||
|
import { sendProxyError } from "../common";
|
||||||
|
import type { RawResponseBodyHandler } from "./index";
|
||||||
|
|
||||||
|
const DECODER_MAP = {
|
||||||
|
gzip: util.promisify(zlib.gunzip),
|
||||||
|
deflate: util.promisify(zlib.inflate),
|
||||||
|
br: util.promisify(zlib.brotliDecompress),
|
||||||
|
};
|
||||||
|
|
||||||
|
const isSupportedContentEncoding = (
|
||||||
|
contentEncoding: string
|
||||||
|
): contentEncoding is keyof typeof DECODER_MAP => {
|
||||||
|
return contentEncoding in DECODER_MAP;
|
||||||
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Handles the response from the upstream service and decodes the body if
|
||||||
|
* necessary. If the response is JSON, it will be parsed and returned as an
|
||||||
|
* object. Otherwise, it will be returned as a string. Does not handle streaming
|
||||||
|
* responses.
|
||||||
|
* @throws {Error} Unsupported content-encoding or invalid application/json body
|
||||||
|
*/
|
||||||
|
export const handleBlockingResponse: RawResponseBodyHandler = async (
|
||||||
|
proxyRes,
|
||||||
|
req,
|
||||||
|
res
|
||||||
|
) => {
|
||||||
|
if (req.isStreaming) {
|
||||||
|
const err = new Error(
|
||||||
|
"handleBlockingResponse called for a streaming request."
|
||||||
|
);
|
||||||
|
req.log.error({ stack: err.stack, api: req.inboundApi }, err.message);
|
||||||
|
throw err;
|
||||||
|
}
|
||||||
|
|
||||||
|
return new Promise<string>((resolve, reject) => {
|
||||||
|
let chunks: Buffer[] = [];
|
||||||
|
proxyRes.on("data", (chunk) => chunks.push(chunk));
|
||||||
|
proxyRes.on("end", async () => {
|
||||||
|
let body = Buffer.concat(chunks);
|
||||||
|
|
||||||
|
const contentEncoding = proxyRes.headers["content-encoding"];
|
||||||
|
if (contentEncoding) {
|
||||||
|
if (isSupportedContentEncoding(contentEncoding)) {
|
||||||
|
const decoder = DECODER_MAP[contentEncoding];
|
||||||
|
// @ts-ignore - started failing after upgrading TypeScript, don't care
|
||||||
|
// as it was never a problem.
|
||||||
|
body = await decoder(body);
|
||||||
|
} else {
|
||||||
|
const error = `Proxy received response with unsupported content-encoding: ${contentEncoding}`;
|
||||||
|
req.log.warn({ contentEncoding, key: req.key?.hash }, error);
|
||||||
|
sendProxyError(req, res, 500, "Internal Server Error", {
|
||||||
|
error,
|
||||||
|
contentEncoding,
|
||||||
|
});
|
||||||
|
return reject(error);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
if (proxyRes.headers["content-type"]?.includes("application/json")) {
|
||||||
|
const json = JSON.parse(body.toString());
|
||||||
|
return resolve(json);
|
||||||
|
}
|
||||||
|
return resolve(body.toString());
|
||||||
|
} catch (e) {
|
||||||
|
const msg = `Proxy received response with invalid JSON: ${e.message}`;
|
||||||
|
req.log.warn({ error: e.stack, key: req.key?.hash }, msg);
|
||||||
|
sendProxyError(req, res, 500, "Internal Server Error", { error: msg });
|
||||||
|
return reject(msg);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
});
|
||||||
|
};
|
||||||
@@ -3,20 +3,21 @@ import { pipeline, Readable, Transform } from "stream";
|
|||||||
import StreamArray from "stream-json/streamers/StreamArray";
|
import StreamArray from "stream-json/streamers/StreamArray";
|
||||||
import { StringDecoder } from "string_decoder";
|
import { StringDecoder } from "string_decoder";
|
||||||
import { promisify } from "util";
|
import { promisify } from "util";
|
||||||
|
import type { logger } from "../../../logger";
|
||||||
|
import { BadRequestError, RetryableError } from "../../../shared/errors";
|
||||||
import { APIFormat, keyPool } from "../../../shared/key-management";
|
import { APIFormat, keyPool } from "../../../shared/key-management";
|
||||||
import {
|
import {
|
||||||
copySseResponseHeaders,
|
copySseResponseHeaders,
|
||||||
initializeSseStream,
|
initializeSseStream,
|
||||||
} from "../../../shared/streaming";
|
} from "../../../shared/streaming";
|
||||||
import type { logger } from "../../../logger";
|
import { reenqueueRequest } from "../../queue";
|
||||||
import { enqueue } from "../../queue";
|
import type { RawResponseBodyHandler } from ".";
|
||||||
import { decodeResponseBody, RawResponseBodyHandler, RetryableError } from ".";
|
import { handleBlockingResponse } from "./handle-blocking-response";
|
||||||
|
import { buildSpoofedSSE, sendErrorToClient } from "./error-generator";
|
||||||
import { getAwsEventStreamDecoder } from "./streaming/aws-event-stream-decoder";
|
import { getAwsEventStreamDecoder } from "./streaming/aws-event-stream-decoder";
|
||||||
import { EventAggregator } from "./streaming/event-aggregator";
|
import { EventAggregator } from "./streaming/event-aggregator";
|
||||||
import { SSEMessageTransformer } from "./streaming/sse-message-transformer";
|
import { SSEMessageTransformer } from "./streaming/sse-message-transformer";
|
||||||
import { SSEStreamAdapter } from "./streaming/sse-stream-adapter";
|
import { SSEStreamAdapter } from "./streaming/sse-stream-adapter";
|
||||||
import { buildSpoofedSSE, sendErrorToClient } from "./error-generator";
|
|
||||||
import { BadRequestError } from "../../../shared/errors";
|
|
||||||
|
|
||||||
const pipelineAsync = promisify(pipeline);
|
const pipelineAsync = promisify(pipeline);
|
||||||
|
|
||||||
@@ -50,7 +51,7 @@ export const handleStreamedResponse: RawResponseBodyHandler = async (
|
|||||||
{ statusCode: proxyRes.statusCode, key: hash },
|
{ statusCode: proxyRes.statusCode, key: hash },
|
||||||
`Streaming request returned error status code. Falling back to non-streaming response handler.`
|
`Streaming request returned error status code. Falling back to non-streaming response handler.`
|
||||||
);
|
);
|
||||||
return decodeResponseBody(proxyRes, req, res);
|
return handleBlockingResponse(proxyRes, req, res);
|
||||||
}
|
}
|
||||||
|
|
||||||
req.log.debug({ headers: proxyRes.headers }, `Starting to proxy SSE stream.`);
|
req.log.debug({ headers: proxyRes.headers }, `Starting to proxy SSE stream.`);
|
||||||
@@ -105,12 +106,7 @@ export const handleStreamedResponse: RawResponseBodyHandler = async (
|
|||||||
} catch (err) {
|
} catch (err) {
|
||||||
if (err instanceof RetryableError) {
|
if (err instanceof RetryableError) {
|
||||||
keyPool.markRateLimited(req.key!);
|
keyPool.markRateLimited(req.key!);
|
||||||
req.log.warn(
|
await reenqueueRequest(req);
|
||||||
{ key: req.key!.hash, retryCount: req.retryCount },
|
|
||||||
`Re-enqueueing request due to retryable error during streaming response.`
|
|
||||||
);
|
|
||||||
req.retryCount++;
|
|
||||||
await enqueue(req);
|
|
||||||
} else if (err instanceof BadRequestError) {
|
} else if (err instanceof BadRequestError) {
|
||||||
sendErrorToClient({
|
sendErrorToClient({
|
||||||
req,
|
req,
|
||||||
@@ -138,7 +134,17 @@ export const handleStreamedResponse: RawResponseBodyHandler = async (
|
|||||||
res.write(`data: [DONE]\n\n`);
|
res.write(`data: [DONE]\n\n`);
|
||||||
res.end();
|
res.end();
|
||||||
}
|
}
|
||||||
throw err;
|
|
||||||
|
// At this point the response is closed. If the request resulted in any
|
||||||
|
// tokens being consumed (suggesting a mid-stream error), we will resolve
|
||||||
|
// and continue the middleware chain so tokens can be counted.
|
||||||
|
if (aggregator.hasEvents()) {
|
||||||
|
return aggregator.getFinalResponse();
|
||||||
|
} else {
|
||||||
|
// If there is nothing, then this was a completely failed prompt that
|
||||||
|
// will not have billed any tokens. Throw to stop the middleware chain.
|
||||||
|
throw err;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|||||||
@@ -1,10 +1,8 @@
|
|||||||
/* This file is fucking horrendous, sorry */
|
/* This file is fucking horrendous, sorry */
|
||||||
import { Request, Response } from "express";
|
import { Request, Response } from "express";
|
||||||
import * as http from "http";
|
import * as http from "http";
|
||||||
import util from "util";
|
import { config } from "../../../config";
|
||||||
import zlib from "zlib";
|
import { HttpError, RetryableError } from "../../../shared/errors";
|
||||||
import { enqueue, trackWaitTime } from "../../queue";
|
|
||||||
import { HttpError } from "../../../shared/errors";
|
|
||||||
import { keyPool } from "../../../shared/key-management";
|
import { keyPool } from "../../../shared/key-management";
|
||||||
import { getOpenAIModelFamily } from "../../../shared/models";
|
import { getOpenAIModelFamily } from "../../../shared/models";
|
||||||
import { countTokens } from "../../../shared/tokenization";
|
import { countTokens } from "../../../shared/tokenization";
|
||||||
@@ -13,6 +11,7 @@ import {
|
|||||||
incrementTokenCount,
|
incrementTokenCount,
|
||||||
} from "../../../shared/users/user-store";
|
} from "../../../shared/users/user-store";
|
||||||
import { assertNever } from "../../../shared/utils";
|
import { assertNever } from "../../../shared/utils";
|
||||||
|
import { reenqueueRequest, trackWaitTime } from "../../queue";
|
||||||
import { refundLastAttempt } from "../../rate-limit";
|
import { refundLastAttempt } from "../../rate-limit";
|
||||||
import {
|
import {
|
||||||
getCompletionFromBody,
|
getCompletionFromBody,
|
||||||
@@ -20,39 +19,23 @@ import {
|
|||||||
isTextGenerationRequest,
|
isTextGenerationRequest,
|
||||||
sendProxyError,
|
sendProxyError,
|
||||||
} from "../common";
|
} from "../common";
|
||||||
|
import { handleBlockingResponse } from "./handle-blocking-response";
|
||||||
import { handleStreamedResponse } from "./handle-streamed-response";
|
import { handleStreamedResponse } from "./handle-streamed-response";
|
||||||
import { logPrompt } from "./log-prompt";
|
import { logPrompt } from "./log-prompt";
|
||||||
|
import { logEvent } from "./log-event";
|
||||||
import { saveImage } from "./save-image";
|
import { saveImage } from "./save-image";
|
||||||
import { config } from "../../../config";
|
|
||||||
|
|
||||||
const DECODER_MAP = {
|
|
||||||
gzip: util.promisify(zlib.gunzip),
|
|
||||||
deflate: util.promisify(zlib.inflate),
|
|
||||||
br: util.promisify(zlib.brotliDecompress),
|
|
||||||
};
|
|
||||||
|
|
||||||
const isSupportedContentEncoding = (
|
|
||||||
contentEncoding: string
|
|
||||||
): contentEncoding is keyof typeof DECODER_MAP => {
|
|
||||||
return contentEncoding in DECODER_MAP;
|
|
||||||
};
|
|
||||||
|
|
||||||
export class RetryableError extends Error {
|
|
||||||
constructor(message: string) {
|
|
||||||
super(message);
|
|
||||||
this.name = "RetryableError";
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Either decodes or streams the entire response body and then passes it as the
|
* Either decodes or streams the entire response body and then resolves with it.
|
||||||
* last argument to the rest of the middleware stack.
|
* @returns The response body as a string or parsed JSON object depending on the
|
||||||
|
* response's content-type.
|
||||||
*/
|
*/
|
||||||
export type RawResponseBodyHandler = (
|
export type RawResponseBodyHandler = (
|
||||||
proxyRes: http.IncomingMessage,
|
proxyRes: http.IncomingMessage,
|
||||||
req: Request,
|
req: Request,
|
||||||
res: Response
|
res: Response
|
||||||
) => Promise<string | Record<string, any>>;
|
) => Promise<string | Record<string, any>>;
|
||||||
|
|
||||||
export type ProxyResHandlerWithBody = (
|
export type ProxyResHandlerWithBody = (
|
||||||
proxyRes: http.IncomingMessage,
|
proxyRes: http.IncomingMessage,
|
||||||
req: Request,
|
req: Request,
|
||||||
@@ -76,6 +59,10 @@ export type ProxyResMiddleware = ProxyResHandlerWithBody[];
|
|||||||
* middleware from executing as it consumes the stream and forwards events to
|
* middleware from executing as it consumes the stream and forwards events to
|
||||||
* the client. Once the stream is closed, the finalized body will be attached
|
* the client. Once the stream is closed, the finalized body will be attached
|
||||||
* to res.body and the remaining middleware will execute.
|
* to res.body and the remaining middleware will execute.
|
||||||
|
*
|
||||||
|
* @param apiMiddleware - Custom middleware to execute after the common response
|
||||||
|
* handlers. These *only* execute for non-streaming responses, so should be used
|
||||||
|
* to transform non-streaming responses into the desired format.
|
||||||
*/
|
*/
|
||||||
export const createOnProxyResHandler = (apiMiddleware: ProxyResMiddleware) => {
|
export const createOnProxyResHandler = (apiMiddleware: ProxyResMiddleware) => {
|
||||||
return async (
|
return async (
|
||||||
@@ -83,36 +70,35 @@ export const createOnProxyResHandler = (apiMiddleware: ProxyResMiddleware) => {
|
|||||||
req: Request,
|
req: Request,
|
||||||
res: Response
|
res: Response
|
||||||
) => {
|
) => {
|
||||||
const initialHandler = req.isStreaming
|
const initialHandler: RawResponseBodyHandler = req.isStreaming
|
||||||
? handleStreamedResponse
|
? handleStreamedResponse
|
||||||
: decodeResponseBody;
|
: handleBlockingResponse;
|
||||||
|
|
||||||
let lastMiddleware = initialHandler.name;
|
let lastMiddleware = initialHandler.name;
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const body = await initialHandler(proxyRes, req, res);
|
const body = await initialHandler(proxyRes, req, res);
|
||||||
|
|
||||||
const middlewareStack: ProxyResMiddleware = [];
|
const middlewareStack: ProxyResMiddleware = [];
|
||||||
|
|
||||||
if (req.isStreaming) {
|
if (req.isStreaming) {
|
||||||
// `handleStreamedResponse` writes to the response and ends it, so
|
// Handlers for streaming requests must never write to the response.
|
||||||
// we can only execute middleware that doesn't write to the response.
|
|
||||||
middlewareStack.push(
|
middlewareStack.push(
|
||||||
trackRateLimit,
|
trackKeyRateLimit,
|
||||||
countResponseTokens,
|
countResponseTokens,
|
||||||
incrementUsage,
|
incrementUsage,
|
||||||
logPrompt
|
logPrompt,
|
||||||
|
logEvent
|
||||||
);
|
);
|
||||||
} else {
|
} else {
|
||||||
middlewareStack.push(
|
middlewareStack.push(
|
||||||
trackRateLimit,
|
trackKeyRateLimit,
|
||||||
addProxyInfo,
|
injectProxyInfo,
|
||||||
handleUpstreamErrors,
|
handleUpstreamErrors,
|
||||||
countResponseTokens,
|
countResponseTokens,
|
||||||
incrementUsage,
|
incrementUsage,
|
||||||
copyHttpHeaders,
|
copyHttpHeaders,
|
||||||
saveImage,
|
saveImage,
|
||||||
logPrompt,
|
logPrompt,
|
||||||
|
logEvent,
|
||||||
...apiMiddleware
|
...apiMiddleware
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@@ -154,72 +140,6 @@ export const createOnProxyResHandler = (apiMiddleware: ProxyResMiddleware) => {
|
|||||||
};
|
};
|
||||||
};
|
};
|
||||||
|
|
||||||
async function reenqueueRequest(req: Request) {
|
|
||||||
req.log.info(
|
|
||||||
{ key: req.key?.hash, retryCount: req.retryCount },
|
|
||||||
`Re-enqueueing request due to retryable error`
|
|
||||||
);
|
|
||||||
req.retryCount++;
|
|
||||||
await enqueue(req);
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Handles the response from the upstream service and decodes the body if
|
|
||||||
* necessary. If the response is JSON, it will be parsed and returned as an
|
|
||||||
* object. Otherwise, it will be returned as a string.
|
|
||||||
* @throws {Error} Unsupported content-encoding or invalid application/json body
|
|
||||||
*/
|
|
||||||
export const decodeResponseBody: RawResponseBodyHandler = async (
|
|
||||||
proxyRes,
|
|
||||||
req,
|
|
||||||
res
|
|
||||||
) => {
|
|
||||||
if (req.isStreaming) {
|
|
||||||
const err = new Error("decodeResponseBody called for a streaming request.");
|
|
||||||
req.log.error({ stack: err.stack, api: req.inboundApi }, err.message);
|
|
||||||
throw err;
|
|
||||||
}
|
|
||||||
|
|
||||||
return new Promise<string>((resolve, reject) => {
|
|
||||||
let chunks: Buffer[] = [];
|
|
||||||
proxyRes.on("data", (chunk) => chunks.push(chunk));
|
|
||||||
proxyRes.on("end", async () => {
|
|
||||||
let body = Buffer.concat(chunks);
|
|
||||||
|
|
||||||
const contentEncoding = proxyRes.headers["content-encoding"];
|
|
||||||
if (contentEncoding) {
|
|
||||||
if (isSupportedContentEncoding(contentEncoding)) {
|
|
||||||
const decoder = DECODER_MAP[contentEncoding];
|
|
||||||
// @ts-ignore - started failing after upgrading TypeScript, don't care
|
|
||||||
// as it was never a problem.
|
|
||||||
body = await decoder(body);
|
|
||||||
} else {
|
|
||||||
const error = `Proxy received response with unsupported content-encoding: ${contentEncoding}`;
|
|
||||||
req.log.warn({ contentEncoding, key: req.key?.hash }, error);
|
|
||||||
sendProxyError(req, res, 500, "Internal Server Error", {
|
|
||||||
error,
|
|
||||||
contentEncoding,
|
|
||||||
});
|
|
||||||
return reject(error);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
try {
|
|
||||||
if (proxyRes.headers["content-type"]?.includes("application/json")) {
|
|
||||||
const json = JSON.parse(body.toString());
|
|
||||||
return resolve(json);
|
|
||||||
}
|
|
||||||
return resolve(body.toString());
|
|
||||||
} catch (e) {
|
|
||||||
const msg = `Proxy received response with invalid JSON: ${e.message}`;
|
|
||||||
req.log.warn({ error: e.stack, key: req.key?.hash }, msg);
|
|
||||||
sendProxyError(req, res, 500, "Internal Server Error", { error: msg });
|
|
||||||
return reject(msg);
|
|
||||||
}
|
|
||||||
});
|
|
||||||
});
|
|
||||||
};
|
|
||||||
|
|
||||||
type ProxiedErrorPayload = {
|
type ProxiedErrorPayload = {
|
||||||
error?: Record<string, any>;
|
error?: Record<string, any>;
|
||||||
message?: string;
|
message?: string;
|
||||||
@@ -242,15 +162,9 @@ const handleUpstreamErrors: ProxyResHandlerWithBody = async (
|
|||||||
) => {
|
) => {
|
||||||
const statusCode = proxyRes.statusCode || 500;
|
const statusCode = proxyRes.statusCode || 500;
|
||||||
const statusMessage = proxyRes.statusMessage || "Internal Server Error";
|
const statusMessage = proxyRes.statusMessage || "Internal Server Error";
|
||||||
|
|
||||||
if (statusCode < 400) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
let errorPayload: ProxiedErrorPayload;
|
let errorPayload: ProxiedErrorPayload;
|
||||||
const tryAgainMessage = keyPool.available(req.body?.model)
|
|
||||||
? `There may be more keys available for this model; try again in a few seconds.`
|
if (statusCode < 400) return;
|
||||||
: "There are no more keys available for this model.";
|
|
||||||
|
|
||||||
try {
|
try {
|
||||||
assertJsonResponse(body);
|
assertJsonResponse(body);
|
||||||
@@ -280,6 +194,9 @@ const handleUpstreamErrors: ProxyResHandlerWithBody = async (
|
|||||||
{ statusCode, type: errorType, errorPayload, key: req.key?.hash },
|
{ statusCode, type: errorType, errorPayload, key: req.key?.hash },
|
||||||
`Received error response from upstream. (${proxyRes.statusMessage})`
|
`Received error response from upstream. (${proxyRes.statusMessage})`
|
||||||
);
|
);
|
||||||
|
|
||||||
|
// TODO: split upstream error handling into separate modules for each service,
|
||||||
|
// this is out of control.
|
||||||
|
|
||||||
const service = req.key!.service;
|
const service = req.key!.service;
|
||||||
if (service === "aws") {
|
if (service === "aws") {
|
||||||
@@ -289,8 +206,6 @@ const handleUpstreamErrors: ProxyResHandlerWithBody = async (
|
|||||||
}
|
}
|
||||||
|
|
||||||
if (statusCode === 400) {
|
if (statusCode === 400) {
|
||||||
// Bad request. For OpenAI, this is usually due to prompt length.
|
|
||||||
// For Anthropic, this is usually due to missing preamble.
|
|
||||||
switch (service) {
|
switch (service) {
|
||||||
case "openai":
|
case "openai":
|
||||||
case "google-ai":
|
case "google-ai":
|
||||||
@@ -303,7 +218,7 @@ const handleUpstreamErrors: ProxyResHandlerWithBody = async (
|
|||||||
} else if (errorPayload.error?.code === "billing_hard_limit_reached") {
|
} else if (errorPayload.error?.code === "billing_hard_limit_reached") {
|
||||||
// For some reason, some models return this 400 error instead of the
|
// For some reason, some models return this 400 error instead of the
|
||||||
// same 429 billing error that other models return.
|
// same 429 billing error that other models return.
|
||||||
await handleOpenAIRateLimitError(req, tryAgainMessage, errorPayload);
|
await handleOpenAIRateLimitError(req, errorPayload);
|
||||||
} else {
|
} else {
|
||||||
errorPayload.proxy_note = `The upstream API rejected the request. Your prompt may be too long for ${req.body?.model}.`;
|
errorPayload.proxy_note = `The upstream API rejected the request. Your prompt may be too long for ${req.body?.model}.`;
|
||||||
}
|
}
|
||||||
@@ -318,38 +233,53 @@ const handleUpstreamErrors: ProxyResHandlerWithBody = async (
|
|||||||
} else if (statusCode === 401) {
|
} else if (statusCode === 401) {
|
||||||
// Key is invalid or was revoked
|
// Key is invalid or was revoked
|
||||||
keyPool.disable(req.key!, "revoked");
|
keyPool.disable(req.key!, "revoked");
|
||||||
errorPayload.proxy_note = `API key is invalid or revoked. ${tryAgainMessage}`;
|
errorPayload.proxy_note = `Assigned API key is invalid or revoked, please try again.`;
|
||||||
} else if (statusCode === 403) {
|
} else if (statusCode === 403) {
|
||||||
if (service === "anthropic") {
|
switch (service) {
|
||||||
keyPool.disable(req.key!, "revoked");
|
case "anthropic":
|
||||||
errorPayload.proxy_note = `API key is invalid or revoked. ${tryAgainMessage}`;
|
if (
|
||||||
return;
|
errorType === "permission_error" &&
|
||||||
}
|
errorPayload.error?.message?.toLowerCase().includes("multimodal")
|
||||||
switch (errorType) {
|
) {
|
||||||
case "UnrecognizedClientException":
|
req.log.warn(
|
||||||
// Key is invalid.
|
{ key: req.key?.hash },
|
||||||
keyPool.disable(req.key!, "revoked");
|
"This Anthropic key does not support multimodal prompts."
|
||||||
errorPayload.proxy_note = `API key is invalid or revoked. ${tryAgainMessage}`;
|
|
||||||
break;
|
|
||||||
case "AccessDeniedException":
|
|
||||||
const isModelAccessError =
|
|
||||||
errorPayload.error?.message?.includes(`specified model ID`);
|
|
||||||
if (!isModelAccessError) {
|
|
||||||
req.log.error(
|
|
||||||
{ key: req.key?.hash, model: req.body?.model },
|
|
||||||
"Disabling key due to AccessDeniedException when invoking model. If credentials are valid, check IAM permissions."
|
|
||||||
);
|
);
|
||||||
|
keyPool.update(req.key!, { allowsMultimodality: false });
|
||||||
|
await reenqueueRequest(req);
|
||||||
|
throw new RetryableError("Claude request re-enqueued because key does not support multimodality.");
|
||||||
|
} else {
|
||||||
keyPool.disable(req.key!, "revoked");
|
keyPool.disable(req.key!, "revoked");
|
||||||
|
errorPayload.proxy_note = `Assigned API key is invalid or revoked, please try again.`;
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
case "aws":
|
||||||
|
switch (errorType) {
|
||||||
|
case "UnrecognizedClientException":
|
||||||
|
// Key is invalid.
|
||||||
|
keyPool.disable(req.key!, "revoked");
|
||||||
|
errorPayload.proxy_note = `Assigned API key is invalid or revoked, please try again.`;
|
||||||
|
break;
|
||||||
|
case "AccessDeniedException":
|
||||||
|
const isModelAccessError =
|
||||||
|
errorPayload.error?.message?.includes(`specified model ID`);
|
||||||
|
if (!isModelAccessError) {
|
||||||
|
req.log.error(
|
||||||
|
{ key: req.key?.hash, model: req.body?.model },
|
||||||
|
"Disabling key due to AccessDeniedException when invoking model. If credentials are valid, check IAM permissions."
|
||||||
|
);
|
||||||
|
keyPool.disable(req.key!, "revoked");
|
||||||
|
}
|
||||||
|
errorPayload.proxy_note = `API key doesn't have access to the requested resource. Model ID: ${req.body?.model}`;
|
||||||
|
break;
|
||||||
|
default:
|
||||||
|
errorPayload.proxy_note = `Received 403 error. Key may be invalid.`;
|
||||||
}
|
}
|
||||||
errorPayload.proxy_note = `API key doesn't have access to the requested resource. Model ID: ${req.body?.model}`;
|
|
||||||
break;
|
|
||||||
default:
|
|
||||||
errorPayload.proxy_note = `Received 403 error. Key may be invalid.`;
|
|
||||||
}
|
}
|
||||||
} else if (statusCode === 429) {
|
} else if (statusCode === 429) {
|
||||||
switch (service) {
|
switch (service) {
|
||||||
case "openai":
|
case "openai":
|
||||||
await handleOpenAIRateLimitError(req, tryAgainMessage, errorPayload);
|
await handleOpenAIRateLimitError(req, errorPayload);
|
||||||
break;
|
break;
|
||||||
case "anthropic":
|
case "anthropic":
|
||||||
await handleAnthropicRateLimitError(req, errorPayload);
|
await handleAnthropicRateLimitError(req, errorPayload);
|
||||||
@@ -459,7 +389,7 @@ async function handleAnthropicBadRequestError(
|
|||||||
"Anthropic key has been disabled."
|
"Anthropic key has been disabled."
|
||||||
);
|
);
|
||||||
keyPool.disable(req.key!, "revoked");
|
keyPool.disable(req.key!, "revoked");
|
||||||
errorPayload.proxy_note = `Assigned key has been disabled. ${error?.message}`;
|
errorPayload.proxy_note = `Assigned key has been disabled. (${error?.message})`;
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -499,7 +429,6 @@ async function handleAwsRateLimitError(
|
|||||||
|
|
||||||
async function handleOpenAIRateLimitError(
|
async function handleOpenAIRateLimitError(
|
||||||
req: Request,
|
req: Request,
|
||||||
tryAgainMessage: string,
|
|
||||||
errorPayload: ProxiedErrorPayload
|
errorPayload: ProxiedErrorPayload
|
||||||
): Promise<Record<string, any>> {
|
): Promise<Record<string, any>> {
|
||||||
const type = errorPayload.error?.type;
|
const type = errorPayload.error?.type;
|
||||||
@@ -508,17 +437,17 @@ async function handleOpenAIRateLimitError(
|
|||||||
case "invalid_request_error": // this is the billing_hard_limit_reached error seen in some cases
|
case "invalid_request_error": // this is the billing_hard_limit_reached error seen in some cases
|
||||||
// Billing quota exceeded (key is dead, disable it)
|
// Billing quota exceeded (key is dead, disable it)
|
||||||
keyPool.disable(req.key!, "quota");
|
keyPool.disable(req.key!, "quota");
|
||||||
errorPayload.proxy_note = `Assigned key's quota has been exceeded. ${tryAgainMessage}`;
|
errorPayload.proxy_note = `Assigned key's quota has been exceeded. Please try again.`;
|
||||||
break;
|
break;
|
||||||
case "access_terminated":
|
case "access_terminated":
|
||||||
// Account banned (key is dead, disable it)
|
// Account banned (key is dead, disable it)
|
||||||
keyPool.disable(req.key!, "revoked");
|
keyPool.disable(req.key!, "revoked");
|
||||||
errorPayload.proxy_note = `Assigned key has been banned by OpenAI for policy violations. ${tryAgainMessage}`;
|
errorPayload.proxy_note = `Assigned key has been banned by OpenAI for policy violations. Please try again.`;
|
||||||
break;
|
break;
|
||||||
case "billing_not_active":
|
case "billing_not_active":
|
||||||
// Key valid but account billing is delinquent
|
// Key valid but account billing is delinquent
|
||||||
keyPool.disable(req.key!, "quota");
|
keyPool.disable(req.key!, "quota");
|
||||||
errorPayload.proxy_note = `Assigned key has been disabled due to delinquent billing. ${tryAgainMessage}`;
|
errorPayload.proxy_note = `Assigned key has been disabled due to delinquent billing. Please try again.`;
|
||||||
break;
|
break;
|
||||||
case "requests":
|
case "requests":
|
||||||
case "tokens":
|
case "tokens":
|
||||||
@@ -684,7 +613,7 @@ const countResponseTokens: ProxyResHandlerWithBody = async (
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
const trackRateLimit: ProxyResHandlerWithBody = async (proxyRes, req) => {
|
const trackKeyRateLimit: ProxyResHandlerWithBody = async (proxyRes, req) => {
|
||||||
keyPool.updateRateLimits(req.key!, proxyRes.headers);
|
keyPool.updateRateLimits(req.key!, proxyRes.headers);
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -714,7 +643,7 @@ const copyHttpHeaders: ProxyResHandlerWithBody = async (
|
|||||||
* or transformed.
|
* or transformed.
|
||||||
* Only used for non-streaming requests.
|
* Only used for non-streaming requests.
|
||||||
*/
|
*/
|
||||||
const addProxyInfo: ProxyResHandlerWithBody = async (
|
const injectProxyInfo: ProxyResHandlerWithBody = async (
|
||||||
_proxyRes,
|
_proxyRes,
|
||||||
req,
|
req,
|
||||||
res,
|
res,
|
||||||
|
|||||||
@@ -0,0 +1,81 @@
|
|||||||
|
import { createHash } from "crypto";
|
||||||
|
import { config } from "../../../config";
|
||||||
|
import { eventLogger } from "../../../shared/prompt-logging";
|
||||||
|
import { getModelFromBody, isTextGenerationRequest } from "../common";
|
||||||
|
import { ProxyResHandlerWithBody } from ".";
|
||||||
|
import {
|
||||||
|
OpenAIChatMessage,
|
||||||
|
AnthropicChatMessage,
|
||||||
|
} from "../../../shared/api-schemas";
|
||||||
|
|
||||||
|
/** If event logging is enabled, logs a chat completion event. */
|
||||||
|
export const logEvent: ProxyResHandlerWithBody = async (
|
||||||
|
_proxyRes,
|
||||||
|
req,
|
||||||
|
_res,
|
||||||
|
responseBody
|
||||||
|
) => {
|
||||||
|
if (!config.eventLogging) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (typeof responseBody !== "object") {
|
||||||
|
throw new Error("Expected body to be an object");
|
||||||
|
}
|
||||||
|
if (!["openai", "anthropic-chat"].includes(req.outboundApi)) {
|
||||||
|
// only chat apis are supported
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (!req.user) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const loggable = isTextGenerationRequest(req);
|
||||||
|
if (!loggable) return;
|
||||||
|
|
||||||
|
const messages = req.body.messages as
|
||||||
|
| OpenAIChatMessage[]
|
||||||
|
| AnthropicChatMessage[];
|
||||||
|
|
||||||
|
let hashes = [];
|
||||||
|
hashes.push(hashMessages(messages));
|
||||||
|
for (
|
||||||
|
let i = 1;
|
||||||
|
i <= Math.min(config.eventLoggingTrim!, messages.length);
|
||||||
|
i++
|
||||||
|
) {
|
||||||
|
hashes.push(hashMessages(messages.slice(0, -i)));
|
||||||
|
}
|
||||||
|
|
||||||
|
const model = getModelFromBody(req, responseBody);
|
||||||
|
const userToken = req.user!.token;
|
||||||
|
const family = req.modelFamily!;
|
||||||
|
eventLogger.logEvent({
|
||||||
|
ip: req.ip,
|
||||||
|
type: "chat_completion",
|
||||||
|
model,
|
||||||
|
family,
|
||||||
|
hashes,
|
||||||
|
userToken,
|
||||||
|
inputTokens: req.promptTokens ?? 0,
|
||||||
|
outputTokens: req.outputTokens ?? 0,
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
|
const hashMessages = (
|
||||||
|
messages: OpenAIChatMessage[] | AnthropicChatMessage[]
|
||||||
|
): string => {
|
||||||
|
let hasher = createHash("sha256");
|
||||||
|
let messageTexts = [];
|
||||||
|
for (const msg of messages) {
|
||||||
|
if (!["system", "user", "assistant"].includes(msg.role)) continue;
|
||||||
|
if (typeof msg.content === "string") {
|
||||||
|
messageTexts.push(msg.content);
|
||||||
|
} else if (Array.isArray(msg.content)) {
|
||||||
|
if (msg.content[0].type === "text") {
|
||||||
|
messageTexts.push(msg.content[0].text);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
hasher.update(messageTexts.join("<|im_sep|>"));
|
||||||
|
return hasher.digest("hex");
|
||||||
|
};
|
||||||
@@ -11,11 +11,10 @@ import { ProxyResHandlerWithBody } from ".";
|
|||||||
import { assertNever } from "../../../shared/utils";
|
import { assertNever } from "../../../shared/utils";
|
||||||
import {
|
import {
|
||||||
AnthropicChatMessage,
|
AnthropicChatMessage,
|
||||||
flattenAnthropicMessages,
|
flattenAnthropicMessages, GoogleAIChatMessage,
|
||||||
MistralAIChatMessage,
|
MistralAIChatMessage,
|
||||||
OpenAIChatMessage,
|
OpenAIChatMessage,
|
||||||
} from "../../../shared/api-support";
|
} from "../../../shared/api-schemas";
|
||||||
import { APIFormat } from "../../../shared/key-management";
|
|
||||||
|
|
||||||
/** If prompt logging is enabled, enqueues the prompt for logging. */
|
/** If prompt logging is enabled, enqueues the prompt for logging. */
|
||||||
export const logPrompt: ProxyResHandlerWithBody = async (
|
export const logPrompt: ProxyResHandlerWithBody = async (
|
||||||
@@ -36,7 +35,7 @@ export const logPrompt: ProxyResHandlerWithBody = async (
|
|||||||
if (!loggable) return;
|
if (!loggable) return;
|
||||||
|
|
||||||
const promptPayload = getPromptForRequest(req, responseBody);
|
const promptPayload = getPromptForRequest(req, responseBody);
|
||||||
const promptFlattened = flattenMessages(promptPayload, req.outboundApi);
|
const promptFlattened = flattenMessages(promptPayload);
|
||||||
const response = getCompletionFromBody(req, responseBody);
|
const response = getCompletionFromBody(req, responseBody);
|
||||||
const model = getModelFromBody(req, responseBody);
|
const model = getModelFromBody(req, responseBody);
|
||||||
|
|
||||||
@@ -63,7 +62,8 @@ const getPromptForRequest = (
|
|||||||
):
|
):
|
||||||
| string
|
| string
|
||||||
| OpenAIChatMessage[]
|
| OpenAIChatMessage[]
|
||||||
| AnthropicChatMessage[]
|
| { contents: GoogleAIChatMessage[] }
|
||||||
|
| { system: string; messages: AnthropicChatMessage[] }
|
||||||
| MistralAIChatMessage[]
|
| MistralAIChatMessage[]
|
||||||
| OaiImageResult => {
|
| OaiImageResult => {
|
||||||
// Since the prompt logger only runs after the request has been proxied, we
|
// Since the prompt logger only runs after the request has been proxied, we
|
||||||
@@ -72,8 +72,9 @@ const getPromptForRequest = (
|
|||||||
switch (req.outboundApi) {
|
switch (req.outboundApi) {
|
||||||
case "openai":
|
case "openai":
|
||||||
case "mistral-ai":
|
case "mistral-ai":
|
||||||
case "anthropic-chat":
|
|
||||||
return req.body.messages;
|
return req.body.messages;
|
||||||
|
case "anthropic-chat":
|
||||||
|
return { system: req.body.system, messages: req.body.messages };
|
||||||
case "openai-text":
|
case "openai-text":
|
||||||
return req.body.prompt;
|
return req.body.prompt;
|
||||||
case "openai-image":
|
case "openai-image":
|
||||||
@@ -87,7 +88,7 @@ const getPromptForRequest = (
|
|||||||
case "anthropic-text":
|
case "anthropic-text":
|
||||||
return req.body.prompt;
|
return req.body.prompt;
|
||||||
case "google-ai":
|
case "google-ai":
|
||||||
return req.body.prompt.text;
|
return { contents: req.body.contents };
|
||||||
default:
|
default:
|
||||||
assertNever(req.outboundApi);
|
assertNever(req.outboundApi);
|
||||||
}
|
}
|
||||||
@@ -98,15 +99,26 @@ const flattenMessages = (
|
|||||||
| string
|
| string
|
||||||
| OaiImageResult
|
| OaiImageResult
|
||||||
| OpenAIChatMessage[]
|
| OpenAIChatMessage[]
|
||||||
| AnthropicChatMessage[]
|
| { contents: GoogleAIChatMessage[] }
|
||||||
| MistralAIChatMessage[],
|
| { system: string; messages: AnthropicChatMessage[] }
|
||||||
format: APIFormat
|
| MistralAIChatMessage[]
|
||||||
): string => {
|
): string => {
|
||||||
if (typeof val === "string") {
|
if (typeof val === "string") {
|
||||||
return val.trim();
|
return val.trim();
|
||||||
}
|
}
|
||||||
if (format === "anthropic-chat") {
|
if (isAnthropicChatPrompt(val)) {
|
||||||
return flattenAnthropicMessages(val as AnthropicChatMessage[]);
|
const { system, messages } = val;
|
||||||
|
return `System: ${system}\n\n${flattenAnthropicMessages(messages)}`;
|
||||||
|
}
|
||||||
|
if (isGoogleAIChatPrompt(val)) {
|
||||||
|
return val.contents
|
||||||
|
.map(({ parts, role }) => {
|
||||||
|
const text = parts
|
||||||
|
.map((p) => p.text)
|
||||||
|
.join("\n");
|
||||||
|
return `${role}: ${text}`;
|
||||||
|
})
|
||||||
|
.join("\n");
|
||||||
}
|
}
|
||||||
if (Array.isArray(val)) {
|
if (Array.isArray(val)) {
|
||||||
return val
|
return val
|
||||||
@@ -127,3 +139,24 @@ const flattenMessages = (
|
|||||||
}
|
}
|
||||||
return val.prompt.trim();
|
return val.prompt.trim();
|
||||||
};
|
};
|
||||||
|
|
||||||
|
function isGoogleAIChatPrompt(
|
||||||
|
val: unknown
|
||||||
|
): val is { contents: GoogleAIChatMessage[] } {
|
||||||
|
return (
|
||||||
|
typeof val === "object" &&
|
||||||
|
val !== null &&
|
||||||
|
"contents" in val
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function isAnthropicChatPrompt(
|
||||||
|
val: unknown
|
||||||
|
): val is { system: string; messages: AnthropicChatMessage[] } {
|
||||||
|
return (
|
||||||
|
typeof val === "object" &&
|
||||||
|
val !== null &&
|
||||||
|
"system" in val &&
|
||||||
|
"messages" in val
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|||||||
@@ -67,6 +67,10 @@ export class EventAggregator {
|
|||||||
assertNever(this.format);
|
assertNever(this.format);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
hasEvents() {
|
||||||
|
return this.events.length > 0;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
function eventIsOpenAIEvent(
|
function eventIsOpenAIEvent(
|
||||||
|
|||||||
@@ -2,9 +2,8 @@ import pino from "pino";
|
|||||||
import { Transform, TransformOptions } from "stream";
|
import { Transform, TransformOptions } from "stream";
|
||||||
import { Message } from "@smithy/eventstream-codec";
|
import { Message } from "@smithy/eventstream-codec";
|
||||||
import { APIFormat } from "../../../../shared/key-management";
|
import { APIFormat } from "../../../../shared/key-management";
|
||||||
import { RetryableError } from "../index";
|
|
||||||
import { buildSpoofedSSE } from "../error-generator";
|
import { buildSpoofedSSE } from "../error-generator";
|
||||||
import { BadRequestError } from "../../../../shared/errors";
|
import { BadRequestError, RetryableError } from "../../../../shared/errors";
|
||||||
|
|
||||||
type SSEStreamAdapterOptions = TransformOptions & {
|
type SSEStreamAdapterOptions = TransformOptions & {
|
||||||
contentType?: string;
|
contentType?: string;
|
||||||
@@ -117,7 +116,7 @@ export class SSEStreamAdapter extends Transform {
|
|||||||
try {
|
try {
|
||||||
const hasParts = candidates[0].content?.parts?.length > 0;
|
const hasParts = candidates[0].content?.parts?.length > 0;
|
||||||
if (hasParts) {
|
if (hasParts) {
|
||||||
return `data: ${JSON.stringify(data)}`;
|
return `data: ${JSON.stringify(data.value ?? data)}\n`;
|
||||||
} else {
|
} else {
|
||||||
this.log.error({ event: data }, "Received bad Google AI event");
|
this.log.error({ event: data }, "Received bad Google AI event");
|
||||||
return `data: ${buildSpoofedSSE({
|
return `data: ${buildSpoofedSSE({
|
||||||
|
|||||||
@@ -70,7 +70,7 @@ export function generateModelList(models = KNOWN_MISTRAL_AI_MODELS) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
const handleModelRequest: RequestHandler = (_req, res) => {
|
const handleModelRequest: RequestHandler = (_req, res) => {
|
||||||
if (new Date().getTime() - modelsCacheTime < 1000 * 60){
|
if (new Date().getTime() - modelsCacheTime < 1000 * 60) {
|
||||||
return res.status(200).json(modelsCache);
|
return res.status(200).json(modelsCache);
|
||||||
}
|
}
|
||||||
const result = generateModelList();
|
const result = generateModelList();
|
||||||
|
|||||||
+8
-4
@@ -28,10 +28,14 @@ import {
|
|||||||
|
|
||||||
// https://platform.openai.com/docs/models/overview
|
// https://platform.openai.com/docs/models/overview
|
||||||
export const KNOWN_OPENAI_MODELS = [
|
export const KNOWN_OPENAI_MODELS = [
|
||||||
"gpt-4-turbo-preview",
|
"gpt-4o",
|
||||||
"gpt-4-0125-preview",
|
"gpt-4o-2024-05-13",
|
||||||
"gpt-4-1106-preview",
|
"gpt-4-turbo", // alias for latest gpt4-turbo stable
|
||||||
"gpt-4-vision-preview",
|
"gpt-4-turbo-2024-04-09", // gpt4-turbo stable, with vision
|
||||||
|
"gpt-4-turbo-preview", // alias for latest turbo preview
|
||||||
|
"gpt-4-0125-preview", // gpt4-turbo preview 2
|
||||||
|
"gpt-4-1106-preview", // gpt4-turbo preview 1
|
||||||
|
"gpt-4-vision-preview", // gpt4-turbo preview 1 with vision
|
||||||
"gpt-4",
|
"gpt-4",
|
||||||
"gpt-4-0613",
|
"gpt-4-0613",
|
||||||
"gpt-4-0314", // EOL 2024-06-13
|
"gpt-4-0314", // EOL 2024-06-13
|
||||||
|
|||||||
+11
-2
@@ -12,7 +12,7 @@
|
|||||||
*/
|
*/
|
||||||
|
|
||||||
import crypto from "crypto";
|
import crypto from "crypto";
|
||||||
import type { Handler, Request } from "express";
|
import { Handler, Request } from "express";
|
||||||
import { BadRequestError, TooManyRequestsError } from "../shared/errors";
|
import { BadRequestError, TooManyRequestsError } from "../shared/errors";
|
||||||
import { keyPool } from "../shared/key-management";
|
import { keyPool } from "../shared/key-management";
|
||||||
import {
|
import {
|
||||||
@@ -67,7 +67,7 @@ const sharesIdentifierWith = (incoming: Request) => (queued: Request) =>
|
|||||||
|
|
||||||
const isFromSharedIp = (req: Request) => SHARED_IP_ADDRESSES.has(req.ip);
|
const isFromSharedIp = (req: Request) => SHARED_IP_ADDRESSES.has(req.ip);
|
||||||
|
|
||||||
export async function enqueue(req: Request) {
|
async function enqueue(req: Request) {
|
||||||
const enqueuedRequestCount = queue.filter(sharesIdentifierWith(req)).length;
|
const enqueuedRequestCount = queue.filter(sharesIdentifierWith(req)).length;
|
||||||
let isGuest = req.user?.token === undefined;
|
let isGuest = req.user?.token === undefined;
|
||||||
|
|
||||||
@@ -136,6 +136,15 @@ export async function enqueue(req: Request) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export async function reenqueueRequest(req: Request) {
|
||||||
|
req.log.info(
|
||||||
|
{ key: req.key?.hash, retryCount: req.retryCount },
|
||||||
|
`Re-enqueueing request due to retryable error`
|
||||||
|
);
|
||||||
|
req.retryCount++;
|
||||||
|
await enqueue(req);
|
||||||
|
}
|
||||||
|
|
||||||
function getQueueForPartition(partition: ModelFamily): Request[] {
|
function getQueueForPartition(partition: ModelFamily): Request[] {
|
||||||
return queue
|
return queue
|
||||||
.filter((req) => getModelFamilyForRequest(req) === partition)
|
.filter((req) => getModelFamilyForRequest(req) === partition)
|
||||||
|
|||||||
+39
-1
@@ -8,6 +8,7 @@ import pinoHttp from "pino-http";
|
|||||||
import os from "os";
|
import os from "os";
|
||||||
import childProcess from "child_process";
|
import childProcess from "child_process";
|
||||||
import { logger } from "./logger";
|
import { logger } from "./logger";
|
||||||
|
import { createBlacklistMiddleware } from "./shared/cidr";
|
||||||
import { setupAssetsDir } from "./shared/file-storage/setup-assets-dir";
|
import { setupAssetsDir } from "./shared/file-storage/setup-assets-dir";
|
||||||
import { keyPool } from "./shared/key-management";
|
import { keyPool } from "./shared/key-management";
|
||||||
import { adminRouter } from "./admin/routes";
|
import { adminRouter } from "./admin/routes";
|
||||||
@@ -21,6 +22,7 @@ import { init as initUserStore } from "./shared/users/user-store";
|
|||||||
import { init as initTokenizers } from "./shared/tokenization";
|
import { init as initTokenizers } from "./shared/tokenization";
|
||||||
import { checkOrigin } from "./proxy/check-origin";
|
import { checkOrigin } from "./proxy/check-origin";
|
||||||
import { sendErrorToClient } from "./proxy/middleware/response/error-generator";
|
import { sendErrorToClient } from "./proxy/middleware/response/error-generator";
|
||||||
|
import { initializeDatabase, getDatabase } from "./shared/database";
|
||||||
|
|
||||||
const PORT = config.port;
|
const PORT = config.port;
|
||||||
const BIND_ADDRESS = config.bindAddress;
|
const BIND_ADDRESS = config.bindAddress;
|
||||||
@@ -31,13 +33,19 @@ app.use(
|
|||||||
pinoHttp({
|
pinoHttp({
|
||||||
quietReqLogger: true,
|
quietReqLogger: true,
|
||||||
logger,
|
logger,
|
||||||
autoLogging: { ignore: ({ url }) => ["/health"].includes(url as string) },
|
autoLogging: {
|
||||||
|
ignore: ({ url }) => {
|
||||||
|
const ignoreList = ["/health", "/res", "/user_content"];
|
||||||
|
return ignoreList.some((path) => (url as string).startsWith(path));
|
||||||
|
},
|
||||||
|
},
|
||||||
redact: {
|
redact: {
|
||||||
paths: [
|
paths: [
|
||||||
"req.headers.cookie",
|
"req.headers.cookie",
|
||||||
'res.headers["set-cookie"]',
|
'res.headers["set-cookie"]',
|
||||||
"req.headers.authorization",
|
"req.headers.authorization",
|
||||||
'req.headers["x-api-key"]',
|
'req.headers["x-api-key"]',
|
||||||
|
'req.headers["api-key"]',
|
||||||
// Don't log the prompt text on transform errors
|
// Don't log the prompt text on transform errors
|
||||||
"body.messages",
|
"body.messages",
|
||||||
"body.prompt",
|
"body.prompt",
|
||||||
@@ -62,9 +70,20 @@ app.set("views", [
|
|||||||
]);
|
]);
|
||||||
|
|
||||||
app.use("/user_content", express.static(USER_ASSETS_DIR, { maxAge: "2h" }));
|
app.use("/user_content", express.static(USER_ASSETS_DIR, { maxAge: "2h" }));
|
||||||
|
app.use(
|
||||||
|
"/res",
|
||||||
|
express.static(path.join(__dirname, "..", "public"), {
|
||||||
|
maxAge: "2h",
|
||||||
|
etag: false,
|
||||||
|
})
|
||||||
|
);
|
||||||
|
|
||||||
app.get("/health", (_req, res) => res.sendStatus(200));
|
app.get("/health", (_req, res) => res.sendStatus(200));
|
||||||
app.use(cors());
|
app.use(cors());
|
||||||
|
|
||||||
|
const blacklist = createBlacklistMiddleware("IP_BLACKLIST", config.ipBlacklist);
|
||||||
|
app.use(blacklist);
|
||||||
|
|
||||||
app.use(checkOrigin);
|
app.use(checkOrigin);
|
||||||
|
|
||||||
app.use("/admin", adminRouter);
|
app.use("/admin", adminRouter);
|
||||||
@@ -125,6 +144,8 @@ async function start() {
|
|||||||
await logQueue.start();
|
await logQueue.start();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
await initializeDatabase();
|
||||||
|
|
||||||
logger.info("Starting request queue...");
|
logger.info("Starting request queue...");
|
||||||
startRequestQueue();
|
startRequestQueue();
|
||||||
|
|
||||||
@@ -146,6 +167,23 @@ async function start() {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function cleanup() {
|
||||||
|
console.log("Shutting down...");
|
||||||
|
if (config.eventLogging) {
|
||||||
|
try {
|
||||||
|
const db = getDatabase();
|
||||||
|
db.close();
|
||||||
|
console.log("Closed sqlite database.");
|
||||||
|
} catch (error) {}
|
||||||
|
}
|
||||||
|
process.exit(0);
|
||||||
|
}
|
||||||
|
|
||||||
|
process.on("exit", () => cleanup());
|
||||||
|
process.on("SIGHUP", () => process.exit(128 + 1));
|
||||||
|
process.on("SIGINT", () => process.exit(128 + 2));
|
||||||
|
process.on("SIGTERM", () => process.exit(128 + 15));
|
||||||
|
|
||||||
function registerUncaughtExceptionHandler() {
|
function registerUncaughtExceptionHandler() {
|
||||||
process.on("uncaughtException", (err: any) => {
|
process.on("uncaughtException", (err: any) => {
|
||||||
logger.error(
|
logger.error(
|
||||||
|
|||||||
+26
-22
@@ -80,6 +80,7 @@ type OpenAIInfo = BaseFamilyInfo & {
|
|||||||
overQuotaKeys?: number;
|
overQuotaKeys?: number;
|
||||||
};
|
};
|
||||||
type AnthropicInfo = BaseFamilyInfo & {
|
type AnthropicInfo = BaseFamilyInfo & {
|
||||||
|
trialKeys?: number;
|
||||||
prefilledKeys?: number;
|
prefilledKeys?: number;
|
||||||
overQuotaKeys?: number;
|
overQuotaKeys?: number;
|
||||||
};
|
};
|
||||||
@@ -140,8 +141,6 @@ const SERVICE_ENDPOINTS: { [s in LLMService]: Record<string, string> } = {
|
|||||||
},
|
},
|
||||||
anthropic: {
|
anthropic: {
|
||||||
anthropic: `%BASE%/anthropic`,
|
anthropic: `%BASE%/anthropic`,
|
||||||
"anthropic-sonnet (⚠️Temporary: for Claude 3 Sonnet)": `%BASE%/anthropic/sonnet`,
|
|
||||||
"anthropic-opus (⚠️Temporary: for Claude 3 Opus)": `%BASE%/anthropic/opus`,
|
|
||||||
},
|
},
|
||||||
"google-ai": {
|
"google-ai": {
|
||||||
"google-ai": `%BASE%/google-ai`,
|
"google-ai": `%BASE%/google-ai`,
|
||||||
@@ -151,7 +150,6 @@ const SERVICE_ENDPOINTS: { [s in LLMService]: Record<string, string> } = {
|
|||||||
},
|
},
|
||||||
aws: {
|
aws: {
|
||||||
aws: `%BASE%/aws/claude`,
|
aws: `%BASE%/aws/claude`,
|
||||||
"aws-sonnet (⚠️Temporary: for AWS Claude 3 Sonnet)": `%BASE%/aws/claude/sonnet`,
|
|
||||||
},
|
},
|
||||||
azure: {
|
azure: {
|
||||||
azure: `%BASE%/azure/openai`,
|
azure: `%BASE%/azure/openai`,
|
||||||
@@ -211,7 +209,8 @@ export function buildInfo(baseUrl: string, forAdmin = false): ServiceInfo {
|
|||||||
}
|
}
|
||||||
|
|
||||||
function getStatus() {
|
function getStatus() {
|
||||||
if (!config.checkKeys) return "Key checking is disabled.";
|
if (!config.checkKeys)
|
||||||
|
return "Key checking is disabled. The data displayed are not reliable.";
|
||||||
|
|
||||||
let unchecked = 0;
|
let unchecked = 0;
|
||||||
for (const service of LLM_SERVICES) {
|
for (const service of LLM_SERVICES) {
|
||||||
@@ -349,6 +348,7 @@ function addKeyToAggregates(k: KeyPoolKey) {
|
|||||||
sumTokens += tokens;
|
sumTokens += tokens;
|
||||||
sumCost += getTokenCostUsd(f, tokens);
|
sumCost += getTokenCostUsd(f, tokens);
|
||||||
increment(modelStats, `${f}__tokens`, tokens);
|
increment(modelStats, `${f}__tokens`, tokens);
|
||||||
|
increment(modelStats, `${f}__trial`, k.tier === "free" ? 1 : 0);
|
||||||
increment(modelStats, `${f}__revoked`, k.isRevoked ? 1 : 0);
|
increment(modelStats, `${f}__revoked`, k.isRevoked ? 1 : 0);
|
||||||
increment(modelStats, `${f}__active`, k.isDisabled ? 0 : 1);
|
increment(modelStats, `${f}__active`, k.isDisabled ? 0 : 1);
|
||||||
increment(modelStats, `${f}__overQuota`, k.isOverQuota ? 1 : 0);
|
increment(modelStats, `${f}__overQuota`, k.isOverQuota ? 1 : 0);
|
||||||
@@ -385,21 +385,22 @@ function addKeyToAggregates(k: KeyPoolKey) {
|
|||||||
}
|
}
|
||||||
case "aws": {
|
case "aws": {
|
||||||
if (!keyIsAwsKey(k)) throw new Error("Invalid key type");
|
if (!keyIsAwsKey(k)) throw new Error("Invalid key type");
|
||||||
const family = "aws-claude";
|
k.modelFamilies.forEach((f) => {
|
||||||
sumTokens += k["aws-claudeTokens"];
|
const tokens = k[`${f}Tokens`];
|
||||||
sumCost += getTokenCostUsd(family, k["aws-claudeTokens"]);
|
sumTokens += tokens;
|
||||||
increment(modelStats, `${family}__active`, k.isDisabled ? 0 : 1);
|
sumCost += getTokenCostUsd(f, tokens);
|
||||||
increment(modelStats, `${family}__revoked`, k.isRevoked ? 1 : 0);
|
increment(modelStats, `${f}__tokens`, tokens);
|
||||||
increment(modelStats, `${family}__tokens`, k["aws-claudeTokens"]);
|
increment(modelStats, `${f}__revoked`, k.isRevoked ? 1 : 0);
|
||||||
increment(modelStats, `${family}__awsSonnet`, k.sonnetEnabled ? 1 : 0);
|
increment(modelStats, `${f}__active`, k.isDisabled ? 0 : 1);
|
||||||
increment(modelStats, `${family}__awsHaiku`, k.haikuEnabled ? 1 : 0);
|
});
|
||||||
|
increment(modelStats, `aws-claude__awsSonnet`, k.sonnetEnabled ? 1 : 0);
|
||||||
|
increment(modelStats, `aws-claude__awsHaiku`, k.haikuEnabled ? 1 : 0);
|
||||||
|
|
||||||
// Ignore revoked keys for aws logging stats, but include keys where the
|
// Ignore revoked keys for aws logging stats, but include keys where the
|
||||||
// logging status is unknown.
|
// logging status is unknown.
|
||||||
const countAsLogged =
|
const countAsLogged =
|
||||||
k.lastChecked && !k.isDisabled && k.awsLoggingStatus !== "disabled";
|
k.lastChecked && !k.isDisabled && k.awsLoggingStatus === "enabled";
|
||||||
increment(modelStats, `${family}__awsLogged`, countAsLogged ? 1 : 0);
|
increment(modelStats, `aws-claude__awsLogged`, countAsLogged ? 1 : 0);
|
||||||
|
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
default:
|
default:
|
||||||
@@ -437,16 +438,19 @@ function getInfoForFamily(family: ModelFamily): BaseFamilyInfo {
|
|||||||
break;
|
break;
|
||||||
case "anthropic":
|
case "anthropic":
|
||||||
info.overQuotaKeys = modelStats.get(`${family}__overQuota`) || 0;
|
info.overQuotaKeys = modelStats.get(`${family}__overQuota`) || 0;
|
||||||
|
info.trialKeys = modelStats.get(`${family}__trial`) || 0;
|
||||||
info.prefilledKeys = modelStats.get(`${family}__pozzed`) || 0;
|
info.prefilledKeys = modelStats.get(`${family}__pozzed`) || 0;
|
||||||
break;
|
break;
|
||||||
case "aws":
|
case "aws":
|
||||||
info.sonnetKeys = modelStats.get(`${family}__awsSonnet`) || 0;
|
if (family === "aws-claude") {
|
||||||
info.haikuKeys = modelStats.get(`${family}__awsHaiku`) || 0;
|
info.sonnetKeys = modelStats.get(`${family}__awsSonnet`) || 0;
|
||||||
const logged = modelStats.get(`${family}__awsLogged`) || 0;
|
info.haikuKeys = modelStats.get(`${family}__awsHaiku`) || 0;
|
||||||
if (logged > 0) {
|
const logged = modelStats.get(`${family}__awsLogged`) || 0;
|
||||||
info.privacy = config.allowAwsLogging
|
if (logged > 0) {
|
||||||
? `${logged} active keys are potentially logged.`
|
info.privacy = config.allowAwsLogging
|
||||||
: `${logged} active keys are potentially logged and can't be used. Set ALLOW_AWS_LOGGING=true to override.`;
|
? `AWS logging verification inactive. Prompts could be logged.`
|
||||||
|
: `${logged} active keys are potentially logged and can't be used. Set ALLOW_AWS_LOGGING=true to override.`;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
|
|||||||
+175
-18
@@ -1,23 +1,98 @@
|
|||||||
import { AnthropicChatMessage, AnthropicV1MessagesSchema } from "./schema";
|
import { z } from "zod";
|
||||||
import { AnthropicV1TextSchema, APIRequestTransformer, OpenAIChatMessage } from "../../index";
|
import { config } from "../../config";
|
||||||
import { BadRequestError } from "../../../errors";
|
import { BadRequestError } from "../errors";
|
||||||
|
import {
|
||||||
|
flattenOpenAIMessageContent,
|
||||||
|
OpenAIChatMessage,
|
||||||
|
OpenAIV1ChatCompletionSchema,
|
||||||
|
} from "./openai";
|
||||||
|
import { APIFormatTransformer } from "./index";
|
||||||
|
|
||||||
import { OpenAIV1ChatCompletionSchema } from "../openai/schema";
|
const CLAUDE_OUTPUT_MAX = config.maxOutputTokensAnthropic;
|
||||||
|
|
||||||
/**
|
const AnthropicV1BaseSchema = z
|
||||||
* Represents the union of all content types without the `string` shorthand
|
.object({
|
||||||
* for `text` content.
|
model: z.string().max(100),
|
||||||
*/
|
stop_sequences: z.array(z.string().max(500)).optional(),
|
||||||
type AnthropicChatMessageContentWithoutString = Exclude<
|
stream: z.boolean().optional().default(false),
|
||||||
AnthropicChatMessage["content"],
|
temperature: z.coerce.number().optional().default(1),
|
||||||
string
|
top_k: z.coerce.number().optional(),
|
||||||
>;
|
top_p: z.coerce.number().optional(),
|
||||||
/** Represents a message with all shorthand `string` content expanded. */
|
metadata: z.object({ user_id: z.string().optional() }).optional(),
|
||||||
type ConvertedAnthropicChatMessage = AnthropicChatMessage & {
|
})
|
||||||
content: AnthropicChatMessageContentWithoutString;
|
.strip();
|
||||||
};
|
|
||||||
|
|
||||||
export const transformOpenAIToAnthropicChat: APIRequestTransformer<
|
// https://docs.anthropic.com/claude/reference/complete_post [deprecated]
|
||||||
|
export const AnthropicV1TextSchema = AnthropicV1BaseSchema.merge(
|
||||||
|
z.object({
|
||||||
|
prompt: z.string(),
|
||||||
|
max_tokens_to_sample: z.coerce
|
||||||
|
.number()
|
||||||
|
.int()
|
||||||
|
.transform((v) => Math.min(v, CLAUDE_OUTPUT_MAX)),
|
||||||
|
})
|
||||||
|
);
|
||||||
|
|
||||||
|
const AnthropicV1MessageMultimodalContentSchema = z.array(
|
||||||
|
z.union([
|
||||||
|
z.object({ type: z.literal("text"), text: z.string() }),
|
||||||
|
z.object({
|
||||||
|
type: z.literal("image"),
|
||||||
|
source: z.object({
|
||||||
|
type: z.literal("base64"),
|
||||||
|
media_type: z.string().max(100),
|
||||||
|
data: z.string(),
|
||||||
|
}),
|
||||||
|
}),
|
||||||
|
])
|
||||||
|
);
|
||||||
|
|
||||||
|
// https://docs.anthropic.com/claude/reference/messages_post
|
||||||
|
export const AnthropicV1MessagesSchema = AnthropicV1BaseSchema.merge(
|
||||||
|
z.object({
|
||||||
|
messages: z.array(
|
||||||
|
z.object({
|
||||||
|
role: z.enum(["user", "assistant"]),
|
||||||
|
content: z.union([
|
||||||
|
z.string(),
|
||||||
|
AnthropicV1MessageMultimodalContentSchema,
|
||||||
|
]),
|
||||||
|
})
|
||||||
|
),
|
||||||
|
max_tokens: z
|
||||||
|
.number()
|
||||||
|
.int()
|
||||||
|
.transform((v) => Math.min(v, CLAUDE_OUTPUT_MAX)),
|
||||||
|
system: z.string().optional(),
|
||||||
|
})
|
||||||
|
);
|
||||||
|
export type AnthropicChatMessage = z.infer<
|
||||||
|
typeof AnthropicV1MessagesSchema
|
||||||
|
>["messages"][0];
|
||||||
|
|
||||||
|
function openAIMessagesToClaudeTextPrompt(messages: OpenAIChatMessage[]) {
|
||||||
|
return (
|
||||||
|
messages
|
||||||
|
.map((m) => {
|
||||||
|
let role: string = m.role;
|
||||||
|
if (role === "assistant") {
|
||||||
|
role = "Assistant";
|
||||||
|
} else if (role === "system") {
|
||||||
|
role = "System";
|
||||||
|
} else if (role === "user") {
|
||||||
|
role = "Human";
|
||||||
|
}
|
||||||
|
const name = m.name?.trim();
|
||||||
|
const content = flattenOpenAIMessageContent(m.content);
|
||||||
|
// https://console.anthropic.com/docs/prompt-design
|
||||||
|
// `name` isn't supported by Anthropic but we can still try to use it.
|
||||||
|
return `\n\n${role}: ${name ? `(as ${name}) ` : ""}${content}`;
|
||||||
|
})
|
||||||
|
.join("") + "\n\nAssistant:"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export const transformOpenAIToAnthropicChat: APIFormatTransformer<
|
||||||
typeof AnthropicV1MessagesSchema
|
typeof AnthropicV1MessagesSchema
|
||||||
> = async (req) => {
|
> = async (req) => {
|
||||||
const { body } = req;
|
const { body } = req;
|
||||||
@@ -52,11 +127,53 @@ export const transformOpenAIToAnthropicChat: APIRequestTransformer<
|
|||||||
};
|
};
|
||||||
};
|
};
|
||||||
|
|
||||||
|
export const transformOpenAIToAnthropicText: APIFormatTransformer<
|
||||||
|
typeof AnthropicV1TextSchema
|
||||||
|
> = async (req) => {
|
||||||
|
const { body } = req;
|
||||||
|
const result = OpenAIV1ChatCompletionSchema.safeParse(body);
|
||||||
|
if (!result.success) {
|
||||||
|
req.log.warn(
|
||||||
|
{ issues: result.error.issues, body },
|
||||||
|
"Invalid OpenAI-to-Anthropic Text request"
|
||||||
|
);
|
||||||
|
throw result.error;
|
||||||
|
}
|
||||||
|
|
||||||
|
req.headers["anthropic-version"] = "2023-06-01";
|
||||||
|
|
||||||
|
const { messages, ...rest } = result.data;
|
||||||
|
const prompt = openAIMessagesToClaudeTextPrompt(messages);
|
||||||
|
|
||||||
|
let stops = rest.stop
|
||||||
|
? Array.isArray(rest.stop)
|
||||||
|
? rest.stop
|
||||||
|
: [rest.stop]
|
||||||
|
: [];
|
||||||
|
// Recommended by Anthropic
|
||||||
|
stops.push("\n\nHuman:");
|
||||||
|
// Helps with jailbreak prompts that send fake system messages and multi-bot
|
||||||
|
// chats that prefix bot messages with "System: Respond as <bot name>".
|
||||||
|
stops.push("\n\nSystem:");
|
||||||
|
// Remove duplicates
|
||||||
|
stops = [...new Set(stops)];
|
||||||
|
|
||||||
|
return {
|
||||||
|
model: rest.model,
|
||||||
|
prompt: prompt,
|
||||||
|
max_tokens_to_sample: rest.max_tokens,
|
||||||
|
stop_sequences: stops,
|
||||||
|
stream: rest.stream,
|
||||||
|
temperature: rest.temperature,
|
||||||
|
top_p: rest.top_p,
|
||||||
|
};
|
||||||
|
};
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Converts an older Anthropic Text Completion prompt to the newer Messages API
|
* Converts an older Anthropic Text Completion prompt to the newer Messages API
|
||||||
* by splitting the flat text into messages.
|
* by splitting the flat text into messages.
|
||||||
*/
|
*/
|
||||||
export const transformAnthropicTextToAnthropicChat: APIRequestTransformer<
|
export const transformAnthropicTextToAnthropicChat: APIFormatTransformer<
|
||||||
typeof AnthropicV1MessagesSchema
|
typeof AnthropicV1MessagesSchema
|
||||||
> = async (req) => {
|
> = async (req) => {
|
||||||
const { body } = req;
|
const { body } = req;
|
||||||
@@ -138,6 +255,39 @@ function validateAnthropicTextPrompt(prompt: string) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export function flattenAnthropicMessages(
|
||||||
|
messages: AnthropicChatMessage[]
|
||||||
|
): string {
|
||||||
|
return messages
|
||||||
|
.map((msg) => {
|
||||||
|
const name = msg.role === "user" ? "Human" : "Assistant";
|
||||||
|
const parts = Array.isArray(msg.content)
|
||||||
|
? msg.content
|
||||||
|
: [{ type: "text", text: msg.content }];
|
||||||
|
return `${name}: ${parts
|
||||||
|
.map((part) =>
|
||||||
|
part.type === "text"
|
||||||
|
? part.text
|
||||||
|
: `[Omitted multimodal content of type ${part.type}]`
|
||||||
|
)
|
||||||
|
.join("\n")}`;
|
||||||
|
})
|
||||||
|
.join("\n\n");
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Represents the union of all content types without the `string` shorthand
|
||||||
|
* for `text` content.
|
||||||
|
*/
|
||||||
|
type AnthropicChatMessageContentWithoutString = Exclude<
|
||||||
|
AnthropicChatMessage["content"],
|
||||||
|
string
|
||||||
|
>;
|
||||||
|
/** Represents a message with all shorthand `string` content expanded. */
|
||||||
|
type ConvertedAnthropicChatMessage = AnthropicChatMessage & {
|
||||||
|
content: AnthropicChatMessageContentWithoutString;
|
||||||
|
};
|
||||||
|
|
||||||
function openAIMessagesToClaudeChatPrompt(messages: OpenAIChatMessage[]): {
|
function openAIMessagesToClaudeChatPrompt(messages: OpenAIChatMessage[]): {
|
||||||
messages: AnthropicChatMessage[];
|
messages: AnthropicChatMessage[];
|
||||||
system: string;
|
system: string;
|
||||||
@@ -288,3 +438,10 @@ function convertOpenAIContent(
|
|||||||
}
|
}
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export function containsImageContent(messages: AnthropicChatMessage[]) {
|
||||||
|
return messages.some(
|
||||||
|
({ content }) =>
|
||||||
|
typeof content !== "string" && content.some((c) => c.type === "image")
|
||||||
|
);
|
||||||
|
}
|
||||||
+38
-6
@@ -1,11 +1,43 @@
|
|||||||
import { APIRequestTransformer, GoogleAIChatMessage } from "../../index";
|
import { z } from "zod";
|
||||||
import { GoogleAIV1GenerateContentSchema } from "./schema";
|
import {
|
||||||
|
flattenOpenAIMessageContent,
|
||||||
|
OpenAIV1ChatCompletionSchema,
|
||||||
|
} from "./openai";
|
||||||
|
import { APIFormatTransformer } from "./index";
|
||||||
|
|
||||||
import { OpenAIV1ChatCompletionSchema } from "../openai/schema";
|
// https://developers.generativeai.google/api/rest/generativelanguage/models/generateContent
|
||||||
|
export const GoogleAIV1GenerateContentSchema = z
|
||||||
|
.object({
|
||||||
|
model: z.string().max(100), //actually specified in path but we need it for the router
|
||||||
|
stream: z.boolean().optional().default(false), // also used for router
|
||||||
|
contents: z.array(
|
||||||
|
z.object({
|
||||||
|
parts: z.array(z.object({ text: z.string() })),
|
||||||
|
role: z.enum(["user", "model"]),
|
||||||
|
})
|
||||||
|
),
|
||||||
|
tools: z.array(z.object({})).max(0).optional(),
|
||||||
|
safetySettings: z.array(z.object({})).max(0).optional(),
|
||||||
|
generationConfig: z.object({
|
||||||
|
temperature: z.number().optional(),
|
||||||
|
maxOutputTokens: z.coerce
|
||||||
|
.number()
|
||||||
|
.int()
|
||||||
|
.optional()
|
||||||
|
.default(16)
|
||||||
|
.transform((v) => Math.min(v, 1024)), // TODO: Add config
|
||||||
|
candidateCount: z.literal(1).optional(),
|
||||||
|
topP: z.number().optional(),
|
||||||
|
topK: z.number().optional(),
|
||||||
|
stopSequences: z.array(z.string().max(500)).max(5).optional(),
|
||||||
|
}),
|
||||||
|
})
|
||||||
|
.strip();
|
||||||
|
export type GoogleAIChatMessage = z.infer<
|
||||||
|
typeof GoogleAIV1GenerateContentSchema
|
||||||
|
>["contents"][0];
|
||||||
|
|
||||||
import { flattenOpenAIMessageContent } from "../openai/stringifier";
|
export const transformOpenAIToGoogleAI: APIFormatTransformer<
|
||||||
|
|
||||||
export const transformOpenAIToGoogleAI: APIRequestTransformer<
|
|
||||||
typeof GoogleAIV1GenerateContentSchema
|
typeof GoogleAIV1GenerateContentSchema
|
||||||
> = async (req) => {
|
> = async (req) => {
|
||||||
const { body } = req;
|
const { body } = req;
|
||||||
@@ -0,0 +1,62 @@
|
|||||||
|
import type { Request } from "express";
|
||||||
|
import { z } from "zod";
|
||||||
|
import { APIFormat } from "../key-management";
|
||||||
|
import {
|
||||||
|
AnthropicV1TextSchema,
|
||||||
|
AnthropicV1MessagesSchema,
|
||||||
|
transformAnthropicTextToAnthropicChat,
|
||||||
|
transformOpenAIToAnthropicText,
|
||||||
|
transformOpenAIToAnthropicChat,
|
||||||
|
} from "./anthropic";
|
||||||
|
import { OpenAIV1ChatCompletionSchema } from "./openai";
|
||||||
|
import {
|
||||||
|
OpenAIV1TextCompletionSchema,
|
||||||
|
transformOpenAIToOpenAIText,
|
||||||
|
} from "./openai-text";
|
||||||
|
import {
|
||||||
|
OpenAIV1ImagesGenerationSchema,
|
||||||
|
transformOpenAIToOpenAIImage,
|
||||||
|
} from "./openai-image";
|
||||||
|
import {
|
||||||
|
GoogleAIV1GenerateContentSchema,
|
||||||
|
transformOpenAIToGoogleAI,
|
||||||
|
} from "./google-ai";
|
||||||
|
import { MistralAIV1ChatCompletionsSchema } from "./mistral-ai";
|
||||||
|
|
||||||
|
export { OpenAIChatMessage } from "./openai";
|
||||||
|
export {
|
||||||
|
AnthropicChatMessage,
|
||||||
|
AnthropicV1TextSchema,
|
||||||
|
AnthropicV1MessagesSchema,
|
||||||
|
flattenAnthropicMessages,
|
||||||
|
} from "./anthropic";
|
||||||
|
export { GoogleAIChatMessage } from "./google-ai";
|
||||||
|
export { MistralAIChatMessage } from "./mistral-ai";
|
||||||
|
|
||||||
|
type APIPair = `${APIFormat}->${APIFormat}`;
|
||||||
|
type TransformerMap = {
|
||||||
|
[key in APIPair]?: APIFormatTransformer<any>;
|
||||||
|
};
|
||||||
|
|
||||||
|
export type APIFormatTransformer<Z extends z.ZodType<any, any>> = (
|
||||||
|
req: Request
|
||||||
|
) => Promise<z.infer<Z>>;
|
||||||
|
|
||||||
|
export const API_REQUEST_TRANSFORMERS: TransformerMap = {
|
||||||
|
"anthropic-text->anthropic-chat": transformAnthropicTextToAnthropicChat,
|
||||||
|
"openai->anthropic-chat": transformOpenAIToAnthropicChat,
|
||||||
|
"openai->anthropic-text": transformOpenAIToAnthropicText,
|
||||||
|
"openai->openai-text": transformOpenAIToOpenAIText,
|
||||||
|
"openai->openai-image": transformOpenAIToOpenAIImage,
|
||||||
|
"openai->google-ai": transformOpenAIToGoogleAI,
|
||||||
|
};
|
||||||
|
|
||||||
|
export const API_REQUEST_VALIDATORS: Record<APIFormat, z.ZodSchema<any>> = {
|
||||||
|
"anthropic-chat": AnthropicV1MessagesSchema,
|
||||||
|
"anthropic-text": AnthropicV1TextSchema,
|
||||||
|
openai: OpenAIV1ChatCompletionSchema,
|
||||||
|
"openai-text": OpenAIV1TextCompletionSchema,
|
||||||
|
"openai-image": OpenAIV1ImagesGenerationSchema,
|
||||||
|
"google-ai": GoogleAIV1GenerateContentSchema,
|
||||||
|
"mistral-ai": MistralAIV1ChatCompletionsSchema,
|
||||||
|
};
|
||||||
+26
-1
@@ -1,4 +1,29 @@
|
|||||||
import { MistralAIChatMessage } from "./schema";
|
import { z } from "zod";
|
||||||
|
import { OPENAI_OUTPUT_MAX } from "./openai";
|
||||||
|
|
||||||
|
// https://docs.mistral.ai/api#operation/createChatCompletion
|
||||||
|
export const MistralAIV1ChatCompletionsSchema = z.object({
|
||||||
|
model: z.string(),
|
||||||
|
messages: z.array(
|
||||||
|
z.object({
|
||||||
|
role: z.enum(["system", "user", "assistant"]),
|
||||||
|
content: z.string(),
|
||||||
|
})
|
||||||
|
),
|
||||||
|
temperature: z.number().optional().default(0.7),
|
||||||
|
top_p: z.number().optional().default(1),
|
||||||
|
max_tokens: z.coerce
|
||||||
|
.number()
|
||||||
|
.int()
|
||||||
|
.nullish()
|
||||||
|
.transform((v) => Math.min(v ?? OPENAI_OUTPUT_MAX, OPENAI_OUTPUT_MAX)),
|
||||||
|
stream: z.boolean().optional().default(false),
|
||||||
|
safe_prompt: z.boolean().optional().default(false),
|
||||||
|
random_seed: z.number().int().optional(),
|
||||||
|
});
|
||||||
|
export type MistralAIChatMessage = z.infer<
|
||||||
|
typeof MistralAIV1ChatCompletionsSchema
|
||||||
|
>["messages"][0];
|
||||||
|
|
||||||
export function fixMistralPrompt(
|
export function fixMistralPrompt(
|
||||||
messages: MistralAIChatMessage[]
|
messages: MistralAIChatMessage[]
|
||||||
+22
-5
@@ -1,9 +1,26 @@
|
|||||||
/* Takes the last chat message and uses it verbatim as the image prompt. */
|
import { z } from "zod";
|
||||||
import { APIRequestTransformer } from "../../index";
|
import { OpenAIV1ChatCompletionSchema } from "./openai";
|
||||||
import { OpenAIV1ImagesGenerationSchema } from "./schema";
|
import { APIFormatTransformer } from "./index";
|
||||||
import { OpenAIV1ChatCompletionSchema } from "../openai/schema";
|
|
||||||
|
|
||||||
export const transformOpenAIToOpenAIImage: APIRequestTransformer<
|
// https://platform.openai.com/docs/api-reference/images/create
|
||||||
|
export const OpenAIV1ImagesGenerationSchema = z
|
||||||
|
.object({
|
||||||
|
prompt: z.string().max(4000),
|
||||||
|
model: z.string().max(100).optional(),
|
||||||
|
quality: z.enum(["standard", "hd"]).optional().default("standard"),
|
||||||
|
n: z.number().int().min(1).max(4).optional().default(1),
|
||||||
|
response_format: z.enum(["url", "b64_json"]).optional(),
|
||||||
|
size: z
|
||||||
|
.enum(["256x256", "512x512", "1024x1024", "1792x1024", "1024x1792"])
|
||||||
|
.optional()
|
||||||
|
.default("1024x1024"),
|
||||||
|
style: z.enum(["vivid", "natural"]).optional().default("vivid"),
|
||||||
|
user: z.string().max(500).optional(),
|
||||||
|
})
|
||||||
|
.strip();
|
||||||
|
|
||||||
|
// Takes the last chat message and uses it verbatim as the image prompt.
|
||||||
|
export const transformOpenAIToOpenAIImage: APIFormatTransformer<
|
||||||
typeof OpenAIV1ImagesGenerationSchema
|
typeof OpenAIV1ImagesGenerationSchema
|
||||||
> = async (req) => {
|
> = async (req) => {
|
||||||
const { body } = req;
|
const { body } = req;
|
||||||
@@ -0,0 +1,58 @@
|
|||||||
|
import { z } from "zod";
|
||||||
|
import {
|
||||||
|
flattenOpenAIChatMessages,
|
||||||
|
OpenAIV1ChatCompletionSchema,
|
||||||
|
} from "./openai";
|
||||||
|
import { APIFormatTransformer } from "./index";
|
||||||
|
|
||||||
|
export const OpenAIV1TextCompletionSchema = z
|
||||||
|
.object({
|
||||||
|
model: z
|
||||||
|
.string()
|
||||||
|
.max(100)
|
||||||
|
.regex(
|
||||||
|
/^gpt-3.5-turbo-instruct/,
|
||||||
|
"Model must start with 'gpt-3.5-turbo-instruct'"
|
||||||
|
),
|
||||||
|
prompt: z.string({
|
||||||
|
required_error:
|
||||||
|
"No `prompt` found. Ensure you've set the correct completion endpoint.",
|
||||||
|
}),
|
||||||
|
logprobs: z.number().int().nullish().default(null),
|
||||||
|
echo: z.boolean().optional().default(false),
|
||||||
|
best_of: z.literal(1).optional(),
|
||||||
|
stop: z
|
||||||
|
.union([z.string().max(500), z.array(z.string().max(500)).max(4)])
|
||||||
|
.optional(),
|
||||||
|
suffix: z.string().max(1000).optional(),
|
||||||
|
})
|
||||||
|
.strip()
|
||||||
|
.merge(OpenAIV1ChatCompletionSchema.omit({ messages: true, logprobs: true }));
|
||||||
|
|
||||||
|
export const transformOpenAIToOpenAIText: APIFormatTransformer<
|
||||||
|
typeof OpenAIV1TextCompletionSchema
|
||||||
|
> = async (req) => {
|
||||||
|
const { body } = req;
|
||||||
|
const result = OpenAIV1ChatCompletionSchema.safeParse(body);
|
||||||
|
if (!result.success) {
|
||||||
|
req.log.warn(
|
||||||
|
{ issues: result.error.issues, body },
|
||||||
|
"Invalid OpenAI-to-OpenAI-text request"
|
||||||
|
);
|
||||||
|
throw result.error;
|
||||||
|
}
|
||||||
|
|
||||||
|
const { messages, ...rest } = result.data;
|
||||||
|
const prompt = flattenOpenAIChatMessages(messages);
|
||||||
|
|
||||||
|
let stops = rest.stop
|
||||||
|
? Array.isArray(rest.stop)
|
||||||
|
? rest.stop
|
||||||
|
: [rest.stop]
|
||||||
|
: [];
|
||||||
|
stops.push("\n\nUser:");
|
||||||
|
stops = [...new Set(stops)];
|
||||||
|
|
||||||
|
const transformed = { ...rest, prompt: prompt, stop: stops };
|
||||||
|
return OpenAIV1TextCompletionSchema.parse(transformed);
|
||||||
|
};
|
||||||
@@ -1,7 +1,8 @@
|
|||||||
import { z } from "zod";
|
import { z } from "zod";
|
||||||
import { config } from "../../../../config";
|
import { config } from "../../config";
|
||||||
|
|
||||||
export const OPENAI_OUTPUT_MAX = config.maxOutputTokensOpenAI;
|
export const OPENAI_OUTPUT_MAX = config.maxOutputTokensOpenAI;
|
||||||
|
|
||||||
// https://platform.openai.com/docs/api-reference/chat/create
|
// https://platform.openai.com/docs/api-reference/chat/create
|
||||||
const OpenAIV1ChatContentArraySchema = z.array(
|
const OpenAIV1ChatContentArraySchema = z.array(
|
||||||
z.union([
|
z.union([
|
||||||
@@ -80,3 +81,63 @@ export const OpenAIV1ChatCompletionSchema = z
|
|||||||
export type OpenAIChatMessage = z.infer<
|
export type OpenAIChatMessage = z.infer<
|
||||||
typeof OpenAIV1ChatCompletionSchema
|
typeof OpenAIV1ChatCompletionSchema
|
||||||
>["messages"][0];
|
>["messages"][0];
|
||||||
|
|
||||||
|
export function flattenOpenAIMessageContent(
|
||||||
|
content: OpenAIChatMessage["content"]
|
||||||
|
): string {
|
||||||
|
return Array.isArray(content)
|
||||||
|
? content
|
||||||
|
.map((contentItem) => {
|
||||||
|
if ("text" in contentItem) return contentItem.text;
|
||||||
|
if ("image_url" in contentItem) return "[ Uploaded Image Omitted ]";
|
||||||
|
})
|
||||||
|
.join("\n")
|
||||||
|
: content;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function flattenOpenAIChatMessages(messages: OpenAIChatMessage[]) {
|
||||||
|
// Temporary to allow experimenting with prompt strategies
|
||||||
|
const PROMPT_VERSION: number = 1;
|
||||||
|
switch (PROMPT_VERSION) {
|
||||||
|
case 1:
|
||||||
|
return (
|
||||||
|
messages
|
||||||
|
.map((m) => {
|
||||||
|
// Claude-style human/assistant turns
|
||||||
|
let role: string = m.role;
|
||||||
|
if (role === "assistant") {
|
||||||
|
role = "Assistant";
|
||||||
|
} else if (role === "system") {
|
||||||
|
role = "System";
|
||||||
|
} else if (role === "user") {
|
||||||
|
role = "User";
|
||||||
|
}
|
||||||
|
return `\n\n${role}: ${flattenOpenAIMessageContent(m.content)}`;
|
||||||
|
})
|
||||||
|
.join("") + "\n\nAssistant:"
|
||||||
|
);
|
||||||
|
case 2:
|
||||||
|
return messages
|
||||||
|
.map((m) => {
|
||||||
|
// Claude without prefixes (except system) and no Assistant priming
|
||||||
|
let role: string = "";
|
||||||
|
if (role === "system") {
|
||||||
|
role = "System: ";
|
||||||
|
}
|
||||||
|
return `\n\n${role}${flattenOpenAIMessageContent(m.content)}`;
|
||||||
|
})
|
||||||
|
.join("");
|
||||||
|
default:
|
||||||
|
throw new Error(`Unknown prompt version: ${PROMPT_VERSION}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export function containsImageContent(
|
||||||
|
messages: OpenAIChatMessage[]
|
||||||
|
): boolean {
|
||||||
|
return messages.some((m) =>
|
||||||
|
Array.isArray(m.content)
|
||||||
|
? m.content.some((contentItem) => "image_url" in contentItem)
|
||||||
|
: false
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -1,84 +0,0 @@
|
|||||||
import type { Request, Response } from "express";
|
|
||||||
import { z } from "zod";
|
|
||||||
import { APIFormat } from "../key-management";
|
|
||||||
import { AnthropicV1MessagesSchema } from "./kits/anthropic-chat/schema";
|
|
||||||
import { AnthropicV1TextSchema } from "./kits/anthropic-text/schema";
|
|
||||||
import { transformOpenAIToAnthropicText } from "./kits/anthropic-text/request-transformers";
|
|
||||||
import {
|
|
||||||
transformAnthropicTextToAnthropicChat,
|
|
||||||
transformOpenAIToAnthropicChat,
|
|
||||||
} from "./kits/anthropic-chat/request-transformers";
|
|
||||||
import { GoogleAIV1GenerateContentSchema } from "./kits/google-ai/schema";
|
|
||||||
import { transformOpenAIToGoogleAI } from "./kits/google-ai/request-transformers";
|
|
||||||
import { MistralAIV1ChatCompletionsSchema } from "./kits/mistral-ai/schema";
|
|
||||||
|
|
||||||
import { OpenAIV1ChatCompletionSchema } from "./kits/openai/schema";
|
|
||||||
import { OpenAIV1ImagesGenerationSchema } from "./kits/openai-image/schema";
|
|
||||||
import { transformOpenAIToOpenAIImage } from "./kits/openai-image/request-transformers";
|
|
||||||
import { OpenAIV1TextCompletionSchema } from "./kits/openai-text/schema";
|
|
||||||
import { transformOpenAIToOpenAIText } from "./kits/openai-text/request-transformers";
|
|
||||||
|
|
||||||
export type APIRequestTransformer<Z extends z.ZodType<any, any>> = (
|
|
||||||
req: Request
|
|
||||||
) => Promise<z.infer<Z>>;
|
|
||||||
|
|
||||||
export type APIResponseTransformer<Z extends z.ZodType<any, any>> = (
|
|
||||||
res: Response
|
|
||||||
) => Promise<z.infer<Z>>;
|
|
||||||
|
|
||||||
/** Represents a transformation from one API format to another. */
|
|
||||||
type APITransformation = `${APIFormat}->${APIFormat}`;
|
|
||||||
|
|
||||||
type APIRequestTransformerMap = {
|
|
||||||
[key in APITransformation]?: APIRequestTransformer<any>;
|
|
||||||
};
|
|
||||||
|
|
||||||
type APIResponseTransformerMap = {
|
|
||||||
[key in APITransformation]?: APIResponseTransformer<any>;
|
|
||||||
};
|
|
||||||
|
|
||||||
export const API_REQUEST_TRANSFORMERS: APIRequestTransformerMap = {
|
|
||||||
"anthropic-text->anthropic-chat": transformAnthropicTextToAnthropicChat,
|
|
||||||
"openai->anthropic-chat": transformOpenAIToAnthropicChat,
|
|
||||||
"openai->anthropic-text": transformOpenAIToAnthropicText,
|
|
||||||
"openai->openai-text": transformOpenAIToOpenAIText,
|
|
||||||
"openai->openai-image": transformOpenAIToOpenAIImage,
|
|
||||||
"openai->google-ai": transformOpenAIToGoogleAI,
|
|
||||||
};
|
|
||||||
|
|
||||||
export const API_REQUEST_VALIDATORS: Record<APIFormat, z.ZodSchema<any>> = {
|
|
||||||
"anthropic-chat": AnthropicV1MessagesSchema,
|
|
||||||
"anthropic-text": AnthropicV1TextSchema,
|
|
||||||
openai: OpenAIV1ChatCompletionSchema,
|
|
||||||
"openai-text": OpenAIV1TextCompletionSchema,
|
|
||||||
"openai-image": OpenAIV1ImagesGenerationSchema,
|
|
||||||
"google-ai": GoogleAIV1GenerateContentSchema,
|
|
||||||
"mistral-ai": MistralAIV1ChatCompletionsSchema,
|
|
||||||
};
|
|
||||||
export { AnthropicChatMessage } from "./kits/anthropic-chat/schema";
|
|
||||||
export { AnthropicV1MessagesSchema } from "./kits/anthropic-chat/schema";
|
|
||||||
export { AnthropicV1TextSchema } from "./kits/anthropic-text/schema";
|
|
||||||
|
|
||||||
export interface APIFormatKit<T extends APIFormat, P> {
|
|
||||||
name: T;
|
|
||||||
/** Zod schema for validating requests in this format. */
|
|
||||||
requestValidator: z.ZodSchema<any>;
|
|
||||||
/** Flattens non-sting prompts (such as message arrays) into a single string. */
|
|
||||||
promptStringifier: (prompt: P) => string;
|
|
||||||
/** Counts the number of tokens in a prompt. */
|
|
||||||
promptTokenCounter: (prompt: P, model: string) => Promise<number>;
|
|
||||||
/** Counts the number of tokens in a completion. */
|
|
||||||
completionTokenCounter: (
|
|
||||||
completion: string,
|
|
||||||
model: string
|
|
||||||
) => Promise<number>;
|
|
||||||
/** Functions which transform requests from other formats into this format. */
|
|
||||||
requestTransformers: APIRequestTransformerMap;
|
|
||||||
/** Functions which transform responses from this format into other formats. */
|
|
||||||
responseTransformers: APIResponseTransformerMap;
|
|
||||||
}
|
|
||||||
export { GoogleAIChatMessage } from "./kits/google-ai";
|
|
||||||
export { MistralAIChatMessage } from "./kits/mistral-ai";
|
|
||||||
|
|
||||||
export { OpenAIChatMessage } from "./kits/openai/schema";
|
|
||||||
export { flattenAnthropicMessages } from "./kits/anthropic-chat/stringifier";
|
|
||||||
@@ -1,4 +0,0 @@
|
|||||||
# API Kits
|
|
||||||
This directory contains "kits" for each supported language model API. Each kit implements the `APIFormatKit` interface and provides functionality that the proxy application needs to be able to validate requests, transform prompts and responses, tokenize text, and so forth.
|
|
||||||
|
|
||||||
## Structure
|
|
||||||
@@ -1,52 +0,0 @@
|
|||||||
import { z } from "zod";
|
|
||||||
import { config } from "../../../../config";
|
|
||||||
|
|
||||||
const CLAUDE_OUTPUT_MAX = config.maxOutputTokensAnthropic;
|
|
||||||
|
|
||||||
export const AnthropicV1BaseSchema = z
|
|
||||||
.object({
|
|
||||||
model: z.string().max(100),
|
|
||||||
stop_sequences: z.array(z.string().max(500)).optional(),
|
|
||||||
stream: z.boolean().optional().default(false),
|
|
||||||
temperature: z.coerce.number().optional().default(1),
|
|
||||||
top_k: z.coerce.number().optional(),
|
|
||||||
top_p: z.coerce.number().optional(),
|
|
||||||
metadata: z.object({ user_id: z.string().optional() }).optional(),
|
|
||||||
})
|
|
||||||
.strip();
|
|
||||||
const AnthropicV1MessageMultimodalContentSchema = z.array(
|
|
||||||
z.union([
|
|
||||||
z.object({ type: z.literal("text"), text: z.string() }),
|
|
||||||
z.object({
|
|
||||||
type: z.literal("image"),
|
|
||||||
source: z.object({
|
|
||||||
type: z.literal("base64"),
|
|
||||||
media_type: z.string().max(100),
|
|
||||||
data: z.string(),
|
|
||||||
}),
|
|
||||||
}),
|
|
||||||
])
|
|
||||||
);
|
|
||||||
|
|
||||||
// https://docs.anthropic.com/claude/reference/messages_post
|
|
||||||
export const AnthropicV1MessagesSchema = AnthropicV1BaseSchema.merge(
|
|
||||||
z.object({
|
|
||||||
messages: z.array(
|
|
||||||
z.object({
|
|
||||||
role: z.enum(["user", "assistant"]),
|
|
||||||
content: z.union([
|
|
||||||
z.string(),
|
|
||||||
AnthropicV1MessageMultimodalContentSchema,
|
|
||||||
]),
|
|
||||||
})
|
|
||||||
),
|
|
||||||
max_tokens: z
|
|
||||||
.number()
|
|
||||||
.int()
|
|
||||||
.transform((v) => Math.min(v, CLAUDE_OUTPUT_MAX)),
|
|
||||||
system: z.string().optional(),
|
|
||||||
})
|
|
||||||
);
|
|
||||||
export type AnthropicChatMessage = z.infer<
|
|
||||||
typeof AnthropicV1MessagesSchema
|
|
||||||
>["messages"][0];
|
|
||||||
@@ -1,21 +0,0 @@
|
|||||||
import { AnthropicChatMessage } from "./schema";
|
|
||||||
|
|
||||||
export function flattenAnthropicMessages(
|
|
||||||
messages: AnthropicChatMessage[]
|
|
||||||
): string {
|
|
||||||
return messages
|
|
||||||
.map((msg) => {
|
|
||||||
const name = msg.role === "user" ? "\n\nHuman: " : "\n\nAssistant: ";
|
|
||||||
const parts = Array.isArray(msg.content)
|
|
||||||
? msg.content
|
|
||||||
: [{ type: "text", text: msg.content }];
|
|
||||||
return `${name}: ${parts
|
|
||||||
.map((part) =>
|
|
||||||
part.type === "text"
|
|
||||||
? part.text
|
|
||||||
: `[Omitted multimodal content of type ${part.type}]`
|
|
||||||
)
|
|
||||||
.join("\n")}`;
|
|
||||||
})
|
|
||||||
.join("\n\n");
|
|
||||||
}
|
|
||||||
@@ -1,73 +0,0 @@
|
|||||||
import {
|
|
||||||
AnthropicV1TextSchema,
|
|
||||||
APIRequestTransformer,
|
|
||||||
OpenAIChatMessage,
|
|
||||||
} from "../../index";
|
|
||||||
|
|
||||||
import { OpenAIV1ChatCompletionSchema } from "../openai/schema";
|
|
||||||
|
|
||||||
import { flattenOpenAIMessageContent } from "../openai/stringifier";
|
|
||||||
|
|
||||||
export const transformOpenAIToAnthropicText: APIRequestTransformer<
|
|
||||||
typeof AnthropicV1TextSchema
|
|
||||||
> = async (req) => {
|
|
||||||
const { body } = req;
|
|
||||||
const result = OpenAIV1ChatCompletionSchema.safeParse(body);
|
|
||||||
if (!result.success) {
|
|
||||||
req.log.warn(
|
|
||||||
{ issues: result.error.issues, body },
|
|
||||||
"Invalid OpenAI-to-Anthropic Text request"
|
|
||||||
);
|
|
||||||
throw result.error;
|
|
||||||
}
|
|
||||||
|
|
||||||
req.headers["anthropic-version"] = "2023-06-01";
|
|
||||||
|
|
||||||
const { messages, ...rest } = result.data;
|
|
||||||
const prompt = openAIMessagesToClaudeTextPrompt(messages);
|
|
||||||
|
|
||||||
let stops = rest.stop
|
|
||||||
? Array.isArray(rest.stop)
|
|
||||||
? rest.stop
|
|
||||||
: [rest.stop]
|
|
||||||
: [];
|
|
||||||
// Recommended by Anthropic
|
|
||||||
stops.push("\n\nHuman:");
|
|
||||||
// Helps with jailbreak prompts that send fake system messages and multi-bot
|
|
||||||
// chats that prefix bot messages with "System: Respond as <bot name>".
|
|
||||||
stops.push("\n\nSystem:");
|
|
||||||
// Remove duplicates
|
|
||||||
stops = [...new Set(stops)];
|
|
||||||
|
|
||||||
return {
|
|
||||||
model: rest.model,
|
|
||||||
prompt: prompt,
|
|
||||||
max_tokens_to_sample: rest.max_tokens,
|
|
||||||
stop_sequences: stops,
|
|
||||||
stream: rest.stream,
|
|
||||||
temperature: rest.temperature,
|
|
||||||
top_p: rest.top_p,
|
|
||||||
};
|
|
||||||
};
|
|
||||||
|
|
||||||
function openAIMessagesToClaudeTextPrompt(messages: OpenAIChatMessage[]) {
|
|
||||||
return (
|
|
||||||
messages
|
|
||||||
.map((m) => {
|
|
||||||
let role: string = m.role;
|
|
||||||
if (role === "assistant") {
|
|
||||||
role = "Assistant";
|
|
||||||
} else if (role === "system") {
|
|
||||||
role = "System";
|
|
||||||
} else if (role === "user") {
|
|
||||||
role = "Human";
|
|
||||||
}
|
|
||||||
const name = m.name?.trim();
|
|
||||||
const content = flattenOpenAIMessageContent(m.content);
|
|
||||||
// https://console.anthropic.com/docs/prompt-design
|
|
||||||
// `name` isn't supported by Anthropic but we can still try to use it.
|
|
||||||
return `\n\n${role}: ${name ? `(as ${name}) ` : ""}${content}`;
|
|
||||||
})
|
|
||||||
.join("") + "\n\nAssistant:"
|
|
||||||
);
|
|
||||||
}
|
|
||||||
@@ -1,16 +0,0 @@
|
|||||||
import { z } from "zod";
|
|
||||||
import { AnthropicV1BaseSchema } from "../anthropic-chat/schema";
|
|
||||||
import { config } from "../../../../config";
|
|
||||||
|
|
||||||
const CLAUDE_OUTPUT_MAX = config.maxOutputTokensAnthropic;
|
|
||||||
|
|
||||||
// https://docs.anthropic.com/claude/reference/complete_post [deprecated]
|
|
||||||
export const AnthropicV1TextSchema = AnthropicV1BaseSchema.merge(
|
|
||||||
z.object({
|
|
||||||
prompt: z.string(),
|
|
||||||
max_tokens_to_sample: z.coerce
|
|
||||||
.number()
|
|
||||||
.int()
|
|
||||||
.transform((v) => Math.min(v, CLAUDE_OUTPUT_MAX)),
|
|
||||||
})
|
|
||||||
);
|
|
||||||
@@ -1 +0,0 @@
|
|||||||
export { GoogleAIChatMessage } from "./schema";
|
|
||||||
@@ -1,34 +0,0 @@
|
|||||||
import { z } from "zod";
|
|
||||||
|
|
||||||
// https://developers.generativeai.google/api/rest/generativelanguage/models/generateContent
|
|
||||||
export const GoogleAIV1GenerateContentSchema = z
|
|
||||||
.object({
|
|
||||||
model: z.string().max(100), //actually specified in path but we need it for the router
|
|
||||||
stream: z.boolean().optional().default(false), // also used for router
|
|
||||||
contents: z.array(
|
|
||||||
z.object({
|
|
||||||
parts: z.array(z.object({ text: z.string() })),
|
|
||||||
role: z.enum(["user", "model"]),
|
|
||||||
})
|
|
||||||
),
|
|
||||||
tools: z.array(z.object({})).max(0).optional(),
|
|
||||||
safetySettings: z.array(z.object({})).max(0).optional(),
|
|
||||||
generationConfig: z.object({
|
|
||||||
temperature: z.number().optional(),
|
|
||||||
maxOutputTokens: z.coerce
|
|
||||||
.number()
|
|
||||||
.int()
|
|
||||||
.optional()
|
|
||||||
.default(16)
|
|
||||||
.transform((v) => Math.min(v, 1024)), // TODO: Add config
|
|
||||||
candidateCount: z.literal(1).optional(),
|
|
||||||
topP: z.number().optional(),
|
|
||||||
topK: z.number().optional(),
|
|
||||||
stopSequences: z.array(z.string().max(500)).max(5).optional(),
|
|
||||||
}),
|
|
||||||
})
|
|
||||||
.strip();
|
|
||||||
|
|
||||||
export type GoogleAIChatMessage = z.infer<
|
|
||||||
typeof GoogleAIV1GenerateContentSchema
|
|
||||||
>["contents"][0];
|
|
||||||
@@ -1 +0,0 @@
|
|||||||
export { MistralAIChatMessage } from "./schema";
|
|
||||||
@@ -1,28 +0,0 @@
|
|||||||
// https://docs.mistral.ai/api#operation/createChatCompletion
|
|
||||||
import { z } from "zod";
|
|
||||||
|
|
||||||
|
|
||||||
import { OPENAI_OUTPUT_MAX } from "../openai/schema";
|
|
||||||
|
|
||||||
export const MistralAIV1ChatCompletionsSchema = z.object({
|
|
||||||
model: z.string(),
|
|
||||||
messages: z.array(
|
|
||||||
z.object({
|
|
||||||
role: z.enum(["system", "user", "assistant"]),
|
|
||||||
content: z.string(),
|
|
||||||
})
|
|
||||||
),
|
|
||||||
temperature: z.number().optional().default(0.7),
|
|
||||||
top_p: z.number().optional().default(1),
|
|
||||||
max_tokens: z.coerce
|
|
||||||
.number()
|
|
||||||
.int()
|
|
||||||
.nullish()
|
|
||||||
.transform((v) => Math.min(v ?? OPENAI_OUTPUT_MAX, OPENAI_OUTPUT_MAX)),
|
|
||||||
stream: z.boolean().optional().default(false),
|
|
||||||
safe_prompt: z.boolean().optional().default(false),
|
|
||||||
random_seed: z.number().int().optional(),
|
|
||||||
});
|
|
||||||
export type MistralAIChatMessage = z.infer<
|
|
||||||
typeof MistralAIV1ChatCompletionsSchema
|
|
||||||
>["messages"][0];
|
|
||||||
@@ -1,18 +0,0 @@
|
|||||||
// https://platform.openai.com/docs/api-reference/images/create
|
|
||||||
import { z } from "zod";
|
|
||||||
|
|
||||||
export const OpenAIV1ImagesGenerationSchema = z
|
|
||||||
.object({
|
|
||||||
prompt: z.string().max(4000),
|
|
||||||
model: z.string().max(100).optional(),
|
|
||||||
quality: z.enum(["standard", "hd"]).optional().default("standard"),
|
|
||||||
n: z.number().int().min(1).max(4).optional().default(1),
|
|
||||||
response_format: z.enum(["url", "b64_json"]).optional(),
|
|
||||||
size: z
|
|
||||||
.enum(["256x256", "512x512", "1024x1024", "1792x1024", "1024x1792"])
|
|
||||||
.optional()
|
|
||||||
.default("1024x1024"),
|
|
||||||
style: z.enum(["vivid", "natural"]).optional().default("vivid"),
|
|
||||||
user: z.string().max(500).optional(),
|
|
||||||
})
|
|
||||||
.strip();
|
|
||||||
@@ -1,33 +0,0 @@
|
|||||||
import { APIRequestTransformer } from "../../index";
|
|
||||||
import { OpenAIV1TextCompletionSchema } from "./schema";
|
|
||||||
import { OpenAIV1ChatCompletionSchema } from "../openai/schema";
|
|
||||||
|
|
||||||
import { flattenOpenAIChatMessages } from "../openai/stringifier";
|
|
||||||
|
|
||||||
export const transformOpenAIToOpenAIText: APIRequestTransformer<
|
|
||||||
typeof OpenAIV1TextCompletionSchema
|
|
||||||
> = async (req) => {
|
|
||||||
const { body } = req;
|
|
||||||
const result = OpenAIV1ChatCompletionSchema.safeParse(body);
|
|
||||||
if (!result.success) {
|
|
||||||
req.log.warn(
|
|
||||||
{ issues: result.error.issues, body },
|
|
||||||
"Invalid OpenAI-to-OpenAI-text request"
|
|
||||||
);
|
|
||||||
throw result.error;
|
|
||||||
}
|
|
||||||
|
|
||||||
const { messages, ...rest } = result.data;
|
|
||||||
const prompt = flattenOpenAIChatMessages(messages);
|
|
||||||
|
|
||||||
let stops = rest.stop
|
|
||||||
? Array.isArray(rest.stop)
|
|
||||||
? rest.stop
|
|
||||||
: [rest.stop]
|
|
||||||
: [];
|
|
||||||
stops.push("\n\nUser:");
|
|
||||||
stops = [...new Set(stops)];
|
|
||||||
|
|
||||||
const transformed = { ...rest, prompt: prompt, stop: stops };
|
|
||||||
return OpenAIV1TextCompletionSchema.parse(transformed);
|
|
||||||
};
|
|
||||||
@@ -1,26 +0,0 @@
|
|||||||
import { z } from "zod";
|
|
||||||
import { OpenAIV1ChatCompletionSchema } from "../openai/schema";
|
|
||||||
|
|
||||||
export const OpenAIV1TextCompletionSchema = z
|
|
||||||
.object({
|
|
||||||
model: z
|
|
||||||
.string()
|
|
||||||
.max(100)
|
|
||||||
.regex(
|
|
||||||
/^gpt-3.5-turbo-instruct/,
|
|
||||||
"Model must start with 'gpt-3.5-turbo-instruct'"
|
|
||||||
),
|
|
||||||
prompt: z.string({
|
|
||||||
required_error:
|
|
||||||
"No `prompt` found. Ensure you've set the correct completion endpoint.",
|
|
||||||
}),
|
|
||||||
logprobs: z.number().int().nullish().default(null),
|
|
||||||
echo: z.boolean().optional().default(false),
|
|
||||||
best_of: z.literal(1).optional(),
|
|
||||||
stop: z
|
|
||||||
.union([z.string().max(500), z.array(z.string().max(500)).max(4)])
|
|
||||||
.optional(),
|
|
||||||
suffix: z.string().max(1000).optional(),
|
|
||||||
})
|
|
||||||
.strip()
|
|
||||||
.merge(OpenAIV1ChatCompletionSchema.omit({ messages: true, logprobs: true }));
|
|
||||||
@@ -1,13 +0,0 @@
|
|||||||
import { APIFormatKit } from "../../index";
|
|
||||||
import { OpenAIChatMessage, OpenAIV1ChatCompletionSchema } from "./schema";
|
|
||||||
import { flattenOpenAIChatMessages } from "./stringifier";
|
|
||||||
import { getOpenAITokenCount } from "./tokenizer";
|
|
||||||
|
|
||||||
const kit: APIFormatKit<"openai", OpenAIChatMessage[]> = {
|
|
||||||
name: "openai",
|
|
||||||
requestValidator: OpenAIV1ChatCompletionSchema,
|
|
||||||
// We never transform from other formats into OpenAI format.
|
|
||||||
requestTransformers: {},
|
|
||||||
promptStringifier: flattenOpenAIChatMessages,
|
|
||||||
promptTokenCounter: getOpenAITokenCount,
|
|
||||||
};
|
|
||||||
@@ -1,33 +0,0 @@
|
|||||||
import { OpenAIChatMessage } from "./schema";
|
|
||||||
|
|
||||||
export function flattenOpenAIChatMessages(messages: OpenAIChatMessage[]) {
|
|
||||||
return (
|
|
||||||
messages
|
|
||||||
.map((m) => {
|
|
||||||
// Claude-style human/assistant turns
|
|
||||||
let role: string = m.role;
|
|
||||||
if (role === "assistant") {
|
|
||||||
role = "Assistant";
|
|
||||||
} else if (role === "system") {
|
|
||||||
role = "System";
|
|
||||||
} else if (role === "user") {
|
|
||||||
role = "User";
|
|
||||||
}
|
|
||||||
return `\n\n${role}: ${flattenOpenAIMessageContent(m.content)}`;
|
|
||||||
})
|
|
||||||
.join("") + "\n\nAssistant:"
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
export function flattenOpenAIMessageContent(
|
|
||||||
content: OpenAIChatMessage["content"],
|
|
||||||
): string {
|
|
||||||
return Array.isArray(content)
|
|
||||||
? content
|
|
||||||
.map((contentItem) => {
|
|
||||||
if ("text" in contentItem) return contentItem.text;
|
|
||||||
if ("image_url" in contentItem) return "[ Uploaded Image Omitted ]";
|
|
||||||
})
|
|
||||||
.join("\n")
|
|
||||||
: content;
|
|
||||||
}
|
|
||||||
@@ -1,154 +0,0 @@
|
|||||||
import { Tiktoken } from "tiktoken/lite";
|
|
||||||
import cl100k_base from "tiktoken/encoders/cl100k_base.json";
|
|
||||||
import { logger } from "../../../../logger";
|
|
||||||
import { libSharp } from "../../../file-storage";
|
|
||||||
import { OpenAIChatMessage } from "./schema";
|
|
||||||
|
|
||||||
const GPT4_VISION_SYSTEM_PROMPT_SIZE = 170;
|
|
||||||
|
|
||||||
const log = logger.child({ module: "tokenizer", service: "openai" });
|
|
||||||
export const encoder = new Tiktoken(
|
|
||||||
cl100k_base.bpe_ranks,
|
|
||||||
cl100k_base.special_tokens,
|
|
||||||
cl100k_base.pat_str
|
|
||||||
);
|
|
||||||
|
|
||||||
export async function getOpenAITokenCount(
|
|
||||||
prompt: string | OpenAIChatMessage[],
|
|
||||||
model: string
|
|
||||||
) {
|
|
||||||
if (typeof prompt === "string") {
|
|
||||||
return getTextTokenCount(prompt);
|
|
||||||
}
|
|
||||||
|
|
||||||
const oldFormatting = model.startsWith("turbo-0301");
|
|
||||||
const vision = model.includes("vision");
|
|
||||||
|
|
||||||
const tokensPerMessage = oldFormatting ? 4 : 3;
|
|
||||||
const tokensPerName = oldFormatting ? -1 : 1; // older formatting replaces role with name if name is present
|
|
||||||
|
|
||||||
let numTokens = vision ? GPT4_VISION_SYSTEM_PROMPT_SIZE : 0;
|
|
||||||
|
|
||||||
for (const message of prompt) {
|
|
||||||
numTokens += tokensPerMessage;
|
|
||||||
for (const key of Object.keys(message)) {
|
|
||||||
{
|
|
||||||
let textContent: string = "";
|
|
||||||
const value = message[key as keyof OpenAIChatMessage];
|
|
||||||
|
|
||||||
if (!value) continue;
|
|
||||||
|
|
||||||
if (Array.isArray(value)) {
|
|
||||||
for (const item of value) {
|
|
||||||
if (item.type === "text") {
|
|
||||||
textContent += item.text;
|
|
||||||
} else if (["image", "image_url"].includes(item.type)) {
|
|
||||||
const { url, detail } = item.image_url;
|
|
||||||
const cost = await getGpt4VisionTokenCost(url, detail);
|
|
||||||
numTokens += cost ?? 0;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
textContent = value;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (textContent.length > 800000 || numTokens > 200000) {
|
|
||||||
throw new Error("Content is too large to tokenize.");
|
|
||||||
}
|
|
||||||
|
|
||||||
numTokens += encoder.encode(textContent).length;
|
|
||||||
if (key === "name") {
|
|
||||||
numTokens += tokensPerName;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
numTokens += 3; // every reply is primed with <|start|>assistant<|message|>
|
|
||||||
return { tokenizer: "tiktoken", token_count: numTokens };
|
|
||||||
}
|
|
||||||
|
|
||||||
async function getGpt4VisionTokenCost(
|
|
||||||
url: string,
|
|
||||||
detail: "auto" | "low" | "high" = "auto"
|
|
||||||
) {
|
|
||||||
// For now we do not allow remote images as the proxy would have to download
|
|
||||||
// them, which is a potential DoS vector.
|
|
||||||
if (!url.startsWith("data:image/")) {
|
|
||||||
throw new Error(
|
|
||||||
"Remote images are not supported. Add the image to your prompt as a base64 data URL."
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
const base64Data = url.split(",")[1];
|
|
||||||
const buffer = Buffer.from(base64Data, "base64");
|
|
||||||
const image = libSharp(buffer);
|
|
||||||
const metadata = await image.metadata();
|
|
||||||
|
|
||||||
if (!metadata || !metadata.width || !metadata.height) {
|
|
||||||
throw new Error("Prompt includes an image that could not be parsed");
|
|
||||||
}
|
|
||||||
|
|
||||||
const { width, height } = metadata;
|
|
||||||
|
|
||||||
let selectedDetail: "low" | "high";
|
|
||||||
if (detail === "auto") {
|
|
||||||
const threshold = 512 * 512;
|
|
||||||
const imageSize = width * height;
|
|
||||||
selectedDetail = imageSize > threshold ? "high" : "low";
|
|
||||||
} else {
|
|
||||||
selectedDetail = detail;
|
|
||||||
}
|
|
||||||
|
|
||||||
// https://platform.openai.com/docs/guides/vision/calculating-costs
|
|
||||||
if (selectedDetail === "low") {
|
|
||||||
log.info(
|
|
||||||
{ width, height, tokens: 85 },
|
|
||||||
"Using fixed GPT-4-Vision token cost for low detail image"
|
|
||||||
);
|
|
||||||
return 85;
|
|
||||||
}
|
|
||||||
|
|
||||||
let newWidth = width;
|
|
||||||
let newHeight = height;
|
|
||||||
if (width > 2048 || height > 2048) {
|
|
||||||
const aspectRatio = width / height;
|
|
||||||
if (width > height) {
|
|
||||||
newWidth = 2048;
|
|
||||||
newHeight = Math.round(2048 / aspectRatio);
|
|
||||||
} else {
|
|
||||||
newHeight = 2048;
|
|
||||||
newWidth = Math.round(2048 * aspectRatio);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if (newWidth < newHeight) {
|
|
||||||
newHeight = Math.round((newHeight / newWidth) * 768);
|
|
||||||
newWidth = 768;
|
|
||||||
} else {
|
|
||||||
newWidth = Math.round((newWidth / newHeight) * 768);
|
|
||||||
newHeight = 768;
|
|
||||||
}
|
|
||||||
|
|
||||||
const tiles = Math.ceil(newWidth / 512) * Math.ceil(newHeight / 512);
|
|
||||||
const tokens = 170 * tiles + 85;
|
|
||||||
|
|
||||||
log.info(
|
|
||||||
{ width, height, newWidth, newHeight, tiles, tokens },
|
|
||||||
"Calculated GPT-4-Vision token cost for high detail image"
|
|
||||||
);
|
|
||||||
return tokens;
|
|
||||||
}
|
|
||||||
|
|
||||||
export function getTextTokenCount(prompt: string) {
|
|
||||||
if (prompt.length > 500000) {
|
|
||||||
return {
|
|
||||||
tokenizer: "length fallback",
|
|
||||||
token_count: 100000,
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
return {
|
|
||||||
tokenizer: "tiktoken",
|
|
||||||
token_count: encoder.encode(prompt).length,
|
|
||||||
};
|
|
||||||
}
|
|
||||||
@@ -0,0 +1,104 @@
|
|||||||
|
import { Request, Response, NextFunction } from "express";
|
||||||
|
import ipaddr, { IPv4, IPv6 } from "ipaddr.js";
|
||||||
|
import { logger } from "../logger";
|
||||||
|
|
||||||
|
const log = logger.child({ module: "cidr" });
|
||||||
|
|
||||||
|
type IpCheckMiddleware = ((
|
||||||
|
req: Request,
|
||||||
|
res: Response,
|
||||||
|
next: NextFunction
|
||||||
|
) => void) & {
|
||||||
|
ranges: string[];
|
||||||
|
updateRanges: (ranges: string[] | string) => void;
|
||||||
|
};
|
||||||
|
|
||||||
|
export const whitelists = new Map<string, IpCheckMiddleware>();
|
||||||
|
export const blacklists = new Map<string, IpCheckMiddleware>();
|
||||||
|
|
||||||
|
export function parseCidrs(cidrs: string[] | string): [IPv4 | IPv6, number][] {
|
||||||
|
const list = Array.isArray(cidrs)
|
||||||
|
? cidrs
|
||||||
|
: cidrs.split(",").map((s) => s.trim());
|
||||||
|
return list
|
||||||
|
.map((input) => {
|
||||||
|
try {
|
||||||
|
if (input.includes("/")) {
|
||||||
|
return ipaddr.parseCIDR(input.trim());
|
||||||
|
} else {
|
||||||
|
const ip = ipaddr.parse(input.trim());
|
||||||
|
return ipaddr.parseCIDR(
|
||||||
|
`${input}/${ip.kind() === "ipv4" ? 32 : 128}`
|
||||||
|
);
|
||||||
|
}
|
||||||
|
} catch (e) {
|
||||||
|
log.error({ input, error: e.message }, "Invalid CIDR mask; skipping");
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
})
|
||||||
|
.filter((cidr): cidr is [IPv4 | IPv6, number] => cidr !== null);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function createWhitelistMiddleware(
|
||||||
|
name: string,
|
||||||
|
base: string[] | string
|
||||||
|
) {
|
||||||
|
let cidrs: string[] = [];
|
||||||
|
let ranges: Record<string, [IPv4 | IPv6, number][]> = {};
|
||||||
|
|
||||||
|
const middleware: IpCheckMiddleware = (req, res, next) => {
|
||||||
|
const ip = ipaddr.process(req.ip);
|
||||||
|
const match = ipaddr.subnetMatch(ip, ranges, "none");
|
||||||
|
if (match === name) {
|
||||||
|
return next();
|
||||||
|
} else {
|
||||||
|
req.log.warn({ ip: req.ip, list: name }, "Request denied by whitelist");
|
||||||
|
res.status(403).json({ error: `Forbidden (by ${name})` });
|
||||||
|
}
|
||||||
|
};
|
||||||
|
middleware.ranges = cidrs;
|
||||||
|
middleware.updateRanges = (r: string[] | string) => {
|
||||||
|
cidrs = Array.isArray(r) ? r.slice() : [r];
|
||||||
|
const parsed = parseCidrs(cidrs);
|
||||||
|
ranges = { [name]: parsed };
|
||||||
|
middleware.ranges = cidrs;
|
||||||
|
log.info({ list: name, ranges }, "IP whitelist configured");
|
||||||
|
};
|
||||||
|
|
||||||
|
middleware.updateRanges(base);
|
||||||
|
|
||||||
|
whitelists.set(name, middleware);
|
||||||
|
return middleware;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function createBlacklistMiddleware(
|
||||||
|
name: string,
|
||||||
|
base: string[] | string
|
||||||
|
) {
|
||||||
|
let cidrs: string[] = [];
|
||||||
|
let ranges: Record<string, [IPv4 | IPv6, number][]> = {};
|
||||||
|
|
||||||
|
const middleware: IpCheckMiddleware = (req, res, next) => {
|
||||||
|
const ip = ipaddr.process(req.ip);
|
||||||
|
const match = ipaddr.subnetMatch(ip, ranges, "none");
|
||||||
|
if (match === name) {
|
||||||
|
req.log.warn({ ip: req.ip, list: name }, "Request denied by blacklist");
|
||||||
|
return res.status(403).json({ error: `Forbidden (by ${name})` });
|
||||||
|
} else {
|
||||||
|
return next();
|
||||||
|
}
|
||||||
|
};
|
||||||
|
middleware.ranges = cidrs;
|
||||||
|
middleware.updateRanges = (r: string[] | string) => {
|
||||||
|
cidrs = Array.isArray(r) ? r.slice() : [r];
|
||||||
|
const parsed = parseCidrs(cidrs);
|
||||||
|
ranges = { [name]: parsed };
|
||||||
|
middleware.ranges = cidrs;
|
||||||
|
log.info({ list: name, ranges }, "IP blacklist configured");
|
||||||
|
};
|
||||||
|
|
||||||
|
middleware.updateRanges(base);
|
||||||
|
|
||||||
|
blacklists.set(name, middleware);
|
||||||
|
return middleware;
|
||||||
|
}
|
||||||
Vendored
+1
-1
@@ -3,8 +3,8 @@
|
|||||||
import type { HttpRequest } from "@smithy/types";
|
import type { HttpRequest } from "@smithy/types";
|
||||||
import { Express } from "express-serve-static-core";
|
import { Express } from "express-serve-static-core";
|
||||||
import { APIFormat, Key } from "./key-management";
|
import { APIFormat, Key } from "./key-management";
|
||||||
import { User } from "./users/schema";
|
|
||||||
import { LLMService, ModelFamily } from "./models";
|
import { LLMService, ModelFamily } from "./models";
|
||||||
|
import { User } from "./database/repos/users";
|
||||||
|
|
||||||
declare global {
|
declare global {
|
||||||
namespace Express {
|
namespace Express {
|
||||||
|
|||||||
@@ -0,0 +1,94 @@
|
|||||||
|
import type sqlite3 from "better-sqlite3";
|
||||||
|
import { config } from "../../config";
|
||||||
|
import { logger } from "../../logger";
|
||||||
|
import { migrations } from "./migrations";
|
||||||
|
|
||||||
|
export const DATABASE_VERSION = 3;
|
||||||
|
|
||||||
|
let database: sqlite3.Database | undefined;
|
||||||
|
let log = logger.child({ module: "database" });
|
||||||
|
|
||||||
|
export function getDatabase(): sqlite3.Database {
|
||||||
|
if (!database) {
|
||||||
|
throw new Error("Sqlite database not initialized.");
|
||||||
|
}
|
||||||
|
return database;
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function initializeDatabase() {
|
||||||
|
if (!config.eventLogging) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
log.info("Initializing database...");
|
||||||
|
|
||||||
|
const sqlite3 = await import("better-sqlite3");
|
||||||
|
database = sqlite3.default(config.sqliteDataPath, {
|
||||||
|
verbose: process.env.SQLITE_VERBOSE === "true"
|
||||||
|
? (msg, ...args) => log.debug({ args }, String(msg))
|
||||||
|
: undefined,
|
||||||
|
});
|
||||||
|
migrateDatabase();
|
||||||
|
database.pragma("journal_mode = WAL");
|
||||||
|
log.info("Database initialized.");
|
||||||
|
}
|
||||||
|
|
||||||
|
export function migrateDatabase(
|
||||||
|
targetVersion = DATABASE_VERSION,
|
||||||
|
targetDb?: sqlite3.Database
|
||||||
|
) {
|
||||||
|
const db = targetDb || getDatabase();
|
||||||
|
|
||||||
|
const currentVersion = db.pragma("user_version", { simple: true });
|
||||||
|
assertNumber(currentVersion);
|
||||||
|
|
||||||
|
if (currentVersion === targetVersion) {
|
||||||
|
log.info("No migrations to run.");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const direction = currentVersion < targetVersion ? "up" : "down";
|
||||||
|
const pending = migrations
|
||||||
|
.slice()
|
||||||
|
.sort((a, b) =>
|
||||||
|
direction === "up" ? a.version - b.version : b.version - a.version
|
||||||
|
)
|
||||||
|
.filter((m) =>
|
||||||
|
direction === "up"
|
||||||
|
? m.version > currentVersion && m.version <= targetVersion
|
||||||
|
: m.version > targetVersion && m.version <= currentVersion
|
||||||
|
);
|
||||||
|
|
||||||
|
if (pending.length === 0) {
|
||||||
|
log.warn("No pending migrations found.");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
for (const migration of pending) {
|
||||||
|
const { version, name, up, down } = migration;
|
||||||
|
if (
|
||||||
|
(direction === "up" && version > currentVersion) ||
|
||||||
|
(direction === "down" && version <= currentVersion)
|
||||||
|
) {
|
||||||
|
if (direction === "up") {
|
||||||
|
log.info({ name }, "Applying migration.");
|
||||||
|
up(db);
|
||||||
|
db.pragma("user_version = " + version);
|
||||||
|
} else {
|
||||||
|
log.info({ name }, "Reverting migration.");
|
||||||
|
down(db);
|
||||||
|
db.pragma("user_version = " + (version - 1));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
log.info("Migrations applied.");
|
||||||
|
}
|
||||||
|
|
||||||
|
function assertNumber(value: unknown): asserts value is number {
|
||||||
|
if (typeof value !== "number") {
|
||||||
|
throw new Error("Expected number");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export { EventLogEntry } from "./repos/events";
|
||||||
@@ -0,0 +1,122 @@
|
|||||||
|
import type sqlite3 from "better-sqlite3";
|
||||||
|
|
||||||
|
type Migration = {
|
||||||
|
name: string;
|
||||||
|
version: number;
|
||||||
|
up: (db: sqlite3.Database) => void;
|
||||||
|
down: (db: sqlite3.Database) => void;
|
||||||
|
};
|
||||||
|
|
||||||
|
export const migrations = [
|
||||||
|
{
|
||||||
|
name: "create db",
|
||||||
|
version: 1,
|
||||||
|
up: () => {},
|
||||||
|
down: () => {},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "add events table",
|
||||||
|
version: 2,
|
||||||
|
up: (db) => {
|
||||||
|
db.exec(
|
||||||
|
`CREATE TABLE IF NOT EXISTS events
|
||||||
|
(
|
||||||
|
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||||
|
type TEXT NOT NULL,
|
||||||
|
ip TEXT NOT NULL,
|
||||||
|
date TEXT NOT NULL,
|
||||||
|
model TEXT NOT NULL,
|
||||||
|
family TEXT NOT NULL,
|
||||||
|
hashes TEXT NOT NULL,
|
||||||
|
userToken TEXT NOT NULL,
|
||||||
|
inputTokens INTEGER NOT NULL,
|
||||||
|
outputTokens INTEGER NOT NULL
|
||||||
|
)`
|
||||||
|
);
|
||||||
|
},
|
||||||
|
down: (db) => db.exec("DROP TABLE events"),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "add events indexes",
|
||||||
|
version: 3,
|
||||||
|
up: (db) => {
|
||||||
|
// language=SQLite
|
||||||
|
db.exec(
|
||||||
|
`BEGIN;
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_events_userToken ON events (userToken);
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_events_ip ON events (ip);
|
||||||
|
COMMIT;`
|
||||||
|
);
|
||||||
|
},
|
||||||
|
down: (db) => {
|
||||||
|
// language=SQLite
|
||||||
|
db.exec(
|
||||||
|
`BEGIN;
|
||||||
|
DROP INDEX idx_events_userToken;
|
||||||
|
DROP INDEX idx_events_ip;
|
||||||
|
COMMIT;`
|
||||||
|
);
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "add users schema",
|
||||||
|
version: 4,
|
||||||
|
up: (db) => {
|
||||||
|
// language=SQLite
|
||||||
|
const sql = `
|
||||||
|
CREATE TABLE IF NOT EXISTS users
|
||||||
|
(
|
||||||
|
token TEXT PRIMARY KEY NOT NULL,
|
||||||
|
nickname TEXT,
|
||||||
|
type TEXT CHECK (type IN ('normal', 'special', 'temporary')) NOT NULL,
|
||||||
|
createdAt INTEGER NOT NULL,
|
||||||
|
lastUsedAt INTEGER,
|
||||||
|
disabledAt INTEGER,
|
||||||
|
disabledReason TEXT,
|
||||||
|
expiresAt INTEGER,
|
||||||
|
maxIps INTEGER,
|
||||||
|
adminNote TEXT
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE TABLE IF NOT EXISTS user_ips
|
||||||
|
(
|
||||||
|
userToken TEXT NOT NULL,
|
||||||
|
ip TEXT NOT NULL,
|
||||||
|
PRIMARY KEY (userToken, ip),
|
||||||
|
FOREIGN KEY (userToken) REFERENCES users (token)
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE TABLE IF NOT EXISTS user_token_counts
|
||||||
|
(
|
||||||
|
userToken TEXT NOT NULL,
|
||||||
|
modelFamily TEXT NOT NULL,
|
||||||
|
inputTokens INTEGER NOT NULL,
|
||||||
|
outputTokens INTEGER NOT NULL,
|
||||||
|
tokenLimit INTEGER NOT NULL,
|
||||||
|
prompts INTEGER NOT NULL,
|
||||||
|
PRIMARY KEY (userToken, modelFamily)
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE TABLE IF NOT EXISTS user_meta
|
||||||
|
(
|
||||||
|
userToken TEXT NOT NULL,
|
||||||
|
key TEXT NOT NULL,
|
||||||
|
value TEXT NOT NULL,
|
||||||
|
PRIMARY KEY (userToken, key),
|
||||||
|
FOREIGN KEY (userToken) REFERENCES users (token)
|
||||||
|
);
|
||||||
|
`;
|
||||||
|
db.exec(sql);
|
||||||
|
},
|
||||||
|
down: (db) => {
|
||||||
|
// language=SQLite
|
||||||
|
const sql = `
|
||||||
|
DROP TABLE users;
|
||||||
|
DROP TABLE user_ips;
|
||||||
|
DROP TABLE user_token_counts;
|
||||||
|
DROP TABLE user_meta;
|
||||||
|
`;
|
||||||
|
db.exec(sql);
|
||||||
|
},
|
||||||
|
},
|
||||||
|
] satisfies Migration[];
|
||||||
@@ -0,0 +1,85 @@
|
|||||||
|
import { getDatabase } from "../index";
|
||||||
|
|
||||||
|
export interface EventLogEntry {
|
||||||
|
date: string;
|
||||||
|
ip: string;
|
||||||
|
type: "chat_completion";
|
||||||
|
model: string;
|
||||||
|
family: string;
|
||||||
|
/**
|
||||||
|
* Prompt hashes are SHA256.
|
||||||
|
* Each message is stripped of whitespace.
|
||||||
|
* Then joined by <|im_sep|>
|
||||||
|
* Then hashed.
|
||||||
|
* First hash: Full prompt.
|
||||||
|
* Next {trim} hashes: Hashes with last 1-{trim} messages removed.
|
||||||
|
*/
|
||||||
|
hashes: string[];
|
||||||
|
userToken: string;
|
||||||
|
inputTokens: number;
|
||||||
|
outputTokens: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface EventsRepo {
|
||||||
|
getUserEvents: (
|
||||||
|
userToken: string,
|
||||||
|
{ limit, cursor }: { limit: number; cursor?: string }
|
||||||
|
) => EventLogEntry[];
|
||||||
|
logEvent: (payload: EventLogEntry) => void;
|
||||||
|
}
|
||||||
|
|
||||||
|
export const eventsRepo: EventsRepo = {
|
||||||
|
getUserEvents: (userToken, { limit, cursor }) => {
|
||||||
|
const db = getDatabase();
|
||||||
|
const params = [];
|
||||||
|
let sql = `
|
||||||
|
SELECT *
|
||||||
|
FROM events
|
||||||
|
WHERE userToken = ?
|
||||||
|
`;
|
||||||
|
params.push(userToken);
|
||||||
|
|
||||||
|
if (cursor) {
|
||||||
|
sql += ` AND date < ?`;
|
||||||
|
params.push(cursor);
|
||||||
|
}
|
||||||
|
|
||||||
|
sql += ` ORDER BY date DESC LIMIT ?`;
|
||||||
|
params.push(limit);
|
||||||
|
|
||||||
|
return db.prepare(sql).all(params).map(marshalEventLogEntry);
|
||||||
|
},
|
||||||
|
logEvent: (payload) => {
|
||||||
|
const db = getDatabase();
|
||||||
|
db.prepare(
|
||||||
|
`
|
||||||
|
INSERT INTO events(date, ip, type, model, family, hashes, userToken, inputTokens, outputTokens)
|
||||||
|
VALUES (:date, :ip, :type, :model, :family, :hashes, :userToken, :inputTokens, :outputTokens)
|
||||||
|
`
|
||||||
|
).run({
|
||||||
|
date: payload.date,
|
||||||
|
ip: payload.ip,
|
||||||
|
type: payload.type,
|
||||||
|
model: payload.model,
|
||||||
|
family: payload.family,
|
||||||
|
hashes: payload.hashes.join(","),
|
||||||
|
userToken: payload.userToken,
|
||||||
|
inputTokens: payload.inputTokens,
|
||||||
|
outputTokens: payload.outputTokens,
|
||||||
|
});
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
|
function marshalEventLogEntry(row: any): EventLogEntry {
|
||||||
|
return {
|
||||||
|
date: row.date,
|
||||||
|
ip: row.ip,
|
||||||
|
type: row.type,
|
||||||
|
model: row.model,
|
||||||
|
family: row.family,
|
||||||
|
hashes: row.hashes.split(","),
|
||||||
|
userToken: row.userToken,
|
||||||
|
inputTokens: parseInt(row.inputTokens),
|
||||||
|
outputTokens: parseInt(row.outputTokens),
|
||||||
|
};
|
||||||
|
}
|
||||||
@@ -0,0 +1,420 @@
|
|||||||
|
import { ZodType, z } from "zod";
|
||||||
|
import { MODEL_FAMILIES, ModelFamily } from "../../models";
|
||||||
|
import { makeOptionalPropsNullable } from "../../utils";
|
||||||
|
import { getDatabase } from "../index";
|
||||||
|
import type { Transaction } from "better-sqlite3";
|
||||||
|
|
||||||
|
// This just dynamically creates a Zod object type with a key for each model
|
||||||
|
// family and an optional number value.
|
||||||
|
export const tokenCountsSchema: ZodType<UserTokenCounts> = z.object(
|
||||||
|
MODEL_FAMILIES.reduce(
|
||||||
|
(acc, family) => {
|
||||||
|
return {
|
||||||
|
...acc,
|
||||||
|
[family]: z.object({
|
||||||
|
input: z.number().optional().default(0),
|
||||||
|
output: z.number().optional().default(0),
|
||||||
|
limit: z.number().optional().default(0),
|
||||||
|
prompts: z.number().optional().default(0),
|
||||||
|
}),
|
||||||
|
};
|
||||||
|
},
|
||||||
|
{} as Record<
|
||||||
|
ModelFamily,
|
||||||
|
ZodType<{ input: number; output: number; limit: number; prompts: number }>
|
||||||
|
>
|
||||||
|
)
|
||||||
|
);
|
||||||
|
|
||||||
|
// Old token counts schema before counts were combined into a single object.
|
||||||
|
const tokenCountsSchemaOld = z.object(
|
||||||
|
MODEL_FAMILIES.reduce(
|
||||||
|
(acc, family) => ({ ...acc, [family]: z.number().optional().default(0) }),
|
||||||
|
{} as Record<ModelFamily, ZodType<number>>
|
||||||
|
)
|
||||||
|
);
|
||||||
|
|
||||||
|
export const UserSchema = z
|
||||||
|
.object({
|
||||||
|
/** User's personal access token. */
|
||||||
|
token: z.string(),
|
||||||
|
/** IP addresses the user has connected from. */
|
||||||
|
ip: z.array(z.string()),
|
||||||
|
/** User's nickname. */
|
||||||
|
nickname: z.string().max(80).optional(),
|
||||||
|
/**
|
||||||
|
* The user's privilege level.
|
||||||
|
* - `normal`: Default role. Subject to usual rate limits and quotas.
|
||||||
|
* - `special`: Special role. Higher quotas and exempt from auto-ban/lockout.
|
||||||
|
**/
|
||||||
|
type: z.enum(["normal", "special", "temporary"]),
|
||||||
|
/** Number of prompts the user has made. */
|
||||||
|
promptCount: z.number(),
|
||||||
|
/**
|
||||||
|
* @deprecated Use `tokenCounts` instead.
|
||||||
|
* Never used; retained for backwards compatibility.
|
||||||
|
*/
|
||||||
|
tokenCount: z.any().optional(),
|
||||||
|
/** Number of tokens the user has consumed, by model family. */
|
||||||
|
tokenCounts: tokenCountsSchemaOld,
|
||||||
|
/** Maximum number of tokens the user can consume, by model family. */
|
||||||
|
tokenLimits: tokenCountsSchemaOld,
|
||||||
|
/** Token data for the user, by model family. */
|
||||||
|
modelTokenCounts: tokenCountsSchema,
|
||||||
|
/** Time at which the user was created. */
|
||||||
|
createdAt: z.number(),
|
||||||
|
/** Time at which the user last connected. */
|
||||||
|
lastUsedAt: z.number().optional(),
|
||||||
|
/** Time at which the user was disabled, if applicable. */
|
||||||
|
disabledAt: z.number().optional(),
|
||||||
|
/** Reason for which the user was disabled, if applicable. */
|
||||||
|
disabledReason: z.string().optional(),
|
||||||
|
/** Time at which the user will expire and be disabled (for temp users). */
|
||||||
|
expiresAt: z.number().optional(),
|
||||||
|
/** The user's maximum number of IP addresses; supercedes global max. */
|
||||||
|
maxIps: z.coerce.number().int().min(0).optional(),
|
||||||
|
/** Private note about the user. */
|
||||||
|
adminNote: z.string().optional(),
|
||||||
|
meta: z.record(z.any()).optional(),
|
||||||
|
})
|
||||||
|
.strict();
|
||||||
|
/**
|
||||||
|
* Variant of `;
|
||||||
|
UserSchema` which allows for partial updates, and makes any
|
||||||
|
* optional properties on the base schema nullable. Null values are used to
|
||||||
|
* indicate that the property should be deleted from the user object.
|
||||||
|
*/
|
||||||
|
export const UserPartialSchema = makeOptionalPropsNullable(UserSchema)
|
||||||
|
.partial()
|
||||||
|
.extend({ token: z.string() });
|
||||||
|
export type UserTokenCounts = {
|
||||||
|
[K in ModelFamily]: {
|
||||||
|
input: number;
|
||||||
|
output: number;
|
||||||
|
limit: number;
|
||||||
|
prompts: number;
|
||||||
|
};
|
||||||
|
};
|
||||||
|
export type UserTokenCountsOld = {
|
||||||
|
[K in ModelFamily]: number | undefined;
|
||||||
|
};
|
||||||
|
export type User = z.infer<typeof UserSchema>;
|
||||||
|
export type UserUpdate = z.infer<typeof UserPartialSchema>;
|
||||||
|
export type VirtualUser = User & { virtual: true; ipCount: number };
|
||||||
|
|
||||||
|
export const UsersRepo = {
|
||||||
|
getUserByToken: (token: string) => {
|
||||||
|
const db = getDatabase();
|
||||||
|
// language=SQLite
|
||||||
|
const sql = `
|
||||||
|
SELECT u.*,
|
||||||
|
json_group_array(ui.ip) as ip,
|
||||||
|
json_group_object(utc.modelFamily,
|
||||||
|
json_object('input', utc.inputTokens,
|
||||||
|
'output', utc.outputTokens,
|
||||||
|
'limit', utc.tokenLimit,
|
||||||
|
'prompts', utc.prompts)) as tokenCounts,
|
||||||
|
json_object(um.key, um.value) as meta
|
||||||
|
FROM users u
|
||||||
|
LEFT JOIN user_ips ui ON u.token = ui.userToken
|
||||||
|
LEFT JOIN user_token_counts utc ON u.token = utc.userToken
|
||||||
|
LEFT JOIN user_meta um ON u.token = um.userToken
|
||||||
|
WHERE u.token = ?;
|
||||||
|
`;
|
||||||
|
|
||||||
|
const user = db.prepare(sql).get(token);
|
||||||
|
if (!user) return;
|
||||||
|
|
||||||
|
return marshalUser(user);
|
||||||
|
},
|
||||||
|
getUsers: (pagination: { limit: number; cursor?: string }): VirtualUser[] => {
|
||||||
|
const db = getDatabase();
|
||||||
|
const { limit, cursor } = pagination;
|
||||||
|
const params = [];
|
||||||
|
let sql = `
|
||||||
|
SELECT u.*,
|
||||||
|
count(ui.ip) as ipCount,
|
||||||
|
json_group_object(utc.modelFamily,
|
||||||
|
json_object('input', utc.inputTokens,
|
||||||
|
'output', utc.outputTokens,
|
||||||
|
'limit', utc.tokenLimit,
|
||||||
|
'prompts', utc.prompts)) as tokenCounts,
|
||||||
|
json_object(um.key, um.value) as meta
|
||||||
|
FROM users u
|
||||||
|
LEFT JOIN user_ips ui ON u.token = ui.userToken
|
||||||
|
LEFT JOIN user_token_counts utc ON u.token = utc.userToken
|
||||||
|
LEFT JOIN user_meta um ON u.token = um.userToken
|
||||||
|
`;
|
||||||
|
|
||||||
|
if (cursor) {
|
||||||
|
sql += ` WHERE u.token < ?`;
|
||||||
|
params.push(cursor);
|
||||||
|
}
|
||||||
|
|
||||||
|
sql += ` GROUP BY u.token ORDER BY u.token DESC LIMIT ?`;
|
||||||
|
params.push(limit);
|
||||||
|
|
||||||
|
return db
|
||||||
|
.prepare(sql)
|
||||||
|
.all(params)
|
||||||
|
.map((r: any) => {
|
||||||
|
const virtual: VirtualUser = {
|
||||||
|
...marshalUser(r),
|
||||||
|
virtual: true,
|
||||||
|
ipCount: r.ipCount ?? 0,
|
||||||
|
};
|
||||||
|
return virtual;
|
||||||
|
});
|
||||||
|
},
|
||||||
|
/**
|
||||||
|
* Upserts a user record by user token. Intended for use via the REST API,
|
||||||
|
* prefer a more targeted method if possible. Undefined values are ignored,
|
||||||
|
* null values are used to indicate that the field should be cleared.
|
||||||
|
*
|
||||||
|
* @param update - The user data to upsert, with `token` required.
|
||||||
|
*/
|
||||||
|
upsertUser: (update: UserUpdate): void => {
|
||||||
|
const db = getDatabase();
|
||||||
|
if (!db.inTransaction) {
|
||||||
|
return db.transaction(() => UsersRepo.upsertUser(update))();
|
||||||
|
}
|
||||||
|
|
||||||
|
const updates: Partial<User> = {};
|
||||||
|
for (const field of Object.entries(update)) {
|
||||||
|
const [key, value] = field as [keyof User, any]; // assertion validated by zod
|
||||||
|
if (value === undefined || key === "token") continue;
|
||||||
|
updates[key] = value;
|
||||||
|
}
|
||||||
|
|
||||||
|
const setFields = Object.keys(updates)
|
||||||
|
.map((key) => `${key} = :${key}`)
|
||||||
|
.join(", ");
|
||||||
|
const params = { ...updates, token: update.token };
|
||||||
|
|
||||||
|
// scalars
|
||||||
|
const sql = `
|
||||||
|
INSERT INTO users (token, nickname, type, createdAt, lastUsedAt, disabledAt, disabledReason, expiresAt, maxIps,
|
||||||
|
adminNote)
|
||||||
|
VALUES (:token, :nickname, :type, :createdAt, :lastUsedAt, :disabledAt, :disabledReason, :expiresAt, :maxIps,
|
||||||
|
:adminNote)
|
||||||
|
ON CONFLICT(token) DO UPDATE SET ${setFields};
|
||||||
|
`;
|
||||||
|
|
||||||
|
db.prepare(sql).run(params);
|
||||||
|
|
||||||
|
// replace ip addresses
|
||||||
|
if (update.ip) {
|
||||||
|
const sql = `
|
||||||
|
DELETE
|
||||||
|
FROM user_ips
|
||||||
|
WHERE userToken = :token;
|
||||||
|
INSERT INTO user_ips (userToken, ip)
|
||||||
|
VALUES ${update.ip.map(() => "(?, ?)").join(", ")};
|
||||||
|
`;
|
||||||
|
|
||||||
|
db.prepare(sql).run(
|
||||||
|
update.ip.flatMap((ip: string) => [update.token, ip])
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (update.modelTokenCounts) {
|
||||||
|
const sql = `
|
||||||
|
INSERT INTO user_token_counts (userToken, modelFamily, inputTokens, outputTokens, tokenLimit, prompts)
|
||||||
|
VALUES (:token, :modelFamily, :inputTokens, :outputTokens, :tokenLimit, :prompts)
|
||||||
|
ON CONFLICT(userToken, modelFamily) DO UPDATE SET inputTokens = :inputTokens,
|
||||||
|
outputTokens = :outputTokens,
|
||||||
|
tokenLimit = :tokenLimit,
|
||||||
|
prompts = :prompts;
|
||||||
|
`;
|
||||||
|
|
||||||
|
for (const [family, counts] of Object.entries(update.modelTokenCounts)) {
|
||||||
|
db.prepare(sql).run({
|
||||||
|
token: update.token,
|
||||||
|
modelFamily: family,
|
||||||
|
...counts,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (update.meta) {
|
||||||
|
const sql = `
|
||||||
|
DELETE
|
||||||
|
FROM user_meta
|
||||||
|
WHERE userToken = :token;
|
||||||
|
INSERT INTO user_meta (userToken, key, value)
|
||||||
|
VALUES ${Object.keys(update.meta)
|
||||||
|
.map(() => "(?, ?, ?)")
|
||||||
|
.join(", ")};
|
||||||
|
`;
|
||||||
|
|
||||||
|
db.prepare(sql).run(
|
||||||
|
Object.entries(update.meta).flatMap(([key, value]) => [
|
||||||
|
update.token,
|
||||||
|
key,
|
||||||
|
value,
|
||||||
|
])
|
||||||
|
);
|
||||||
|
}
|
||||||
|
},
|
||||||
|
/**
|
||||||
|
* Inserts or updates multiple user records in a single transaction.
|
||||||
|
* Periodically commits the transaction and yields to the event loop to
|
||||||
|
* prevent blocking the main thread for too long.
|
||||||
|
* @param updates - The user data to upsert.
|
||||||
|
*/
|
||||||
|
upsertUsers: async (updates: UserUpdate[]) => {
|
||||||
|
const db = getDatabase();
|
||||||
|
const BATCH_SIZE = 50;
|
||||||
|
const chunked = updates.reduce<UserUpdate[][]>((acc, _, i) => {
|
||||||
|
if (i % BATCH_SIZE === 0) acc.push(updates.slice(i, i + BATCH_SIZE));
|
||||||
|
return acc;
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
const transaction = db.transaction((updates: UserUpdate[]) => {
|
||||||
|
for (const update of updates) {
|
||||||
|
UsersRepo.upsertUser(update);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
for (const chunk of chunked) {
|
||||||
|
await new Promise((resolve) => setTimeout(resolve, 0));
|
||||||
|
transaction(chunk);
|
||||||
|
}
|
||||||
|
},
|
||||||
|
/**
|
||||||
|
* Increments the token usage counters for a user's token by the provided
|
||||||
|
* values, and increments prompt count by 1.
|
||||||
|
*/
|
||||||
|
incrementUsage(
|
||||||
|
userToken: string,
|
||||||
|
family: ModelFamily,
|
||||||
|
input: number,
|
||||||
|
output: number
|
||||||
|
) {
|
||||||
|
const db = getDatabase();
|
||||||
|
|
||||||
|
const sql = `
|
||||||
|
INSERT INTO user_token_counts (userToken, modelFamily, inputTokens, outputTokens, tokenLimit, prompts)
|
||||||
|
VALUES (:userToken, :modelFamily, :inputTokens, :outputTokens, 0, 1)
|
||||||
|
ON CONFLICT(userToken, modelFamily) DO UPDATE SET inputTokens = inputTokens + :inputTokens,
|
||||||
|
outputTokens = outputTokens + :outputTokens,
|
||||||
|
prompts = prompts + 1;
|
||||||
|
`;
|
||||||
|
|
||||||
|
db.prepare(sql).run({
|
||||||
|
userToken,
|
||||||
|
modelFamily: family,
|
||||||
|
inputTokens: input,
|
||||||
|
outputTokens: output,
|
||||||
|
});
|
||||||
|
},
|
||||||
|
/**
|
||||||
|
* Disables user, optionally with reason.
|
||||||
|
*/
|
||||||
|
disableUser(userToken: string, reason?: string) {
|
||||||
|
const db = getDatabase();
|
||||||
|
const disabledAt = Date.now();
|
||||||
|
const sql = `
|
||||||
|
UPDATE users
|
||||||
|
SET disabledAt = :disabledAt,
|
||||||
|
disabledReason = :reason
|
||||||
|
WHERE token = :userToken;
|
||||||
|
INSERT OR REPLACE INTO user_meta (userToken, key, value)
|
||||||
|
VALUES (:userToken, 'refreshable', 'false');
|
||||||
|
`;
|
||||||
|
|
||||||
|
db.prepare(sql).run({ userToken, disabledAt, reason });
|
||||||
|
},
|
||||||
|
/**
|
||||||
|
* Restores quotas for a user by adding the provided token counts to their
|
||||||
|
* existing counts.
|
||||||
|
*/
|
||||||
|
refreshQuotas(
|
||||||
|
userToken: string,
|
||||||
|
tokensByFamily: Record<ModelFamily, number>
|
||||||
|
): void {
|
||||||
|
const db = getDatabase();
|
||||||
|
if (!db.inTransaction) {
|
||||||
|
return db.transaction(() =>
|
||||||
|
UsersRepo.refreshQuotas(userToken, tokensByFamily)
|
||||||
|
)();
|
||||||
|
}
|
||||||
|
|
||||||
|
// for each provided family, increment the tokenLimit to equal inputTokens + outputTokens + refresh amount
|
||||||
|
const sql = `
|
||||||
|
INSERT INTO user_token_counts (userToken, modelFamily, inputTokens, outputTokens, tokenLimit, prompts)
|
||||||
|
VALUES (:userToken, :modelFamily, 0, 0, :refreshAmount, 0)
|
||||||
|
ON CONFLICT(userToken, modelFamily) DO UPDATE SET tokenLimit = inputTokens + outputTokens + :refreshAmount;
|
||||||
|
`;
|
||||||
|
|
||||||
|
for (const [family, tokens] of Object.entries(tokensByFamily)) {
|
||||||
|
db.prepare(sql).run({
|
||||||
|
userToken,
|
||||||
|
modelFamily: family,
|
||||||
|
refreshAmount: tokens,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
},
|
||||||
|
/**
|
||||||
|
* Resets token usage counters for a given user to zero.
|
||||||
|
*/
|
||||||
|
resetUsage(userToken: string) {
|
||||||
|
const db = getDatabase();
|
||||||
|
const sql = `
|
||||||
|
DELETE
|
||||||
|
FROM user_token_counts
|
||||||
|
WHERE userToken = :token
|
||||||
|
`;
|
||||||
|
db.prepare(sql).run({ token: userToken });
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
|
function marshalUser(row: any): User {
|
||||||
|
const user: Partial<User> = {
|
||||||
|
token: row.token,
|
||||||
|
nickname: row.nickname,
|
||||||
|
type: row.type,
|
||||||
|
createdAt: row.createdAt,
|
||||||
|
lastUsedAt: row.lastUsedAt,
|
||||||
|
disabledAt: row.disabledAt,
|
||||||
|
disabledReason: row.disabledReason,
|
||||||
|
expiresAt: row.expiresAt,
|
||||||
|
maxIps: row.maxIps,
|
||||||
|
adminNote: row.adminNote,
|
||||||
|
};
|
||||||
|
|
||||||
|
user.ip = row.ip ? JSON.parse(row.ip) : [];
|
||||||
|
user.meta = row.meta ? JSON.parse(row.meta) : {};
|
||||||
|
user.modelTokenCounts = JSON.parse(row.tokenCounts ?? "{}") as z.infer<
|
||||||
|
typeof tokenCountsSchema
|
||||||
|
>;
|
||||||
|
// legacy token fields
|
||||||
|
user.promptCount = 0;
|
||||||
|
user.tokenCount = 0;
|
||||||
|
user.tokenCounts = {} as z.infer<typeof tokenCountsSchemaOld>;
|
||||||
|
|
||||||
|
if (row.tokenCounts) {
|
||||||
|
// initialize missing model families
|
||||||
|
for (const family of MODEL_FAMILIES) {
|
||||||
|
if (!user.modelTokenCounts[family]) {
|
||||||
|
user.modelTokenCounts[family] = {
|
||||||
|
input: 0,
|
||||||
|
output: 0,
|
||||||
|
limit: 0,
|
||||||
|
prompts: 0,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
// aggregate legacy fields
|
||||||
|
user.promptCount += user.modelTokenCounts[family].prompts;
|
||||||
|
user.tokenCount +=
|
||||||
|
user.modelTokenCounts[family].input +
|
||||||
|
user.modelTokenCounts[family].output;
|
||||||
|
user.tokenCounts[family] =
|
||||||
|
user.modelTokenCounts[family].input +
|
||||||
|
user.modelTokenCounts[family].output;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return user as User;
|
||||||
|
}
|
||||||
@@ -34,3 +34,10 @@ export class TooManyRequestsError extends HttpError {
|
|||||||
super(429, message);
|
super(429, message);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export class RetryableError extends Error {
|
||||||
|
constructor(message: string) {
|
||||||
|
super(message);
|
||||||
|
this.name = "RetryableError";
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
@@ -1,9 +1,9 @@
|
|||||||
import axios, { AxiosError } from "axios";
|
import axios, { AxiosError, AxiosResponse } from "axios";
|
||||||
import { KeyCheckerBase } from "../key-checker-base";
|
import { KeyCheckerBase } from "../key-checker-base";
|
||||||
import type { AnthropicKey, AnthropicKeyProvider } from "./provider";
|
import type { AnthropicKey, AnthropicKeyProvider } from "./provider";
|
||||||
|
|
||||||
const MIN_CHECK_INTERVAL = 3 * 1000; // 3 seconds
|
const MIN_CHECK_INTERVAL = 3 * 1000; // 3 seconds
|
||||||
const KEY_CHECK_PERIOD = 60 * 60 * 1000; // 1 hour
|
const KEY_CHECK_PERIOD = 1000 * 60 * 60 * 6; // 6 hours
|
||||||
const POST_MESSAGES_URL = "https://api.anthropic.com/v1/messages";
|
const POST_MESSAGES_URL = "https://api.anthropic.com/v1/messages";
|
||||||
const TEST_MODEL = "claude-3-sonnet-20240229";
|
const TEST_MODEL = "claude-3-sonnet-20240229";
|
||||||
const SYSTEM = "Obey all instructions from the user.";
|
const SYSTEM = "Obey all instructions from the user.";
|
||||||
@@ -52,10 +52,13 @@ export class AnthropicKeyChecker extends KeyCheckerBase<AnthropicKey> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
protected async testKeyOrFail(key: AnthropicKey) {
|
protected async testKeyOrFail(key: AnthropicKey) {
|
||||||
const [{ pozzed }] = await Promise.all([this.testLiveness(key)]);
|
const [{ pozzed, tier }] = await Promise.all([this.testLiveness(key)]);
|
||||||
const updates = { isPozzed: pozzed };
|
const updates = { isPozzed: pozzed, tier };
|
||||||
this.updateKey(key.hash, updates);
|
this.updateKey(key.hash, updates);
|
||||||
this.log.info({ key: key.hash, models: key.modelFamilies }, "Checked key.");
|
this.log.info(
|
||||||
|
{ key: key.hash, tier, models: key.modelFamilies },
|
||||||
|
"Checked key."
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
protected handleAxiosError(key: AnthropicKey, error: AxiosError) {
|
protected handleAxiosError(key: AnthropicKey, error: AxiosError) {
|
||||||
@@ -124,7 +127,9 @@ export class AnthropicKeyChecker extends KeyCheckerBase<AnthropicKey> {
|
|||||||
this.updateKey(key.hash, { lastChecked: next });
|
this.updateKey(key.hash, { lastChecked: next });
|
||||||
}
|
}
|
||||||
|
|
||||||
private async testLiveness(key: AnthropicKey): Promise<{ pozzed: boolean }> {
|
private async testLiveness(
|
||||||
|
key: AnthropicKey
|
||||||
|
): Promise<{ pozzed: boolean; tier: AnthropicKey["tier"] }> {
|
||||||
const payload = {
|
const payload = {
|
||||||
model: TEST_MODEL,
|
model: TEST_MODEL,
|
||||||
max_tokens: 40,
|
max_tokens: 40,
|
||||||
@@ -133,24 +138,27 @@ export class AnthropicKeyChecker extends KeyCheckerBase<AnthropicKey> {
|
|||||||
system: SYSTEM,
|
system: SYSTEM,
|
||||||
messages: DETECTION_PROMPT,
|
messages: DETECTION_PROMPT,
|
||||||
};
|
};
|
||||||
const { data } = await axios.post<MessageResponse>(
|
const { data, headers } = await axios.post<MessageResponse>(
|
||||||
POST_MESSAGES_URL,
|
POST_MESSAGES_URL,
|
||||||
payload,
|
payload,
|
||||||
{ headers: AnthropicKeyChecker.getHeaders(key) }
|
{ headers: AnthropicKeyChecker.getRequestHeaders(key) }
|
||||||
);
|
);
|
||||||
this.log.debug({ data }, "Response from Anthropic");
|
this.log.debug({ data }, "Response from Anthropic");
|
||||||
|
|
||||||
|
const tier = AnthropicKeyChecker.detectTier(headers);
|
||||||
|
|
||||||
const completion = data.content.map((part) => part.text).join("");
|
const completion = data.content.map((part) => part.text).join("");
|
||||||
if (POZZ_PROMPT.some((re) => re.test(completion))) {
|
if (POZZ_PROMPT.some((re) => re.test(completion))) {
|
||||||
this.log.info({ key: key.hash, response: completion }, "Key is pozzed.");
|
this.log.info({ key: key.hash, response: completion }, "Key is pozzed.");
|
||||||
return { pozzed: true };
|
return { pozzed: true, tier };
|
||||||
} else if (COPYRIGHT_PROMPT.some((re) => re.test(completion))) {
|
} else if (COPYRIGHT_PROMPT.some((re) => re.test(completion))) {
|
||||||
this.log.info(
|
this.log.info(
|
||||||
{ key: key.hash, response: completion },
|
{ key: key.hash, response: completion },
|
||||||
"Key has copyright CYA prompt."
|
"Key has copyright CYA prompt."
|
||||||
);
|
);
|
||||||
return { pozzed: true };
|
return { pozzed: true, tier };
|
||||||
} else {
|
} else {
|
||||||
return { pozzed: false };
|
return { pozzed: false, tier };
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -161,7 +169,19 @@ export class AnthropicKeyChecker extends KeyCheckerBase<AnthropicKey> {
|
|||||||
return data?.error?.type;
|
return data?.error?.type;
|
||||||
}
|
}
|
||||||
|
|
||||||
static getHeaders(key: AnthropicKey) {
|
static getRequestHeaders(key: AnthropicKey) {
|
||||||
return { "X-API-Key": key.key, "anthropic-version": "2023-06-01" };
|
return { "X-API-Key": key.key, "anthropic-version": "2023-06-01" };
|
||||||
}
|
}
|
||||||
|
|
||||||
|
static detectTier(headers: AxiosResponse["headers"]) {
|
||||||
|
const tokensLimit = headers["anthropic-ratelimit-tokens-limit"];
|
||||||
|
const intTokensLimit = parseInt(tokensLimit, 10);
|
||||||
|
if (!tokensLimit || isNaN(intTokensLimit)) return "unknown";
|
||||||
|
if (intTokensLimit <= 25000) return "free";
|
||||||
|
if (intTokensLimit <= 50000) return "build_1";
|
||||||
|
if (intTokensLimit <= 100000) return "build_2";
|
||||||
|
if (intTokensLimit <= 200000) return "build_3";
|
||||||
|
if (intTokensLimit <= 400000) return "build_4";
|
||||||
|
return "scale";
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -4,7 +4,7 @@ import { config } from "../../../config";
|
|||||||
import { logger } from "../../../logger";
|
import { logger } from "../../../logger";
|
||||||
import { AnthropicModelFamily, getClaudeModelFamily } from "../../models";
|
import { AnthropicModelFamily, getClaudeModelFamily } from "../../models";
|
||||||
import { AnthropicKeyChecker } from "./checker";
|
import { AnthropicKeyChecker } from "./checker";
|
||||||
import { HttpError, PaymentRequiredError } from "../../errors";
|
import { PaymentRequiredError } from "../../errors";
|
||||||
|
|
||||||
export type AnthropicKeyUpdate = Omit<
|
export type AnthropicKeyUpdate = Omit<
|
||||||
Partial<AnthropicKey>,
|
Partial<AnthropicKey>,
|
||||||
@@ -45,13 +45,40 @@ export interface AnthropicKey extends Key, AnthropicKeyUsage {
|
|||||||
*/
|
*/
|
||||||
isPozzed: boolean;
|
isPozzed: boolean;
|
||||||
isOverQuota: boolean;
|
isOverQuota: boolean;
|
||||||
|
allowsMultimodality: boolean;
|
||||||
|
/**
|
||||||
|
* Key billing tier (https://docs.anthropic.com/claude/reference/rate-limits)
|
||||||
|
**/
|
||||||
|
tier: (typeof TIER_PRIORITY)[number];
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Upon being rate limited, a key will be locked out for this many milliseconds
|
* Selection priority for Anthropic keys. Aims to maximize throughput by
|
||||||
* while we wait for other concurrent requests to finish.
|
* saturating concurrency-limited keys first, then trying keys with increasingly
|
||||||
|
* strict rate limits. Free keys have very limited throughput and are used last.
|
||||||
*/
|
*/
|
||||||
const RATE_LIMIT_LOCKOUT = 2000;
|
const TIER_PRIORITY = [
|
||||||
|
"unknown",
|
||||||
|
"scale",
|
||||||
|
"build_4",
|
||||||
|
"build_3",
|
||||||
|
"build_2",
|
||||||
|
"build_1",
|
||||||
|
"free",
|
||||||
|
] as const;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Upon being rate limited, a Scale-tier key will be locked out for this many
|
||||||
|
* milliseconds while we wait for other concurrent requests to finish.
|
||||||
|
*/
|
||||||
|
const SCALE_RATE_LIMIT_LOCKOUT = 2000;
|
||||||
|
/**
|
||||||
|
* Upon being rate limited, a Build-tier key will be locked out for this many
|
||||||
|
* milliseconds while we wait for the per-minute rate limit to reset. Because
|
||||||
|
* the reset provided in the headers specifies the time for the full quota to
|
||||||
|
* become available, the key may become available before that time.
|
||||||
|
*/
|
||||||
|
const BUILD_RATE_LIMIT_LOCKOUT = 10000;
|
||||||
/**
|
/**
|
||||||
* Upon assigning a key, we will wait this many milliseconds before allowing it
|
* Upon assigning a key, we will wait this many milliseconds before allowing it
|
||||||
* to be used again. This is to prevent the queue from flooding a key with too
|
* to be used again. This is to prevent the queue from flooding a key with too
|
||||||
@@ -85,6 +112,7 @@ export class AnthropicKeyProvider implements KeyProvider<AnthropicKey> {
|
|||||||
isOverQuota: false,
|
isOverQuota: false,
|
||||||
isRevoked: false,
|
isRevoked: false,
|
||||||
isPozzed: false,
|
isPozzed: false,
|
||||||
|
allowsMultimodality: true,
|
||||||
promptCount: 0,
|
promptCount: 0,
|
||||||
lastUsed: 0,
|
lastUsed: 0,
|
||||||
rateLimitedAt: 0,
|
rateLimitedAt: 0,
|
||||||
@@ -98,6 +126,7 @@ export class AnthropicKeyProvider implements KeyProvider<AnthropicKey> {
|
|||||||
lastChecked: 0,
|
lastChecked: 0,
|
||||||
claudeTokens: 0,
|
claudeTokens: 0,
|
||||||
"claude-opusTokens": 0,
|
"claude-opusTokens": 0,
|
||||||
|
tier: "unknown",
|
||||||
};
|
};
|
||||||
this.keys.push(newKey);
|
this.keys.push(newKey);
|
||||||
}
|
}
|
||||||
@@ -115,33 +144,43 @@ export class AnthropicKeyProvider implements KeyProvider<AnthropicKey> {
|
|||||||
return this.keys.map((k) => Object.freeze({ ...k, key: undefined }));
|
return this.keys.map((k) => Object.freeze({ ...k, key: undefined }));
|
||||||
}
|
}
|
||||||
|
|
||||||
public get(_model: string) {
|
public get(rawModel: string) {
|
||||||
// Currently, all Anthropic keys have access to all models. This will almost
|
this.log.debug({ model: rawModel }, "Selecting key");
|
||||||
// certainly change when they move out of beta later this year.
|
const needsMultimodal = rawModel.endsWith("-multimodal");
|
||||||
const availableKeys = this.keys.filter((k) => !k.isDisabled);
|
|
||||||
|
const availableKeys = this.keys.filter((k) => {
|
||||||
|
return !k.isDisabled && (!needsMultimodal || k.allowsMultimodality);
|
||||||
|
});
|
||||||
|
|
||||||
if (availableKeys.length === 0) {
|
if (availableKeys.length === 0) {
|
||||||
throw new PaymentRequiredError("No Anthropic keys available.");
|
throw new PaymentRequiredError(
|
||||||
|
needsMultimodal
|
||||||
|
? "No multimodal Anthropic keys available. Please disable multimodal input (such as inline images) and try again."
|
||||||
|
: "No Anthropic keys available."
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
// (largely copied from the OpenAI provider, without trial key support)
|
|
||||||
// Select a key, from highest priority to lowest priority:
|
// Select a key, from highest priority to lowest priority:
|
||||||
// 1. Keys which are not rate limited
|
// 1. Keys which are not rate limit locked
|
||||||
// a. If all keys were rate limited recently, select the least-recently
|
// 2. Keys with the highest tier
|
||||||
// rate limited key.
|
// 3. Keys which are not pozzed
|
||||||
// 2. Keys which are not pozzed
|
// 4. Keys which have not been used in the longest time
|
||||||
// 3. Keys which have not been used in the longest time
|
|
||||||
|
|
||||||
const now = Date.now();
|
const now = Date.now();
|
||||||
|
|
||||||
const keysByPriority = availableKeys.sort((a, b) => {
|
const keysByPriority = availableKeys.sort((a, b) => {
|
||||||
const aRateLimited = now - a.rateLimitedAt < RATE_LIMIT_LOCKOUT;
|
const aLockoutPeriod = getKeyLockout(a);
|
||||||
const bRateLimited = now - b.rateLimitedAt < RATE_LIMIT_LOCKOUT;
|
const bLockoutPeriod = getKeyLockout(b);
|
||||||
|
|
||||||
|
const aRateLimited = now - a.rateLimitedAt < aLockoutPeriod;
|
||||||
|
const bRateLimited = now - b.rateLimitedAt < bLockoutPeriod;
|
||||||
|
|
||||||
if (aRateLimited && !bRateLimited) return 1;
|
if (aRateLimited && !bRateLimited) return 1;
|
||||||
if (!aRateLimited && bRateLimited) return -1;
|
if (!aRateLimited && bRateLimited) return -1;
|
||||||
if (aRateLimited && bRateLimited) {
|
|
||||||
return a.rateLimitedAt - b.rateLimitedAt;
|
const aTierIndex = TIER_PRIORITY.indexOf(a.tier);
|
||||||
}
|
const bTierIndex = TIER_PRIORITY.indexOf(b.tier);
|
||||||
|
if (aTierIndex > bTierIndex) return -1;
|
||||||
|
|
||||||
if (a.isPozzed && !b.isPozzed) return 1;
|
if (a.isPozzed && !b.isPozzed) return 1;
|
||||||
if (!a.isPozzed && b.isPozzed) return -1;
|
if (!a.isPozzed && b.isPozzed) return -1;
|
||||||
@@ -207,7 +246,7 @@ export class AnthropicKeyProvider implements KeyProvider<AnthropicKey> {
|
|||||||
const key = this.keys.find((k) => k.hash === keyHash)!;
|
const key = this.keys.find((k) => k.hash === keyHash)!;
|
||||||
const now = Date.now();
|
const now = Date.now();
|
||||||
key.rateLimitedAt = now;
|
key.rateLimitedAt = now;
|
||||||
key.rateLimitedUntil = now + RATE_LIMIT_LOCKOUT;
|
key.rateLimitedUntil = now + SCALE_RATE_LIMIT_LOCKOUT;
|
||||||
}
|
}
|
||||||
|
|
||||||
public recheck() {
|
public recheck() {
|
||||||
@@ -239,3 +278,9 @@ export class AnthropicKeyProvider implements KeyProvider<AnthropicKey> {
|
|||||||
key.rateLimitedUntil = Math.max(currentRateLimit, nextRateLimit);
|
key.rateLimitedUntil = Math.max(currentRateLimit, nextRateLimit);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function getKeyLockout(key: AnthropicKey) {
|
||||||
|
return ["scale", "unknown"].includes(key.tier)
|
||||||
|
? SCALE_RATE_LIMIT_LOCKOUT
|
||||||
|
: BUILD_RATE_LIMIT_LOCKOUT;
|
||||||
|
}
|
||||||
|
|||||||
@@ -5,9 +5,11 @@ import axios, { AxiosError, AxiosRequestConfig, AxiosHeaders } from "axios";
|
|||||||
import { URL } from "url";
|
import { URL } from "url";
|
||||||
import { KeyCheckerBase } from "../key-checker-base";
|
import { KeyCheckerBase } from "../key-checker-base";
|
||||||
import type { AwsBedrockKey, AwsBedrockKeyProvider } from "./provider";
|
import type { AwsBedrockKey, AwsBedrockKeyProvider } from "./provider";
|
||||||
|
import { AwsBedrockModelFamily } from "../../models";
|
||||||
|
import { config } from "../../../config";
|
||||||
|
|
||||||
const MIN_CHECK_INTERVAL = 3 * 1000; // 3 seconds
|
const MIN_CHECK_INTERVAL = 3 * 1000; // 3 seconds
|
||||||
const KEY_CHECK_PERIOD = 30 * 60 * 1000; // 30 minutes
|
const KEY_CHECK_PERIOD = 90 * 60 * 1000; // 90 minutes
|
||||||
const AMZ_HOST =
|
const AMZ_HOST =
|
||||||
process.env.AMZ_HOST || "bedrock-runtime.%REGION%.amazonaws.com";
|
process.env.AMZ_HOST || "bedrock-runtime.%REGION%.amazonaws.com";
|
||||||
const GET_CALLER_IDENTITY_URL = `https://sts.amazonaws.com/?Action=GetCallerIdentity&Version=2011-06-15`;
|
const GET_CALLER_IDENTITY_URL = `https://sts.amazonaws.com/?Action=GetCallerIdentity&Version=2011-06-15`;
|
||||||
@@ -54,18 +56,41 @@ export class AwsKeyChecker extends KeyCheckerBase<AwsBedrockKey> {
|
|||||||
this.invokeModel("anthropic.claude-v2", key),
|
this.invokeModel("anthropic.claude-v2", key),
|
||||||
this.invokeModel("anthropic.claude-3-sonnet-20240229-v1:0", key),
|
this.invokeModel("anthropic.claude-3-sonnet-20240229-v1:0", key),
|
||||||
this.invokeModel("anthropic.claude-3-haiku-20240307-v1:0", key),
|
this.invokeModel("anthropic.claude-3-haiku-20240307-v1:0", key),
|
||||||
|
this.invokeModel("anthropic.claude-3-opus-20240229-v1:0", key),
|
||||||
];
|
];
|
||||||
}
|
}
|
||||||
checks.unshift(this.checkLoggingConfiguration(key));
|
checks.unshift(this.checkLoggingConfiguration(key));
|
||||||
|
|
||||||
const [_logging, _claudeV2, sonnet, haiku] = await Promise.all(checks);
|
const [_logging, claudeV2, sonnet, haiku, opus] = await Promise.all(checks);
|
||||||
|
|
||||||
if (isInitialCheck) {
|
if (isInitialCheck) {
|
||||||
this.updateKey(key.hash, { sonnetEnabled: sonnet, haikuEnabled: haiku });
|
const families: AwsBedrockModelFamily[] = [];
|
||||||
|
if (claudeV2 || sonnet || haiku) families.push("aws-claude");
|
||||||
|
if (opus) families.push("aws-claude-opus");
|
||||||
|
|
||||||
|
if (families.length === 0) {
|
||||||
|
this.log.warn(
|
||||||
|
{ key: key.hash },
|
||||||
|
"Key does not have access to any models; disabling."
|
||||||
|
);
|
||||||
|
return this.updateKey(key.hash, { isDisabled: true });
|
||||||
|
}
|
||||||
|
|
||||||
|
this.updateKey(key.hash, {
|
||||||
|
sonnetEnabled: sonnet,
|
||||||
|
haikuEnabled: haiku,
|
||||||
|
modelFamilies: families,
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
this.log.info(
|
this.log.info(
|
||||||
{ key: key.hash, sonnet, haiku, logged: key.awsLoggingStatus },
|
{
|
||||||
|
key: key.hash,
|
||||||
|
sonnet,
|
||||||
|
haiku,
|
||||||
|
families: key.modelFamilies,
|
||||||
|
logged: key.awsLoggingStatus,
|
||||||
|
},
|
||||||
"Checked key."
|
"Checked key."
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@@ -175,13 +200,14 @@ export class AwsKeyChecker extends KeyCheckerBase<AwsBedrockKey> {
|
|||||||
const correctErrorType = errorType === "ValidationException";
|
const correctErrorType = errorType === "ValidationException";
|
||||||
const correctErrorMessage = errorMessage?.match(/max_tokens/);
|
const correctErrorMessage = errorMessage?.match(/max_tokens/);
|
||||||
if (!correctErrorType || !correctErrorMessage) {
|
if (!correctErrorType || !correctErrorMessage) {
|
||||||
throw new AxiosError(
|
return false;
|
||||||
`Unexpected error when invoking model ${model}: ${errorMessage}`,
|
// throw new AxiosError(
|
||||||
"AWS_ERROR",
|
// `Unexpected error when invoking model ${model}: ${errorMessage}`,
|
||||||
response.config,
|
// "AWS_ERROR",
|
||||||
response.request,
|
// response.config,
|
||||||
response
|
// response.request,
|
||||||
);
|
// response
|
||||||
|
// );
|
||||||
}
|
}
|
||||||
|
|
||||||
this.log.debug(
|
this.log.debug(
|
||||||
@@ -192,16 +218,22 @@ export class AwsKeyChecker extends KeyCheckerBase<AwsBedrockKey> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
private async checkLoggingConfiguration(key: AwsBedrockKey) {
|
private async checkLoggingConfiguration(key: AwsBedrockKey) {
|
||||||
|
if (config.allowAwsLogging) {
|
||||||
|
// Don't check logging status if we're allowing it to reduce API calls.
|
||||||
|
this.updateKey(key.hash, { awsLoggingStatus: "unknown" });
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
const creds = AwsKeyChecker.getCredentialsFromKey(key);
|
const creds = AwsKeyChecker.getCredentialsFromKey(key);
|
||||||
const config: AxiosRequestConfig = {
|
const req: AxiosRequestConfig = {
|
||||||
method: "GET",
|
method: "GET",
|
||||||
url: GET_INVOCATION_LOGGING_CONFIG_URL(creds.region),
|
url: GET_INVOCATION_LOGGING_CONFIG_URL(creds.region),
|
||||||
headers: { accept: "application/json" },
|
headers: { accept: "application/json" },
|
||||||
validateStatus: () => true,
|
validateStatus: () => true,
|
||||||
};
|
};
|
||||||
await AwsKeyChecker.signRequestForAws(config, key);
|
await AwsKeyChecker.signRequestForAws(req, key);
|
||||||
const { data, status, headers } =
|
const { data, status, headers } =
|
||||||
await axios.request<GetLoggingConfigResponse>(config);
|
await axios.request<GetLoggingConfigResponse>(req);
|
||||||
|
|
||||||
let result: AwsBedrockKey["awsLoggingStatus"] = "unknown";
|
let result: AwsBedrockKey["awsLoggingStatus"] = "unknown";
|
||||||
|
|
||||||
|
|||||||
@@ -2,7 +2,7 @@ import crypto from "crypto";
|
|||||||
import { Key, KeyProvider } from "..";
|
import { Key, KeyProvider } from "..";
|
||||||
import { config } from "../../../config";
|
import { config } from "../../../config";
|
||||||
import { logger } from "../../../logger";
|
import { logger } from "../../../logger";
|
||||||
import type { AwsBedrockModelFamily } from "../../models";
|
import { AwsBedrockModelFamily, getAwsBedrockModelFamily } from "../../models";
|
||||||
import { AwsKeyChecker } from "./checker";
|
import { AwsKeyChecker } from "./checker";
|
||||||
import { PaymentRequiredError } from "../../errors";
|
import { PaymentRequiredError } from "../../errors";
|
||||||
|
|
||||||
@@ -78,6 +78,7 @@ export class AwsBedrockKeyProvider implements KeyProvider<AwsBedrockKey> {
|
|||||||
sonnetEnabled: true,
|
sonnetEnabled: true,
|
||||||
haikuEnabled: false,
|
haikuEnabled: false,
|
||||||
["aws-claudeTokens"]: 0,
|
["aws-claudeTokens"]: 0,
|
||||||
|
["aws-claude-opusTokens"]: 0,
|
||||||
};
|
};
|
||||||
this.keys.push(newKey);
|
this.keys.push(newKey);
|
||||||
}
|
}
|
||||||
@@ -97,14 +98,18 @@ export class AwsBedrockKeyProvider implements KeyProvider<AwsBedrockKey> {
|
|||||||
|
|
||||||
public get(model: string) {
|
public get(model: string) {
|
||||||
const availableKeys = this.keys.filter((k) => {
|
const availableKeys = this.keys.filter((k) => {
|
||||||
const isNotLogged = k.awsLoggingStatus === "disabled";
|
const isNotLogged = k.awsLoggingStatus !== "enabled";
|
||||||
const needsSonnet = model.includes("sonnet");
|
const neededFamily = getAwsBedrockModelFamily(model);
|
||||||
const needsHaiku = model.includes("haiku");
|
const needsSonnet =
|
||||||
|
model.includes("sonnet") && neededFamily === "aws-claude";
|
||||||
|
const needsHaiku =
|
||||||
|
model.includes("haiku") && neededFamily === "aws-claude";
|
||||||
return (
|
return (
|
||||||
!k.isDisabled &&
|
!k.isDisabled &&
|
||||||
(isNotLogged || config.allowAwsLogging) &&
|
(isNotLogged || config.allowAwsLogging) &&
|
||||||
(k.sonnetEnabled || !needsSonnet) &&
|
(k.sonnetEnabled || !needsSonnet) && // sonnet and haiku are both under aws-claude, while opus is not
|
||||||
(k.haikuEnabled || !needsHaiku)
|
(k.haikuEnabled || !needsHaiku) &&
|
||||||
|
k.modelFamilies.includes(neededFamily)
|
||||||
);
|
);
|
||||||
});
|
});
|
||||||
if (availableKeys.length === 0) {
|
if (availableKeys.length === 0) {
|
||||||
@@ -157,11 +162,11 @@ export class AwsBedrockKeyProvider implements KeyProvider<AwsBedrockKey> {
|
|||||||
return this.keys.filter((k) => !k.isDisabled).length;
|
return this.keys.filter((k) => !k.isDisabled).length;
|
||||||
}
|
}
|
||||||
|
|
||||||
public incrementUsage(hash: string, _model: string, tokens: number) {
|
public incrementUsage(hash: string, model: string, tokens: number) {
|
||||||
const key = this.keys.find((k) => k.hash === hash);
|
const key = this.keys.find((k) => k.hash === hash);
|
||||||
if (!key) return;
|
if (!key) return;
|
||||||
key.promptCount++;
|
key.promptCount++;
|
||||||
key["aws-claudeTokens"] += tokens;
|
key[`${getAwsBedrockModelFamily(model)}Tokens`] += tokens;
|
||||||
}
|
}
|
||||||
|
|
||||||
public getLockoutPeriod() {
|
public getLockoutPeriod() {
|
||||||
|
|||||||
@@ -72,6 +72,7 @@ export class AzureOpenAIKeyProvider implements KeyProvider<AzureOpenAIKey> {
|
|||||||
"azure-gpt4Tokens": 0,
|
"azure-gpt4Tokens": 0,
|
||||||
"azure-gpt4-32kTokens": 0,
|
"azure-gpt4-32kTokens": 0,
|
||||||
"azure-gpt4-turboTokens": 0,
|
"azure-gpt4-turboTokens": 0,
|
||||||
|
"azure-gpt4oTokens": 0,
|
||||||
"azure-dall-eTokens": 0,
|
"azure-dall-eTokens": 0,
|
||||||
};
|
};
|
||||||
this.keys.push(newKey);
|
this.keys.push(newKey);
|
||||||
|
|||||||
@@ -13,15 +13,15 @@ type KeyCheckerOptions<TKey extends Key = Key> = {
|
|||||||
|
|
||||||
export abstract class KeyCheckerBase<TKey extends Key> {
|
export abstract class KeyCheckerBase<TKey extends Key> {
|
||||||
protected readonly service: string;
|
protected readonly service: string;
|
||||||
protected readonly RECURRING_CHECKS_ENABLED: boolean;
|
protected readonly recurringChecksEnabled: boolean;
|
||||||
/** Minimum time in between any two key checks. */
|
/** Minimum time in between any two key checks. */
|
||||||
protected readonly MIN_CHECK_INTERVAL: number;
|
protected readonly minCheckInterval: number;
|
||||||
/**
|
/**
|
||||||
* Minimum time in between checks for a given key. Because we can no longer
|
* Minimum time in between checks for a given key. Because we can no longer
|
||||||
* read quota usage, there is little reason to check a single key more often
|
* read quota usage, there is little reason to check a single key more often
|
||||||
* than this.
|
* than this.
|
||||||
*/
|
*/
|
||||||
protected readonly KEY_CHECK_PERIOD: number;
|
protected readonly keyCheckPeriod: number;
|
||||||
protected readonly updateKey: (hash: string, props: Partial<TKey>) => void;
|
protected readonly updateKey: (hash: string, props: Partial<TKey>) => void;
|
||||||
protected readonly keys: TKey[] = [];
|
protected readonly keys: TKey[] = [];
|
||||||
protected log: pino.Logger;
|
protected log: pino.Logger;
|
||||||
@@ -29,14 +29,13 @@ export abstract class KeyCheckerBase<TKey extends Key> {
|
|||||||
protected lastCheck = 0;
|
protected lastCheck = 0;
|
||||||
|
|
||||||
protected constructor(keys: TKey[], opts: KeyCheckerOptions<TKey>) {
|
protected constructor(keys: TKey[], opts: KeyCheckerOptions<TKey>) {
|
||||||
const { service, keyCheckPeriod, minCheckInterval } = opts;
|
|
||||||
this.keys = keys;
|
this.keys = keys;
|
||||||
this.KEY_CHECK_PERIOD = keyCheckPeriod;
|
this.keyCheckPeriod = opts.keyCheckPeriod;
|
||||||
this.MIN_CHECK_INTERVAL = minCheckInterval;
|
this.minCheckInterval = opts.minCheckInterval;
|
||||||
this.RECURRING_CHECKS_ENABLED = opts.recurringChecksEnabled ?? true;
|
this.recurringChecksEnabled = opts.recurringChecksEnabled ?? true;
|
||||||
this.updateKey = opts.updateKey;
|
this.updateKey = opts.updateKey;
|
||||||
this.service = service;
|
this.service = opts.service;
|
||||||
this.log = logger.child({ module: "key-checker", service });
|
this.log = logger.child({ module: "key-checker", service: opts.service });
|
||||||
}
|
}
|
||||||
|
|
||||||
public start() {
|
public start() {
|
||||||
@@ -102,7 +101,7 @@ export abstract class KeyCheckerBase<TKey extends Key> {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!this.RECURRING_CHECKS_ENABLED) {
|
if (!this.recurringChecksEnabled) {
|
||||||
checkLog.info(
|
checkLog.info(
|
||||||
"Initial checks complete and recurring checks are disabled for this service. Stopping."
|
"Initial checks complete and recurring checks are disabled for this service. Stopping."
|
||||||
);
|
);
|
||||||
@@ -117,17 +116,20 @@ export abstract class KeyCheckerBase<TKey extends Key> {
|
|||||||
// Don't check any individual key too often.
|
// Don't check any individual key too often.
|
||||||
// Don't check anything at all at a rate faster than once per 3 seconds.
|
// Don't check anything at all at a rate faster than once per 3 seconds.
|
||||||
const nextCheck = Math.max(
|
const nextCheck = Math.max(
|
||||||
oldestKey.lastChecked + this.KEY_CHECK_PERIOD,
|
oldestKey.lastChecked + this.keyCheckPeriod,
|
||||||
this.lastCheck + this.MIN_CHECK_INTERVAL
|
this.lastCheck + this.minCheckInterval
|
||||||
);
|
);
|
||||||
|
|
||||||
const delay = nextCheck - Date.now();
|
const baseDelay = nextCheck - Date.now();
|
||||||
|
const jitter = (Math.random() - 0.5) * baseDelay * 0.5;
|
||||||
|
const jitteredDelay = Math.max(1000, baseDelay + jitter);
|
||||||
|
|
||||||
this.timeout = setTimeout(
|
this.timeout = setTimeout(
|
||||||
() => this.checkKey(oldestKey).then(() => this.scheduleNextCheck()),
|
() => this.checkKey(oldestKey).then(() => this.scheduleNextCheck()),
|
||||||
delay
|
jitteredDelay
|
||||||
);
|
);
|
||||||
checkLog.debug(
|
checkLog.debug(
|
||||||
{ key: oldestKey.hash, nextCheck: new Date(nextCheck), delay },
|
{ key: oldestKey.hash, nextCheck: new Date(nextCheck), jitteredDelay },
|
||||||
"Scheduled next recurring check."
|
"Scheduled next recurring check."
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -41,7 +41,13 @@ export class KeyPool {
|
|||||||
this.scheduleRecheck();
|
this.scheduleRecheck();
|
||||||
}
|
}
|
||||||
|
|
||||||
public get(model: string, service?: LLMService): Key {
|
public get(model: string, service?: LLMService, multimodal?: boolean): Key {
|
||||||
|
// hack for some claude requests needing keys with particular permissions
|
||||||
|
// even though they use the same models as the non-multimodal requests
|
||||||
|
if (multimodal) {
|
||||||
|
model += "-multimodal";
|
||||||
|
}
|
||||||
|
|
||||||
const queryService = service || this.getServiceForModel(model);
|
const queryService = service || this.getServiceForModel(model);
|
||||||
return this.getKeyProvider(queryService).get(model);
|
return this.getKeyProvider(queryService).get(model);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -96,6 +96,7 @@ export class OpenAIKeyProvider implements KeyProvider<OpenAIKey> {
|
|||||||
"turbo" as const,
|
"turbo" as const,
|
||||||
"gpt4" as const,
|
"gpt4" as const,
|
||||||
"gpt4-turbo" as const,
|
"gpt4-turbo" as const,
|
||||||
|
"gpt4o" as const,
|
||||||
],
|
],
|
||||||
isTrial: false,
|
isTrial: false,
|
||||||
isDisabled: false,
|
isDisabled: false,
|
||||||
@@ -116,6 +117,7 @@ export class OpenAIKeyProvider implements KeyProvider<OpenAIKey> {
|
|||||||
gpt4Tokens: 0,
|
gpt4Tokens: 0,
|
||||||
"gpt4-32kTokens": 0,
|
"gpt4-32kTokens": 0,
|
||||||
"gpt4-turboTokens": 0,
|
"gpt4-turboTokens": 0,
|
||||||
|
gpt4oTokens: 0,
|
||||||
"dall-eTokens": 0,
|
"dall-eTokens": 0,
|
||||||
gpt4Rpm: 0,
|
gpt4Rpm: 0,
|
||||||
modelSnapshots: [],
|
modelSnapshots: [],
|
||||||
|
|||||||
+12
-3
@@ -21,6 +21,7 @@ export type OpenAIModelFamily =
|
|||||||
| "gpt4"
|
| "gpt4"
|
||||||
| "gpt4-32k"
|
| "gpt4-32k"
|
||||||
| "gpt4-turbo"
|
| "gpt4-turbo"
|
||||||
|
| "gpt4o"
|
||||||
| "dall-e";
|
| "dall-e";
|
||||||
export type AnthropicModelFamily = "claude" | "claude-opus";
|
export type AnthropicModelFamily = "claude" | "claude-opus";
|
||||||
export type GoogleAIModelFamily = "gemini-pro";
|
export type GoogleAIModelFamily = "gemini-pro";
|
||||||
@@ -29,7 +30,7 @@ export type MistralAIModelFamily =
|
|||||||
| "mistral-small"
|
| "mistral-small"
|
||||||
| "mistral-medium"
|
| "mistral-medium"
|
||||||
| "mistral-large";
|
| "mistral-large";
|
||||||
export type AwsBedrockModelFamily = "aws-claude";
|
export type AwsBedrockModelFamily = "aws-claude" | "aws-claude-opus";
|
||||||
export type AzureOpenAIModelFamily = `azure-${OpenAIModelFamily}`;
|
export type AzureOpenAIModelFamily = `azure-${OpenAIModelFamily}`;
|
||||||
export type ModelFamily =
|
export type ModelFamily =
|
||||||
| OpenAIModelFamily
|
| OpenAIModelFamily
|
||||||
@@ -46,6 +47,7 @@ export const MODEL_FAMILIES = (<A extends readonly ModelFamily[]>(
|
|||||||
"gpt4",
|
"gpt4",
|
||||||
"gpt4-32k",
|
"gpt4-32k",
|
||||||
"gpt4-turbo",
|
"gpt4-turbo",
|
||||||
|
"gpt4o",
|
||||||
"dall-e",
|
"dall-e",
|
||||||
"claude",
|
"claude",
|
||||||
"claude-opus",
|
"claude-opus",
|
||||||
@@ -55,10 +57,12 @@ export const MODEL_FAMILIES = (<A extends readonly ModelFamily[]>(
|
|||||||
"mistral-medium",
|
"mistral-medium",
|
||||||
"mistral-large",
|
"mistral-large",
|
||||||
"aws-claude",
|
"aws-claude",
|
||||||
|
"aws-claude-opus",
|
||||||
"azure-turbo",
|
"azure-turbo",
|
||||||
"azure-gpt4",
|
"azure-gpt4",
|
||||||
"azure-gpt4-32k",
|
"azure-gpt4-32k",
|
||||||
"azure-gpt4-turbo",
|
"azure-gpt4-turbo",
|
||||||
|
"azure-gpt4o",
|
||||||
"azure-dall-e",
|
"azure-dall-e",
|
||||||
] as const);
|
] as const);
|
||||||
|
|
||||||
@@ -74,6 +78,8 @@ export const LLM_SERVICES = (<A extends readonly LLMService[]>(
|
|||||||
] as const);
|
] as const);
|
||||||
|
|
||||||
export const OPENAI_MODEL_FAMILY_MAP: { [regex: string]: OpenAIModelFamily } = {
|
export const OPENAI_MODEL_FAMILY_MAP: { [regex: string]: OpenAIModelFamily } = {
|
||||||
|
"^gpt-4o": "gpt4o",
|
||||||
|
"^gpt-4-turbo(-\\d{4}-\\d{2}-\\d{2})?$": "gpt4-turbo",
|
||||||
"^gpt-4-turbo(-preview)?$": "gpt4-turbo",
|
"^gpt-4-turbo(-preview)?$": "gpt4-turbo",
|
||||||
"^gpt-4-(0125|1106)(-preview)?$": "gpt4-turbo",
|
"^gpt-4-(0125|1106)(-preview)?$": "gpt4-turbo",
|
||||||
"^gpt-4(-\\d{4})?-vision(-preview)?$": "gpt4-turbo",
|
"^gpt-4(-\\d{4})?-vision(-preview)?$": "gpt4-turbo",
|
||||||
@@ -93,14 +99,17 @@ export const MODEL_FAMILY_SERVICE: {
|
|||||||
gpt4: "openai",
|
gpt4: "openai",
|
||||||
"gpt4-turbo": "openai",
|
"gpt4-turbo": "openai",
|
||||||
"gpt4-32k": "openai",
|
"gpt4-32k": "openai",
|
||||||
|
"gpt4o": "openai",
|
||||||
"dall-e": "openai",
|
"dall-e": "openai",
|
||||||
claude: "anthropic",
|
claude: "anthropic",
|
||||||
"claude-opus": "anthropic",
|
"claude-opus": "anthropic",
|
||||||
"aws-claude": "aws",
|
"aws-claude": "aws",
|
||||||
|
"aws-claude-opus": "aws",
|
||||||
"azure-turbo": "azure",
|
"azure-turbo": "azure",
|
||||||
"azure-gpt4": "azure",
|
"azure-gpt4": "azure",
|
||||||
"azure-gpt4-32k": "azure",
|
"azure-gpt4-32k": "azure",
|
||||||
"azure-gpt4-turbo": "azure",
|
"azure-gpt4-turbo": "azure",
|
||||||
|
"azure-gpt4o": "azure",
|
||||||
"azure-dall-e": "azure",
|
"azure-dall-e": "azure",
|
||||||
"gemini-pro": "google-ai",
|
"gemini-pro": "google-ai",
|
||||||
"mistral-tiny": "mistral-ai",
|
"mistral-tiny": "mistral-ai",
|
||||||
@@ -149,8 +158,8 @@ export function getMistralAIModelFamily(model: string): MistralAIModelFamily {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
export function getAwsBedrockModelFamily(model: string): ModelFamily {
|
export function getAwsBedrockModelFamily(model: string): AwsBedrockModelFamily {
|
||||||
if (model.includes("opus")) return "claude-opus";
|
if (model.includes("opus")) return "aws-claude-opus";
|
||||||
return "aws-claude";
|
return "aws-claude";
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,95 @@
|
|||||||
|
// stolen from https://gitgud.io/fiz1/oai-reverse-proxy
|
||||||
|
|
||||||
|
import { promises as fs } from "fs";
|
||||||
|
import * as path from "path";
|
||||||
|
import { USER_ASSETS_DIR, config } from "../../../config";
|
||||||
|
import { logger } from "../../../logger";
|
||||||
|
import { LogBackend, PromptLogEntry } from "../index";
|
||||||
|
import { glob } from "glob";
|
||||||
|
|
||||||
|
const MAX_FILE_SIZE = 100 * 1024 * 1024;
|
||||||
|
|
||||||
|
let currentFileNumber = 0;
|
||||||
|
let currentFilePath = "";
|
||||||
|
let currentFileSize = 0;
|
||||||
|
|
||||||
|
export { currentFileNumber };
|
||||||
|
|
||||||
|
export const fileBackend: LogBackend = {
|
||||||
|
init: async (_onStop: () => void) => {
|
||||||
|
try {
|
||||||
|
await createNewLogFile();
|
||||||
|
} catch (error) {
|
||||||
|
logger.error("Error initializing file backend", error);
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
|
||||||
|
const files = glob.sync(
|
||||||
|
path.join(USER_ASSETS_DIR, `${config.promptLoggingFilePrefix}*.jsonl`),
|
||||||
|
{ windowsPathsNoEscape: true }
|
||||||
|
);
|
||||||
|
const sorted = files.sort((a, b) => {
|
||||||
|
const aNum = parseInt(path.basename(a).replace(/[^0-9]/g, ""), 10);
|
||||||
|
const bNum = parseInt(path.basename(b).replace(/[^0-9]/g, ""), 10);
|
||||||
|
return aNum - bNum;
|
||||||
|
});
|
||||||
|
|
||||||
|
if (sorted.length > 0) {
|
||||||
|
const latestFile = sorted[sorted.length - 1];
|
||||||
|
const stats = await fs.stat(latestFile);
|
||||||
|
currentFileNumber = parseInt(
|
||||||
|
path.basename(latestFile).replace(/[^0-9]/g, ""),
|
||||||
|
10
|
||||||
|
);
|
||||||
|
currentFilePath = latestFile;
|
||||||
|
currentFileSize = stats.size;
|
||||||
|
}
|
||||||
|
|
||||||
|
logger.info(
|
||||||
|
{ currentFileNumber, currentFilePath, currentFileSize },
|
||||||
|
"File backend initialized"
|
||||||
|
);
|
||||||
|
},
|
||||||
|
appendBatch: async (batch: PromptLogEntry[]) => {
|
||||||
|
try {
|
||||||
|
if (currentFileSize > MAX_FILE_SIZE) {
|
||||||
|
await createNewLogFile();
|
||||||
|
}
|
||||||
|
|
||||||
|
const batchString =
|
||||||
|
batch
|
||||||
|
.map((entry) =>
|
||||||
|
JSON.stringify({
|
||||||
|
endpoint: entry.endpoint,
|
||||||
|
model: entry.model,
|
||||||
|
prompt: entry.promptRaw,
|
||||||
|
response: entry.response,
|
||||||
|
})
|
||||||
|
)
|
||||||
|
.join("\n") + "\n";
|
||||||
|
const batchSizeBytes = Buffer.byteLength(batchString);
|
||||||
|
const batchLines = batch.length;
|
||||||
|
logger.debug(
|
||||||
|
{ batchLines, batchSizeBytes, currentFileSize, file: currentFilePath },
|
||||||
|
"Appending batch to file"
|
||||||
|
);
|
||||||
|
await fs.appendFile(currentFilePath, batchString);
|
||||||
|
currentFileSize += Buffer.byteLength(batchString);
|
||||||
|
} catch (error) {
|
||||||
|
logger.error("Error appending batch to file", error);
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
|
async function createNewLogFile() {
|
||||||
|
currentFileNumber++;
|
||||||
|
currentFilePath = path.join(
|
||||||
|
USER_ASSETS_DIR,
|
||||||
|
`${config.promptLoggingFilePrefix}${currentFileNumber}.jsonl`
|
||||||
|
);
|
||||||
|
currentFileSize = 0;
|
||||||
|
|
||||||
|
await fs.writeFile(currentFilePath, "");
|
||||||
|
logger.info(`Created new log file: ${currentFilePath}`);
|
||||||
|
}
|
||||||
@@ -1 +1,2 @@
|
|||||||
export * as sheets from "./sheets";
|
export * as sheets from "./sheets";
|
||||||
|
export { fileBackend as file } from "./file";
|
||||||
|
|||||||
@@ -0,0 +1,10 @@
|
|||||||
|
import { config } from "../../config";
|
||||||
|
import type { EventLogEntry } from "../database";
|
||||||
|
import { eventsRepo } from "../database/repos/events";
|
||||||
|
|
||||||
|
export const logEvent = (payload: Omit<EventLogEntry, "date">) => {
|
||||||
|
if (!config.eventLogging) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
eventsRepo.logEvent({ ...payload, date: new Date().toISOString() });
|
||||||
|
};
|
||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user