Compare commits
42 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 8d5059534a | |||
| 0ea43f61c2 | |||
| ca4321b4cb | |||
| 7660ed8b94 | |||
| 55f1bbed3b | |||
| 57fd17ede0 | |||
| 9d00b8a9de | |||
| 155e185c6e | |||
| 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 |
+30
-8
@@ -40,12 +40,22 @@ NODE_ENV=production
|
||||
|
||||
# Which model types users are allowed to access.
|
||||
# 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'.
|
||||
# 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.
|
||||
# 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
|
||||
|
||||
# Which services can be used to process prompts containing images via multimodal
|
||||
# models. The following services are recognized:
|
||||
# openai | anthropic | aws | azure | google-ai | mistral-ai
|
||||
# Do not enable this feature unless all users are trusted, as you will be liable
|
||||
# for any user-submitted images containing illegal content.
|
||||
# By default, no image services are allowed and image prompts are rejected.
|
||||
# ALLOWED_VISION_SERVICES=
|
||||
|
||||
# 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.
|
||||
# BLOCKED_ORIGINS=reddit.com,9gag.com
|
||||
# Message to show when requests are blocked.
|
||||
@@ -58,7 +68,7 @@ NODE_ENV=production
|
||||
# Avoid short or common phrases as this tests the entire prompt.
|
||||
# REJECT_PHRASES="phrase one,phrase two,"phrase three, which has a comma",phrase four"
|
||||
# Message to show when requests are rejected.
|
||||
# REJECT_MESSAGE="This content violates /aicg/'s acceptable use policy."
|
||||
# REJECT_MESSAGE="You can't say that here."
|
||||
|
||||
# Whether prompts should be logged to Google Sheets.
|
||||
# Requires additional setup. See `docs/google-sheets.md` for more information.
|
||||
@@ -74,6 +84,13 @@ NODE_ENV=production
|
||||
# Detail level of logging. (trace | debug | info | warn | error)
|
||||
# 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:
|
||||
# See `docs/user-management.md` for more information and setup instructions.
|
||||
@@ -93,18 +110,19 @@ NODE_ENV=production
|
||||
# ALLOW_NICKNAME_CHANGES=true
|
||||
|
||||
# Default token quotas for each model family. (0 for unlimited)
|
||||
# DALL-E "tokens" are counted at a rate of 100000 tokens per US$1.00 generated,
|
||||
# which is similar to the cost of GPT-4 Turbo.
|
||||
# DALL-E 3 costs around US$0.10 per image (10000 tokens).
|
||||
# See `docs/dall-e-configuration.md` for more information.
|
||||
# Specify as TOKEN_QUOTA_MODEL_FAMILY=value, replacing dashes with underscores.
|
||||
# TOKEN_QUOTA_TURBO=0
|
||||
# TOKEN_QUOTA_GPT4=0
|
||||
# TOKEN_QUOTA_GPT4_32K=0
|
||||
# TOKEN_QUOTA_GPT4_TURBO=0
|
||||
# TOKEN_QUOTA_DALL_E=0
|
||||
# TOKEN_QUOTA_CLAUDE=0
|
||||
# TOKEN_QUOTA_GEMINI_PRO=0
|
||||
# TOKEN_QUOTA_AWS_CLAUDE=0
|
||||
# "Tokens" for image-generation models are counted at a rate of 100000 tokens
|
||||
# per US$1.00 generated, which is similar to the cost of GPT-4 Turbo.
|
||||
# DALL-E 3 costs around US$0.10 per image (10000 tokens).
|
||||
# See `docs/dall-e-configuration.md` for more information.
|
||||
# TOKEN_QUOTA_DALL_E=0
|
||||
|
||||
# How often to refresh token quotas. (hourly | daily)
|
||||
# Leave unset to never automatically refresh quotas.
|
||||
@@ -136,6 +154,10 @@ AZURE_CREDENTIALS=azure-resource-name:deployment-id:api-key,another-azure-resour
|
||||
|
||||
# With user_token gatekeeper, the admin password used to manage users.
|
||||
# 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.
|
||||
# FIREBASE_KEY=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
|
||||
|
||||
+3
-4
@@ -1,11 +1,10 @@
|
||||
{
|
||||
"plugins": ["prettier-plugin-ejs"],
|
||||
"overrides": [
|
||||
{
|
||||
"files": [
|
||||
"*.ejs"
|
||||
],
|
||||
"files": "*.ejs",
|
||||
"options": {
|
||||
"printWidth": 160,
|
||||
"printWidth": 120,
|
||||
"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)
|
||||
- [Firebase Realtime Database](#firebase-realtime-database)
|
||||
- [Firebase setup instructions](#firebase-setup-instructions)
|
||||
- [Whitelisting admin IP addresses](#whitelisting-admin-ip-addresses)
|
||||
|
||||
## 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.
|
||||
|
||||
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,::0`, which will allow access from any IPv4 or IPv6 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",
|
||||
"scripts": {
|
||||
"build": "tsc && copyfiles -u 1 src/**/*.ejs build",
|
||||
"database:migrate": "ts-node scripts/migrate.ts",
|
||||
"prepare": "husky install",
|
||||
"start": "node build/server.js",
|
||||
"start:dev": "nodemon --watch src --exec ts-node --transpile-only src/server.ts",
|
||||
@@ -19,6 +20,7 @@
|
||||
"dependencies": {
|
||||
"@anthropic-ai/tokenizer": "^0.0.4",
|
||||
"@aws-crypto/sha256-js": "^5.2.0",
|
||||
"@node-rs/argon2": "^1.8.3",
|
||||
"@smithy/eventstream-codec": "^2.1.3",
|
||||
"@smithy/eventstream-serde-node": "^2.1.3",
|
||||
"@smithy/protocol-http": "^3.2.1",
|
||||
@@ -26,18 +28,21 @@
|
||||
"@smithy/types": "^2.10.1",
|
||||
"@smithy/util-utf8": "^2.1.1",
|
||||
"axios": "^1.3.5",
|
||||
"better-sqlite3": "^10.0.0",
|
||||
"check-disk-space": "^3.4.0",
|
||||
"cookie-parser": "^1.4.6",
|
||||
"copyfiles": "^2.4.1",
|
||||
"cors": "^2.8.5",
|
||||
"csrf-csrf": "^2.3.0",
|
||||
"dotenv": "^16.3.1",
|
||||
"ejs": "^3.1.9",
|
||||
"ejs": "^3.1.10",
|
||||
"express": "^4.18.2",
|
||||
"express-session": "^1.17.3",
|
||||
"firebase-admin": "^11.10.1",
|
||||
"firebase-admin": "^12.1.0",
|
||||
"glob": "^10.3.12",
|
||||
"googleapis": "^122.0.0",
|
||||
"http-proxy-middleware": "^3.0.0-beta.1",
|
||||
"ipaddr.js": "^2.1.0",
|
||||
"memorystore": "^1.6.7",
|
||||
"multer": "^1.4.5-lts.1",
|
||||
"node-schedule": "^2.1.1",
|
||||
@@ -55,6 +60,7 @@
|
||||
"zod-error": "^1.5.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/better-sqlite3": "^7.6.10",
|
||||
"@types/cookie-parser": "^1.4.3",
|
||||
"@types/cors": "^2.8.13",
|
||||
"@types/express": "^4.17.17",
|
||||
@@ -72,11 +78,11 @@
|
||||
"nodemon": "^3.0.1",
|
||||
"pino-pretty": "^10.2.3",
|
||||
"prettier": "^3.0.3",
|
||||
"prettier-plugin-ejs": "^1.0.3",
|
||||
"ts-node": "^10.9.1",
|
||||
"typescript": "^5.4.2"
|
||||
},
|
||||
"overrides": {
|
||||
"google-gax": "^3.6.1",
|
||||
"postcss": "^8.4.31",
|
||||
"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/event";
|
||||
|
||||
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 };
|
||||
+19
-4
@@ -1,17 +1,31 @@
|
||||
import express, { Router } from "express";
|
||||
import { authorize } from "./auth";
|
||||
import { createWhitelistMiddleware } from "../shared/cidr";
|
||||
import { HttpError } from "../shared/errors";
|
||||
import { injectCsrfToken, checkCsrfToken } from "../shared/inject-csrf";
|
||||
import { injectLocals } from "../shared/inject-locals";
|
||||
import { withSession } from "../shared/with-session";
|
||||
import { injectCsrfToken, checkCsrfToken } from "../shared/inject-csrf";
|
||||
import { config } from "../config";
|
||||
import { renderPage } from "../info-page";
|
||||
import { buildInfo } from "../service-info";
|
||||
import { authorize } from "./auth";
|
||||
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 { logger } from "../logger";
|
||||
|
||||
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(
|
||||
express.json({ limit: "20mb" }),
|
||||
express.urlencoded({ extended: true, limit: "20mb" })
|
||||
@@ -19,7 +33,8 @@ adminRouter.use(
|
||||
adminRouter.use(withSession);
|
||||
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(injectLocals);
|
||||
|
||||
+193
-5
@@ -1,4 +1,5 @@
|
||||
import { Router } from "express";
|
||||
import ipaddr from "ipaddr.js";
|
||||
import multer from "multer";
|
||||
import { z } from "zod";
|
||||
import { config } from "../../config";
|
||||
@@ -15,6 +16,8 @@ import {
|
||||
UserTokenCounts,
|
||||
} from "../../shared/users/schema";
|
||||
import { getLastNImages } from "../../shared/file-storage/image-history";
|
||||
import { blacklists, parseCidrs, whitelists } from "../../shared/cidr";
|
||||
import { invalidatePowHmacKey } from "../../user/web/pow-captcha";
|
||||
|
||||
const router = Router();
|
||||
|
||||
@@ -40,6 +43,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) => {
|
||||
const body = req.body;
|
||||
|
||||
@@ -223,10 +294,14 @@ router.post("/maintenance", (req, res) => {
|
||||
break;
|
||||
}
|
||||
case "downloadImageMetadata": {
|
||||
const data = JSON.stringify({
|
||||
exportedAt: new Date().toISOString(),
|
||||
generations: getLastNImages()
|
||||
}, null, 2);
|
||||
const data = JSON.stringify(
|
||||
{
|
||||
exportedAt: new Date().toISOString(),
|
||||
generations: getLastNImages(),
|
||||
},
|
||||
null,
|
||||
2
|
||||
);
|
||||
res.setHeader(
|
||||
"Content-Disposition",
|
||||
`attachment; filename=image-metadata-${new Date().toISOString()}.json`
|
||||
@@ -234,14 +309,127 @@ router.post("/maintenance", (req, res) => {
|
||||
res.setHeader("Content-Type", "application/json");
|
||||
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: {
|
||||
throw new HttpError(400, "Invalid action");
|
||||
}
|
||||
}
|
||||
|
||||
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) => {
|
||||
|
||||
@@ -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>
|
||||
<div class="temporary-user-fieldset">
|
||||
<p class="full-width">
|
||||
Temporary users will be disabled after the specified duration, and their records will be deleted 72 hours after that.
|
||||
These options apply only to new
|
||||
temporary users; existing ones use whatever options were in effect when they were created.
|
||||
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 temporary users; existing ones use whatever options were in effect when they were created.
|
||||
</p>
|
||||
<label for="temporaryUserDuration" class="full-width">Access duration (in minutes)</label>
|
||||
<input type="number" name="temporaryUserDuration" id="temporaryUserDuration" value="60" class="full-width" />
|
||||
|
||||
@@ -5,18 +5,6 @@
|
||||
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 {
|
||||
margin: 0;
|
||||
padding-left: 2em;
|
||||
@@ -33,17 +21,17 @@
|
||||
}
|
||||
</style>
|
||||
<h1>Download Stats</h1>
|
||||
<p>
|
||||
Download usage statistics to a Markdown document. You can paste this into a service like Rentry.org to share it.
|
||||
</p>
|
||||
<p>Download usage statistics to a Markdown document. You can paste this into a service like Rentry.org to share it.</p>
|
||||
<div>
|
||||
<h3>Options</h3>
|
||||
<form id="statsForm" action="/admin/manage/generate-stats" method="post"
|
||||
style="display: flex; flex-direction: column;">
|
||||
<form
|
||||
id="statsForm"
|
||||
action="/admin/manage/generate-stats"
|
||||
method="post"
|
||||
style="display: flex; flex-direction: column">
|
||||
<input id="_csrf" type="hidden" name="_csrf" value="<%= csrfToken %>" />
|
||||
<div>
|
||||
<label for="anon">Anonymize</label>
|
||||
<input id="anon" type="checkbox" name="anon" value="true" />
|
||||
<label for="anon"><input id="anon" type="checkbox" name="anon" value="true" /> <span>Anonymize</span></label>
|
||||
</div>
|
||||
<div>
|
||||
<label for="sort">Sort</label>
|
||||
@@ -64,11 +52,12 @@
|
||||
</select>
|
||||
</div>
|
||||
<div>
|
||||
<label for="format">Custom Format <ul>
|
||||
<li><code>{{header}}</code></li>
|
||||
<li><code>{{stats}}</code></li>
|
||||
<li><code>{{time}}</code></li>
|
||||
</ul></label>
|
||||
<label for="format">Custom Format</label>
|
||||
<ul>
|
||||
<li><code>{{header}}</code></li>
|
||||
<li><code>{{stats}}</code></li>
|
||||
<li><code>{{time}}</code></li>
|
||||
</ul>
|
||||
<textarea id="format" name="format" rows="10" cols="50" placeholder="{{stats}}">
|
||||
# Stats
|
||||
{{header}}
|
||||
@@ -115,33 +104,35 @@
|
||||
loadDefaults();
|
||||
|
||||
async function fetchAndCopy() {
|
||||
const form = document.getElementById('statsForm');
|
||||
const form = document.getElementById("statsForm");
|
||||
const formData = new FormData(form);
|
||||
|
||||
const response = await fetch(form.action, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
|
||||
credentials: 'same-origin',
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/x-www-form-urlencoded" },
|
||||
credentials: "same-origin",
|
||||
body: new URLSearchParams(formData),
|
||||
});
|
||||
|
||||
|
||||
if (response.ok) {
|
||||
const content = await response.text();
|
||||
copyToClipboard(content);
|
||||
} 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) {
|
||||
navigator.clipboard.writeText(text).then(() => {
|
||||
alert('Copied to clipboard');
|
||||
}).catch(err => {
|
||||
alert('Failed to copy to clipboard. Try downloading the file instead.');
|
||||
});
|
||||
navigator.clipboard
|
||||
.writeText(text)
|
||||
.then(() => {
|
||||
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>
|
||||
<%- include("partials/admin-footer") %>
|
||||
|
||||
@@ -25,13 +25,14 @@
|
||||
<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/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>
|
||||
</ul>
|
||||
<h3>Maintenance</h3>
|
||||
<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="" />
|
||||
<div display="flex" flex-direction="column">
|
||||
<div>
|
||||
<fieldset>
|
||||
<legend>Key Recheck</legend>
|
||||
<button id="recheck-keys" type="button" onclick="submitForm('recheck')">Force Key Recheck</button>
|
||||
|
||||
@@ -4,9 +4,8 @@
|
||||
<% if (users.length === 0) { %>
|
||||
<p>No users found.</p>
|
||||
<% } else { %>
|
||||
<input type="checkbox" id="toggle-nicknames" onchange="toggleNicknames()" />
|
||||
<label for="toggle-nicknames">Show Nicknames</label>
|
||||
<table class="striped">
|
||||
<label for="toggle-nicknames"><input type="checkbox" id="toggle-nicknames" onchange="toggleNicknames()" /> Show Nicknames</label>
|
||||
<table class="striped full-width">
|
||||
<thead>
|
||||
<tr>
|
||||
<th>User</th>
|
||||
|
||||
@@ -55,8 +55,9 @@
|
||||
<td><%- user.disabledReason %></td>
|
||||
<% if (user.disabledAt) { %>
|
||||
<td class="actions">
|
||||
<a title="Edit" id="edit-disabledReason" href="#" data-field="disabledReason"
|
||||
data-token="<%= user.token %>">✏️</a>
|
||||
<a title="Edit" id="edit-disabledReason" href="#" data-field="disabledReason" data-token="<%= user.token %>"
|
||||
>✏️</a
|
||||
>
|
||||
</td>
|
||||
<% } %>
|
||||
</tr>
|
||||
@@ -72,7 +73,8 @@
|
||||
<td colspan="2"><%- include("partials/shared_user_ip_list", { user, shouldRedact: false }) %></td>
|
||||
</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>
|
||||
<td><%- user.adminNote ?? "none" %></td>
|
||||
<td class="actions">
|
||||
@@ -85,10 +87,16 @@
|
||||
<td colspan="2"><%- user.expiresAt %></td>
|
||||
</tr>
|
||||
<% } %>
|
||||
<% if (user.meta) { %>
|
||||
<tr>
|
||||
<th scope="row">Meta</th>
|
||||
<td colspan="2"><%- JSON.stringify(user.meta) %></td>
|
||||
</tr>
|
||||
<% } %>
|
||||
</tbody>
|
||||
</table>
|
||||
|
||||
<form style="display:none" id="current-values">
|
||||
<form style="display: none" id="current-values">
|
||||
<input type="hidden" name="token" value="<%- user.token %>" />
|
||||
<% ["nickname", "type", "disabledAt", "disabledReason", "maxIps", "adminNote"].forEach(function (key) { %>
|
||||
<input type="hidden" name="<%- key %>" value="<%- user[key] %>" />
|
||||
@@ -102,7 +110,8 @@
|
||||
<input type="hidden" name="_csrf" value="<%- csrfToken %>" />
|
||||
<button type="submit" class="btn btn-primary">Refresh Quotas for User</button>
|
||||
</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>
|
||||
|
||||
@@ -144,4 +153,5 @@
|
||||
});
|
||||
</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>
|
||||
+221
-14
@@ -1,8 +1,9 @@
|
||||
import crypto from "crypto";
|
||||
import dotenv from "dotenv";
|
||||
import type firebase from "firebase-admin";
|
||||
import path from "path";
|
||||
import pino from "pino";
|
||||
import type { ModelFamily } from "./shared/models";
|
||||
import type { LLMService, ModelFamily } from "./shared/models";
|
||||
import { MODEL_FAMILIES } from "./shared/models";
|
||||
|
||||
dotenv.config();
|
||||
@@ -107,9 +108,70 @@ type Config = {
|
||||
* `maxIpsPerUser` limit, or if only connections from new IPs are be rejected.
|
||||
*/
|
||||
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;
|
||||
/** Per-IP limit for requests per minute to image generation models. */
|
||||
/** Per-user limit for requests per minute to image generation models. */
|
||||
imageModelRateLimit: number;
|
||||
/**
|
||||
* 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.
|
||||
*/
|
||||
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. */
|
||||
promptLogging?: boolean;
|
||||
/** 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. */
|
||||
googleSheetsKey?: string;
|
||||
/** Google Sheets spreadsheet ID. */
|
||||
@@ -249,11 +339,38 @@ type Config = {
|
||||
* risk.
|
||||
*/
|
||||
allowOpenAIToolUsage?: boolean;
|
||||
/**
|
||||
* Which services will accept prompts containing images, for use with
|
||||
* multimodal models. Users with `special` role are exempt from this
|
||||
* restriction.
|
||||
*
|
||||
* Do not enable this feature for untrusted users, as malicious users could
|
||||
* send images which violate your provider's terms of service or local laws.
|
||||
*
|
||||
* Defaults to no services, meaning image prompts are disabled. Use a comma-
|
||||
* separated list. Available services are:
|
||||
* openai,anthropic,google-ai,mistral-ai,aws,azure
|
||||
*/
|
||||
allowedVisionServices: LLMService[];
|
||||
/**
|
||||
* Allows overriding the default proxy endpoint route. Defaults to /proxy.
|
||||
* A leading slash is required.
|
||||
*/
|
||||
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.
|
||||
@@ -270,10 +387,22 @@ export const config: Config = {
|
||||
proxyKey: getEnvWithDefault("PROXY_KEY", ""),
|
||||
adminKey: getEnvWithDefault("ADMIN_KEY", ""),
|
||||
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"),
|
||||
gatekeeperStore: getEnvWithDefault("GATEKEEPER_STORE", "memory"),
|
||||
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),
|
||||
firebaseKey: getEnvWithDefault("FIREBASE_KEY", undefined),
|
||||
textModelRateLimit: getEnvWithDefault("TEXT_MODEL_RATE_LIMIT", 4),
|
||||
@@ -296,6 +425,7 @@ export const config: Config = {
|
||||
"gpt4",
|
||||
"gpt4-32k",
|
||||
"gpt4-turbo",
|
||||
"gpt4o",
|
||||
"claude",
|
||||
"claude-opus",
|
||||
"gemini-pro",
|
||||
@@ -304,10 +434,12 @@ export const config: Config = {
|
||||
"mistral-medium",
|
||||
"mistral-large",
|
||||
"aws-claude",
|
||||
"aws-claude-opus",
|
||||
"azure-turbo",
|
||||
"azure-gpt4",
|
||||
"azure-gpt4-turbo",
|
||||
"azure-gpt4-32k",
|
||||
"azure-gpt4-turbo",
|
||||
"azure-gpt4o",
|
||||
]),
|
||||
rejectPhrases: parseCsv(getEnvWithDefault("REJECT_PHRASES", "")),
|
||||
rejectMessage: getEnvWithDefault(
|
||||
@@ -320,6 +452,10 @@ export const config: Config = {
|
||||
allowAwsLogging: getEnvWithDefault("ALLOW_AWS_LOGGING", false),
|
||||
promptLogging: getEnvWithDefault("PROMPT_LOGGING", false),
|
||||
promptLoggingBackend: getEnvWithDefault("PROMPT_LOGGING_BACKEND", undefined),
|
||||
promptLoggingFilePrefix: getEnvWithDefault(
|
||||
"PROMPT_LOGGING_FILE_PREFIX",
|
||||
"prompt-logs"
|
||||
),
|
||||
googleSheetsKey: getEnvWithDefault("GOOGLE_SHEETS_KEY", undefined),
|
||||
googleSheetsSpreadsheetId: getEnvWithDefault(
|
||||
"GOOGLE_SHEETS_SPREADSHEET_ID",
|
||||
@@ -348,20 +484,50 @@ export const config: Config = {
|
||||
staticServiceInfo: getEnvWithDefault("STATIC_SERVICE_INFO", false),
|
||||
trustedProxies: getEnvWithDefault("TRUSTED_PROXIES", 1),
|
||||
allowOpenAIToolUsage: getEnvWithDefault("ALLOW_OPENAI_TOOL_USAGE", false),
|
||||
allowedVisionServices: parseCsv(
|
||||
getEnvWithDefault("ALLOWED_VISION_SERVICES", "")
|
||||
) as LLMService[],
|
||||
proxyEndpointRoute: getEnvWithDefault("PROXY_ENDPOINT_ROUTE", "/proxy"),
|
||||
adminWhitelist: parseCsv(
|
||||
getEnvWithDefault("ADMIN_WHITELIST", "0.0.0.0/0,::/0")
|
||||
),
|
||||
ipBlacklist: parseCsv(getEnvWithDefault("IP_BLACKLIST", "")),
|
||||
} as const;
|
||||
|
||||
function generateCookieSecret() {
|
||||
function generateSigningKey() {
|
||||
if (process.env.COOKIE_SECRET !== undefined) {
|
||||
// legacy, replaced by SIGNING_KEY
|
||||
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 crypto = require("crypto");
|
||||
const secrets = [
|
||||
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");
|
||||
}
|
||||
|
||||
export const COOKIE_SECRET = generateCookieSecret();
|
||||
const signingKey = generateSigningKey();
|
||||
export const COOKIE_SECRET = signingKey;
|
||||
|
||||
export async function assertConfigIsValid() {
|
||||
if (process.env.MODEL_RATE_LIMIT !== undefined) {
|
||||
@@ -377,6 +543,23 @@ export async function assertConfigIsValid() {
|
||||
);
|
||||
}
|
||||
|
||||
if (process.env.ALLOW_IMAGE_PROMPTS === "true") {
|
||||
const hasAllowedServices = config.allowedVisionServices.length > 0;
|
||||
if (!hasAllowedServices) {
|
||||
config.allowedVisionServices = ["openai", "anthropic"];
|
||||
startupLogger.warn(
|
||||
{ allowedVisionServices: config.allowedVisionServices },
|
||||
"ALLOW_IMAGE_PROMPTS is deprecated. Use ALLOWED_VISION_SERVICES instead."
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
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)) {
|
||||
throw new Error(
|
||||
`Invalid gatekeeper mode: ${config.gatekeeper}. Must be one of: none, proxy_key, user_token.`
|
||||
@@ -389,15 +572,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(
|
||||
"`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(
|
||||
"`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 +653,13 @@ export const OMITTED_KEYS = [
|
||||
"rejectPhrases",
|
||||
"rejectMessage",
|
||||
"showTokenCosts",
|
||||
"promptLoggingFilePrefix",
|
||||
"googleSheetsKey",
|
||||
"firebaseKey",
|
||||
"firebaseRtdbUrl",
|
||||
"sqliteDataPath",
|
||||
"eventLogging",
|
||||
"eventLoggingTrim",
|
||||
"gatekeeperStore",
|
||||
"maxIpsPerUser",
|
||||
"blockedOrigins",
|
||||
@@ -469,6 +673,9 @@ export const OMITTED_KEYS = [
|
||||
"allowedModelFamilies",
|
||||
"trustedProxies",
|
||||
"proxyEndpointRoute",
|
||||
"adminWhitelist",
|
||||
"ipBlacklist",
|
||||
"powTokenPurgeHours",
|
||||
] satisfies (keyof Config)[];
|
||||
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-32k": "GPT-4 32k",
|
||||
"gpt4-turbo": "GPT-4 Turbo",
|
||||
gpt4o: "GPT-4o",
|
||||
"dall-e": "DALL-E",
|
||||
claude: "Claude (Sonnet)",
|
||||
"claude-opus": "Claude (Opus)",
|
||||
@@ -25,10 +26,12 @@ const MODEL_FAMILY_FRIENDLY_NAME: { [f in ModelFamily]: string } = {
|
||||
"mistral-medium": "Mistral Medium",
|
||||
"mistral-large": "Mistral Large",
|
||||
"aws-claude": "AWS Claude (Sonnet)",
|
||||
"aws-claude-opus": "AWS Claude (Opus)",
|
||||
"azure-turbo": "Azure GPT-3.5 Turbo",
|
||||
"azure-gpt4": "Azure GPT-4",
|
||||
"azure-gpt4-32k": "Azure GPT-4 32k",
|
||||
"azure-gpt4-turbo": "Azure GPT-4 Turbo",
|
||||
"azure-gpt4o": "Azure GPT-4o",
|
||||
"azure-dall-e": "Azure DALL-E",
|
||||
};
|
||||
|
||||
@@ -60,36 +63,42 @@ export function renderPage(info: ServiceInfo) {
|
||||
const title = getServerTitle();
|
||||
const headerHtml = buildInfoPageHeader(info);
|
||||
|
||||
return `<!DOCTYPE html>
|
||||
return `<!doctype html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8" />
|
||||
<meta name="robots" content="noindex" />
|
||||
<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>
|
||||
body {
|
||||
font-family: sans-serif;
|
||||
background-color: #f0f0f0;
|
||||
padding: 1em;
|
||||
max-width: 900px;
|
||||
margin: 0;
|
||||
}
|
||||
@media (prefers-color-scheme: dark) {
|
||||
body {
|
||||
background-color: #222;
|
||||
color: #eee;
|
||||
}
|
||||
|
||||
a:link, a:visited {
|
||||
color: #bbe;
|
||||
}
|
||||
|
||||
.self-service-links {
|
||||
display: flex;
|
||||
justify-content: center;
|
||||
margin-bottom: 1em;
|
||||
padding: 0.5em;
|
||||
font-size: 0.8em;
|
||||
}
|
||||
|
||||
.self-service-links a {
|
||||
margin: 0 0.5em;
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
${headerHtml}
|
||||
<hr />
|
||||
${getSelfServiceLinks()}
|
||||
<h2>Service Info</h2>
|
||||
<pre>${JSON.stringify(info, null, 2)}</pre>
|
||||
${getSelfServiceLinks()}
|
||||
</body>
|
||||
</html>`;
|
||||
}
|
||||
@@ -143,7 +152,15 @@ This proxy keeps full logs of all prompts and AI responses. Prompt logs are anon
|
||||
|
||||
function getSelfServiceLinks() {
|
||||
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() {
|
||||
@@ -190,7 +207,7 @@ function buildRecentImageSection() {
|
||||
</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;
|
||||
}
|
||||
@@ -201,7 +218,9 @@ function escapeHtml(unsafe: string) {
|
||||
.replace(/</g, "<")
|
||||
.replace(/>/g, ">")
|
||||
.replace(/"/g, """)
|
||||
.replace(/'/g, "'");
|
||||
.replace(/'/g, "'")
|
||||
.replace(/\[/g, "[")
|
||||
.replace(/]/g, "]");
|
||||
}
|
||||
|
||||
function getExternalUrlForHuggingfaceSpaceId(spaceId: string) {
|
||||
|
||||
@@ -156,7 +156,7 @@ function transformAnthropicTextResponseToOpenAI(
|
||||
};
|
||||
}
|
||||
|
||||
function transformAnthropicChatResponseToOpenAI(
|
||||
export function transformAnthropicChatResponseToOpenAI(
|
||||
anthropicBody: Record<string, any>
|
||||
): Record<string, any> {
|
||||
return {
|
||||
|
||||
+40
-12
@@ -16,7 +16,7 @@ import {
|
||||
ProxyResHandlerWithBody,
|
||||
createOnProxyResHandler,
|
||||
} from "./middleware/response";
|
||||
import { transformAnthropicChatResponseToAnthropicText } from "./anthropic";
|
||||
import { transformAnthropicChatResponseToAnthropicText, transformAnthropicChatResponseToOpenAI } from "./anthropic";
|
||||
import { sendErrorToClient } from "./middleware/response/error-generator";
|
||||
|
||||
const LATEST_AWS_V2_MINOR_VERSION = "1";
|
||||
@@ -37,6 +37,7 @@ const getModelsResponse = () => {
|
||||
"anthropic.claude-v2:1",
|
||||
"anthropic.claude-3-haiku-20240307-v1:0",
|
||||
"anthropic.claude-3-sonnet-20240229-v1:0",
|
||||
"anthropic.claude-3-opus-20240229-v1:0",
|
||||
];
|
||||
|
||||
const models = variants.map((id) => ({
|
||||
@@ -76,8 +77,10 @@ const awsResponseHandler: ProxyResHandlerWithBody = async (
|
||||
req.log.info("Transforming Anthropic Text back to OpenAI format");
|
||||
newBody = transformAwsTextResponseToOpenAI(body, req);
|
||||
break;
|
||||
// case "openai<-anthropic-chat":
|
||||
// todo: implement this
|
||||
case "openai<-anthropic-chat":
|
||||
req.log.info("Transforming AWS Anthropic Chat back to OpenAI format");
|
||||
newBody = transformAnthropicChatResponseToOpenAI(body);
|
||||
break;
|
||||
case "anthropic-text<-anthropic-chat":
|
||||
req.log.info("Transforming AWS Anthropic Chat back to Text format");
|
||||
newBody = transformAnthropicChatResponseToAnthropicText(body);
|
||||
@@ -159,7 +162,7 @@ const textToChatPreprocessor = createPreprocessorMiddleware(
|
||||
* Routes text completion prompts to aws anthropic-chat if they need translation
|
||||
* (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")) {
|
||||
textToChatPreprocessor(req, res, next);
|
||||
} 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();
|
||||
awsRouter.get("/v1/models", handleModelRequest);
|
||||
// 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.
|
||||
awsRouter.post(
|
||||
"/v1/messages",
|
||||
@@ -198,10 +223,7 @@ awsRouter.post(
|
||||
awsRouter.post(
|
||||
"/v1/chat/completions",
|
||||
ipLimiter,
|
||||
createPreprocessorMiddleware(
|
||||
{ inApi: "openai", outApi: "anthropic-text", service: "aws" },
|
||||
{ afterTransform: [maybeReassignModel] }
|
||||
),
|
||||
preprocessOpenAICompatRequest,
|
||||
awsProxy
|
||||
);
|
||||
|
||||
@@ -222,7 +244,7 @@ function maybeReassignModel(req: Request) {
|
||||
}
|
||||
|
||||
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);
|
||||
|
||||
// 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.
|
||||
const variant = match[8]; // sonnet or opus
|
||||
const variant = match[8]; // sonnet, opus, or haiku
|
||||
const variantVersion = match[9];
|
||||
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;
|
||||
}
|
||||
|
||||
|
||||
+44
-10
@@ -1,6 +1,7 @@
|
||||
import type { Request, RequestHandler } from "express";
|
||||
import type { Request, Response, RequestHandler } from "express";
|
||||
import { config } from "../config";
|
||||
import { authenticate, getUser } from "../shared/users/user-store";
|
||||
import { sendErrorToClient } from "./middleware/response/error-generator";
|
||||
|
||||
const GATEKEEPER = config.gatekeeper;
|
||||
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.
|
||||
// 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.
|
||||
const ip = req.risuToken?.length ?
|
||||
`risu${req.risuToken}-${req.ip}` :
|
||||
req.ip;
|
||||
const ip = req.risuToken?.length
|
||||
? `risu${req.risuToken}-${req.ip}`
|
||||
: req.ip;
|
||||
|
||||
const { user, result } = authenticate(token, ip);
|
||||
|
||||
@@ -61,17 +62,50 @@ export const gatekeeper: RequestHandler = (req, res, next) => {
|
||||
req.user = user;
|
||||
return next();
|
||||
case "limited":
|
||||
return res.status(403).json({
|
||||
error: `Forbidden: no more IPs can authenticate with this token`,
|
||||
});
|
||||
return sendError(
|
||||
req,
|
||||
res,
|
||||
403,
|
||||
`Forbidden: no more IP addresses allowed for this user token`,
|
||||
{ currentIp: ip, maxIps: user?.maxIps }
|
||||
);
|
||||
case "disabled":
|
||||
const bannedUser = getUser(token);
|
||||
if (bannedUser?.disabledAt) {
|
||||
const reason = bannedUser.disabledReason || "Token disabled";
|
||||
return res.status(403).json({ error: `Forbidden: ${reason}` });
|
||||
const reason = bannedUser.disabledReason || "User token disabled";
|
||||
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,
|
||||
data: any = {}
|
||||
) {
|
||||
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,
|
||||
obj: data,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
@@ -3,10 +3,10 @@ import http from "http";
|
||||
import httpProxy from "http-proxy";
|
||||
import { ZodError } from "zod";
|
||||
import { generateErrorMessage } from "zod-error";
|
||||
import { HttpError } from "../../shared/errors";
|
||||
import { assertNever } from "../../shared/utils";
|
||||
import { QuotaExceededError } from "./request/preprocessors/apply-quota-limits";
|
||||
import { sendErrorToClient } from "./response/error-generator";
|
||||
import { HttpError } from "../../shared/errors";
|
||||
|
||||
const OPENAI_CHAT_COMPLETION_ENDPOINT = "/v1/chat/completions";
|
||||
const OPENAI_TEXT_COMPLETION_ENDPOINT = "/v1/completions";
|
||||
@@ -54,13 +54,13 @@ export function sendProxyError(
|
||||
const msg =
|
||||
statusCode === 500
|
||||
? `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({
|
||||
options: {
|
||||
format: req.inboundApi,
|
||||
title: `Proxy error (HTTP ${statusCode} ${statusMessage})`,
|
||||
message: `${msg} Further technical details are provided below.`,
|
||||
message: `${msg} Further details are provided below.`,
|
||||
obj: errorPayload,
|
||||
reqId: req.id,
|
||||
model: req.body?.model,
|
||||
|
||||
@@ -11,16 +11,17 @@ export {
|
||||
// Express middleware (runs before http-proxy-middleware, can be async)
|
||||
export { addAzureKey } from "./preprocessors/add-azure-key";
|
||||
export { applyQuotaLimits } from "./preprocessors/apply-quota-limits";
|
||||
export { validateContextSize } from "./preprocessors/validate-context-size";
|
||||
export { countPromptTokens } from "./preprocessors/count-prompt-tokens";
|
||||
export { languageFilter } from "./preprocessors/language-filter";
|
||||
export { setApiFormat } from "./preprocessors/set-api-format";
|
||||
export { signAwsRequest } from "./preprocessors/sign-aws-request";
|
||||
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)
|
||||
export { addKey, addKeyForEmbeddingsRequest } from "./onproxyreq/add-key";
|
||||
export { addAnthropicPreamble } from "./onproxyreq/add-anthropic-preamble";
|
||||
export { addKey, addKeyForEmbeddingsRequest } from "./onproxyreq/add-key";
|
||||
export { blockZoomerOrigins } from "./onproxyreq/block-zoomer-origins";
|
||||
export { checkModelFamily } from "./onproxyreq/check-model-family";
|
||||
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 { isEmbeddingsRequest } from "../../common";
|
||||
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.");
|
||||
}
|
||||
|
||||
let needsMultimodal = false;
|
||||
if (outboundApi === "anthropic-chat") {
|
||||
needsMultimodal = containsImageContent(
|
||||
body.messages as AnthropicChatMessage[]
|
||||
);
|
||||
}
|
||||
|
||||
if (inboundApi === outboundApi) {
|
||||
assignedKey = keyPool.get(body.model, service);
|
||||
assignedKey = keyPool.get(body.model, service, needsMultimodal);
|
||||
} else {
|
||||
switch (outboundApi) {
|
||||
// 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.
|
||||
// TODO: This whole else condition is probably no longer needed since API
|
||||
// translation now reassigns the model earlier in the request pipeline.
|
||||
case "anthropic-chat":
|
||||
case "anthropic-text":
|
||||
assignedKey = keyPool.get("claude-v1", service);
|
||||
case "anthropic-chat":
|
||||
assignedKey = keyPool.get("claude-v1", service, needsMultimodal);
|
||||
break;
|
||||
case "openai-text":
|
||||
assignedKey = keyPool.get("gpt-3.5-turbo-instruct", service);
|
||||
|
||||
@@ -7,10 +7,15 @@ import { HPMRequestCallback } from "../index";
|
||||
export const stripHeaders: HPMRequestCallback = (proxyReq) => {
|
||||
proxyReq.setHeader("origin", "");
|
||||
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("forwarded");
|
||||
proxyReq.removeHeader("true-client-ip");
|
||||
proxyReq.removeHeader("x-forwarded-for");
|
||||
proxyReq.removeHeader("x-forwarded-host");
|
||||
proxyReq.removeHeader("x-forwarded-proto");
|
||||
proxyReq.removeHeader("x-real-ip");
|
||||
};
|
||||
|
||||
@@ -4,11 +4,12 @@ import { initializeSseStream } from "../../../shared/streaming";
|
||||
import { classifyErrorAndSend } from "../common";
|
||||
import {
|
||||
RequestPreprocessor,
|
||||
validateContextSize,
|
||||
countPromptTokens,
|
||||
languageFilter,
|
||||
setApiFormat,
|
||||
transformOutboundPayload,
|
||||
languageFilter,
|
||||
validateContextSize,
|
||||
validateVision,
|
||||
} from ".";
|
||||
|
||||
type RequestPreprocessorOptions = {
|
||||
@@ -50,6 +51,7 @@ export const createPreprocessorMiddleware = (
|
||||
languageFilter,
|
||||
...(afterTransform ?? []),
|
||||
validateContextSize,
|
||||
validateVision,
|
||||
];
|
||||
return async (...args) => executePreprocessors(preprocessors, args);
|
||||
};
|
||||
|
||||
@@ -6,7 +6,7 @@ import {
|
||||
GoogleAIChatMessage,
|
||||
MistralAIChatMessage,
|
||||
OpenAIChatMessage,
|
||||
} from "../../../../shared/api-support";
|
||||
} from "../../../../shared/api-schemas";
|
||||
|
||||
/**
|
||||
* 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": {
|
||||
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 });
|
||||
break;
|
||||
}
|
||||
|
||||
@@ -7,7 +7,7 @@ import {
|
||||
MistralAIChatMessage,
|
||||
OpenAIChatMessage,
|
||||
flattenAnthropicMessages,
|
||||
} from "../../../../shared/api-support";
|
||||
} from "../../../../shared/api-schemas";
|
||||
|
||||
const rejectedClients = new Map<string, number>();
|
||||
|
||||
|
||||
@@ -5,7 +5,7 @@ import { HttpRequest } from "@smithy/protocol-http";
|
||||
import {
|
||||
AnthropicV1TextSchema,
|
||||
AnthropicV1MessagesSchema,
|
||||
} from "../../../../shared/api-support";
|
||||
} from "../../../../shared/api-schemas";
|
||||
import { keyPool } from "../../../../shared/key-management";
|
||||
import { RequestPreprocessor } from "../index";
|
||||
|
||||
@@ -38,6 +38,7 @@ export const signAwsRequest: RequestPreprocessor = async (req) => {
|
||||
if (req.outboundApi === "anthropic-chat") {
|
||||
strippedParams = AnthropicV1MessagesSchema.pick({
|
||||
messages: true,
|
||||
system: true,
|
||||
max_tokens: true,
|
||||
stop_sequences: true,
|
||||
temperature: true,
|
||||
|
||||
@@ -1,14 +1,14 @@
|
||||
import {
|
||||
API_REQUEST_VALIDATORS,
|
||||
API_REQUEST_TRANSFORMERS,
|
||||
} from "../../../../shared/api-support";
|
||||
} from "../../../../shared/api-schemas";
|
||||
import { BadRequestError } from "../../../../shared/errors";
|
||||
import { fixMistralPrompt } from "../../../../shared/api-schemas/mistral-ai";
|
||||
import {
|
||||
isImageGenerationRequest,
|
||||
isTextGenerationRequest,
|
||||
} from "../../common";
|
||||
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. */
|
||||
export const transformOutboundPayload: RequestPreprocessor = async (req) => {
|
||||
|
||||
@@ -46,9 +46,18 @@ export const validateContextSize: RequestPreprocessor = async (req) => {
|
||||
}
|
||||
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;
|
||||
if (model.match(/gpt-3.5-turbo-16k/)) {
|
||||
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)?$/)) {
|
||||
modelMax = 131072;
|
||||
} 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)?$/)) {
|
||||
modelMax = 131072;
|
||||
} else if (model.match(/gpt-3.5-turbo/)) {
|
||||
modelMax = 4096;
|
||||
modelMax = 16384;
|
||||
} else if (model.match(/gpt-4-32k/)) {
|
||||
modelMax = 32768;
|
||||
} else if (model.match(/gpt-4/)) {
|
||||
@@ -75,7 +84,7 @@ export const validateContextSize: RequestPreprocessor = async (req) => {
|
||||
modelMax = GOOGLE_AI_MAX_CONTEXT;
|
||||
} else if (model.match(/^mistral-(tiny|small|medium)$/)) {
|
||||
modelMax = MISTRAL_AI_MAX_CONTENT;
|
||||
} else if (model.match(/^anthropic\.claude-3-sonnet/)) {
|
||||
} else if (model.match(/^anthropic\.claude-3/)) {
|
||||
modelMax = 200000;
|
||||
} else if (model.match(/^anthropic\.claude-v2:\d/)) {
|
||||
modelMax = 200000;
|
||||
|
||||
@@ -0,0 +1,43 @@
|
||||
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 (req.service === undefined) {
|
||||
throw new Error("Request service must be set before validateVision");
|
||||
}
|
||||
|
||||
if (req.user?.type === "special") return;
|
||||
if (config.allowedVisionServices.includes(req.service)) return;
|
||||
|
||||
// vision not allowed for req's service, block prompts with images
|
||||
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,34 @@ function getMessageContent({
|
||||
}
|
||||
```
|
||||
*/
|
||||
|
||||
const note = obj?.proxy_note || obj?.error?.message || "";
|
||||
const friendlyMessage = note ? `${message}\n\n***\n\n*${note}*` : message;
|
||||
const details = JSON.parse(JSON.stringify(obj ?? {}));
|
||||
let stack = "";
|
||||
if (details.stack) {
|
||||
stack = `\n\nInclude this trace when reporting an issue.\n\`\`\`\n${details.stack}\n\`\`\``;
|
||||
delete details.stack;
|
||||
const header = `### **${title}**`;
|
||||
const friendlyMessage = note ? `${message}\n\n----\n\n*${note}*` : message;
|
||||
|
||||
const serializedObj = obj
|
||||
? ["```", JSON.stringify(obj, null, 2), "```"].join("\n")
|
||||
: "";
|
||||
|
||||
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,
|
||||
"<!-- oai-proxy-error -->",
|
||||
].join("\n\n");
|
||||
}
|
||||
|
||||
type ErrorGeneratorOptions = {
|
||||
@@ -105,6 +122,11 @@ export function sendErrorToClient({
|
||||
const isStreaming =
|
||||
req.isStreaming || req.body.stream === true || req.body.stream === "true";
|
||||
|
||||
if (!res.headersSent) {
|
||||
res.setHeader("x-oai-proxy-error", options.title);
|
||||
res.setHeader("x-oai-proxy-error-status", options.statusCode || 500);
|
||||
}
|
||||
|
||||
if (isStreaming) {
|
||||
if (!res.headersSent) {
|
||||
initializeSseStream(res);
|
||||
|
||||
@@ -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 { StringDecoder } from "string_decoder";
|
||||
import { promisify } from "util";
|
||||
import type { logger } from "../../../logger";
|
||||
import { BadRequestError, RetryableError } from "../../../shared/errors";
|
||||
import { APIFormat, keyPool } from "../../../shared/key-management";
|
||||
import {
|
||||
copySseResponseHeaders,
|
||||
initializeSseStream,
|
||||
} from "../../../shared/streaming";
|
||||
import type { logger } from "../../../logger";
|
||||
import { enqueue } from "../../queue";
|
||||
import { decodeResponseBody, RawResponseBodyHandler, RetryableError } from ".";
|
||||
import { reenqueueRequest } from "../../queue";
|
||||
import type { RawResponseBodyHandler } from ".";
|
||||
import { handleBlockingResponse } from "./handle-blocking-response";
|
||||
import { buildSpoofedSSE, sendErrorToClient } from "./error-generator";
|
||||
import { getAwsEventStreamDecoder } from "./streaming/aws-event-stream-decoder";
|
||||
import { EventAggregator } from "./streaming/event-aggregator";
|
||||
import { SSEMessageTransformer } from "./streaming/sse-message-transformer";
|
||||
import { SSEStreamAdapter } from "./streaming/sse-stream-adapter";
|
||||
import { buildSpoofedSSE, sendErrorToClient } from "./error-generator";
|
||||
import { BadRequestError } from "../../../shared/errors";
|
||||
|
||||
const pipelineAsync = promisify(pipeline);
|
||||
|
||||
@@ -50,7 +51,7 @@ export const handleStreamedResponse: RawResponseBodyHandler = async (
|
||||
{ statusCode: proxyRes.statusCode, key: hash },
|
||||
`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.`);
|
||||
@@ -105,12 +106,7 @@ export const handleStreamedResponse: RawResponseBodyHandler = async (
|
||||
} catch (err) {
|
||||
if (err instanceof RetryableError) {
|
||||
keyPool.markRateLimited(req.key!);
|
||||
req.log.warn(
|
||||
{ key: req.key!.hash, retryCount: req.retryCount },
|
||||
`Re-enqueueing request due to retryable error during streaming response.`
|
||||
);
|
||||
req.retryCount++;
|
||||
await enqueue(req);
|
||||
await reenqueueRequest(req);
|
||||
} else if (err instanceof BadRequestError) {
|
||||
sendErrorToClient({
|
||||
req,
|
||||
@@ -138,7 +134,17 @@ export const handleStreamedResponse: RawResponseBodyHandler = async (
|
||||
res.write(`data: [DONE]\n\n`);
|
||||
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 */
|
||||
import { Request, Response } from "express";
|
||||
import * as http from "http";
|
||||
import util from "util";
|
||||
import zlib from "zlib";
|
||||
import { enqueue, trackWaitTime } from "../../queue";
|
||||
import { HttpError } from "../../../shared/errors";
|
||||
import { config } from "../../../config";
|
||||
import { HttpError, RetryableError } from "../../../shared/errors";
|
||||
import { keyPool } from "../../../shared/key-management";
|
||||
import { getOpenAIModelFamily } from "../../../shared/models";
|
||||
import { countTokens } from "../../../shared/tokenization";
|
||||
@@ -13,6 +11,7 @@ import {
|
||||
incrementTokenCount,
|
||||
} from "../../../shared/users/user-store";
|
||||
import { assertNever } from "../../../shared/utils";
|
||||
import { reenqueueRequest, trackWaitTime } from "../../queue";
|
||||
import { refundLastAttempt } from "../../rate-limit";
|
||||
import {
|
||||
getCompletionFromBody,
|
||||
@@ -20,39 +19,23 @@ import {
|
||||
isTextGenerationRequest,
|
||||
sendProxyError,
|
||||
} from "../common";
|
||||
import { handleBlockingResponse } from "./handle-blocking-response";
|
||||
import { handleStreamedResponse } from "./handle-streamed-response";
|
||||
import { logPrompt } from "./log-prompt";
|
||||
import { logEvent } from "./log-event";
|
||||
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
|
||||
* last argument to the rest of the middleware stack.
|
||||
* Either decodes or streams the entire response body and then resolves with it.
|
||||
* @returns The response body as a string or parsed JSON object depending on the
|
||||
* response's content-type.
|
||||
*/
|
||||
export type RawResponseBodyHandler = (
|
||||
proxyRes: http.IncomingMessage,
|
||||
req: Request,
|
||||
res: Response
|
||||
) => Promise<string | Record<string, any>>;
|
||||
|
||||
export type ProxyResHandlerWithBody = (
|
||||
proxyRes: http.IncomingMessage,
|
||||
req: Request,
|
||||
@@ -76,6 +59,10 @@ export type ProxyResMiddleware = ProxyResHandlerWithBody[];
|
||||
* 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
|
||||
* 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) => {
|
||||
return async (
|
||||
@@ -83,36 +70,35 @@ export const createOnProxyResHandler = (apiMiddleware: ProxyResMiddleware) => {
|
||||
req: Request,
|
||||
res: Response
|
||||
) => {
|
||||
const initialHandler = req.isStreaming
|
||||
const initialHandler: RawResponseBodyHandler = req.isStreaming
|
||||
? handleStreamedResponse
|
||||
: decodeResponseBody;
|
||||
|
||||
: handleBlockingResponse;
|
||||
let lastMiddleware = initialHandler.name;
|
||||
|
||||
try {
|
||||
const body = await initialHandler(proxyRes, req, res);
|
||||
|
||||
const middlewareStack: ProxyResMiddleware = [];
|
||||
|
||||
if (req.isStreaming) {
|
||||
// `handleStreamedResponse` writes to the response and ends it, so
|
||||
// we can only execute middleware that doesn't write to the response.
|
||||
// Handlers for streaming requests must never write to the response.
|
||||
middlewareStack.push(
|
||||
trackRateLimit,
|
||||
trackKeyRateLimit,
|
||||
countResponseTokens,
|
||||
incrementUsage,
|
||||
logPrompt
|
||||
logPrompt,
|
||||
logEvent
|
||||
);
|
||||
} else {
|
||||
middlewareStack.push(
|
||||
trackRateLimit,
|
||||
addProxyInfo,
|
||||
trackKeyRateLimit,
|
||||
injectProxyInfo,
|
||||
handleUpstreamErrors,
|
||||
countResponseTokens,
|
||||
incrementUsage,
|
||||
copyHttpHeaders,
|
||||
saveImage,
|
||||
logPrompt,
|
||||
logEvent,
|
||||
...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 = {
|
||||
error?: Record<string, any>;
|
||||
message?: string;
|
||||
@@ -242,15 +162,9 @@ const handleUpstreamErrors: ProxyResHandlerWithBody = async (
|
||||
) => {
|
||||
const statusCode = proxyRes.statusCode || 500;
|
||||
const statusMessage = proxyRes.statusMessage || "Internal Server Error";
|
||||
|
||||
if (statusCode < 400) {
|
||||
return;
|
||||
}
|
||||
|
||||
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.`
|
||||
: "There are no more keys available for this model.";
|
||||
|
||||
if (statusCode < 400) return;
|
||||
|
||||
try {
|
||||
assertJsonResponse(body);
|
||||
@@ -280,6 +194,9 @@ const handleUpstreamErrors: ProxyResHandlerWithBody = async (
|
||||
{ statusCode, type: errorType, errorPayload, key: req.key?.hash },
|
||||
`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;
|
||||
if (service === "aws") {
|
||||
@@ -289,8 +206,6 @@ const handleUpstreamErrors: ProxyResHandlerWithBody = async (
|
||||
}
|
||||
|
||||
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) {
|
||||
case "openai":
|
||||
case "google-ai":
|
||||
@@ -303,7 +218,7 @@ const handleUpstreamErrors: ProxyResHandlerWithBody = async (
|
||||
} else if (errorPayload.error?.code === "billing_hard_limit_reached") {
|
||||
// For some reason, some models return this 400 error instead of the
|
||||
// same 429 billing error that other models return.
|
||||
await handleOpenAIRateLimitError(req, tryAgainMessage, errorPayload);
|
||||
await handleOpenAIRateLimitError(req, errorPayload);
|
||||
} else {
|
||||
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) {
|
||||
// Key is invalid or was 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) {
|
||||
if (service === "anthropic") {
|
||||
keyPool.disable(req.key!, "revoked");
|
||||
errorPayload.proxy_note = `API key is invalid or revoked. ${tryAgainMessage}`;
|
||||
return;
|
||||
}
|
||||
switch (errorType) {
|
||||
case "UnrecognizedClientException":
|
||||
// Key is invalid.
|
||||
keyPool.disable(req.key!, "revoked");
|
||||
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."
|
||||
switch (service) {
|
||||
case "anthropic":
|
||||
if (
|
||||
errorType === "permission_error" &&
|
||||
errorPayload.error?.message?.toLowerCase().includes("multimodal")
|
||||
) {
|
||||
req.log.warn(
|
||||
{ key: req.key?.hash },
|
||||
"This Anthropic key does not support multimodal prompts."
|
||||
);
|
||||
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");
|
||||
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) {
|
||||
switch (service) {
|
||||
case "openai":
|
||||
await handleOpenAIRateLimitError(req, tryAgainMessage, errorPayload);
|
||||
await handleOpenAIRateLimitError(req, errorPayload);
|
||||
break;
|
||||
case "anthropic":
|
||||
await handleAnthropicRateLimitError(req, errorPayload);
|
||||
@@ -459,7 +389,7 @@ async function handleAnthropicBadRequestError(
|
||||
"Anthropic key has been disabled."
|
||||
);
|
||||
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;
|
||||
}
|
||||
|
||||
@@ -499,7 +429,6 @@ async function handleAwsRateLimitError(
|
||||
|
||||
async function handleOpenAIRateLimitError(
|
||||
req: Request,
|
||||
tryAgainMessage: string,
|
||||
errorPayload: ProxiedErrorPayload
|
||||
): Promise<Record<string, any>> {
|
||||
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
|
||||
// Billing quota exceeded (key is dead, disable it)
|
||||
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;
|
||||
case "access_terminated":
|
||||
// Account banned (key is dead, disable it)
|
||||
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;
|
||||
case "billing_not_active":
|
||||
// Key valid but account billing is delinquent
|
||||
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;
|
||||
case "requests":
|
||||
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);
|
||||
};
|
||||
|
||||
@@ -714,7 +643,7 @@ const copyHttpHeaders: ProxyResHandlerWithBody = async (
|
||||
* or transformed.
|
||||
* Only used for non-streaming requests.
|
||||
*/
|
||||
const addProxyInfo: ProxyResHandlerWithBody = async (
|
||||
const injectProxyInfo: ProxyResHandlerWithBody = async (
|
||||
_proxyRes,
|
||||
req,
|
||||
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 {
|
||||
AnthropicChatMessage,
|
||||
flattenAnthropicMessages,
|
||||
flattenAnthropicMessages, GoogleAIChatMessage,
|
||||
MistralAIChatMessage,
|
||||
OpenAIChatMessage,
|
||||
} from "../../../shared/api-support";
|
||||
import { APIFormat } from "../../../shared/key-management";
|
||||
} from "../../../shared/api-schemas";
|
||||
|
||||
/** If prompt logging is enabled, enqueues the prompt for logging. */
|
||||
export const logPrompt: ProxyResHandlerWithBody = async (
|
||||
@@ -36,7 +35,7 @@ export const logPrompt: ProxyResHandlerWithBody = async (
|
||||
if (!loggable) return;
|
||||
|
||||
const promptPayload = getPromptForRequest(req, responseBody);
|
||||
const promptFlattened = flattenMessages(promptPayload, req.outboundApi);
|
||||
const promptFlattened = flattenMessages(promptPayload);
|
||||
const response = getCompletionFromBody(req, responseBody);
|
||||
const model = getModelFromBody(req, responseBody);
|
||||
|
||||
@@ -63,7 +62,8 @@ const getPromptForRequest = (
|
||||
):
|
||||
| string
|
||||
| OpenAIChatMessage[]
|
||||
| AnthropicChatMessage[]
|
||||
| { contents: GoogleAIChatMessage[] }
|
||||
| { system: string; messages: AnthropicChatMessage[] }
|
||||
| MistralAIChatMessage[]
|
||||
| OaiImageResult => {
|
||||
// Since the prompt logger only runs after the request has been proxied, we
|
||||
@@ -72,8 +72,9 @@ const getPromptForRequest = (
|
||||
switch (req.outboundApi) {
|
||||
case "openai":
|
||||
case "mistral-ai":
|
||||
case "anthropic-chat":
|
||||
return req.body.messages;
|
||||
case "anthropic-chat":
|
||||
return { system: req.body.system, messages: req.body.messages };
|
||||
case "openai-text":
|
||||
return req.body.prompt;
|
||||
case "openai-image":
|
||||
@@ -87,7 +88,7 @@ const getPromptForRequest = (
|
||||
case "anthropic-text":
|
||||
return req.body.prompt;
|
||||
case "google-ai":
|
||||
return req.body.prompt.text;
|
||||
return { contents: req.body.contents };
|
||||
default:
|
||||
assertNever(req.outboundApi);
|
||||
}
|
||||
@@ -98,15 +99,26 @@ const flattenMessages = (
|
||||
| string
|
||||
| OaiImageResult
|
||||
| OpenAIChatMessage[]
|
||||
| AnthropicChatMessage[]
|
||||
| MistralAIChatMessage[],
|
||||
format: APIFormat
|
||||
| { contents: GoogleAIChatMessage[] }
|
||||
| { system: string; messages: AnthropicChatMessage[] }
|
||||
| MistralAIChatMessage[]
|
||||
): string => {
|
||||
if (typeof val === "string") {
|
||||
return val.trim();
|
||||
}
|
||||
if (format === "anthropic-chat") {
|
||||
return flattenAnthropicMessages(val as AnthropicChatMessage[]);
|
||||
if (isAnthropicChatPrompt(val)) {
|
||||
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)) {
|
||||
return val
|
||||
@@ -127,3 +139,24 @@ const flattenMessages = (
|
||||
}
|
||||
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);
|
||||
}
|
||||
}
|
||||
|
||||
hasEvents() {
|
||||
return this.events.length > 0;
|
||||
}
|
||||
}
|
||||
|
||||
function eventIsOpenAIEvent(
|
||||
|
||||
@@ -2,9 +2,8 @@ import pino from "pino";
|
||||
import { Transform, TransformOptions } from "stream";
|
||||
import { Message } from "@smithy/eventstream-codec";
|
||||
import { APIFormat } from "../../../../shared/key-management";
|
||||
import { RetryableError } from "../index";
|
||||
import { buildSpoofedSSE } from "../error-generator";
|
||||
import { BadRequestError } from "../../../../shared/errors";
|
||||
import { BadRequestError, RetryableError } from "../../../../shared/errors";
|
||||
|
||||
type SSEStreamAdapterOptions = TransformOptions & {
|
||||
contentType?: string;
|
||||
@@ -117,7 +116,7 @@ export class SSEStreamAdapter extends Transform {
|
||||
try {
|
||||
const hasParts = candidates[0].content?.parts?.length > 0;
|
||||
if (hasParts) {
|
||||
return `data: ${JSON.stringify(data)}`;
|
||||
return `data: ${JSON.stringify(data.value ?? data)}\n`;
|
||||
} else {
|
||||
this.log.error({ event: data }, "Received bad Google AI event");
|
||||
return `data: ${buildSpoofedSSE({
|
||||
|
||||
@@ -70,7 +70,7 @@ export function generateModelList(models = KNOWN_MISTRAL_AI_MODELS) {
|
||||
}
|
||||
|
||||
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);
|
||||
}
|
||||
const result = generateModelList();
|
||||
|
||||
+8
-4
@@ -28,10 +28,14 @@ import {
|
||||
|
||||
// https://platform.openai.com/docs/models/overview
|
||||
export const KNOWN_OPENAI_MODELS = [
|
||||
"gpt-4-turbo-preview",
|
||||
"gpt-4-0125-preview",
|
||||
"gpt-4-1106-preview",
|
||||
"gpt-4-vision-preview",
|
||||
"gpt-4o",
|
||||
"gpt-4o-2024-05-13",
|
||||
"gpt-4-turbo", // alias for latest gpt4-turbo stable
|
||||
"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-0613",
|
||||
"gpt-4-0314", // EOL 2024-06-13
|
||||
|
||||
+11
-2
@@ -12,7 +12,7 @@
|
||||
*/
|
||||
|
||||
import crypto from "crypto";
|
||||
import type { Handler, Request } from "express";
|
||||
import { Handler, Request } from "express";
|
||||
import { BadRequestError, TooManyRequestsError } from "../shared/errors";
|
||||
import { keyPool } from "../shared/key-management";
|
||||
import {
|
||||
@@ -67,7 +67,7 @@ const sharesIdentifierWith = (incoming: Request) => (queued: Request) =>
|
||||
|
||||
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;
|
||||
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[] {
|
||||
return queue
|
||||
.filter((req) => getModelFamilyForRequest(req) === partition)
|
||||
|
||||
+36
-1
@@ -8,6 +8,7 @@ import pinoHttp from "pino-http";
|
||||
import os from "os";
|
||||
import childProcess from "child_process";
|
||||
import { logger } from "./logger";
|
||||
import { createBlacklistMiddleware } from "./shared/cidr";
|
||||
import { setupAssetsDir } from "./shared/file-storage/setup-assets-dir";
|
||||
import { keyPool } from "./shared/key-management";
|
||||
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 { checkOrigin } from "./proxy/check-origin";
|
||||
import { sendErrorToClient } from "./proxy/middleware/response/error-generator";
|
||||
import { initializeDatabase, getDatabase } from "./shared/database";
|
||||
|
||||
const PORT = config.port;
|
||||
const BIND_ADDRESS = config.bindAddress;
|
||||
@@ -31,13 +33,19 @@ app.use(
|
||||
pinoHttp({
|
||||
quietReqLogger: true,
|
||||
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: {
|
||||
paths: [
|
||||
"req.headers.cookie",
|
||||
'res.headers["set-cookie"]',
|
||||
"req.headers.authorization",
|
||||
'req.headers["x-api-key"]',
|
||||
'req.headers["api-key"]',
|
||||
// Don't log the prompt text on transform errors
|
||||
"body.messages",
|
||||
"body.prompt",
|
||||
@@ -62,9 +70,20 @@ app.set("views", [
|
||||
]);
|
||||
|
||||
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.use(cors());
|
||||
|
||||
const blacklist = createBlacklistMiddleware("IP_BLACKLIST", config.ipBlacklist);
|
||||
app.use(blacklist);
|
||||
|
||||
app.use(checkOrigin);
|
||||
|
||||
app.use("/admin", adminRouter);
|
||||
@@ -125,6 +144,8 @@ async function start() {
|
||||
await logQueue.start();
|
||||
}
|
||||
|
||||
await initializeDatabase();
|
||||
|
||||
logger.info("Starting request queue...");
|
||||
startRequestQueue();
|
||||
|
||||
@@ -146,6 +167,20 @@ 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("SIGINT", cleanup);
|
||||
|
||||
function registerUncaughtExceptionHandler() {
|
||||
process.on("uncaughtException", (err: any) => {
|
||||
logger.error(
|
||||
|
||||
+26
-22
@@ -80,6 +80,7 @@ type OpenAIInfo = BaseFamilyInfo & {
|
||||
overQuotaKeys?: number;
|
||||
};
|
||||
type AnthropicInfo = BaseFamilyInfo & {
|
||||
trialKeys?: number;
|
||||
prefilledKeys?: number;
|
||||
overQuotaKeys?: number;
|
||||
};
|
||||
@@ -140,8 +141,6 @@ const SERVICE_ENDPOINTS: { [s in LLMService]: Record<string, string> } = {
|
||||
},
|
||||
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": `%BASE%/google-ai`,
|
||||
@@ -151,7 +150,6 @@ const SERVICE_ENDPOINTS: { [s in LLMService]: Record<string, string> } = {
|
||||
},
|
||||
aws: {
|
||||
aws: `%BASE%/aws/claude`,
|
||||
"aws-sonnet (⚠️Temporary: for AWS Claude 3 Sonnet)": `%BASE%/aws/claude/sonnet`,
|
||||
},
|
||||
azure: {
|
||||
azure: `%BASE%/azure/openai`,
|
||||
@@ -211,7 +209,8 @@ export function buildInfo(baseUrl: string, forAdmin = false): ServiceInfo {
|
||||
}
|
||||
|
||||
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;
|
||||
for (const service of LLM_SERVICES) {
|
||||
@@ -349,6 +348,7 @@ function addKeyToAggregates(k: KeyPoolKey) {
|
||||
sumTokens += tokens;
|
||||
sumCost += getTokenCostUsd(f, 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}__active`, k.isDisabled ? 0 : 1);
|
||||
increment(modelStats, `${f}__overQuota`, k.isOverQuota ? 1 : 0);
|
||||
@@ -385,21 +385,22 @@ function addKeyToAggregates(k: KeyPoolKey) {
|
||||
}
|
||||
case "aws": {
|
||||
if (!keyIsAwsKey(k)) throw new Error("Invalid key type");
|
||||
const family = "aws-claude";
|
||||
sumTokens += k["aws-claudeTokens"];
|
||||
sumCost += getTokenCostUsd(family, k["aws-claudeTokens"]);
|
||||
increment(modelStats, `${family}__active`, k.isDisabled ? 0 : 1);
|
||||
increment(modelStats, `${family}__revoked`, k.isRevoked ? 1 : 0);
|
||||
increment(modelStats, `${family}__tokens`, k["aws-claudeTokens"]);
|
||||
increment(modelStats, `${family}__awsSonnet`, k.sonnetEnabled ? 1 : 0);
|
||||
increment(modelStats, `${family}__awsHaiku`, k.haikuEnabled ? 1 : 0);
|
||||
k.modelFamilies.forEach((f) => {
|
||||
const tokens = k[`${f}Tokens`];
|
||||
sumTokens += tokens;
|
||||
sumCost += getTokenCostUsd(f, tokens);
|
||||
increment(modelStats, `${f}__tokens`, tokens);
|
||||
increment(modelStats, `${f}__revoked`, k.isRevoked ? 1 : 0);
|
||||
increment(modelStats, `${f}__active`, k.isDisabled ? 0 : 1);
|
||||
});
|
||||
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
|
||||
// logging status is unknown.
|
||||
const countAsLogged =
|
||||
k.lastChecked && !k.isDisabled && k.awsLoggingStatus !== "disabled";
|
||||
increment(modelStats, `${family}__awsLogged`, countAsLogged ? 1 : 0);
|
||||
|
||||
k.lastChecked && !k.isDisabled && k.awsLoggingStatus === "enabled";
|
||||
increment(modelStats, `aws-claude__awsLogged`, countAsLogged ? 1 : 0);
|
||||
break;
|
||||
}
|
||||
default:
|
||||
@@ -437,16 +438,19 @@ function getInfoForFamily(family: ModelFamily): BaseFamilyInfo {
|
||||
break;
|
||||
case "anthropic":
|
||||
info.overQuotaKeys = modelStats.get(`${family}__overQuota`) || 0;
|
||||
info.trialKeys = modelStats.get(`${family}__trial`) || 0;
|
||||
info.prefilledKeys = modelStats.get(`${family}__pozzed`) || 0;
|
||||
break;
|
||||
case "aws":
|
||||
info.sonnetKeys = modelStats.get(`${family}__awsSonnet`) || 0;
|
||||
info.haikuKeys = modelStats.get(`${family}__awsHaiku`) || 0;
|
||||
const logged = modelStats.get(`${family}__awsLogged`) || 0;
|
||||
if (logged > 0) {
|
||||
info.privacy = config.allowAwsLogging
|
||||
? `${logged} active keys are potentially logged.`
|
||||
: `${logged} active keys are potentially logged and can't be used. Set ALLOW_AWS_LOGGING=true to override.`;
|
||||
if (family === "aws-claude") {
|
||||
info.sonnetKeys = modelStats.get(`${family}__awsSonnet`) || 0;
|
||||
info.haikuKeys = modelStats.get(`${family}__awsHaiku`) || 0;
|
||||
const logged = modelStats.get(`${family}__awsLogged`) || 0;
|
||||
if (logged > 0) {
|
||||
info.privacy = config.allowAwsLogging
|
||||
? `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;
|
||||
}
|
||||
|
||||
+177
-19
@@ -1,23 +1,98 @@
|
||||
import { AnthropicChatMessage, AnthropicV1MessagesSchema } from "./schema";
|
||||
import { AnthropicV1TextSchema, APIRequestTransformer, OpenAIChatMessage } from "../../index";
|
||||
import { BadRequestError } from "../../../errors";
|
||||
import { z } from "zod";
|
||||
import { config } from "../../config";
|
||||
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;
|
||||
|
||||
/**
|
||||
* 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;
|
||||
};
|
||||
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();
|
||||
|
||||
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
|
||||
> = async (req) => {
|
||||
const { body } = req;
|
||||
@@ -44,7 +119,8 @@ export const transformOpenAIToAnthropicChat: APIRequestTransformer<
|
||||
stream: rest.stream,
|
||||
temperature: rest.temperature,
|
||||
top_p: rest.top_p,
|
||||
stop_sequences: typeof rest.stop === "string" ? [rest.stop] : rest.stop,
|
||||
stop_sequences:
|
||||
typeof rest.stop === "string" ? [rest.stop] : rest.stop || undefined,
|
||||
...(rest.user ? { metadata: { user_id: rest.user } } : {}),
|
||||
// Anthropic supports top_k, but OpenAI does not
|
||||
// OpenAI supports frequency_penalty, presence_penalty, logit_bias, n, seed,
|
||||
@@ -52,11 +128,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
|
||||
* by splitting the flat text into messages.
|
||||
*/
|
||||
export const transformAnthropicTextToAnthropicChat: APIRequestTransformer<
|
||||
export const transformAnthropicTextToAnthropicChat: APIFormatTransformer<
|
||||
typeof AnthropicV1MessagesSchema
|
||||
> = async (req) => {
|
||||
const { body } = req;
|
||||
@@ -138,6 +256,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[]): {
|
||||
messages: AnthropicChatMessage[];
|
||||
system: string;
|
||||
@@ -288,3 +439,10 @@ function convertOpenAIContent(
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
export function containsImageContent(messages: AnthropicChatMessage[]) {
|
||||
return messages.some(
|
||||
({ content }) =>
|
||||
typeof content !== "string" && content.some((c) => c.type === "image")
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,181 @@
|
||||
import { z } from "zod";
|
||||
import {
|
||||
OPENAI_OUTPUT_MAX,
|
||||
OpenAIV1ChatCompletionSchema,
|
||||
flattenOpenAIMessageContent,
|
||||
} from "./openai";
|
||||
import { APIFormatTransformer } from ".";
|
||||
|
||||
// https://docs.cohere.com/reference/chat
|
||||
export const CohereV1ChatSchema = z
|
||||
.object({
|
||||
message: z.string(),
|
||||
model: z.string().default("command-r-plus"),
|
||||
stream: z.boolean().default(false).optional(),
|
||||
preamble: z.string().optional(),
|
||||
chat_history: z
|
||||
.array(
|
||||
// Either a message from a chat participant, or a past tool call
|
||||
z.union([
|
||||
z.object({
|
||||
role: z.enum(["CHATBOT", "SYSTEM", "USER"]),
|
||||
message: z.string(),
|
||||
tool_calls: z
|
||||
.array(z.object({ name: z.string(), parameters: z.any() }))
|
||||
.optional(),
|
||||
}),
|
||||
z.object({
|
||||
role: z.enum(["TOOL"]),
|
||||
tool_results: z.array(
|
||||
z.object({
|
||||
call: z.object({ name: z.string(), parameters: z.any() }),
|
||||
outputs: z.array(z.any()),
|
||||
})
|
||||
),
|
||||
}),
|
||||
])
|
||||
)
|
||||
.optional(),
|
||||
// Don't allow conversation_id as it causes calls to be stateful and we don't
|
||||
// offer guarantees about which key a user's request will be routed to.
|
||||
conversation_id: z.literal(undefined).optional(),
|
||||
prompt_truncation: z
|
||||
.enum(["AUTO", "AUTO_PRESERVE_ORDER", "OFF"])
|
||||
.optional(),
|
||||
/*
|
||||
Supporting RAG is complex because documents can be arbitrary size and have
|
||||
to have embeddings generated, which incurs a cost that is not trivial to
|
||||
estimate. We don't support it for now.
|
||||
connectors: z
|
||||
.array(
|
||||
z.object({
|
||||
id: z.string(),
|
||||
user_access_token: z.string().optional(),
|
||||
continue_on_failure: z.boolean().default(false).optional(),
|
||||
options: z.any().optional(),
|
||||
})
|
||||
)
|
||||
.optional(),
|
||||
search_queries_only: z.boolean().default(false).optional(),
|
||||
documents: z
|
||||
.array(
|
||||
z.object({
|
||||
id: z.string().optional(),
|
||||
title: z.string().optional(),
|
||||
text: z.string(),
|
||||
_excludes: z.array(z.string()).optional(),
|
||||
})
|
||||
)
|
||||
.optional(),
|
||||
citation_quality: z.enum(["accurate", "fast"]).optional(),
|
||||
*/
|
||||
temperature: z.number().default(0.3).optional(),
|
||||
max_tokens: z
|
||||
.number()
|
||||
.int()
|
||||
.nullish()
|
||||
.default(Math.min(OPENAI_OUTPUT_MAX, 4096))
|
||||
.transform((v) => Math.min(v ?? OPENAI_OUTPUT_MAX, OPENAI_OUTPUT_MAX)),
|
||||
max_input_tokens: z.number().int().optional(),
|
||||
k: z.number().int().min(0).max(500).default(0).optional(),
|
||||
p: z.number().min(0.01).max(0.99).default(0.75).optional(),
|
||||
seed: z.number().int().optional(),
|
||||
stop_sequences: z.array(z.string()).max(5).optional(),
|
||||
frequency_penalty: z.number().min(0).max(1).default(0).optional(),
|
||||
presence_penalty: z.number().min(0).max(1).default(0).optional(),
|
||||
tools: z
|
||||
.array(
|
||||
z.object({
|
||||
name: z.string(),
|
||||
description: z.string(),
|
||||
parameter_definitions: z.record(
|
||||
z.object({
|
||||
description: z.string().optional(),
|
||||
type: z.string(),
|
||||
required: z.boolean().optional().default(false),
|
||||
})
|
||||
),
|
||||
})
|
||||
)
|
||||
.optional(),
|
||||
tool_results: z
|
||||
.array(
|
||||
z.object({
|
||||
call: z.object({
|
||||
name: z.string(),
|
||||
parameters: z.record(z.any()),
|
||||
}),
|
||||
outputs: z.array(z.record(z.any())),
|
||||
})
|
||||
)
|
||||
.optional(),
|
||||
// We always force single step to avoid stateful calls or expensive multi-step
|
||||
// generations when tools are involved.
|
||||
force_single_step: z.literal(true).default(true).optional(),
|
||||
})
|
||||
.strip();
|
||||
export type CohereChatMessage = NonNullable<
|
||||
z.infer<typeof CohereV1ChatSchema>["chat_history"]
|
||||
>[number];
|
||||
|
||||
export function flattenCohereMessageContent(
|
||||
message: CohereChatMessage
|
||||
): string {
|
||||
return message.role === "TOOL"
|
||||
? message.tool_results.map((r) => r.outputs[0].text).join("\n")
|
||||
: message.message;
|
||||
}
|
||||
|
||||
export const transformOpenAIToCohere: APIFormatTransformer<
|
||||
typeof CohereV1ChatSchema
|
||||
> = async (req) => {
|
||||
const { body } = req;
|
||||
const result = OpenAIV1ChatCompletionSchema.safeParse({
|
||||
...body,
|
||||
model: "gpt-3.5-turbo",
|
||||
});
|
||||
if (!result.success) {
|
||||
req.log.warn(
|
||||
{ issues: result.error.issues, body },
|
||||
"Invalid OpenAI-to-Cohere request"
|
||||
);
|
||||
throw result.error;
|
||||
}
|
||||
|
||||
const { messages, ...rest } = result.data;
|
||||
// Final OAI message becomes the `message` field in Cohere
|
||||
const message = messages[messages.length - 1];
|
||||
// If the first message has system role, use it as preamble.
|
||||
const hasSystemPreamble = messages[0]?.role === "system";
|
||||
const preamble = hasSystemPreamble
|
||||
? flattenOpenAIMessageContent(messages[0].content)
|
||||
: undefined;
|
||||
|
||||
const chatHistory = messages.slice(0, -1).map((m) => {
|
||||
const role: Exclude<CohereChatMessage["role"], "TOOL"> =
|
||||
m.role === "assistant"
|
||||
? "CHATBOT"
|
||||
: m.role === "system"
|
||||
? "SYSTEM"
|
||||
: "USER";
|
||||
const content = flattenOpenAIMessageContent(m.content);
|
||||
const message = m.name ? `${m.name}: ${content}` : content;
|
||||
return { role, message };
|
||||
});
|
||||
|
||||
return {
|
||||
model: rest.model,
|
||||
preamble,
|
||||
chat_history: chatHistory,
|
||||
message: flattenOpenAIMessageContent(message.content),
|
||||
stop_sequences:
|
||||
typeof rest.stop === "string" ? [rest.stop] : rest.stop ?? undefined,
|
||||
max_tokens: rest.max_tokens,
|
||||
temperature: rest.temperature,
|
||||
p: rest.top_p,
|
||||
frequency_penalty: rest.frequency_penalty,
|
||||
presence_penalty: rest.presence_penalty,
|
||||
seed: rest.seed,
|
||||
stream: rest.stream,
|
||||
};
|
||||
};
|
||||
+38
-6
@@ -1,11 +1,43 @@
|
||||
import { APIRequestTransformer, GoogleAIChatMessage } from "../../index";
|
||||
import { GoogleAIV1GenerateContentSchema } from "./schema";
|
||||
import { z } from "zod";
|
||||
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: APIRequestTransformer<
|
||||
export const transformOpenAIToGoogleAI: APIFormatTransformer<
|
||||
typeof GoogleAIV1GenerateContentSchema
|
||||
> = async (req) => {
|
||||
const { body } = req;
|
||||
@@ -0,0 +1,82 @@
|
||||
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";
|
||||
import { CohereV1ChatSchema, transformOpenAIToCohere } from "./cohere";
|
||||
|
||||
export { OpenAIChatMessage } from "./openai";
|
||||
export {
|
||||
AnthropicChatMessage,
|
||||
AnthropicV1TextSchema,
|
||||
AnthropicV1MessagesSchema,
|
||||
flattenAnthropicMessages,
|
||||
} from "./anthropic";
|
||||
export { GoogleAIChatMessage } from "./google-ai";
|
||||
export { MistralAIChatMessage } from "./mistral-ai";
|
||||
|
||||
/** Represents a pair of API formats that can be transformed between. */
|
||||
type APIPair = `${APIFormat}->${APIFormat}`;
|
||||
/** Represents a map of API format pairs to transformer functions. */
|
||||
type TransformerMap = {
|
||||
[key in APIPair]?: APIFormatTransformer<any>;
|
||||
};
|
||||
|
||||
/**
|
||||
* Represents a transformer function that takes a Request and returns a Promise
|
||||
* resolving to a value of the specified Zod schema type.
|
||||
*
|
||||
* @template Z The Zod schema type to transform the request into (from api-schemas).
|
||||
* @param req The incoming Request to transform.
|
||||
* @returns A Promise resolving to the transformed request body.
|
||||
*/
|
||||
export type APIFormatTransformer<Z extends z.ZodType<any, any>> = (
|
||||
req: Request
|
||||
) => Promise<z.infer<Z>>;
|
||||
|
||||
/**
|
||||
* Specifies possible translations between API formats and the corresponding
|
||||
* transformer functions to apply them.
|
||||
*/
|
||||
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,
|
||||
"openai->cohere-chat": transformOpenAIToCohere,
|
||||
};
|
||||
|
||||
/**
|
||||
* Specifies the schema for each API format to validate incoming requests.
|
||||
*/
|
||||
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,
|
||||
"cohere-chat": CohereV1ChatSchema,
|
||||
};
|
||||
+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(
|
||||
messages: MistralAIChatMessage[]
|
||||
+22
-5
@@ -1,9 +1,26 @@
|
||||
/* Takes the last chat message and uses it verbatim as the image prompt. */
|
||||
import { APIRequestTransformer } from "../../index";
|
||||
import { OpenAIV1ImagesGenerationSchema } from "./schema";
|
||||
import { OpenAIV1ChatCompletionSchema } from "../openai/schema";
|
||||
import { z } from "zod";
|
||||
import { OpenAIV1ChatCompletionSchema } from "./openai";
|
||||
import { APIFormatTransformer } from "./index";
|
||||
|
||||
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
|
||||
> = async (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 { config } from "../../../../config";
|
||||
import { config } from "../../config";
|
||||
|
||||
export const OPENAI_OUTPUT_MAX = config.maxOutputTokensOpenAI;
|
||||
|
||||
// https://platform.openai.com/docs/api-reference/chat/create
|
||||
const OpenAIV1ChatContentArraySchema = z.array(
|
||||
z.union([
|
||||
@@ -46,7 +47,7 @@ export const OpenAIV1ChatCompletionSchema = z
|
||||
stream: z.boolean().optional().default(false),
|
||||
stop: z
|
||||
.union([z.string().max(500), z.array(z.string().max(500))])
|
||||
.optional(),
|
||||
.nullish(),
|
||||
max_tokens: z.coerce
|
||||
.number()
|
||||
.int()
|
||||
@@ -80,3 +81,63 @@ export const OpenAIV1ChatCompletionSchema = z
|
||||
export type OpenAIChatMessage = z.infer<
|
||||
typeof OpenAIV1ChatCompletionSchema
|
||||
>["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;
|
||||
}
|
||||
@@ -0,0 +1,89 @@
|
||||
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);
|
||||
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/event";
|
||||
@@ -0,0 +1,61 @@
|
||||
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;`
|
||||
);
|
||||
},
|
||||
},
|
||||
] 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),
|
||||
};
|
||||
}
|
||||
@@ -34,3 +34,10 @@ export class TooManyRequestsError extends HttpError {
|
||||
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 type { AnthropicKey, AnthropicKeyProvider } from "./provider";
|
||||
|
||||
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 TEST_MODEL = "claude-3-sonnet-20240229";
|
||||
const SYSTEM = "Obey all instructions from the user.";
|
||||
@@ -52,10 +52,13 @@ export class AnthropicKeyChecker extends KeyCheckerBase<AnthropicKey> {
|
||||
}
|
||||
|
||||
protected async testKeyOrFail(key: AnthropicKey) {
|
||||
const [{ pozzed }] = await Promise.all([this.testLiveness(key)]);
|
||||
const updates = { isPozzed: pozzed };
|
||||
const [{ pozzed, tier }] = await Promise.all([this.testLiveness(key)]);
|
||||
const updates = { isPozzed: pozzed, tier };
|
||||
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) {
|
||||
@@ -124,7 +127,9 @@ export class AnthropicKeyChecker extends KeyCheckerBase<AnthropicKey> {
|
||||
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 = {
|
||||
model: TEST_MODEL,
|
||||
max_tokens: 40,
|
||||
@@ -133,24 +138,27 @@ export class AnthropicKeyChecker extends KeyCheckerBase<AnthropicKey> {
|
||||
system: SYSTEM,
|
||||
messages: DETECTION_PROMPT,
|
||||
};
|
||||
const { data } = await axios.post<MessageResponse>(
|
||||
const { data, headers } = await axios.post<MessageResponse>(
|
||||
POST_MESSAGES_URL,
|
||||
payload,
|
||||
{ headers: AnthropicKeyChecker.getHeaders(key) }
|
||||
{ headers: AnthropicKeyChecker.getRequestHeaders(key) }
|
||||
);
|
||||
this.log.debug({ data }, "Response from Anthropic");
|
||||
|
||||
const tier = AnthropicKeyChecker.detectTier(headers);
|
||||
|
||||
const completion = data.content.map((part) => part.text).join("");
|
||||
if (POZZ_PROMPT.some((re) => re.test(completion))) {
|
||||
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))) {
|
||||
this.log.info(
|
||||
{ key: key.hash, response: completion },
|
||||
"Key has copyright CYA prompt."
|
||||
);
|
||||
return { pozzed: true };
|
||||
return { pozzed: true, tier };
|
||||
} else {
|
||||
return { pozzed: false };
|
||||
return { pozzed: false, tier };
|
||||
}
|
||||
}
|
||||
|
||||
@@ -161,7 +169,19 @@ export class AnthropicKeyChecker extends KeyCheckerBase<AnthropicKey> {
|
||||
return data?.error?.type;
|
||||
}
|
||||
|
||||
static getHeaders(key: AnthropicKey) {
|
||||
static getRequestHeaders(key: AnthropicKey) {
|
||||
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 { AnthropicModelFamily, getClaudeModelFamily } from "../../models";
|
||||
import { AnthropicKeyChecker } from "./checker";
|
||||
import { HttpError, PaymentRequiredError } from "../../errors";
|
||||
import { PaymentRequiredError } from "../../errors";
|
||||
|
||||
export type AnthropicKeyUpdate = Omit<
|
||||
Partial<AnthropicKey>,
|
||||
@@ -45,13 +45,40 @@ export interface AnthropicKey extends Key, AnthropicKeyUsage {
|
||||
*/
|
||||
isPozzed: 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
|
||||
* while we wait for other concurrent requests to finish.
|
||||
* Selection priority for Anthropic keys. Aims to maximize throughput by
|
||||
* 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
|
||||
* 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,
|
||||
isRevoked: false,
|
||||
isPozzed: false,
|
||||
allowsMultimodality: true,
|
||||
promptCount: 0,
|
||||
lastUsed: 0,
|
||||
rateLimitedAt: 0,
|
||||
@@ -98,6 +126,7 @@ export class AnthropicKeyProvider implements KeyProvider<AnthropicKey> {
|
||||
lastChecked: 0,
|
||||
claudeTokens: 0,
|
||||
"claude-opusTokens": 0,
|
||||
tier: "unknown",
|
||||
};
|
||||
this.keys.push(newKey);
|
||||
}
|
||||
@@ -115,33 +144,43 @@ export class AnthropicKeyProvider implements KeyProvider<AnthropicKey> {
|
||||
return this.keys.map((k) => Object.freeze({ ...k, key: undefined }));
|
||||
}
|
||||
|
||||
public get(_model: string) {
|
||||
// Currently, all Anthropic keys have access to all models. This will almost
|
||||
// certainly change when they move out of beta later this year.
|
||||
const availableKeys = this.keys.filter((k) => !k.isDisabled);
|
||||
public get(rawModel: string) {
|
||||
this.log.debug({ model: rawModel }, "Selecting key");
|
||||
const needsMultimodal = rawModel.endsWith("-multimodal");
|
||||
|
||||
const availableKeys = this.keys.filter((k) => {
|
||||
return !k.isDisabled && (!needsMultimodal || k.allowsMultimodality);
|
||||
});
|
||||
|
||||
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:
|
||||
// 1. Keys which are not rate limited
|
||||
// a. If all keys were rate limited recently, select the least-recently
|
||||
// rate limited key.
|
||||
// 2. Keys which are not pozzed
|
||||
// 3. Keys which have not been used in the longest time
|
||||
// 1. Keys which are not rate limit locked
|
||||
// 2. Keys with the highest tier
|
||||
// 3. Keys which are not pozzed
|
||||
// 4. Keys which have not been used in the longest time
|
||||
|
||||
const now = Date.now();
|
||||
|
||||
const keysByPriority = availableKeys.sort((a, b) => {
|
||||
const aRateLimited = now - a.rateLimitedAt < RATE_LIMIT_LOCKOUT;
|
||||
const bRateLimited = now - b.rateLimitedAt < RATE_LIMIT_LOCKOUT;
|
||||
const aLockoutPeriod = getKeyLockout(a);
|
||||
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 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;
|
||||
@@ -207,7 +246,7 @@ export class AnthropicKeyProvider implements KeyProvider<AnthropicKey> {
|
||||
const key = this.keys.find((k) => k.hash === keyHash)!;
|
||||
const now = Date.now();
|
||||
key.rateLimitedAt = now;
|
||||
key.rateLimitedUntil = now + RATE_LIMIT_LOCKOUT;
|
||||
key.rateLimitedUntil = now + SCALE_RATE_LIMIT_LOCKOUT;
|
||||
}
|
||||
|
||||
public recheck() {
|
||||
@@ -239,3 +278,9 @@ export class AnthropicKeyProvider implements KeyProvider<AnthropicKey> {
|
||||
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 { KeyCheckerBase } from "../key-checker-base";
|
||||
import type { AwsBedrockKey, AwsBedrockKeyProvider } from "./provider";
|
||||
import { AwsBedrockModelFamily } from "../../models";
|
||||
import { config } from "../../../config";
|
||||
|
||||
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 =
|
||||
process.env.AMZ_HOST || "bedrock-runtime.%REGION%.amazonaws.com";
|
||||
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-3-sonnet-20240229-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));
|
||||
|
||||
const [_logging, _claudeV2, sonnet, haiku] = await Promise.all(checks);
|
||||
const [_logging, claudeV2, sonnet, haiku, opus] = await Promise.all(checks);
|
||||
|
||||
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(
|
||||
{ key: key.hash, sonnet, haiku, logged: key.awsLoggingStatus },
|
||||
{
|
||||
key: key.hash,
|
||||
sonnet,
|
||||
haiku,
|
||||
families: key.modelFamilies,
|
||||
logged: key.awsLoggingStatus,
|
||||
},
|
||||
"Checked key."
|
||||
);
|
||||
}
|
||||
@@ -175,13 +200,14 @@ export class AwsKeyChecker extends KeyCheckerBase<AwsBedrockKey> {
|
||||
const correctErrorType = errorType === "ValidationException";
|
||||
const correctErrorMessage = errorMessage?.match(/max_tokens/);
|
||||
if (!correctErrorType || !correctErrorMessage) {
|
||||
throw new AxiosError(
|
||||
`Unexpected error when invoking model ${model}: ${errorMessage}`,
|
||||
"AWS_ERROR",
|
||||
response.config,
|
||||
response.request,
|
||||
response
|
||||
);
|
||||
return false;
|
||||
// throw new AxiosError(
|
||||
// `Unexpected error when invoking model ${model}: ${errorMessage}`,
|
||||
// "AWS_ERROR",
|
||||
// response.config,
|
||||
// response.request,
|
||||
// response
|
||||
// );
|
||||
}
|
||||
|
||||
this.log.debug(
|
||||
@@ -192,16 +218,22 @@ export class AwsKeyChecker extends KeyCheckerBase<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 config: AxiosRequestConfig = {
|
||||
const req: AxiosRequestConfig = {
|
||||
method: "GET",
|
||||
url: GET_INVOCATION_LOGGING_CONFIG_URL(creds.region),
|
||||
headers: { accept: "application/json" },
|
||||
validateStatus: () => true,
|
||||
};
|
||||
await AwsKeyChecker.signRequestForAws(config, key);
|
||||
await AwsKeyChecker.signRequestForAws(req, key);
|
||||
const { data, status, headers } =
|
||||
await axios.request<GetLoggingConfigResponse>(config);
|
||||
await axios.request<GetLoggingConfigResponse>(req);
|
||||
|
||||
let result: AwsBedrockKey["awsLoggingStatus"] = "unknown";
|
||||
|
||||
|
||||
@@ -2,7 +2,7 @@ import crypto from "crypto";
|
||||
import { Key, KeyProvider } from "..";
|
||||
import { config } from "../../../config";
|
||||
import { logger } from "../../../logger";
|
||||
import type { AwsBedrockModelFamily } from "../../models";
|
||||
import { AwsBedrockModelFamily, getAwsBedrockModelFamily } from "../../models";
|
||||
import { AwsKeyChecker } from "./checker";
|
||||
import { PaymentRequiredError } from "../../errors";
|
||||
|
||||
@@ -78,6 +78,7 @@ export class AwsBedrockKeyProvider implements KeyProvider<AwsBedrockKey> {
|
||||
sonnetEnabled: true,
|
||||
haikuEnabled: false,
|
||||
["aws-claudeTokens"]: 0,
|
||||
["aws-claude-opusTokens"]: 0,
|
||||
};
|
||||
this.keys.push(newKey);
|
||||
}
|
||||
@@ -97,14 +98,18 @@ export class AwsBedrockKeyProvider implements KeyProvider<AwsBedrockKey> {
|
||||
|
||||
public get(model: string) {
|
||||
const availableKeys = this.keys.filter((k) => {
|
||||
const isNotLogged = k.awsLoggingStatus === "disabled";
|
||||
const needsSonnet = model.includes("sonnet");
|
||||
const needsHaiku = model.includes("haiku");
|
||||
const isNotLogged = k.awsLoggingStatus !== "enabled";
|
||||
const neededFamily = getAwsBedrockModelFamily(model);
|
||||
const needsSonnet =
|
||||
model.includes("sonnet") && neededFamily === "aws-claude";
|
||||
const needsHaiku =
|
||||
model.includes("haiku") && neededFamily === "aws-claude";
|
||||
return (
|
||||
!k.isDisabled &&
|
||||
(isNotLogged || config.allowAwsLogging) &&
|
||||
(k.sonnetEnabled || !needsSonnet) &&
|
||||
(k.haikuEnabled || !needsHaiku)
|
||||
(k.sonnetEnabled || !needsSonnet) && // sonnet and haiku are both under aws-claude, while opus is not
|
||||
(k.haikuEnabled || !needsHaiku) &&
|
||||
k.modelFamilies.includes(neededFamily)
|
||||
);
|
||||
});
|
||||
if (availableKeys.length === 0) {
|
||||
@@ -157,11 +162,11 @@ export class AwsBedrockKeyProvider implements KeyProvider<AwsBedrockKey> {
|
||||
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);
|
||||
if (!key) return;
|
||||
key.promptCount++;
|
||||
key["aws-claudeTokens"] += tokens;
|
||||
key[`${getAwsBedrockModelFamily(model)}Tokens`] += tokens;
|
||||
}
|
||||
|
||||
public getLockoutPeriod() {
|
||||
|
||||
@@ -72,6 +72,7 @@ export class AzureOpenAIKeyProvider implements KeyProvider<AzureOpenAIKey> {
|
||||
"azure-gpt4Tokens": 0,
|
||||
"azure-gpt4-32kTokens": 0,
|
||||
"azure-gpt4-turboTokens": 0,
|
||||
"azure-gpt4oTokens": 0,
|
||||
"azure-dall-eTokens": 0,
|
||||
};
|
||||
this.keys.push(newKey);
|
||||
|
||||
@@ -9,7 +9,8 @@ export type APIFormat =
|
||||
| "anthropic-chat" // Anthropic's newer messages array format
|
||||
| "anthropic-text" // Legacy flat string prompt format
|
||||
| "google-ai"
|
||||
| "mistral-ai";
|
||||
| "mistral-ai"
|
||||
| "cohere-chat";
|
||||
|
||||
export interface Key {
|
||||
/** The API key itself. Never log this, use `hash` instead. */
|
||||
|
||||
@@ -13,15 +13,15 @@ type KeyCheckerOptions<TKey extends Key = Key> = {
|
||||
|
||||
export abstract class KeyCheckerBase<TKey extends Key> {
|
||||
protected readonly service: string;
|
||||
protected readonly RECURRING_CHECKS_ENABLED: boolean;
|
||||
protected readonly recurringChecksEnabled: boolean;
|
||||
/** 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
|
||||
* read quota usage, there is little reason to check a single key more often
|
||||
* than this.
|
||||
*/
|
||||
protected readonly KEY_CHECK_PERIOD: number;
|
||||
protected readonly keyCheckPeriod: number;
|
||||
protected readonly updateKey: (hash: string, props: Partial<TKey>) => void;
|
||||
protected readonly keys: TKey[] = [];
|
||||
protected log: pino.Logger;
|
||||
@@ -29,14 +29,13 @@ export abstract class KeyCheckerBase<TKey extends Key> {
|
||||
protected lastCheck = 0;
|
||||
|
||||
protected constructor(keys: TKey[], opts: KeyCheckerOptions<TKey>) {
|
||||
const { service, keyCheckPeriod, minCheckInterval } = opts;
|
||||
this.keys = keys;
|
||||
this.KEY_CHECK_PERIOD = keyCheckPeriod;
|
||||
this.MIN_CHECK_INTERVAL = minCheckInterval;
|
||||
this.RECURRING_CHECKS_ENABLED = opts.recurringChecksEnabled ?? true;
|
||||
this.keyCheckPeriod = opts.keyCheckPeriod;
|
||||
this.minCheckInterval = opts.minCheckInterval;
|
||||
this.recurringChecksEnabled = opts.recurringChecksEnabled ?? true;
|
||||
this.updateKey = opts.updateKey;
|
||||
this.service = service;
|
||||
this.log = logger.child({ module: "key-checker", service });
|
||||
this.service = opts.service;
|
||||
this.log = logger.child({ module: "key-checker", service: opts.service });
|
||||
}
|
||||
|
||||
public start() {
|
||||
@@ -102,7 +101,7 @@ export abstract class KeyCheckerBase<TKey extends Key> {
|
||||
return;
|
||||
}
|
||||
|
||||
if (!this.RECURRING_CHECKS_ENABLED) {
|
||||
if (!this.recurringChecksEnabled) {
|
||||
checkLog.info(
|
||||
"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 anything at all at a rate faster than once per 3 seconds.
|
||||
const nextCheck = Math.max(
|
||||
oldestKey.lastChecked + this.KEY_CHECK_PERIOD,
|
||||
this.lastCheck + this.MIN_CHECK_INTERVAL
|
||||
oldestKey.lastChecked + this.keyCheckPeriod,
|
||||
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.checkKey(oldestKey).then(() => this.scheduleNextCheck()),
|
||||
delay
|
||||
jitteredDelay
|
||||
);
|
||||
checkLog.debug(
|
||||
{ key: oldestKey.hash, nextCheck: new Date(nextCheck), delay },
|
||||
{ key: oldestKey.hash, nextCheck: new Date(nextCheck), jitteredDelay },
|
||||
"Scheduled next recurring check."
|
||||
);
|
||||
}
|
||||
|
||||
@@ -41,7 +41,13 @@ export class KeyPool {
|
||||
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);
|
||||
return this.getKeyProvider(queryService).get(model);
|
||||
}
|
||||
|
||||
@@ -96,6 +96,7 @@ export class OpenAIKeyProvider implements KeyProvider<OpenAIKey> {
|
||||
"turbo" as const,
|
||||
"gpt4" as const,
|
||||
"gpt4-turbo" as const,
|
||||
"gpt4o" as const,
|
||||
],
|
||||
isTrial: false,
|
||||
isDisabled: false,
|
||||
@@ -116,6 +117,7 @@ export class OpenAIKeyProvider implements KeyProvider<OpenAIKey> {
|
||||
gpt4Tokens: 0,
|
||||
"gpt4-32kTokens": 0,
|
||||
"gpt4-turboTokens": 0,
|
||||
gpt4oTokens: 0,
|
||||
"dall-eTokens": 0,
|
||||
gpt4Rpm: 0,
|
||||
modelSnapshots: [],
|
||||
|
||||
+30
-5
@@ -14,13 +14,15 @@ export type LLMService =
|
||||
| "google-ai"
|
||||
| "mistral-ai"
|
||||
| "aws"
|
||||
| "azure";
|
||||
| "azure"
|
||||
| "cohere";
|
||||
|
||||
export type OpenAIModelFamily =
|
||||
| "turbo"
|
||||
| "gpt4"
|
||||
| "gpt4-32k"
|
||||
| "gpt4-turbo"
|
||||
| "gpt4o"
|
||||
| "dall-e";
|
||||
export type AnthropicModelFamily = "claude" | "claude-opus";
|
||||
export type GoogleAIModelFamily = "gemini-pro";
|
||||
@@ -29,15 +31,17 @@ export type MistralAIModelFamily =
|
||||
| "mistral-small"
|
||||
| "mistral-medium"
|
||||
| "mistral-large";
|
||||
export type AwsBedrockModelFamily = "aws-claude";
|
||||
export type AwsBedrockModelFamily = "aws-claude" | "aws-claude-opus";
|
||||
export type AzureOpenAIModelFamily = `azure-${OpenAIModelFamily}`;
|
||||
export type CohereModelFamily = "command-r" | "command-r-plus";
|
||||
export type ModelFamily =
|
||||
| OpenAIModelFamily
|
||||
| AnthropicModelFamily
|
||||
| GoogleAIModelFamily
|
||||
| MistralAIModelFamily
|
||||
| AwsBedrockModelFamily
|
||||
| AzureOpenAIModelFamily;
|
||||
| AzureOpenAIModelFamily
|
||||
| CohereModelFamily;
|
||||
|
||||
export const MODEL_FAMILIES = (<A extends readonly ModelFamily[]>(
|
||||
arr: A & ([ModelFamily] extends [A[number]] ? unknown : never)
|
||||
@@ -46,6 +50,7 @@ export const MODEL_FAMILIES = (<A extends readonly ModelFamily[]>(
|
||||
"gpt4",
|
||||
"gpt4-32k",
|
||||
"gpt4-turbo",
|
||||
"gpt4o",
|
||||
"dall-e",
|
||||
"claude",
|
||||
"claude-opus",
|
||||
@@ -55,11 +60,15 @@ export const MODEL_FAMILIES = (<A extends readonly ModelFamily[]>(
|
||||
"mistral-medium",
|
||||
"mistral-large",
|
||||
"aws-claude",
|
||||
"aws-claude-opus",
|
||||
"azure-turbo",
|
||||
"azure-gpt4",
|
||||
"azure-gpt4-32k",
|
||||
"azure-gpt4-turbo",
|
||||
"azure-gpt4o",
|
||||
"azure-dall-e",
|
||||
"command-r",
|
||||
"command-r-plus",
|
||||
] as const);
|
||||
|
||||
export const LLM_SERVICES = (<A extends readonly LLMService[]>(
|
||||
@@ -71,9 +80,12 @@ export const LLM_SERVICES = (<A extends readonly LLMService[]>(
|
||||
"mistral-ai",
|
||||
"aws",
|
||||
"azure",
|
||||
"cohere",
|
||||
] as const);
|
||||
|
||||
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-(0125|1106)(-preview)?$": "gpt4-turbo",
|
||||
"^gpt-4(-\\d{4})?-vision(-preview)?$": "gpt4-turbo",
|
||||
@@ -93,20 +105,25 @@ export const MODEL_FAMILY_SERVICE: {
|
||||
gpt4: "openai",
|
||||
"gpt4-turbo": "openai",
|
||||
"gpt4-32k": "openai",
|
||||
"gpt4o": "openai",
|
||||
"dall-e": "openai",
|
||||
claude: "anthropic",
|
||||
"claude-opus": "anthropic",
|
||||
"aws-claude": "aws",
|
||||
"aws-claude-opus": "aws",
|
||||
"azure-turbo": "azure",
|
||||
"azure-gpt4": "azure",
|
||||
"azure-gpt4-32k": "azure",
|
||||
"azure-gpt4-turbo": "azure",
|
||||
"azure-gpt4o": "azure",
|
||||
"azure-dall-e": "azure",
|
||||
"gemini-pro": "google-ai",
|
||||
"mistral-tiny": "mistral-ai",
|
||||
"mistral-small": "mistral-ai",
|
||||
"mistral-medium": "mistral-ai",
|
||||
"mistral-large": "mistral-ai",
|
||||
"command-r": "cohere",
|
||||
"command-r-plus": "cohere",
|
||||
};
|
||||
|
||||
export const IMAGE_GEN_MODELS: ModelFamily[] = ["dall-e", "azure-dall-e"];
|
||||
@@ -149,8 +166,8 @@ export function getMistralAIModelFamily(model: string): MistralAIModelFamily {
|
||||
}
|
||||
}
|
||||
|
||||
export function getAwsBedrockModelFamily(model: string): ModelFamily {
|
||||
if (model.includes("opus")) return "claude-opus";
|
||||
export function getAwsBedrockModelFamily(model: string): AwsBedrockModelFamily {
|
||||
if (model.includes("opus")) return "aws-claude-opus";
|
||||
return "aws-claude";
|
||||
}
|
||||
|
||||
@@ -172,6 +189,11 @@ export function getAzureOpenAIModelFamily(
|
||||
return defaultFamily;
|
||||
}
|
||||
|
||||
export function getCohereModelFamily(model: string): CohereModelFamily {
|
||||
if (model.includes("plus")) return "command-r-plus";
|
||||
return "command-r";
|
||||
}
|
||||
|
||||
export function assertIsKnownModelFamily(
|
||||
modelFamily: string
|
||||
): asserts modelFamily is ModelFamily {
|
||||
@@ -211,6 +233,9 @@ export function getModelFamilyForRequest(req: Request): ModelFamily {
|
||||
case "mistral-ai":
|
||||
modelFamily = getMistralAIModelFamily(model);
|
||||
break;
|
||||
case "cohere-chat":
|
||||
modelFamily = getCohereModelFamily(model);
|
||||
break;
|
||||
default:
|
||||
assertNever(req.outboundApi);
|
||||
}
|
||||
|
||||
@@ -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 { fileBackend as file } from "./file";
|
||||
|
||||
@@ -0,0 +1,10 @@
|
||||
import { config } from "../../config";
|
||||
import type { EventLogEntry } from "../database";
|
||||
import { eventsRepo } from "../database/repos/event";
|
||||
|
||||
export const logEvent = (payload: Omit<EventLogEntry, "date">) => {
|
||||
if (!config.eventLogging) {
|
||||
return;
|
||||
}
|
||||
eventsRepo.logEvent({ ...payload, date: new Date().toISOString() });
|
||||
};
|
||||
@@ -17,4 +17,10 @@ export interface PromptLogEntry {
|
||||
// TODO: temperature, top_p, top_k, etc.
|
||||
}
|
||||
|
||||
export interface LogBackend {
|
||||
init: (onStop: () => void) => Promise<void>;
|
||||
appendBatch: (batch: PromptLogEntry[]) => Promise<void>;
|
||||
}
|
||||
|
||||
export * as logQueue from "./log-queue";
|
||||
export * as eventLogger from "./event-logger";
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user