middleware: param-override, model-map, system-prompt, word-guard and think-tags — gateway middleware that magpie runs on every agent's requests and replies, mostly New API's channel settings with the same JSON (the owner) — magpie can now run a plugin as gateway middleware (onRequest, onEvent, onResponse, in-process on moejs), and these are the first ones: param-override is New API's param_override (both forms, operations with gjson paths and conditions, return_error); model-map is model_mapping (chains, /regex/ keys with $1) and puts the asked-for name back into replies; system-prompt adds a prompt in each API's own place, keeping an agent's own unless override (New API's semantics), by agent or model; word-guard is the sensitive-word filter (reject or mask the user's text, optionally replies); think-tags strips a leading <think>…</think> from replies across stream chunks, or puts Chat reasoning_content into the text (thinking_to_content). Each is one file with no imports, named @magpie-community/middleware-<name>, with magpie.options as the example the app's editor starts from; registry.json lists them with "kind": "middleware" and no providers; check.mjs skips middleware-only packages. scripts/middleware.mjs calls the hooks as the gateway does (events split, [DONE] passed by) and runs each package's cases.json. Tested with a real DeepSeek account and real Claude Code through magpie's gateway: a mapped model named back in message_start, max_tokens capped, a system prompt appended for claude only, a word turned away as a 400 in Anthropic's shape, return_error as a 403 in Chat's, <think> stripped from Chat and Responses streams and an Anthropic whole reply, reasoning_content moved into the text. bun test (61 for these five) and bun scripts/check.mjs pass; packages/devin's two image tests fail on this machine only, as on main. Their first npm version has to be published by hand (trusted publishing can't create a package); until then magpie shows them as Coming soon.
This commit is contained in:
@@ -1,7 +1,8 @@
|
||||
# magpie-community plugins
|
||||
|
||||
[OpenCode](https://opencode.ai) provider plugins for coding-plan
|
||||
subscriptions, maintained by the community. Each package signs in to one
|
||||
subscriptions, and [gateway middleware](#gateway-middleware) for magpie,
|
||||
maintained by the community. Each package signs in to one
|
||||
subscription and makes its requests. The packages work in OpenCode and in
|
||||
[magpie](https://usemagpie.ai), which runs OpenCode's provider plugins.
|
||||
|
||||
@@ -25,6 +26,31 @@ subscription and makes its requests. The packages work in OpenCode and in
|
||||
| [zcode](packages/zcode) | ZCode: Z.ai / BigModel (智谱) GLM Coding Plan, team seats, Start Plan | `zcode` |
|
||||
| [zed](packages/zed) | Zed (Pro, Pro Trial, Student, Business): Anthropic, OpenAI, Google and xAI models hosted by Zed | `zed` |
|
||||
|
||||
## Gateway middleware
|
||||
|
||||
These packages aren't OpenCode plugins. magpie runs them in its gateway, on the requests every agent sends and the replies it gets back, whichever provider serves them. Each one is a port of something [New API](https://github.com/QuantumNous/new-api) does for its channels, or something agents commonly need.
|
||||
|
||||
| Package | What it does |
|
||||
|---|---|
|
||||
| [param-override](packages/param-override) | New API's 参数覆盖 (`param_override`): set, delete, move, copy or rewrite request fields, for some models or under conditions, or turn a request away |
|
||||
| [model-map](packages/model-map) | New API's 模型重定向 (`model_mapping`): send a model under another name, by name or `/pattern/`; replies name the model asked for |
|
||||
| [system-prompt](packages/system-prompt) | Your own system prompt on every request, or on some agents' or models', in each API's own place |
|
||||
| [word-guard](packages/word-guard) | New API's 敏感词过滤: turn away or mask words and patterns in what users send, and in replies |
|
||||
| [think-tags](packages/think-tags) | Take `<think>…</think>` out of a reply's text, or put a Chat reply's `reasoning_content` into it (`thinking_to_content`) |
|
||||
|
||||
```sh
|
||||
magpie plugin add @magpie-community/middleware-<name>
|
||||
magpie plugin options <name> '<json>'
|
||||
```
|
||||
|
||||
In the app, they're under Plugins › Discover › Gateway middleware, and each one's **Options** button edits its options in its row.
|
||||
|
||||
A middleware package is a folder under `packages/<name>/` with:
|
||||
|
||||
- **`package.json`**: name `@magpie-community/middleware-<name>`, `"magpie": {"middleware": "./<name>.middleware.js", "options": {…}}`, no `main`. `options` is the example magpie offers when none are set.
|
||||
- **`<name>.middleware.js`**: exports `onRequest`, `onEvent` and/or `onResponse` ([the hooks](https://usemagpie.ai/docs/plugins#middleware)). It runs in magpie's gateway on moejs, so it is one file and imports nothing.
|
||||
- **`cases.json`** and a test that runs them with `check()` from `scripts/middleware.mjs`, which calls the hooks the way the gateway does.
|
||||
|
||||
## Use
|
||||
|
||||
magpie:
|
||||
@@ -97,8 +123,8 @@ MIT
|
||||
|
||||
## The market
|
||||
|
||||
`registry.json` is the list magpie's Plugins tab shows. The packages here
|
||||
come first, then other OpenCode provider plugins worth knowing. magpie
|
||||
`registry.json` is the list magpie's Plugins tab shows: the packages
|
||||
here. A middleware's entry has `"kind": "middleware"` and no `providers`. magpie
|
||||
fetches it every few hours and keeps a copy built into the app for when
|
||||
it can't. To list a plugin, add an entry with its npm `package`, a
|
||||
`name`, `providers` (the provider ids it signs in to), an `icon` and a
|
||||
|
||||
@@ -0,0 +1,25 @@
|
||||
# @magpie-community/middleware-model-map
|
||||
|
||||
New API's **模型重定向** (a channel's `model_mapping`) as [magpie](https://usemagpie.ai) gateway middleware. The model an agent asks for is sent upstream as another model. Replies then name the model the agent asked for, so an agent that reads its model's name back (Claude Code does, to size its context window) sees the name it asked for.
|
||||
|
||||
Install it from magpie's **Plugins › Discover**, or with `magpie plugin add @magpie-community/middleware-model-map`. Set its options under **Plugins › Installed › Options**, or with `magpie plugin options model-map '<json>'`.
|
||||
|
||||
## Options
|
||||
|
||||
```json
|
||||
{ "mapping": {
|
||||
"fast": "deepseek-chat",
|
||||
"/^claude-(.*)$/": "glm-$1"
|
||||
} }
|
||||
```
|
||||
|
||||
- **Mapping.** A name maps to its target. Names chain (`a → b → c`) until there is nothing more to map, and a cycle stops before it repeats.
|
||||
- **Patterns.** A key written `/like this/` is a regular expression, and its target can use `$1` for the first group.
|
||||
- **Flat form.** New API's flat form, `{"fast": "deepseek-chat"}`, works as well.
|
||||
- **`keep_upstream_name`.** Set it to `true` to leave the upstream model's name in replies.
|
||||
|
||||
The target has to be a model magpie can route: a model of one of your providers, or one of magpie's own ids (`deepseek/deepseek-chat`, for example).
|
||||
|
||||
**Gemini.** A Gemini request names its model in the URL, not in the body, so this middleware leaves Gemini requests alone.
|
||||
|
||||
中文:New API 的「模型重定向」,作为 magpie 网关中间件。回复里的模型名会还原成 agent 请求时用的名字。
|
||||
@@ -0,0 +1,61 @@
|
||||
[
|
||||
{ "name": "an exact name is sent as its target",
|
||||
"options": { "mapping": { "fast": "deepseek-chat" } },
|
||||
"request": { "model": "fast", "messages": [] },
|
||||
"expect_request": { "model": "deepseek-chat", "messages": [] } },
|
||||
{ "name": "New API's flat form",
|
||||
"options": { "fast": "deepseek-chat" },
|
||||
"request": { "model": "fast" },
|
||||
"expect_request": { "model": "deepseek-chat" } },
|
||||
{ "name": "a name not mapped passes as it is, and so does its reply",
|
||||
"options": { "mapping": { "fast": "deepseek-chat" } },
|
||||
"request": { "model": "deepseek-chat" },
|
||||
"events": [{ "event": "message_start", "data": { "type": "message_start", "message": { "model": "deepseek-chat" } } }] },
|
||||
{ "name": "chains, and a cycle stops",
|
||||
"options": { "mapping": { "a": "b", "b": "c", "x": "y", "y": "x" } },
|
||||
"request": { "model": "a", "n": [{ "model": "x" }] },
|
||||
"expect_request": { "model": "c", "n": [{ "model": "x" }] } },
|
||||
{ "name": "a cycle stops where it would repeat",
|
||||
"options": { "mapping": { "x": "y", "y": "x" } },
|
||||
"request": { "model": "x" },
|
||||
"expect_request": { "model": "y" } },
|
||||
{ "name": "a pattern with a group",
|
||||
"options": { "mapping": { "/^claude-(.*)$/": "glm-$1" } },
|
||||
"request": { "model": "claude-4.6" },
|
||||
"expect_request": { "model": "glm-4.6" } },
|
||||
{ "name": "Anthropic's stream names the asked model",
|
||||
"options": { "mapping": { "fast": "deepseek-chat" } },
|
||||
"request": { "model": "fast", "stream": true },
|
||||
"expect_request": { "model": "deepseek-chat", "stream": true },
|
||||
"events": [
|
||||
{ "event": "message_start", "data": { "type": "message_start", "message": { "id": "m1", "model": "deepseek-chat", "content": [] } } },
|
||||
{ "event": "content_block_delta", "data": { "type": "content_block_delta", "index": 0, "delta": { "type": "text_delta", "text": "hi" } } }],
|
||||
"expect_events": [
|
||||
{ "type": "message_start", "message": { "id": "m1", "model": "fast", "content": [] } },
|
||||
{ "type": "content_block_delta", "index": 0, "delta": { "type": "text_delta", "text": "hi" } }] },
|
||||
{ "name": "Chat chunks name the asked model; [DONE] passes",
|
||||
"ctx": { "protocol": "chat" },
|
||||
"options": { "mapping": { "fast": "deepseek-chat" } },
|
||||
"request": { "model": "fast" },
|
||||
"expect_request": { "model": "deepseek-chat" },
|
||||
"events": [{ "data": { "id": "c", "model": "deepseek-chat", "choices": [{ "delta": { "content": "hi" } }] } }, { "data": "[DONE]" }],
|
||||
"expect_events": [{ "id": "c", "model": "fast", "choices": [{ "delta": { "content": "hi" } }] }, "[DONE]"] },
|
||||
{ "name": "Responses events and a whole reply",
|
||||
"ctx": { "protocol": "responses" },
|
||||
"options": { "mapping": { "fast": "gpt-5" } },
|
||||
"request": { "model": "fast" },
|
||||
"expect_request": { "model": "gpt-5" },
|
||||
"events": [{ "event": "response.created", "data": { "type": "response.created", "response": { "model": "gpt-5" } } }],
|
||||
"expect_events": [{ "type": "response.created", "response": { "model": "fast" } }],
|
||||
"response": { "id": "r", "model": "gpt-5", "output": [] },
|
||||
"expect_response": { "id": "r", "model": "fast", "output": [] } },
|
||||
{ "name": "keep_upstream_name leaves replies alone",
|
||||
"options": { "mapping": { "fast": "deepseek-chat" }, "keep_upstream_name": true },
|
||||
"request": { "model": "fast" },
|
||||
"expect_request": { "model": "deepseek-chat" },
|
||||
"response": { "model": "deepseek-chat" } },
|
||||
{ "name": "Gemini's body has no model to map",
|
||||
"ctx": { "protocol": "gemini", "model": "fast" },
|
||||
"options": { "mapping": { "fast": "x" } },
|
||||
"request": { "contents": [] } }
|
||||
]
|
||||
@@ -0,0 +1,89 @@
|
||||
// New API's 模型重定向 (a channel's model_mapping) as magpie gateway
|
||||
// middleware: the model an agent asks for is sent as another, and the
|
||||
// reply names the model the agent asked for again, so an agent that reads
|
||||
// its model's name back (Claude Code does, for its context window) sees
|
||||
// what it asked for.
|
||||
//
|
||||
// {"mapping": {"fast": "deepseek-chat", "/^claude-(.*)$/": "glm-$1"}}
|
||||
//
|
||||
// New API's own flat form, {"fast": "deepseek-chat"}, works too. A name
|
||||
// maps on (a → b → c) until it maps to nothing more; a cycle stops where
|
||||
// it would repeat. A key written /like this/ is a regular expression, and
|
||||
// its value can use $1. "keep_upstream_name": true leaves the upstream
|
||||
// model's name in replies.
|
||||
|
||||
export function onRequest(body, ctx) {
|
||||
// Gemini's model is in the request's path, not its body
|
||||
if (ctx.protocol === "gemini" || typeof body.model !== "string") return
|
||||
const to = map(body.model, rules(ctx.options))
|
||||
if (to === body.model) return
|
||||
ctx.state.asked = body.model
|
||||
body.model = to
|
||||
return body
|
||||
}
|
||||
|
||||
export function onEvent(ev, ctx) {
|
||||
const asked = ctx.state.asked
|
||||
if (!asked || ctx.options.keep_upstream_name) return
|
||||
if (ev.type === "message_start" && ev.message && typeof ev.message.model === "string") {
|
||||
ev.message.model = asked
|
||||
return ev
|
||||
}
|
||||
if (typeof ev.model === "string" && ev.model !== asked) {
|
||||
ev.model = asked
|
||||
return ev
|
||||
}
|
||||
if (ev.response && typeof ev.response.model === "string") {
|
||||
ev.response.model = asked
|
||||
return ev
|
||||
}
|
||||
}
|
||||
|
||||
export function onResponse(body, ctx) {
|
||||
const asked = ctx.state.asked
|
||||
if (!asked || ctx.options.keep_upstream_name || ctx.status >= 400) return
|
||||
if (typeof body.model === "string") {
|
||||
body.model = asked
|
||||
return body
|
||||
}
|
||||
if (body.response && typeof body.response.model === "string") {
|
||||
body.response.model = asked
|
||||
return body
|
||||
}
|
||||
}
|
||||
|
||||
// rules are the options' mappings, compiled: exact names, and patterns
|
||||
function rules(o) {
|
||||
if (!o || typeof o !== "object") return { exact: {}, patterns: [] }
|
||||
const m = o.mapping && typeof o.mapping === "object" ? o.mapping : o
|
||||
const exact = {}
|
||||
const patterns = []
|
||||
for (const k of Object.keys(m)) {
|
||||
const v = m[k]
|
||||
if (typeof v !== "string" || !v || k === "keep_upstream_name") continue
|
||||
const re = /^\/(.+)\/([a-z]*)$/.exec(k)
|
||||
if (re) patterns.push([new RegExp(re[1], re[2].replace("g", "")), v])
|
||||
else exact[k] = v
|
||||
}
|
||||
return { exact, patterns }
|
||||
}
|
||||
|
||||
function map(name, r) {
|
||||
const seen = [name]
|
||||
let cur = name
|
||||
for (let i = 0; i < 16; i++) {
|
||||
let next = Object.prototype.hasOwnProperty.call(r.exact, cur) ? r.exact[cur] : undefined
|
||||
if (next === undefined) {
|
||||
for (const [re, to] of r.patterns) {
|
||||
if (re.test(cur)) {
|
||||
next = cur.replace(re, to)
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
if (next === undefined || next === cur || seen.includes(next)) return cur
|
||||
seen.push(next)
|
||||
cur = next
|
||||
}
|
||||
return cur
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
import * as mod from "./model-map.middleware.js"
|
||||
import { check } from "../../scripts/middleware.mjs"
|
||||
|
||||
check(import.meta.dir, mod)
|
||||
@@ -0,0 +1,14 @@
|
||||
{
|
||||
"name": "@magpie-community/middleware-model-map",
|
||||
"version": "0.1.0",
|
||||
"description": "New API's model_mapping (模型重定向) as magpie gateway middleware: send the model an agent asks for as another, and keep the asked name in replies",
|
||||
"type": "module",
|
||||
"files": ["model-map.middleware.js", "README.md"],
|
||||
"keywords": ["magpie", "magpie-middleware", "new-api", "model-mapping", "llm-gateway"],
|
||||
"license": "MIT",
|
||||
"repository": { "type": "git", "url": "git+https://github.com/magpie-community/plugins.git", "directory": "packages/model-map" },
|
||||
"magpie": {
|
||||
"middleware": "./model-map.middleware.js",
|
||||
"options": { "mapping": { "fast": "deepseek-chat", "/^gpt-4o(-.*)?$/": "deepseek-chat" } }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
# @magpie-community/middleware-param-override
|
||||
|
||||
New API's **参数覆盖** (a channel's `param_override`) as [magpie](https://usemagpie.ai) gateway middleware. It sets, deletes, moves and rewrites any field of the requests agents send through magpie, whichever provider serves them. The options are New API's JSON as it is, so you can paste a `param_override` from New API unchanged.
|
||||
|
||||
Install it from magpie's **Plugins › Discover**, or with `magpie plugin add @magpie-community/middleware-param-override`. Then set its options under **Plugins › Installed › Options**, or with `magpie plugin options param-override '<json>'`.
|
||||
|
||||
## Options
|
||||
|
||||
There are two forms, as in New API:
|
||||
|
||||
```json
|
||||
{ "temperature": 0.2, "max_tokens": 8000 }
|
||||
```
|
||||
|
||||
Each key is set on the body as it is.
|
||||
|
||||
```json
|
||||
{ "operations": [
|
||||
{ "path": "max_tokens", "mode": "set", "value": 32000,
|
||||
"conditions": [{ "path": "max_tokens", "mode": "gt", "value": 32000 }] },
|
||||
{ "path": "temperature", "mode": "delete",
|
||||
"conditions": [{ "path": "model", "mode": "contains", "value": "reasoner" }] },
|
||||
{ "mode": "return_error", "value": { "message": "opus is not allowed here", "status_code": 403 },
|
||||
"conditions": [{ "path": "model", "mode": "contains", "value": "opus" }] }
|
||||
] }
|
||||
```
|
||||
|
||||
The operations run in order. Keys set beside `operations` are applied first.
|
||||
|
||||
| Field | |
|
||||
| --- | --- |
|
||||
| `path` | A gjson path: `a.b.0`. `messages.-1` counts from the end, `tools.*.name` matches every item, and `\.` is a dot inside a key. |
|
||||
| `mode` | `set` (`keep_origin`: only when missing), `delete`, `move` / `copy` (`from`, `to`), `prepend` / `append` (arrays joined, strings joined, objects merged; `keep_origin` keeps keys already there), `trim_prefix`, `trim_suffix`, `ensure_prefix`, `ensure_suffix`, `trim_space`, `to_lower`, `to_upper`, `replace` / `regex_replace` (`from`, `to`; Go's `${1}` works), `return_error`, `prune_objects` |
|
||||
| `value` | What to set, join or trim. For `return_error`, a message or `{message, status_code}`; the agent gets the error in its own API's shape. For `prune_objects`, a `type` or `{type, where, conditions, logic, recursive}`. |
|
||||
| `conditions` | `[{path, mode, value, invert, pass_missing_key}]`, where `mode` is `full`, `prefix`, `suffix`, `contains`, `gt`, `gte`, `lt` or `lte`. A path is looked up in the body first, then in the request: `model`, `request_path`, `protocol` (`anthropic`, `chat`, `responses`, `gemini`), `agent`, `stream`. |
|
||||
| `logic` | `OR` (New API's default) or `AND`. |
|
||||
|
||||
Some of New API's modes have nothing to act on here and are left out: the header modes (`set_header`, `pass_headers`…), `sync_fields`, and conditions on retries, users and groups. The middleware sees only the body.
|
||||
|
||||
Unlike New API, an operation that can't apply is skipped (a `move` from a missing path, `trim_prefix` on a number) and the request goes on. If the middleware itself fails, magpie sends the request as it came.
|
||||
|
||||
## Recipes
|
||||
|
||||
- Cap `max_tokens` for a provider with a lower limit: the first example above.
|
||||
- Drop a parameter a provider refuses: `{"path": "tools.*.input_examples", "mode": "delete"}`.
|
||||
- Strip a vendor prefix from model names: `{"path": "model", "mode": "trim_prefix", "value": "openai/"}`.
|
||||
- Keep an agent off a model: `return_error` with a `model` condition.
|
||||
- Remove old thinking blocks: `{"path": "messages", "mode": "prune_objects", "value": "thinking"}`.
|
||||
|
||||
中文:New API 的「参数覆盖」,作为 magpie 网关中间件。配置是 New API 的同一份 JSON,可以原样粘贴过来。
|
||||
@@ -0,0 +1,94 @@
|
||||
[
|
||||
{ "name": "legacy keys are set as they are",
|
||||
"options": { "temperature": 0.2, "max_tokens": 8000 },
|
||||
"request": { "model": "m", "max_tokens": 64000, "messages": [] },
|
||||
"expect_request": { "model": "m", "max_tokens": 8000, "messages": [], "temperature": 0.2 } },
|
||||
{ "name": "nothing to do leaves the body",
|
||||
"options": { "operations": [{ "path": "temperature", "mode": "delete" }] },
|
||||
"request": { "model": "m", "messages": [] } },
|
||||
{ "name": "a cap: set only when over",
|
||||
"options": { "operations": [{ "path": "max_tokens", "mode": "set", "value": 32000, "conditions": [{ "path": "max_tokens", "mode": "gt", "value": 32000 }] }] },
|
||||
"request": { "model": "m", "max_tokens": 64000 },
|
||||
"expect_request": { "model": "m", "max_tokens": 32000 } },
|
||||
{ "name": "a cap under the limit stays",
|
||||
"options": { "operations": [{ "path": "max_tokens", "mode": "set", "value": 32000, "conditions": [{ "path": "max_tokens", "mode": "gt", "value": 32000 }] }] },
|
||||
"request": { "model": "m", "max_tokens": 4000 } },
|
||||
{ "name": "keep_origin fills only what is missing",
|
||||
"options": { "operations": [{ "path": "metadata.user_id", "mode": "set", "value": "me", "keep_origin": true }, { "path": "top_p", "mode": "set", "value": 0.9, "keep_origin": true }] },
|
||||
"request": { "model": "m", "top_p": 0.5 },
|
||||
"expect_request": { "model": "m", "top_p": 0.5, "metadata": { "user_id": "me" } } },
|
||||
{ "name": "conditions on the request: model prefix, protocol, AND",
|
||||
"ctx": { "protocol": "chat", "model": "deepseek-reasoner" },
|
||||
"options": { "operations": [{ "path": "temperature", "mode": "delete", "logic": "AND", "conditions": [{ "path": "model", "mode": "prefix", "value": "deepseek-r" }, { "path": "protocol", "mode": "full", "value": "chat" }] }] },
|
||||
"request": { "model": "deepseek-reasoner", "temperature": 1, "messages": [] },
|
||||
"expect_request": { "model": "deepseek-reasoner", "messages": [] } },
|
||||
{ "name": "AND with one false does nothing; invert",
|
||||
"ctx": { "protocol": "anthropic" },
|
||||
"options": { "operations": [
|
||||
{ "path": "temperature", "mode": "delete", "logic": "AND", "conditions": [{ "path": "model", "mode": "prefix", "value": "m" }, { "path": "protocol", "mode": "full", "value": "chat" }] },
|
||||
{ "path": "x", "mode": "set", "value": 1, "conditions": [{ "path": "protocol", "mode": "full", "value": "chat", "invert": true }] }] },
|
||||
"request": { "model": "m", "temperature": 1 },
|
||||
"expect_request": { "model": "m", "temperature": 1, "x": 1 } },
|
||||
{ "name": "a missing key fails a condition unless pass_missing_key",
|
||||
"options": { "operations": [
|
||||
{ "path": "a", "mode": "set", "value": 1, "conditions": [{ "path": "nope", "mode": "full", "value": 1 }] },
|
||||
{ "path": "b", "mode": "set", "value": 2, "conditions": [{ "path": "nope", "mode": "full", "value": 1, "pass_missing_key": true }] }] },
|
||||
"request": { "model": "m" },
|
||||
"expect_request": { "model": "m", "b": 2 } },
|
||||
{ "name": "return_error turns the request away",
|
||||
"options": { "operations": [{ "mode": "return_error", "value": { "message": "opus is not allowed here", "status_code": 403 }, "conditions": [{ "path": "model", "mode": "contains", "value": "opus" }] }] },
|
||||
"request": { "model": "claude-opus-4-5" },
|
||||
"reject": { "status": 403, "message": "opus is not allowed" } },
|
||||
{ "name": "return_error as a string is a 400",
|
||||
"options": { "operations": [{ "mode": "return_error", "value": "no" }] },
|
||||
"request": { "model": "m" },
|
||||
"reject": { "status": 400, "message": "no" } },
|
||||
{ "name": "move and copy",
|
||||
"options": { "operations": [{ "mode": "move", "from": "max_completion_tokens", "to": "max_tokens" }, { "mode": "copy", "from": "metadata.user_id", "to": "user" }] },
|
||||
"request": { "model": "m", "max_completion_tokens": 100, "metadata": { "user_id": "u1" } },
|
||||
"expect_request": { "model": "m", "max_tokens": 100, "metadata": { "user_id": "u1" }, "user": "u1" } },
|
||||
{ "name": "prepend to a string system, append to an array, merge an object",
|
||||
"options": { "operations": [
|
||||
{ "path": "system", "mode": "prepend", "value": "Be brief.\n" },
|
||||
{ "path": "stop", "mode": "append", "value": ["END"] },
|
||||
{ "path": "metadata", "mode": "append", "value": { "a": 1, "b": 2 }, "keep_origin": true }] },
|
||||
"request": { "model": "m", "system": "You code.", "stop": ["\n\n"], "metadata": { "a": 0 } },
|
||||
"expect_request": { "model": "m", "system": "Be brief.\nYou code.", "stop": ["\n\n", "END"], "metadata": { "a": 0, "b": 2 } } },
|
||||
{ "name": "prepend a block to an array system",
|
||||
"options": { "operations": [{ "path": "system", "mode": "prepend", "value": { "type": "text", "text": "Be brief." } }] },
|
||||
"request": { "model": "m", "system": [{ "type": "text", "text": "You code." }] },
|
||||
"expect_request": { "model": "m", "system": [{ "type": "text", "text": "Be brief." }, { "type": "text", "text": "You code." }] } },
|
||||
{ "name": "string modes",
|
||||
"options": { "operations": [
|
||||
{ "path": "model", "mode": "trim_prefix", "value": "openai/" },
|
||||
{ "path": "a", "mode": "ensure_suffix", "value": "!" },
|
||||
{ "path": "b", "mode": "trim_space" },
|
||||
{ "path": "c", "mode": "to_upper" },
|
||||
{ "path": "d", "mode": "replace", "from": "x", "to": "y" },
|
||||
{ "path": "e", "mode": "regex_replace", "from": "(?i)^CLAUDE-(\\d)", "to": "c${1}" }] },
|
||||
"request": { "model": "openai/gpt-5", "a": "hi", "b": " sp ", "c": "up", "d": "xax", "e": "claude-4-sonnet" },
|
||||
"expect_request": { "model": "gpt-5", "a": "hi!", "b": "sp", "c": "UP", "d": "yay", "e": "c4-sonnet" } },
|
||||
{ "name": "wildcards and negative indexes",
|
||||
"options": { "operations": [
|
||||
{ "path": "tools.*.input_examples", "mode": "delete" },
|
||||
{ "path": "messages.-1.content", "mode": "append", "value": " (be brief)" }] },
|
||||
"request": { "model": "m", "tools": [{ "name": "a", "input_examples": [1] }, { "name": "b" }, { "name": "c", "input_examples": [] }], "messages": [{ "role": "user", "content": "one" }, { "role": "user", "content": "two" }] },
|
||||
"expect_request": { "model": "m", "tools": [{ "name": "a" }, { "name": "b" }, { "name": "c" }], "messages": [{ "role": "user", "content": "one" }, { "role": "user", "content": "two (be brief)" }] } },
|
||||
{ "name": "delete over a wildcard of array items",
|
||||
"options": { "operations": [{ "path": "messages.*", "mode": "delete", "conditions": [{ "path": "model", "mode": "full", "value": "m" }] }] },
|
||||
"request": { "model": "m", "messages": [1, 2, 3] },
|
||||
"expect_request": { "model": "m", "messages": [] } },
|
||||
{ "name": "prune_objects by type, and with where",
|
||||
"options": { "operations": [
|
||||
{ "path": "messages", "mode": "prune_objects", "value": "thinking" },
|
||||
{ "path": "tools", "mode": "prune_objects", "value": { "where": { "name": "WebSearch" } } }] },
|
||||
"request": { "model": "m", "messages": [{ "role": "assistant", "content": [{ "type": "thinking", "thinking": "x" }, { "type": "text", "text": "hi" }] }], "tools": [{ "name": "WebSearch" }, { "name": "Read" }] },
|
||||
"expect_request": { "model": "m", "messages": [{ "role": "assistant", "content": [{ "type": "text", "text": "hi" }] }], "tools": [{ "name": "Read" }] } },
|
||||
{ "name": "header modes have nothing to act on",
|
||||
"options": { "operations": [{ "mode": "set_header", "path": "X-A", "value": "1" }] },
|
||||
"request": { "model": "m" } },
|
||||
{ "name": "replies pass untouched",
|
||||
"options": { "temperature": 0 },
|
||||
"events": [{ "event": "message_start", "data": { "type": "message_start", "message": { "model": "m" } } }, { "data": "[DONE]" }],
|
||||
"response": { "id": "x", "model": "m" } }
|
||||
]
|
||||
@@ -0,0 +1,19 @@
|
||||
{
|
||||
"name": "@magpie-community/middleware-param-override",
|
||||
"version": "0.1.0",
|
||||
"description": "New API's param_override (参数覆盖) as magpie gateway middleware: set, delete, move and rewrite any field of what agents send, with conditions",
|
||||
"type": "module",
|
||||
"files": ["param-override.middleware.js", "README.md"],
|
||||
"keywords": ["magpie", "magpie-middleware", "new-api", "param-override", "llm-gateway"],
|
||||
"license": "MIT",
|
||||
"repository": { "type": "git", "url": "git+https://github.com/magpie-community/plugins.git", "directory": "packages/param-override" },
|
||||
"magpie": {
|
||||
"middleware": "./param-override.middleware.js",
|
||||
"options": {
|
||||
"operations": [
|
||||
{ "path": "max_tokens", "mode": "set", "value": 32000, "conditions": [{ "path": "max_tokens", "mode": "gt", "value": 32000 }] },
|
||||
{ "path": "temperature", "mode": "delete", "conditions": [{ "path": "model", "mode": "contains", "value": "reasoner" }] }
|
||||
]
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,346 @@
|
||||
// New API's 参数覆盖 (a channel's param_override) as magpie gateway
|
||||
// middleware: the same JSON, so a param_override copied from New API works
|
||||
// here unchanged, on every request an agent sends through magpie.
|
||||
//
|
||||
// Two forms, as in New API:
|
||||
// {"temperature": 0.2, "max_tokens": 8000} each key set as it is
|
||||
// {"operations": [{path, mode, value, ...}]} run in order
|
||||
// Keys beside "operations" are set first, the operations after.
|
||||
//
|
||||
// A path is gjson's: "a.b.0", "messages.-1" from the end, "*" any key or
|
||||
// index, "\." a dot in a key. A condition looks in the body first, then in
|
||||
// the request: model, original_model, request_path, protocol, agent, stream.
|
||||
// What New API does with headers (set_header, pass_headers…) and with
|
||||
// retries has nothing to act on here and is left out.
|
||||
|
||||
export function onRequest(body, ctx) {
|
||||
const o = ctx.options
|
||||
if (!o || typeof o !== "object") return
|
||||
const req = { model: ctx.model, original_model: ctx.model, upstream_model: ctx.model, request_path: ctx.path, protocol: ctx.protocol, agent: ctx.agent, stream: ctx.stream }
|
||||
let root = body
|
||||
let changed = false
|
||||
for (const k of Object.keys(o)) {
|
||||
if (k === "operations") continue
|
||||
root[k] = o[k]
|
||||
changed = true
|
||||
}
|
||||
const ops = Array.isArray(o.operations) ? o.operations : []
|
||||
for (const op of ops) {
|
||||
if (!op || typeof op !== "object" || !when(root, req, op.conditions, op.logic || "OR")) continue
|
||||
const r = run(root, op, req, ctx)
|
||||
if (r === REJECTED) return
|
||||
if (r !== UNCHANGED) {
|
||||
root = r
|
||||
changed = true
|
||||
}
|
||||
}
|
||||
return changed ? root : undefined
|
||||
}
|
||||
|
||||
const REJECTED = {}
|
||||
const UNCHANGED = {}
|
||||
|
||||
// run applies one operation, giving the new root, UNCHANGED when it touched
|
||||
// nothing, or REJECTED when it turned the request away.
|
||||
function run(root, op, req, ctx) {
|
||||
const mode = String(op.mode || "")
|
||||
if (mode === "return_error") {
|
||||
const e = returnError(op.value)
|
||||
ctx.reject(e.status, e.message)
|
||||
return REJECTED
|
||||
}
|
||||
if (mode === "move" || mode === "copy") {
|
||||
const from = resolve(root, split(op.from))
|
||||
const to = resolve(root, split(op.to))
|
||||
if (from.length !== 1 || to.length !== 1) return UNCHANGED
|
||||
const v = getAt(root, from[0])
|
||||
if (v === undefined) return UNCHANGED
|
||||
root = setAt(root, to[0], clone(v))
|
||||
if (mode === "move") delAt(root, from[0])
|
||||
return root
|
||||
}
|
||||
const paths = mode === "prune_objects" && !op.path ? [[]] : resolve(root, split(op.path))
|
||||
if (!paths.length) return UNCHANGED
|
||||
let touched = false
|
||||
// deleting from the end keeps the indexes still to come in place
|
||||
if (mode === "delete") paths.reverse()
|
||||
for (const p of paths) {
|
||||
const cur = getAt(root, p)
|
||||
let next
|
||||
switch (mode) {
|
||||
case "set":
|
||||
if (op.keep_origin && cur !== undefined) continue
|
||||
next = clone(op.value)
|
||||
break
|
||||
case "delete":
|
||||
if (cur === undefined) continue
|
||||
delAt(root, p)
|
||||
touched = true
|
||||
continue
|
||||
case "prepend":
|
||||
case "append":
|
||||
next = join(cur, op.value, mode === "prepend", op.keep_origin)
|
||||
if (next === undefined) continue
|
||||
break
|
||||
case "trim_prefix":
|
||||
case "trim_suffix":
|
||||
case "ensure_prefix":
|
||||
case "ensure_suffix": {
|
||||
if (typeof cur !== "string" || op.value == null) continue
|
||||
const v = String(op.value)
|
||||
if (mode === "trim_prefix") next = cur.startsWith(v) ? cur.slice(v.length) : cur
|
||||
else if (mode === "trim_suffix") next = v && cur.endsWith(v) ? cur.slice(0, cur.length - v.length) : cur
|
||||
else if (mode === "ensure_prefix") next = cur.startsWith(v) ? cur : v + cur
|
||||
else next = cur.endsWith(v) ? cur : cur + v
|
||||
break
|
||||
}
|
||||
case "trim_space":
|
||||
if (typeof cur !== "string") continue
|
||||
next = cur.trim()
|
||||
break
|
||||
case "to_lower":
|
||||
if (typeof cur !== "string") continue
|
||||
next = cur.toLowerCase()
|
||||
break
|
||||
case "to_upper":
|
||||
if (typeof cur !== "string") continue
|
||||
next = cur.toUpperCase()
|
||||
break
|
||||
case "replace":
|
||||
if (typeof cur !== "string" || !op.from) continue
|
||||
next = cur.split(String(op.from)).join(String(op.to ?? ""))
|
||||
break
|
||||
case "regex_replace":
|
||||
if (typeof cur !== "string" || !op.from) continue
|
||||
next = cur.replace(goRegexp(String(op.from)), goReplacement(String(op.to ?? "")))
|
||||
break
|
||||
case "prune_objects":
|
||||
if (cur === undefined) continue
|
||||
next = prune(cur, pruneRule(op.value), req, true)
|
||||
break
|
||||
default:
|
||||
// header modes, sync_fields and anything unknown
|
||||
return UNCHANGED
|
||||
}
|
||||
if (next === cur) continue
|
||||
root = setAt(root, p, next)
|
||||
touched = true
|
||||
}
|
||||
return touched ? root : UNCHANGED
|
||||
}
|
||||
|
||||
// join is prepend/append: arrays are joined (an array value spread in),
|
||||
// strings joined, objects merged (keep_origin keeps the keys already there).
|
||||
function join(cur, value, before, keep) {
|
||||
if (Array.isArray(cur)) {
|
||||
const add = Array.isArray(value) ? clone(value) : [clone(value)]
|
||||
return before ? add.concat(cur) : cur.concat(add)
|
||||
}
|
||||
if (typeof cur === "string") {
|
||||
const v = typeof value === "string" ? value : JSON.stringify(value)
|
||||
return before ? v + cur : cur + v
|
||||
}
|
||||
if (isObj(cur) && isObj(value)) {
|
||||
const out = { ...cur }
|
||||
for (const k of Object.keys(value)) if (!keep || !(k in out)) out[k] = clone(value[k])
|
||||
return out
|
||||
}
|
||||
}
|
||||
|
||||
function returnError(v) {
|
||||
let status = 400
|
||||
let message = ""
|
||||
if (typeof v === "string") message = v.trim()
|
||||
else if (isObj(v)) {
|
||||
message = String(v.message ?? v.msg ?? "").trim()
|
||||
const s = Number(v.status_code ?? v.status)
|
||||
if (Number.isInteger(s)) status = s
|
||||
}
|
||||
return { status, message: message || "turned away by param-override" }
|
||||
}
|
||||
|
||||
// prune_objects' value: a type, or {type, where, conditions, logic, recursive}
|
||||
function pruneRule(v) {
|
||||
const r = { conds: [], logic: "AND", recursive: true }
|
||||
if (typeof v === "string" && v.trim()) r.conds.push({ path: "type", mode: "full", value: v.trim() })
|
||||
else if (isObj(v)) {
|
||||
if (typeof v.logic === "string" && v.logic.trim()) r.logic = v.logic
|
||||
if (typeof v.recursive === "boolean") r.recursive = v.recursive
|
||||
r.conds.push(...conditions(v.conditions))
|
||||
if (isObj(v.where)) for (const k of Object.keys(v.where)) r.conds.push({ path: k, mode: "full", value: v.where[k] })
|
||||
if (v.type !== undefined) r.conds.push({ path: "type", mode: "full", value: v.type })
|
||||
}
|
||||
return r
|
||||
}
|
||||
|
||||
// prune drops every object below node the rule matches; node itself stays
|
||||
function prune(node, rule, req, top) {
|
||||
if (!rule.conds.length) return node
|
||||
const keep = (x) => !(isObj(x) && when(x, req, rule.conds, rule.logic))
|
||||
const deeper = (x) => (rule.recursive && (isObj(x) || Array.isArray(x)) ? prune(x, rule, req, false) : x)
|
||||
if (Array.isArray(node)) {
|
||||
let out = node.filter(keep).map(deeper)
|
||||
const same = out.length === node.length && out.every((x, i) => x === node[i])
|
||||
return same ? node : out
|
||||
}
|
||||
if (isObj(node)) {
|
||||
let out = null
|
||||
for (const k of Object.keys(node)) {
|
||||
const x = node[k]
|
||||
if (!keep(x)) {
|
||||
if (!out) out = { ...node }
|
||||
delete out[k]
|
||||
} else {
|
||||
const y = deeper(x)
|
||||
if (y !== x) {
|
||||
if (!out) out = { ...node }
|
||||
out[k] = y
|
||||
}
|
||||
}
|
||||
}
|
||||
return out ?? node
|
||||
}
|
||||
return node
|
||||
}
|
||||
|
||||
function conditions(c) {
|
||||
if (Array.isArray(c)) return c.filter(isObj)
|
||||
if (isObj(c)) return Object.keys(c).map((k) => ({ path: k, mode: "full", value: c[k] }))
|
||||
return []
|
||||
}
|
||||
|
||||
// when says whether the conditions hold: any of them (New API's default,
|
||||
// OR), or all with logic AND. None hold always.
|
||||
function when(body, req, raw, logic) {
|
||||
const cs = conditions(raw)
|
||||
if (!cs.length) return true
|
||||
const hit = (c) => {
|
||||
let v = lookup(body, String(c.path ?? ""))
|
||||
if (v === undefined) v = lookup(req, String(c.path ?? ""))
|
||||
if (v === undefined) return !!c.pass_missing_key
|
||||
const r = compare(v, c.value, String(c.mode || "full").toLowerCase())
|
||||
return c.invert ? !r : r
|
||||
}
|
||||
return String(logic).toUpperCase() === "AND" ? cs.every(hit) : cs.some(hit)
|
||||
}
|
||||
|
||||
function lookup(root, path) {
|
||||
const ps = resolve(root, split(path))
|
||||
return ps.length === 1 ? getAt(root, ps[0]) : undefined
|
||||
}
|
||||
|
||||
function compare(v, t, mode) {
|
||||
const s = (x) => (typeof x === "string" ? x : JSON.stringify(x))
|
||||
switch (mode) {
|
||||
case "full":
|
||||
if (v === null || t === null || typeof v !== typeof t) return v === t
|
||||
return typeof v === "object" ? JSON.stringify(v) === JSON.stringify(t) : v === t
|
||||
case "prefix":
|
||||
return s(v).startsWith(s(t))
|
||||
case "suffix":
|
||||
return s(v).endsWith(s(t))
|
||||
case "contains":
|
||||
return s(v).includes(s(t))
|
||||
case "gt":
|
||||
case "gte":
|
||||
case "lt":
|
||||
case "lte":
|
||||
if (typeof v !== "number" || typeof t !== "number") return false
|
||||
return mode === "gt" ? v > t : mode === "gte" ? v >= t : mode === "lt" ? v < t : v <= t
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// split is a gjson path's keys: "a.b\.c.0" is a, b.c, 0
|
||||
function split(path) {
|
||||
path = String(path ?? "")
|
||||
if (!path) return []
|
||||
const out = []
|
||||
let cur = ""
|
||||
for (let i = 0; i < path.length; i++) {
|
||||
const c = path[i]
|
||||
if (c === "\\" && i + 1 < path.length) cur += path[++i]
|
||||
else if (c === ".") {
|
||||
out.push(cur)
|
||||
cur = ""
|
||||
} else cur += c
|
||||
}
|
||||
out.push(cur)
|
||||
return out
|
||||
}
|
||||
|
||||
// resolve is the concrete paths keys stand for in root: "*" is each key or
|
||||
// index there, "-1" an array's last. A key not there yet resolves (set makes
|
||||
// it); a wildcard over nothing resolves to nothing.
|
||||
function resolve(root, keys) {
|
||||
let paths = [[]]
|
||||
for (const k of keys) {
|
||||
const next = []
|
||||
for (const p of paths) {
|
||||
const node = getAt(root, p)
|
||||
if (k === "*") {
|
||||
if (Array.isArray(node)) node.forEach((_, i) => next.push(p.concat(i)))
|
||||
else if (isObj(node)) Object.keys(node).sort().forEach((key) => next.push(p.concat(key)))
|
||||
} else if (Array.isArray(node)) {
|
||||
let i = /^-?\d+$/.test(k) ? Number(k) : NaN
|
||||
if (i < 0) i += node.length
|
||||
if (i >= 0 && i < node.length) next.push(p.concat(i))
|
||||
} else if (node === undefined || isObj(node)) next.push(p.concat(k))
|
||||
}
|
||||
paths = next
|
||||
}
|
||||
return paths
|
||||
}
|
||||
|
||||
function getAt(root, p) {
|
||||
let n = root
|
||||
for (const k of p) {
|
||||
if (n === null || typeof n !== "object") return undefined
|
||||
n = n[k]
|
||||
}
|
||||
return n
|
||||
}
|
||||
|
||||
function setAt(root, p, v) {
|
||||
if (!p.length) return v
|
||||
let n = root
|
||||
for (let i = 0; i < p.length - 1; i++) {
|
||||
if (n[p[i]] === null || typeof n[p[i]] !== "object") n[p[i]] = {}
|
||||
n = n[p[i]]
|
||||
}
|
||||
n[p[p.length - 1]] = v
|
||||
return root
|
||||
}
|
||||
|
||||
function delAt(root, p) {
|
||||
const parent = getAt(root, p.slice(0, -1))
|
||||
const k = p[p.length - 1]
|
||||
if (Array.isArray(parent)) parent.splice(k, 1)
|
||||
else if (isObj(parent)) delete parent[k]
|
||||
}
|
||||
|
||||
// goRegexp is New API's (Go's) pattern as JavaScript's: Go's leading flag
|
||||
// group (?i) becomes a flag, and every match is replaced, as Go's
|
||||
// ReplaceAllString does.
|
||||
function goRegexp(src) {
|
||||
let flags = "g"
|
||||
const m = /^\(\?([imsU]+)\)/.exec(src)
|
||||
if (m) {
|
||||
src = src.slice(m[0].length)
|
||||
for (const f of m[1]) if (f !== "U" && !flags.includes(f)) flags += f
|
||||
}
|
||||
return new RegExp(src.replace(/\(\?P</g, "(?<"), flags)
|
||||
}
|
||||
|
||||
// goReplacement is Go's ${1} and ${name} as JavaScript's $1 and $<name>
|
||||
function goReplacement(to) {
|
||||
return to.replace(/\$\{(\d+)\}/g, "$$$1").replace(/\$\{([A-Za-z_]\w*)\}/g, "$$<$1>")
|
||||
}
|
||||
|
||||
function clone(v) {
|
||||
return v === undefined || v === null || typeof v !== "object" ? v : JSON.parse(JSON.stringify(v))
|
||||
}
|
||||
|
||||
function isObj(v) {
|
||||
return v !== null && typeof v === "object" && !Array.isArray(v)
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
import * as mod from "./param-override.middleware.js"
|
||||
import { check } from "../../scripts/middleware.mjs"
|
||||
|
||||
check(import.meta.dir, mod)
|
||||
@@ -0,0 +1,31 @@
|
||||
# @magpie-community/middleware-system-prompt
|
||||
|
||||
New API's **系统提示词** (a channel's `system_prompt` and its override switch) as [magpie](https://usemagpie.ai) gateway middleware. It gives the requests agents send a system prompt of yours, in each API's own place for one:
|
||||
|
||||
| API | Where the prompt goes |
|
||||
| --- | --- |
|
||||
| Anthropic | `system` |
|
||||
| Chat | the first `system` or `developer` message |
|
||||
| Responses | `instructions` |
|
||||
| Gemini | `systemInstruction` |
|
||||
|
||||
Install it from magpie's **Plugins › Discover**, or with `magpie plugin add @magpie-community/middleware-system-prompt`. Set its options under **Plugins › Installed › Options**, or with `magpie plugin options system-prompt '<json>'`.
|
||||
|
||||
## Options
|
||||
|
||||
```json
|
||||
{ "system_prompt": "Reply in the language the user writes in.",
|
||||
"override": true, "position": "append",
|
||||
"agents": ["claude"], "models": ["deepseek"] }
|
||||
```
|
||||
|
||||
- **No system prompt yet.** A request without one gets yours.
|
||||
- **`override`.** A request that has its own prompt keeps it unchanged, unless `override` is `true`. Then yours goes in as well, placed by `position`:
|
||||
- `"append"` (the default) puts yours after it. Agents cache their own prompt, so adding after it keeps that cache.
|
||||
- `"prepend"` puts yours before it, as New API does. This makes the provider read the whole prompt again on every turn.
|
||||
- **`agents`.** When given, the prompt applies only to these agents, by magpie's agent ids: `claude`, `codex`, `opencode`, and so on.
|
||||
- **`models`.** When given, the prompt applies only to models whose names begin with one of these prefixes.
|
||||
|
||||
Codex sends its own model instructions, and changing them can change how its models behave. Use `agents` to leave Codex out if you don't want that.
|
||||
|
||||
中文:New API 的「系统提示词」,作为 magpie 网关中间件。默认把你的提示词加在 agent 自己的提示词之后,这样不会破坏提示缓存。
|
||||
@@ -0,0 +1,48 @@
|
||||
[
|
||||
{ "name": "Anthropic: none is given this one",
|
||||
"options": { "system_prompt": "Be brief." },
|
||||
"request": { "model": "m", "messages": [] },
|
||||
"expect_request": { "model": "m", "messages": [], "system": "Be brief." } },
|
||||
{ "name": "Anthropic: an agent's own stays without override",
|
||||
"options": { "system_prompt": "Be brief." },
|
||||
"request": { "model": "m", "system": "You code." } },
|
||||
{ "name": "Anthropic: override appends a block after the cached ones",
|
||||
"options": { "system_prompt": "Be brief.", "override": true },
|
||||
"request": { "model": "m", "system": [{ "type": "text", "text": "You code.", "cache_control": { "type": "ephemeral" } }] },
|
||||
"expect_request": { "model": "m", "system": [{ "type": "text", "text": "You code.", "cache_control": { "type": "ephemeral" } }, { "type": "text", "text": "Be brief." }] } },
|
||||
{ "name": "Anthropic: override prepends to a string, New API's way",
|
||||
"options": { "system_prompt": "Be brief.", "override": true, "position": "prepend" },
|
||||
"request": { "model": "m", "system": "You code." },
|
||||
"expect_request": { "model": "m", "system": "Be brief.\nYou code." } },
|
||||
{ "name": "Chat: a system message first",
|
||||
"ctx": { "protocol": "chat" },
|
||||
"options": { "system_prompt": "Be brief." },
|
||||
"request": { "model": "m", "messages": [{ "role": "user", "content": "hi" }] },
|
||||
"expect_request": { "model": "m", "messages": [{ "role": "system", "content": "Be brief." }, { "role": "user", "content": "hi" }] } },
|
||||
{ "name": "Chat: override on a developer message",
|
||||
"ctx": { "protocol": "chat" },
|
||||
"options": { "system_prompt": "Be brief.", "override": true },
|
||||
"request": { "model": "m", "messages": [{ "role": "developer", "content": "You code." }, { "role": "user", "content": "hi" }] },
|
||||
"expect_request": { "model": "m", "messages": [{ "role": "developer", "content": "You code.\nBe brief." }, { "role": "user", "content": "hi" }] } },
|
||||
{ "name": "Responses: instructions",
|
||||
"ctx": { "protocol": "responses" },
|
||||
"options": { "system_prompt": "Be brief.", "override": true },
|
||||
"request": { "model": "m", "instructions": "You code.", "input": [] },
|
||||
"expect_request": { "model": "m", "instructions": "You code.\nBe brief.", "input": [] } },
|
||||
{ "name": "Gemini: systemInstruction",
|
||||
"ctx": { "protocol": "gemini" },
|
||||
"options": { "system_prompt": "Be brief." },
|
||||
"request": { "contents": [] },
|
||||
"expect_request": { "contents": [], "systemInstruction": { "parts": [{ "text": "Be brief." }] } } },
|
||||
{ "name": "only the agents named",
|
||||
"ctx": { "agent": "codex" },
|
||||
"options": { "system_prompt": "Be brief.", "agents": ["claude"] },
|
||||
"request": { "model": "m" } },
|
||||
{ "name": "only the models named",
|
||||
"options": { "system_prompt": "Be brief.", "models": ["deepseek"] },
|
||||
"request": { "model": "deepseek-chat" },
|
||||
"expect_request": { "model": "deepseek-chat", "system": "Be brief." } },
|
||||
{ "name": "no prompt, nothing done",
|
||||
"options": {},
|
||||
"request": { "model": "m" } }
|
||||
]
|
||||
@@ -0,0 +1,14 @@
|
||||
{
|
||||
"name": "@magpie-community/middleware-system-prompt",
|
||||
"version": "0.1.0",
|
||||
"description": "New API's system_prompt (系统提示词) as magpie gateway middleware: give agents' requests a system prompt of yours, in each API's own place for it",
|
||||
"type": "module",
|
||||
"files": ["system-prompt.middleware.js", "README.md"],
|
||||
"keywords": ["magpie", "magpie-middleware", "new-api", "system-prompt", "llm-gateway"],
|
||||
"license": "MIT",
|
||||
"repository": { "type": "git", "url": "git+https://github.com/magpie-community/plugins.git", "directory": "packages/system-prompt" },
|
||||
"magpie": {
|
||||
"middleware": "./system-prompt.middleware.js",
|
||||
"options": { "system_prompt": "Reply in the language the user writes in.", "override": true, "position": "append" }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,91 @@
|
||||
// New API's 系统提示词 (a channel's system_prompt, with its "override"
|
||||
// switch) as magpie gateway middleware, in each agent API's own place for
|
||||
// it: Anthropic's system, Chat's first system or developer message,
|
||||
// Responses' instructions, Gemini's systemInstruction.
|
||||
//
|
||||
// {"system_prompt": "Answer in English.", "override": false,
|
||||
// "position": "append", "agents": [], "models": []}
|
||||
//
|
||||
// A request with no system prompt is given this one. One that has its own
|
||||
// keeps it as it is, unless override is true: then this one is added
|
||||
// before it ("prepend", New API's way) or after it ("append", the
|
||||
// default, which keeps a prompt cache on the agent's own prompt). agents
|
||||
// and models, when given, are the only agents and model name prefixes it
|
||||
// applies to.
|
||||
|
||||
export function onRequest(body, ctx) {
|
||||
const o = ctx.options || {}
|
||||
const prompt = typeof o.system_prompt === "string" ? o.system_prompt : ""
|
||||
if (!prompt) return
|
||||
if (Array.isArray(o.agents) && o.agents.length && !o.agents.includes(ctx.agent)) return
|
||||
if (Array.isArray(o.models) && o.models.length && !o.models.some((m) => typeof m === "string" && String(body.model ?? ctx.model ?? "").startsWith(m))) return
|
||||
const before = o.position === "prepend"
|
||||
const over = !!o.override
|
||||
switch (ctx.protocol) {
|
||||
case "anthropic":
|
||||
return anthropic(body, prompt, over, before)
|
||||
case "chat":
|
||||
return chat(body, prompt, over, before)
|
||||
case "responses":
|
||||
return responses(body, prompt, over, before)
|
||||
case "gemini":
|
||||
return gemini(body, prompt, over, before)
|
||||
}
|
||||
}
|
||||
|
||||
function anthropic(body, prompt, over, before) {
|
||||
const s = body.system
|
||||
if (s === undefined || s === null || s === "" || (Array.isArray(s) && !s.length)) {
|
||||
body.system = prompt
|
||||
return body
|
||||
}
|
||||
if (!over) return
|
||||
if (typeof s === "string") body.system = before ? prompt + "\n" + s : s + "\n" + prompt
|
||||
else if (Array.isArray(s)) {
|
||||
const block = { type: "text", text: prompt }
|
||||
if (before) s.unshift(block)
|
||||
else s.push(block)
|
||||
} else return
|
||||
return body
|
||||
}
|
||||
|
||||
function chat(body, prompt, over, before) {
|
||||
if (!Array.isArray(body.messages)) return
|
||||
const first = body.messages[0]
|
||||
if (!first || (first.role !== "system" && first.role !== "developer")) {
|
||||
body.messages.unshift({ role: "system", content: prompt })
|
||||
return body
|
||||
}
|
||||
if (!over) return
|
||||
if (typeof first.content === "string") first.content = before ? prompt + "\n" + first.content : first.content + "\n" + prompt
|
||||
else if (Array.isArray(first.content)) {
|
||||
const part = { type: "text", text: prompt }
|
||||
if (before) first.content.unshift(part)
|
||||
else first.content.push(part)
|
||||
} else return
|
||||
return body
|
||||
}
|
||||
|
||||
function responses(body, prompt, over, before) {
|
||||
const s = body.instructions
|
||||
if (typeof s !== "string" || !s) {
|
||||
body.instructions = prompt
|
||||
return body
|
||||
}
|
||||
if (!over) return
|
||||
body.instructions = before ? prompt + "\n" + s : s + "\n" + prompt
|
||||
return body
|
||||
}
|
||||
|
||||
function gemini(body, prompt, over, before) {
|
||||
const key = body.system_instruction && !body.systemInstruction ? "system_instruction" : "systemInstruction"
|
||||
const s = body[key]
|
||||
if (!s || !Array.isArray(s.parts) || !s.parts.length) {
|
||||
body[key] = { parts: [{ text: prompt }] }
|
||||
return body
|
||||
}
|
||||
if (!over) return
|
||||
if (before) s.parts.unshift({ text: prompt })
|
||||
else s.parts.push({ text: prompt })
|
||||
return body
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
import * as mod from "./system-prompt.middleware.js"
|
||||
import { check } from "../../scripts/middleware.mjs"
|
||||
|
||||
check(import.meta.dir, mod)
|
||||
@@ -0,0 +1,24 @@
|
||||
# @magpie-community/middleware-think-tags
|
||||
|
||||
A model's thinking, where its reply's text is, as [magpie](https://usemagpie.ai) gateway middleware. It either takes thinking out of the text, or puts it in (New API's `thinking_to_content`).
|
||||
|
||||
Install it from magpie's **Plugins › Discover**, or with `magpie plugin add @magpie-community/middleware-think-tags`. Set its options under **Plugins › Installed › Options**, or with `magpie plugin options think-tags '<json>'`.
|
||||
|
||||
## Options
|
||||
|
||||
```json
|
||||
{ "mode": "strip" }
|
||||
```
|
||||
|
||||
**`strip`** (the default). Some models (open reasoning models served by vLLM, Ollama and many relays) write their thinking into the reply as `<think>…</think>`. This mode takes that block out, so an agent doesn't keep it in its history and send it back every turn.
|
||||
|
||||
- Only a block at the start of the text is taken out. A `<think>` the model writes later, in code for example, stays.
|
||||
- A tag split across streamed chunks is still found.
|
||||
- It works on Anthropic, Chat and Responses replies, streamed or whole.
|
||||
|
||||
**`to_content`**. A Chat reply's `reasoning_content` (or `reasoning`) is put into its text as `<think>…</think>`, for a client that shows only the text.
|
||||
|
||||
- This mode works on Chat replies only. An Anthropic thinking block carries a signature, and turned into text it would fail the next turn.
|
||||
- It changes what the agent keeps and sends back, so it suits a chat client better than a coding agent.
|
||||
|
||||
中文:`strip` 去掉回复开头模型写出的 `<think>…</think>`;`to_content` 把 Chat 回复的 reasoning_content 放进正文(New API 的 thinking_to_content)。
|
||||
@@ -0,0 +1,67 @@
|
||||
[
|
||||
{ "name": "strip: a think block split across Chat chunks",
|
||||
"ctx": { "protocol": "chat", "stream": true },
|
||||
"events": [
|
||||
{ "data": { "choices": [{ "index": 0, "delta": { "role": "assistant", "content": "<thi" } }] } },
|
||||
{ "data": { "choices": [{ "index": 0, "delta": { "content": "nk>plan it" } }] } },
|
||||
{ "data": { "choices": [{ "index": 0, "delta": { "content": " out</th" } }] } },
|
||||
{ "data": { "choices": [{ "index": 0, "delta": { "content": "ink>\n\nHello" } }] } },
|
||||
{ "data": { "choices": [{ "index": 0, "delta": { "content": " <think> stays" } }] } },
|
||||
{ "data": { "choices": [{ "index": 0, "delta": {}, "finish_reason": "stop" }] } },
|
||||
{ "data": "[DONE]" }],
|
||||
"expect_events": [
|
||||
{ "choices": [{ "index": 0, "delta": { "role": "assistant", "content": "" } }] },
|
||||
{ "choices": [{ "index": 0, "delta": { "content": "" } }] },
|
||||
{ "choices": [{ "index": 0, "delta": { "content": "" } }] },
|
||||
{ "choices": [{ "index": 0, "delta": { "content": "Hello" } }] },
|
||||
{ "choices": [{ "index": 0, "delta": { "content": " <think> stays" } }] },
|
||||
{ "choices": [{ "index": 0, "delta": {}, "finish_reason": "stop" }] },
|
||||
"[DONE]"] },
|
||||
{ "name": "strip: text without a block passes untouched",
|
||||
"ctx": { "protocol": "chat", "stream": true },
|
||||
"events": [
|
||||
{ "data": { "choices": [{ "index": 0, "delta": { "content": "a < b" } }] } },
|
||||
{ "data": { "choices": [{ "index": 0, "delta": { "content": "<think>" } }] } }] },
|
||||
{ "name": "strip: a stream that ends on held text gives it back",
|
||||
"ctx": { "protocol": "chat", "stream": true },
|
||||
"events": [
|
||||
{ "data": { "choices": [{ "index": 0, "delta": { "content": "<" } }] } },
|
||||
{ "data": { "choices": [{ "index": 0, "delta": {}, "finish_reason": "stop" }] } }],
|
||||
"expect_events": [
|
||||
{ "choices": [{ "index": 0, "delta": { "content": "" } }] },
|
||||
{ "choices": [{ "index": 0, "delta": { "content": "<" }, "finish_reason": "stop" }] }] },
|
||||
{ "name": "strip: Anthropic text deltas",
|
||||
"events": [
|
||||
{ "event": "content_block_delta", "data": { "type": "content_block_delta", "index": 0, "delta": { "type": "text_delta", "text": "<think>x</think>" } } },
|
||||
{ "event": "content_block_delta", "data": { "type": "content_block_delta", "index": 0, "delta": { "type": "text_delta", "text": "\nDone." } } },
|
||||
{ "event": "content_block_delta", "data": { "type": "content_block_delta", "index": 1, "delta": { "type": "input_json_delta", "partial_json": "<think>" } } }],
|
||||
"expect_events": [
|
||||
{ "type": "content_block_delta", "index": 0, "delta": { "type": "text_delta", "text": "" } },
|
||||
{ "type": "content_block_delta", "index": 0, "delta": { "type": "text_delta", "text": "Done." } },
|
||||
{ "type": "content_block_delta", "index": 1, "delta": { "type": "input_json_delta", "partial_json": "<think>" } }] },
|
||||
{ "name": "strip: whole replies",
|
||||
"response": { "content": [{ "type": "text", "text": "<think>\nhmm\n</think>\n\nHi" }] },
|
||||
"expect_response": { "content": [{ "type": "text", "text": "Hi" }] } },
|
||||
{ "name": "strip: a whole Chat reply",
|
||||
"ctx": { "protocol": "chat" },
|
||||
"response": { "choices": [{ "message": { "content": "<think>x</think>Hi" } }] },
|
||||
"expect_response": { "choices": [{ "message": { "content": "Hi" } }] } },
|
||||
{ "name": "to_content: reasoning_content into the text",
|
||||
"ctx": { "protocol": "chat", "stream": true },
|
||||
"options": { "mode": "to_content" },
|
||||
"events": [
|
||||
{ "data": { "choices": [{ "index": 0, "delta": { "role": "assistant", "reasoning_content": "Let me" } }] } },
|
||||
{ "data": { "choices": [{ "index": 0, "delta": { "reasoning_content": " see." } }] } },
|
||||
{ "data": { "choices": [{ "index": 0, "delta": { "content": "Hi" } }] } },
|
||||
{ "data": { "choices": [{ "index": 0, "delta": { "content": "!" }, "finish_reason": "stop" }] } }],
|
||||
"expect_events": [
|
||||
{ "choices": [{ "index": 0, "delta": { "role": "assistant", "content": "<think>\nLet me" } }] },
|
||||
{ "choices": [{ "index": 0, "delta": { "content": " see." } }] },
|
||||
{ "choices": [{ "index": 0, "delta": { "content": "\n</think>\n\nHi" } }] },
|
||||
{ "choices": [{ "index": 0, "delta": { "content": "!" }, "finish_reason": "stop" }] }] },
|
||||
{ "name": "to_content: a whole reply",
|
||||
"ctx": { "protocol": "chat" },
|
||||
"options": { "mode": "to_content" },
|
||||
"response": { "choices": [{ "message": { "role": "assistant", "reasoning_content": "hmm", "content": "Hi" } }] },
|
||||
"expect_response": { "choices": [{ "message": { "role": "assistant", "content": "<think>\nhmm\n</think>\n\nHi" } }] } }
|
||||
]
|
||||
@@ -0,0 +1,14 @@
|
||||
{
|
||||
"name": "@magpie-community/middleware-think-tags",
|
||||
"version": "0.1.0",
|
||||
"description": "Take a model's <think>…</think> out of its reply's text, or put a Chat reply's reasoning_content into it (New API's thinking_to_content), as magpie gateway middleware",
|
||||
"type": "module",
|
||||
"files": ["think-tags.middleware.js", "README.md"],
|
||||
"keywords": ["magpie", "magpie-middleware", "new-api", "reasoning", "think", "llm-gateway"],
|
||||
"license": "MIT",
|
||||
"repository": { "type": "git", "url": "git+https://github.com/magpie-community/plugins.git", "directory": "packages/think-tags" },
|
||||
"magpie": {
|
||||
"middleware": "./think-tags.middleware.js",
|
||||
"options": { "mode": "strip" }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,206 @@
|
||||
// A model's thinking, where its reply's text is: New API's
|
||||
// thinking_to_content, and the other way round.
|
||||
//
|
||||
// {"mode": "strip"} (the default)
|
||||
// {"mode": "to_content"}
|
||||
//
|
||||
// "strip": a model that writes its thinking into the reply as
|
||||
// <think>…</think> at the start of its text has that block taken out, so
|
||||
// an agent doesn't keep it in its history and send it back each turn. Only
|
||||
// a block that opens the text is taken; <think> later on, in code the model
|
||||
// writes, stays. Anthropic, Chat and Responses replies, streamed or whole.
|
||||
//
|
||||
// "to_content": a Chat reply's reasoning_content (or reasoning) is put in
|
||||
// its text as <think>…</think>, for a client that shows only the text.
|
||||
// Chat only: an Anthropic thinking block carries a signature, and turned
|
||||
// into text it would fail the next turn. It changes what the agent keeps
|
||||
// and sends back, so it suits a chat client better than a coding agent.
|
||||
|
||||
const OPEN = "<think>"
|
||||
const CLOSE = "</think>"
|
||||
|
||||
export function onEvent(ev, ctx) {
|
||||
const toContent = ctx.options && ctx.options.mode === "to_content"
|
||||
if (toContent) return Array.isArray(ev.choices) ? reasoningToText(ev, ctx.state) : undefined
|
||||
const st = ctx.state
|
||||
if (ev.type === "content_block_delta" && ev.delta && ev.delta.type === "text_delta") {
|
||||
return edit(ev.delta, "text", strip(st, "a" + ev.index), ev)
|
||||
}
|
||||
if (ev.type === "response.output_text.delta") return edit(ev, "delta", strip(st, "r" + ev.item_id + ":" + ev.content_index), ev)
|
||||
if (ev.type === "response.output_text.done" && typeof ev.text === "string") return edit(ev, "text", stripWhole, ev)
|
||||
if (ev.type === "response.content_part.done" && ev.part && typeof ev.part.text === "string") return edit(ev.part, "text", stripWhole, ev)
|
||||
if (ev.type === "response.output_item.done" && ev.item) return stripItem(ev.item) ? ev : undefined
|
||||
if (ev.type === "response.completed" && ev.response && Array.isArray(ev.response.output)) {
|
||||
let changed = false
|
||||
for (const it of ev.response.output) changed = stripItem(it) || changed
|
||||
return changed ? ev : undefined
|
||||
}
|
||||
if (Array.isArray(ev.choices)) {
|
||||
let changed = false
|
||||
for (const c of ev.choices) {
|
||||
if (!c || !c.delta) continue
|
||||
const s = strip(st, "c" + c.index)
|
||||
if (typeof c.delta.content === "string") {
|
||||
const u = s(c.delta.content)
|
||||
if (u !== c.delta.content) {
|
||||
c.delta.content = u
|
||||
changed = true
|
||||
}
|
||||
}
|
||||
// a stream that ends while text is held back gives it back
|
||||
if (c.finish_reason && st["c" + c.index] && st["c" + c.index].carry) {
|
||||
c.delta.content = (c.delta.content || "") + st["c" + c.index].carry
|
||||
st["c" + c.index].carry = ""
|
||||
changed = true
|
||||
}
|
||||
}
|
||||
return changed ? ev : undefined
|
||||
}
|
||||
}
|
||||
|
||||
export function onResponse(body, ctx) {
|
||||
if (ctx.status >= 400) return
|
||||
let changed = false
|
||||
const fix = (o, k) => {
|
||||
if (o && typeof o[k] === "string") {
|
||||
const u = stripWhole(o[k])
|
||||
if (u !== o[k]) {
|
||||
o[k] = u
|
||||
changed = true
|
||||
}
|
||||
}
|
||||
}
|
||||
if (ctx.options && ctx.options.mode === "to_content") {
|
||||
if (!Array.isArray(body.choices)) return
|
||||
for (const c of body.choices) {
|
||||
const m = c && c.message
|
||||
if (!m) continue
|
||||
const r = typeof m.reasoning_content === "string" ? m.reasoning_content : typeof m.reasoning === "string" ? m.reasoning : ""
|
||||
if (!r) continue
|
||||
m.content = OPEN + "\n" + r + "\n" + CLOSE + "\n\n" + (m.content || "")
|
||||
delete m.reasoning_content
|
||||
delete m.reasoning
|
||||
changed = true
|
||||
}
|
||||
return changed ? body : undefined
|
||||
}
|
||||
if (Array.isArray(body.content)) {
|
||||
const first = body.content.find((b) => b && b.type === "text")
|
||||
fix(first, "text")
|
||||
}
|
||||
if (Array.isArray(body.choices)) for (const c of body.choices) fix(c && c.message, "content")
|
||||
if (Array.isArray(body.output)) for (const it of body.output) changed = stripItem(it) || changed
|
||||
return changed ? body : undefined
|
||||
}
|
||||
|
||||
function edit(obj, key, f, ev) {
|
||||
if (!obj || typeof obj[key] !== "string") return
|
||||
const u = f(obj[key])
|
||||
if (u === obj[key]) return
|
||||
obj[key] = u
|
||||
return ev
|
||||
}
|
||||
|
||||
function stripItem(it) {
|
||||
if (!it || it.type !== "message" || !Array.isArray(it.content)) return false
|
||||
const p = it.content.find((x) => x && x.type === "output_text")
|
||||
if (!p || typeof p.text !== "string") return false
|
||||
const u = stripWhole(p.text)
|
||||
if (u === p.text) return false
|
||||
p.text = u
|
||||
return true
|
||||
}
|
||||
|
||||
// stripWhole takes a think block off the start of a whole text
|
||||
function stripWhole(t) {
|
||||
const m = /^\s*<think>[\s\S]*?<\/think>\s*/.exec(t)
|
||||
return m ? t.slice(m[0].length) : t
|
||||
}
|
||||
|
||||
// strip is a stream's text, a piece at a time, without a think block at
|
||||
// its start. Its state, by stream: inside the block, text held back that
|
||||
// may be the start of a tag, whether the text has begun.
|
||||
function strip(state, key) {
|
||||
const st = state[key] || (state[key] = { inside: false, carry: "", begun: false, trim: false })
|
||||
return (piece) => {
|
||||
if (st.begun) return piece
|
||||
let s = st.carry + piece
|
||||
st.carry = ""
|
||||
let out = ""
|
||||
for (;;) {
|
||||
if (st.inside) {
|
||||
const i = s.indexOf(CLOSE)
|
||||
if (i < 0) {
|
||||
st.carry = tail(s, CLOSE)
|
||||
return out
|
||||
}
|
||||
s = s.slice(i + CLOSE.length)
|
||||
st.inside = false
|
||||
st.trim = true
|
||||
continue
|
||||
}
|
||||
if (st.trim) {
|
||||
s = s.replace(/^\s+/, "")
|
||||
if (!s) return out
|
||||
st.trim = false
|
||||
st.begun = true
|
||||
return out + s
|
||||
}
|
||||
const lead = /^\s*/.exec(s)[0]
|
||||
const rest = s.slice(lead.length)
|
||||
if (rest.startsWith(OPEN)) {
|
||||
s = rest.slice(OPEN.length)
|
||||
st.inside = true
|
||||
continue
|
||||
}
|
||||
if (rest.length < OPEN.length && OPEN.startsWith(rest)) {
|
||||
// maybe the start of <think>: wait for the next piece
|
||||
st.carry = s
|
||||
return out
|
||||
}
|
||||
st.begun = true
|
||||
return out + s
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// tail is the end of s that may begin tag
|
||||
function tail(s, tag) {
|
||||
for (let n = Math.min(tag.length - 1, s.length); n > 0; n--) if (tag.startsWith(s.slice(s.length - n))) return s.slice(s.length - n)
|
||||
return ""
|
||||
}
|
||||
|
||||
// reasoningToText moves a Chat chunk's reasoning into its text, opening
|
||||
// <think> on the first and closing it when the text or the end comes.
|
||||
function reasoningToText(ev, state) {
|
||||
let changed = false
|
||||
for (const c of ev.choices) {
|
||||
const d = c && c.delta
|
||||
if (!d) continue
|
||||
const key = "t" + c.index
|
||||
const r = typeof d.reasoning_content === "string" ? d.reasoning_content : typeof d.reasoning === "string" ? d.reasoning : null
|
||||
let text = ""
|
||||
if (r !== null) {
|
||||
delete d.reasoning_content
|
||||
delete d.reasoning
|
||||
changed = true
|
||||
if (r) {
|
||||
if (!state[key]) {
|
||||
state[key] = "open"
|
||||
text += OPEN + "\n"
|
||||
}
|
||||
text += r
|
||||
}
|
||||
}
|
||||
const content = typeof d.content === "string" ? d.content : ""
|
||||
if (state[key] === "open" && (content || c.finish_reason)) {
|
||||
text += "\n" + CLOSE + "\n\n"
|
||||
state[key] = "closed"
|
||||
}
|
||||
if (text) {
|
||||
d.content = text + content
|
||||
changed = true
|
||||
}
|
||||
}
|
||||
return changed ? ev : undefined
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
import * as mod from "./think-tags.middleware.js"
|
||||
import { check } from "../../scripts/middleware.mjs"
|
||||
|
||||
check(import.meta.dir, mod)
|
||||
@@ -0,0 +1,27 @@
|
||||
# @magpie-community/middleware-word-guard
|
||||
|
||||
New API's **敏感词过滤** as [magpie](https://usemagpie.ai) gateway middleware. It keeps the words and patterns you list out of what agents send: a request with one is turned away, or has the word masked. It can mask them in replies too.
|
||||
|
||||
Install it from magpie's **Plugins › Discover**, or with `magpie plugin add @magpie-community/middleware-word-guard`. Set its options under **Plugins › Installed › Options**, or with `magpie plugin options word-guard '<json>'`.
|
||||
|
||||
## Options
|
||||
|
||||
```json
|
||||
{ "words": ["project-codename"],
|
||||
"patterns": ["\\b\\d{3}-\\d{4}\\b"],
|
||||
"action": "reject",
|
||||
"check": "last" }
|
||||
```
|
||||
|
||||
- **`words`.** Words matched anywhere in the text, ignoring case.
|
||||
- **`patterns`.** Regular expressions, also matched ignoring case.
|
||||
- **`action`.** `reject` (the default) turns the request away with a 400 that names the word, in the agent's API's error shape. `mask` replaces each match with `mask` (default `***`) and sends the request on.
|
||||
- **`check`.** `last` (the default) reads only the last user message that has text, which is the turn being sent. That is what New API reads. `all` reads every user message, so a word earlier in the conversation keeps turning requests away.
|
||||
- **`replies`.** Set it to `true` to mask matches in the text that comes back as well. A word split across two streamed events isn't caught.
|
||||
- **`message`.** The error text to use in place of the default one.
|
||||
|
||||
The middleware reads only the user's own text. It doesn't read tool results, tool calls or the system prompt, so a file an agent reads that contains the word doesn't stop it.
|
||||
|
||||
magpie already redacts secrets (API keys and tokens) before a request leaves your computer, and puts them back in the reply. You don't need this middleware for secrets.
|
||||
|
||||
中文:New API 的「敏感词过滤」,作为 magpie 网关中间件。只检查用户自己写的文字,可拒绝请求或替换成 `***`,也可以替换回复里的词。
|
||||
@@ -0,0 +1,60 @@
|
||||
[
|
||||
{ "name": "a listed word in the last user text is turned away",
|
||||
"options": { "words": ["Project-X"] },
|
||||
"request": { "model": "m", "messages": [{ "role": "user", "content": [{ "type": "text", "text": "tell me about project-x" }] }] },
|
||||
"reject": { "status": 400, "message": "project-x" } },
|
||||
{ "name": "a custom message",
|
||||
"options": { "words": ["secret"], "message": "No." },
|
||||
"request": { "model": "m", "messages": [{ "role": "user", "content": "a secret" }] },
|
||||
"reject": { "status": 400, "message": "No." } },
|
||||
{ "name": "clean text passes untouched",
|
||||
"options": { "words": ["project-x"] },
|
||||
"request": { "model": "m", "messages": [{ "role": "user", "content": "hello" }] } },
|
||||
{ "name": "tool results and earlier turns aren't read with check last",
|
||||
"options": { "words": ["project-x"] },
|
||||
"request": { "model": "m", "messages": [
|
||||
{ "role": "user", "content": "project-x" },
|
||||
{ "role": "assistant", "content": [{ "type": "tool_use", "id": "t", "name": "Read", "input": {} }] },
|
||||
{ "role": "user", "content": [{ "type": "tool_result", "tool_use_id": "t", "content": "project-x" }] },
|
||||
{ "role": "user", "content": [{ "type": "text", "text": "go on" }] }] } },
|
||||
{ "name": "check all reads earlier turns",
|
||||
"options": { "words": ["project-x"], "check": "all" },
|
||||
"request": { "model": "m", "messages": [{ "role": "user", "content": "project-x" }, { "role": "user", "content": "go on" }] },
|
||||
"reject": { "status": 400 } },
|
||||
{ "name": "mask swaps words and patterns",
|
||||
"options": { "words": ["acme"], "patterns": ["\\b\\d{3}-\\d{4}\\b"], "action": "mask", "mask": "[x]" },
|
||||
"request": { "model": "m", "messages": [{ "role": "user", "content": [{ "type": "text", "text": "ACME at 555-1234" }, { "type": "image", "source": {} }] }] },
|
||||
"expect_request": { "model": "m", "messages": [{ "role": "user", "content": [{ "type": "text", "text": "[x] at [x]" }, { "type": "image", "source": {} }] }] } },
|
||||
{ "name": "Chat: string content",
|
||||
"ctx": { "protocol": "chat" },
|
||||
"options": { "words": ["acme"], "action": "mask" },
|
||||
"request": { "model": "m", "messages": [{ "role": "system", "content": "acme" }, { "role": "user", "content": "acme!" }] },
|
||||
"expect_request": { "model": "m", "messages": [{ "role": "system", "content": "acme" }, { "role": "user", "content": "***!" }] } },
|
||||
{ "name": "Responses: input_text",
|
||||
"ctx": { "protocol": "responses" },
|
||||
"options": { "words": ["acme"] },
|
||||
"request": { "model": "m", "input": [{ "role": "user", "content": [{ "type": "input_text", "text": "acme" }] }] },
|
||||
"reject": { "status": 400 } },
|
||||
{ "name": "Gemini: parts",
|
||||
"ctx": { "protocol": "gemini" },
|
||||
"options": { "words": ["acme"], "action": "mask" },
|
||||
"request": { "contents": [{ "role": "user", "parts": [{ "text": "acme" }] }] },
|
||||
"expect_request": { "contents": [{ "role": "user", "parts": [{ "text": "***" }] }] } },
|
||||
{ "name": "replies masked in Anthropic and Chat streams",
|
||||
"options": { "words": ["acme"], "action": "mask", "replies": true },
|
||||
"events": [
|
||||
{ "event": "content_block_delta", "data": { "type": "content_block_delta", "index": 0, "delta": { "type": "text_delta", "text": "Acme Inc" } } },
|
||||
{ "data": { "choices": [{ "index": 0, "delta": { "content": "acme" } }] } },
|
||||
{ "event": "message_stop", "data": { "type": "message_stop" } }],
|
||||
"expect_events": [
|
||||
{ "type": "content_block_delta", "index": 0, "delta": { "type": "text_delta", "text": "*** Inc" } },
|
||||
{ "choices": [{ "index": 0, "delta": { "content": "***" } }] },
|
||||
{ "type": "message_stop" }] },
|
||||
{ "name": "a whole reply masked",
|
||||
"options": { "words": ["acme"], "action": "mask", "replies": true },
|
||||
"response": { "content": [{ "type": "text", "text": "acme" }, { "type": "tool_use", "input": { "q": "acme" } }] },
|
||||
"expect_response": { "content": [{ "type": "text", "text": "***" }, { "type": "tool_use", "input": { "q": "acme" } }] } },
|
||||
{ "name": "replies untouched unless asked",
|
||||
"options": { "words": ["acme"], "action": "mask" },
|
||||
"response": { "content": [{ "type": "text", "text": "acme" }] } }
|
||||
]
|
||||
@@ -0,0 +1,14 @@
|
||||
{
|
||||
"name": "@magpie-community/middleware-word-guard",
|
||||
"version": "0.1.0",
|
||||
"description": "New API's sensitive-word filter (敏感词过滤) as magpie gateway middleware: turn away or mask words and patterns in what agents send, and in replies",
|
||||
"type": "module",
|
||||
"files": ["word-guard.middleware.js", "README.md"],
|
||||
"keywords": ["magpie", "magpie-middleware", "new-api", "sensitive-words", "guardrails", "llm-gateway"],
|
||||
"license": "MIT",
|
||||
"repository": { "type": "git", "url": "git+https://github.com/magpie-community/plugins.git", "directory": "packages/word-guard" },
|
||||
"magpie": {
|
||||
"middleware": "./word-guard.middleware.js",
|
||||
"options": { "words": ["project-codename"], "patterns": [], "action": "reject", "check": "last" }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,134 @@
|
||||
// New API's 敏感词过滤 as magpie gateway middleware: words or patterns you
|
||||
// list are kept out of what agents send, turned away or masked, and can be
|
||||
// masked in what comes back.
|
||||
//
|
||||
// {"words": ["project-x"], "patterns": ["\\b\\d{3}-\\d{4}\\b"],
|
||||
// "action": "reject", "check": "last", "mask": "***",
|
||||
// "replies": false, "message": ""}
|
||||
//
|
||||
// Only the user's own text is read: the API's user messages' text, not
|
||||
// tool results, tool calls or the system prompt. "check": "last" reads the
|
||||
// last user message that has text (New API reads the prompt, that is, the
|
||||
// turn being sent), "all" every user message. Words match ignoring case.
|
||||
// "action": "reject" turns the request away with an error naming the word;
|
||||
// "mask" swaps each match for "mask". "replies": true masks matches in the
|
||||
// text that comes back as well; a word split across two streamed events
|
||||
// isn't seen.
|
||||
|
||||
export function onRequest(body, ctx) {
|
||||
const re = matcher(ctx.options)
|
||||
if (!re) return
|
||||
const o = ctx.options
|
||||
const all = o.check === "all"
|
||||
if (o.action === "mask") {
|
||||
const mask = typeof o.mask === "string" ? o.mask : "***"
|
||||
let changed = false
|
||||
userTexts(body, ctx.protocol, all, (t) => {
|
||||
re.lastIndex = 0
|
||||
const u = t.replace(re, mask)
|
||||
if (u !== t) changed = true
|
||||
return u
|
||||
})
|
||||
return changed ? body : undefined
|
||||
}
|
||||
let hit = null
|
||||
userTexts(body, ctx.protocol, all, (t) => {
|
||||
if (hit === null) {
|
||||
re.lastIndex = 0
|
||||
const m = re.exec(t)
|
||||
if (m) hit = m[0]
|
||||
}
|
||||
return t
|
||||
})
|
||||
if (hit !== null) ctx.reject(400, o.message || `this request has "${hit}", which this gateway doesn't send`)
|
||||
}
|
||||
|
||||
export function onEvent(ev, ctx) {
|
||||
const o = ctx.options
|
||||
if (!o || !o.replies || o.action !== "mask") return
|
||||
const re = matcher(o)
|
||||
if (!re) return
|
||||
const mask = typeof o.mask === "string" ? o.mask : "***"
|
||||
const sub = (t) => {
|
||||
re.lastIndex = 0
|
||||
return typeof t === "string" ? t.replace(re, mask) : t
|
||||
}
|
||||
let changed = false
|
||||
const set = (obj, k) => {
|
||||
if (obj && typeof obj[k] === "string") {
|
||||
const u = sub(obj[k])
|
||||
if (u !== obj[k]) {
|
||||
obj[k] = u
|
||||
changed = true
|
||||
}
|
||||
}
|
||||
}
|
||||
if (ev.type === "content_block_delta") set(ev.delta, "text")
|
||||
else if (ev.type === "response.output_text.delta") set(ev, "delta")
|
||||
else if (ev.type === "response.output_text.done") set(ev, "text")
|
||||
else if (Array.isArray(ev.choices)) for (const c of ev.choices) set(c.delta, "content")
|
||||
return changed ? ev : undefined
|
||||
}
|
||||
|
||||
export function onResponse(body, ctx) {
|
||||
const o = ctx.options
|
||||
if (!o || !o.replies || o.action !== "mask" || ctx.status >= 400) return
|
||||
const re = matcher(o)
|
||||
if (!re) return
|
||||
const mask = typeof o.mask === "string" ? o.mask : "***"
|
||||
let changed = false
|
||||
const fix = (obj, k) => {
|
||||
if (obj && typeof obj[k] === "string") {
|
||||
re.lastIndex = 0
|
||||
const u = obj[k].replace(re, mask)
|
||||
if (u !== obj[k]) {
|
||||
obj[k] = u
|
||||
changed = true
|
||||
}
|
||||
}
|
||||
}
|
||||
if (Array.isArray(body.content)) for (const b of body.content) if (b && b.type === "text") fix(b, "text")
|
||||
if (Array.isArray(body.choices)) for (const c of body.choices) fix(c.message, "content")
|
||||
if (Array.isArray(body.output)) for (const it of body.output) if (it && Array.isArray(it.content)) for (const p of it.content) fix(p, "text")
|
||||
if (Array.isArray(body.candidates)) for (const c of body.candidates) if (c.content && Array.isArray(c.content.parts)) for (const p of c.content.parts) fix(p, "text")
|
||||
return changed ? body : undefined
|
||||
}
|
||||
|
||||
// matcher is one expression for every word and pattern; null for none.
|
||||
// A runtime is kept for a request's hooks, so it is built once a request.
|
||||
let cached = null
|
||||
function matcher(o) {
|
||||
if (!o || typeof o !== "object") return null
|
||||
const key = JSON.stringify([o.words, o.patterns])
|
||||
if (cached && cached.key === key) return cached.re
|
||||
const parts = []
|
||||
for (const w of Array.isArray(o.words) ? o.words : []) if (typeof w === "string" && w.trim()) parts.push(w.trim().replace(/[.*+?^${}()|[\]\\]/g, "\\$&"))
|
||||
for (const p of Array.isArray(o.patterns) ? o.patterns : []) if (typeof p === "string" && p) parts.push("(?:" + p + ")")
|
||||
const re = parts.length ? new RegExp(parts.join("|"), "gi") : null
|
||||
cached = { key, re }
|
||||
return re
|
||||
}
|
||||
|
||||
// userTexts calls fn on each text of the user's own in body, in its API's
|
||||
// shape, and puts back what fn gives: the last user message with text, or
|
||||
// all of them.
|
||||
function userTexts(body, protocol, all, fn) {
|
||||
let msgs = []
|
||||
if (protocol === "gemini") {
|
||||
msgs = (Array.isArray(body.contents) ? body.contents : []).filter((m) => m && (m.role === "user" || !m.role)).map((m) => ({ m, list: m.parts, key: "text", only: (p) => p && typeof p.text === "string" }))
|
||||
} else if (protocol === "responses") {
|
||||
if (typeof body.input === "string") {
|
||||
body.input = fn(body.input)
|
||||
return
|
||||
}
|
||||
msgs = (Array.isArray(body.input) ? body.input : []).filter((m) => m && m.role === "user").map((m) => ({ m, list: m.content, key: "text", only: (p) => p && (p.type === "input_text" || p.type === "text") }))
|
||||
} else {
|
||||
msgs = (Array.isArray(body.messages) ? body.messages : []).filter((m) => m && m.role === "user").map((m) => ({ m, list: m.content, key: "text", only: (p) => p && p.type === "text" }))
|
||||
}
|
||||
const hasText = (x) => typeof x.m.content === "string" || (Array.isArray(x.list) && x.list.some(x.only))
|
||||
const chosen = all ? msgs.filter(hasText) : msgs.filter(hasText).slice(-1)
|
||||
for (const x of chosen) {
|
||||
if (typeof x.m.content === "string") x.m.content = fn(x.m.content)
|
||||
else for (const p of x.list) if (x.only(p)) p[x.key] = fn(p[x.key])
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
import * as mod from "./word-guard.middleware.js"
|
||||
import { check } from "../../scripts/middleware.mjs"
|
||||
|
||||
check(import.meta.dir, mod)
|
||||
+11
-1
@@ -28,6 +28,16 @@
|
||||
{ "package": "@magpie-community/opencode-cline-auth", "name": "Cline", "icon": "cline", "providers": ["cline"], "community": true,
|
||||
"summary": { "en": "Cline's models on your own Cline account — usage billing, ClinePass and Cline's free models — with Cline's device sign-in or an API key.", "zh": "用自己的 Cline 账号使用 Cline 的模型——用量计费、ClinePass 与免费模型——支持 Cline 设备登录或 API key。" } },
|
||||
{ "package": "@magpie-community/opencode-trae-auth", "name": "Trae", "icon": "trae", "providers": ["trae-cn", "trae-global"], "community": true,
|
||||
"summary": { "en": "Trae CN (trae.cn) and Trae international (trae.ai) models with your own account, free tier included — Trae's own browser sign-in. Experimental.", "zh": "用 Trae CN(trae.cn)与 Trae 国际版(trae.ai)账号使用各自的模型,含免费版,使用 Trae 自己的浏览器登录。实验性。" } }
|
||||
"summary": { "en": "Trae CN (trae.cn) and Trae international (trae.ai) models with your own account, free tier included — Trae's own browser sign-in. Experimental.", "zh": "用 Trae CN(trae.cn)与 Trae 国际版(trae.ai)账号使用各自的模型,含免费版,使用 Trae 自己的浏览器登录。实验性。" } },
|
||||
{ "package": "@magpie-community/middleware-param-override", "name": "Param Override", "kind": "middleware", "community": true,
|
||||
"summary": { "en": "New API's parameter override: set, delete, move or rewrite fields of every request, by model or by condition.", "zh": "New API 的参数覆盖:按模型或条件设置、删除、移动或改写每个请求的字段。" } },
|
||||
{ "package": "@magpie-community/middleware-model-map", "name": "Model Map", "kind": "middleware", "community": true,
|
||||
"summary": { "en": "New API's model redirection: send a model under another name, by name or pattern; replies keep the name asked for.", "zh": "New API 的模型重定向:按名称或正则把模型换成另一个发出,回复里仍是原来的名字。" } },
|
||||
{ "package": "@magpie-community/middleware-system-prompt", "name": "System Prompt", "kind": "middleware", "community": true,
|
||||
"summary": { "en": "Add your own system prompt to every request, or only some agents' or models', in each API's own place.", "zh": "给每个请求(或指定 agent、模型)加上自己的系统提示词,放在各 API 自己的位置。" } },
|
||||
{ "package": "@magpie-community/middleware-word-guard", "name": "Word Guard", "kind": "middleware", "community": true,
|
||||
"summary": { "en": "New API's sensitive-word filter: turn away or mask words and patterns in what you send, and in replies.", "zh": "New API 的敏感词过滤:拒绝或替换你发出的内容和回复里的词与正则。" } },
|
||||
{ "package": "@magpie-community/middleware-think-tags", "name": "Think Tags", "kind": "middleware", "community": true,
|
||||
"summary": { "en": "Take a model's <think>…</think> out of its reply's text, or put a Chat reply's reasoning into it.", "zh": "去掉回复正文开头的 <think>…</think>,或把 Chat 回复的思考内容放进正文。" } }
|
||||
]
|
||||
}
|
||||
|
||||
@@ -14,6 +14,8 @@ for (const name of readdirSync(root)) {
|
||||
const pj = join(dir, "package.json")
|
||||
if (!existsSync(pj)) continue
|
||||
const pkg = JSON.parse(readFileSync(pj, "utf8"))
|
||||
// gateway middleware has no OpenCode plugin; its own tests check it
|
||||
if (pkg.magpie?.middleware) continue
|
||||
const problems = []
|
||||
try {
|
||||
const mod = await import(pathToFileURL(join(dir, pkg.main ?? "index.mjs")).href)
|
||||
|
||||
@@ -0,0 +1,67 @@
|
||||
// Runs a gateway middleware's cases the way magpie's gateway calls it: one
|
||||
// ctx for the request's hooks (so ctx.state carries over), each body a fresh
|
||||
// copy of its JSON, undefined keeping what came in, null dropping an event.
|
||||
// The same cases.json runs in magpie's own JavaScript engine (moejs), so a
|
||||
// middleware is checked in both.
|
||||
import { readFileSync } from "node:fs"
|
||||
import { join } from "node:path"
|
||||
import { expect, test } from "bun:test"
|
||||
|
||||
export function cases(dir) {
|
||||
return JSON.parse(readFileSync(join(dir, "cases.json"), "utf8"))
|
||||
}
|
||||
|
||||
export async function run(mod, c) {
|
||||
const m = mod.default ?? mod
|
||||
let rejected
|
||||
const ctx = {
|
||||
protocol: "anthropic", model: "", stream: false, path: "", ...c.ctx,
|
||||
options: c.options ?? {}, state: {},
|
||||
reject(status, message) { rejected ??= { status, message } },
|
||||
}
|
||||
const copy = (v) => JSON.parse(JSON.stringify(v))
|
||||
const out = {}
|
||||
if (c.request) {
|
||||
const r = m.onRequest ? await m.onRequest(copy(c.request), ctx) : undefined
|
||||
if (rejected) out.reject = rejected
|
||||
else out.request = r === undefined ? c.request : copy(r)
|
||||
}
|
||||
if (c.events) {
|
||||
out.events = []
|
||||
for (const e of c.events) {
|
||||
const wants = !m.events || (e.event && m.events.includes(e.event))
|
||||
if (typeof e.data !== "object" || !m.onEvent || !wants) {
|
||||
out.events.push(e.data)
|
||||
continue
|
||||
}
|
||||
const r = await m.onEvent(copy(e.data), ctx)
|
||||
if (r === null) continue
|
||||
out.events.push(r === undefined ? e.data : copy(r))
|
||||
}
|
||||
}
|
||||
if (c.response) {
|
||||
ctx.status = c.status ?? 200
|
||||
const r = m.onResponse ? await m.onResponse(copy(c.response), ctx) : undefined
|
||||
out.response = r === undefined ? c.response : copy(r)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// check runs each case and compares it with what it expects: a request,
|
||||
// events or response not expected are expected to pass unchanged.
|
||||
export function check(dir, mod) {
|
||||
for (const c of cases(dir)) {
|
||||
test(c.name, async () => {
|
||||
const got = await run(mod, c)
|
||||
if (c.reject) {
|
||||
expect(got.reject?.status).toBe(c.reject.status)
|
||||
if (c.reject.message) expect(got.reject?.message).toContain(c.reject.message)
|
||||
} else {
|
||||
expect(got.reject).toBeUndefined()
|
||||
if (c.request) expect(got.request).toEqual(c.expect_request ?? c.request)
|
||||
}
|
||||
if (c.events) expect(got.events).toEqual(c.expect_events ?? c.events.map((e) => e.data))
|
||||
if (c.response) expect(got.response).toEqual(c.expect_response ?? c.response)
|
||||
})
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user