otel: export the gateway key's name as magpie.gateway_key.name (#5751)

reyoung (#5751) shares one magpie through several gateway keys and wants
requests in Langfuse or another collector told apart by key. The ledger
row already had CallerKeyName, but the OTLP allow-list dropped it, and
the observer's root and attempt records never carried it.

Ported from reyoung's 9d82162aa (reyoung/magpie feat/otel-gateway-key-name),
applied unchanged onto current main:
- observeRequest takes access.Caller(r).KeyName when observing begins
  and puts it on every End and Attempt record (CallerKeyName), so the
  root span and every try (failures, retries, fallbacks) carry it with
  no lookup at export time.
- otlp's allow-list grows by this one attribute, on generation and
  ledger spans (otelAttributes, so the duration and token histograms
  too) and on the root span. Omitted when the name is empty. The key's
  id and secret are never sent; provider account names stay out.
- docs/reference.md, plugin-runtime.md and the en/zh/ja privacy pages
  say the name goes to the user's collector.

Added on top: docs/reference.md says each key name multiplies a
metric's series, and that keys sharing a name are counted together.

Review of the fork (read every line; run only on mote): no new address,
dependency or credential; the name is read from the auth context at
request time, the same source appendUsage uses for the ledger row;
reported rows (another computer's) already have the caller key cleared
and never reach observers; session spans of local transcripts have no
key. READMEs (en, zh) mention OTLP only as a feature, with no list of
what is sent, so they are unchanged.

Run on mote (lockf ~/suite.lock), at base c7ebb6f8d plus this change:
- gofmt -l internal/gateway internal/otlp: clean.
- go vet ./..., GOOS=linux go vet -tags nogui ./..., GOOS=windows go
  vet ./...: ok.
- go test ./internal/otlp ./internal/gateway -run 'TestOTel|TestObserve':
  ok.
- go test -count=1 -timeout 45m ./internal/otlp ./internal/gateway
  ./plugins/otel: ok.
- go test -count=1 -timeout 45m ./... (macOS): every package ok (92),
  exit 0.

Rebased onto 136178803 after that run (5 commits; gateway.go and
prev_response.go, nothing in observe.go, otel*.go or internal/otlp).
The touched packages' run at the pushed head is queued behind mote's
suite lock and was not done before the push.

Broken by hand (each on mote, then restored):
- observeRequest without the name (o := &observed{}):
  TestOTelExportsGatewayKeyName/true red, "span 0: gateway key name ""
  seen 0 times".
- gatewayKeyAttr returning before adding the attribute:
  TestOTelBatchWireAndPrivacy red (attributes lack
  magpie.gateway_key.name) and TestOTelExportsGatewayKeyName/true red.

Not tried: a real Langfuse collector; Windows and Linux runtime runs (vet
only); the site pages are not deployed by this commit.

Co-authored-by: reyoung <728699+reyoung@users.noreply.github.com>
This commit is contained in:
yetone
2026-11-09 17:21:48 +08:00
co-authored by reyoung
parent 136178803b
commit 4314f4b776
9 changed files with 137 additions and 18 deletions
+7 -2
View File
@@ -3754,7 +3754,9 @@ environment: `MAGPIE_OTEL_ENDPOINT=https://cloud.langfuse.com/api/public/otel`
and `MAGPIE_OTEL_HEADERS=Authorization=Basic%20<base64(public-key:secret-key)>,x-langfuse-ingestion-version=4`.
Traces include agent, provider, model, token counts (including cache and
reasoning), HTTP status, timing, and route ID. Attempts with the same route ID
reasoning), HTTP status, timing, route ID, and the name of the gateway key the
request came with (`magpie.gateway_key.name`, absent without a key; never the
key's ID or secret). Attempts with the same route ID
share a trace ID. Chat, Responses, Anthropic and Gemini gateway requests
also export a parent request span and child spans for every routing attempt,
including unbilled failures, retries and fallbacks, so Langfuse can render a
@@ -3863,7 +3865,10 @@ details. It reads this computer's local sessions, including calls made without
Magpie as the proxy.
Metrics group duration and input/output token histograms by agent, provider,
model, operation and error status. Prompt/reply text is exported only when
model, operation, error status and gateway key name. Each gateway key name
multiplies a metric's series (one set per name requests came with), which
matters to a collector that limits or bills by series; a name is not unique,
so keys sharing one are counted together. Prompt/reply text is exported only when
**Include request and response bodies** is enabled (`MAGPIE_OTEL_BODIES=true`);
secrets are masked and each body is limited to 256 KiB unless **Include the
whole bodies** is enabled. Conversation IDs are exported only with
+1 -1
View File
@@ -180,7 +180,7 @@ plugin off the gateway does no observing work.
| --- | --- | --- |
| `usage.Observer` | `Serve() (stop)`, `Bodies()`, `Begin(Request) Watch` and `Ledger(Record)`. An observer watches what the gateway serves and what the ledger is written, and never changes either. `Observe(o)` registers one until its remove; `Observers` lists them. It lives in `internal/usage`, not the gateway, because every row is a usage `Record` and the ledger's other writers reach it too. | [`observe.go`](../../internal/usage/observe.go) |
| Serving | `ServeObservers()` starts every observer registered, and each one registered later, until the last of its stops (it is counted). Only the process serving the gateway calls it (`Server.ListenAndServe`), so a CLI that writes a usage row exports nothing. Remove stops a serving observer. | [`observe.go`](../../internal/usage/observe.go), [`gateway.go`](../../internal/gateway/gateway.go) |
| `Begin` and `Watch` | As a request starts the gateway asks each observer (`observeRequest`) with `usage.Request`: its header, agent, session (the native one when the agent names it), call kind (`auxiliary` for Claude's tool-less helper calls) and `Plain` (loopback, no gateway key, not passed on from another magpie). A `Watch` it returns gets `Attempt` for each routing attempt, unbilled failures and retries too, and `End` once. With no observer, or none watching, the request carries nothing. | [`observe.go`](../../internal/gateway/observe.go) |
| `Begin` and `Watch` | As a request starts the gateway asks each observer (`observeRequest`) with `usage.Request`: its header, agent, session (the native one when the agent names it), call kind (`auxiliary` for Claude's tool-less helper calls) and `Plain` (loopback, no gateway key, not passed on from another magpie). A `Watch` it returns gets `Attempt` for each routing attempt, unbilled failures and retries too, and `End` once. Both records carry `CallerKeyName`, captured from the authenticated caller when observing begins. The OTLP exporter sends this nonempty name as `magpie.gateway_key.name` on the root, attempts, ledger spans and metric points; it never sends the key's ID or secret (see [OTLP export](../reference.md#otlp-export)). With no observer, or none watching, the request carries nothing. | [`observe.go`](../../internal/gateway/observe.go) |
| Bodies | `Bodies()` is `NoBodies`, `CapturedBodies` (the first 256 KiB, cut with `usage.BodyCut`) or `WholeBodies` (the reply spooled whole as it streams, #538). The gateway takes the most any observer wants now (`ObservedBodies`): it keeps the whole reply only when one asks for it, and puts bodies on an attempt's record only when one asks for any. | [`observe.go`](../../internal/gateway/observe.go), [`capture.go`](../../internal/gateway/capture.go) |
| `Ledger` and `Watched` | Every row `Append` writes is passed to each observer. A row of a request some observer watched has `Watched` set (`appendUsage`), so an observer that sent the request's attempts doesn't send its row again. | [`usage.go`](../../internal/usage/usage.go), [`lan.go`](../../internal/gateway/lan.go) |
| `internal/otlp` | The OTLP/HTTP exporter, moved whole out of `internal/usage`: `otlp.New()` is an `Exporter`, a `usage.Observer`. Its Begin leaves a local agent's own turn to the agent's transcript when session tracing reads it, and takes a W3C `traceparent` as the parent. Settings are read on each call, as before. Both signals' resource is `service.name=magpie` with `OTEL_RESOURCE_ATTRIBUTES` merged over it and `OTEL_SERVICE_NAME` over that (`otelResourceAttributes`, #5167); an invalid variable is discarded whole and logged once, by entry position only. Nothing about the host is collected. | [`otlp/`](../../internal/otlp) |
+9 -4
View File
@@ -14,6 +14,10 @@ import (
type observed struct {
watches []usage.Watch
routeID int64
// keyName is the gateway key the request came with, by the name the
// user gave it (access.Identity.KeyName), never its secret; "" without
// one. Each span carries it as the ledger's row does (CallerKeyName).
keyName string
}
type observedKey struct{}
@@ -27,9 +31,10 @@ func observeRequest(r *http.Request, kind string, body []byte) (*http.Request, *
}
// the agent it is recorded as, another magpie's own (callerFrom)
agent := callerOf(r).agent
who := access.Caller(r.Context())
q := usage.Request{Header: r.Header, Agent: agent, Session: observedSession(r.Header), Kind: observedKind(agent, kind, body),
Plain: local(r) && access.Caller(r.Context()).KeyID == "" && callerOf(r).via == ""}
o := &observed{}
Plain: local(r) && who.KeyID == "" && callerOf(r).via == ""}
o := &observed{keyName: who.KeyName}
for _, ob := range observers {
if w := ob.Begin(q); w != nil {
o.watches = append(o.watches, w)
@@ -63,7 +68,7 @@ func (o *observed) end(call Call, millis int64) {
if o == nil {
return
}
rec := usage.Record{RouteID: o.routeID, Time: call.Time, Agent: call.Agent, Model: call.Model, Status: call.Status, Millis: millis}
rec := usage.Record{RouteID: o.routeID, Time: call.Time, Agent: call.Agent, Model: call.Model, Status: call.Status, Millis: millis, CallerKeyName: o.keyName}
canceledAs(&rec, call.Status, call.Error)
for _, w := range o.watches {
w.End(rec)
@@ -80,7 +85,7 @@ func (o *observed) attempt(call Call, attempt Try, providerID, effort string, he
rec := usage.Record{RouteID: o.routeID, Time: attempt.Start, Agent: call.Agent,
Provider: providerID, Model: attempt.Model, Requested: call.Model, Served: u.Served, Effort: effort,
Input: u.Input, Output: u.Output, CacheRead: u.CacheRead, CacheWrite: u.CacheWrite, CacheUnknown: u.cacheNotCounted(), Reasoning: u.Reasoning,
Millis: time.Since(attempt.Start).Milliseconds(), Status: attempt.Status, TTFT: attempt.TTFT, FirstText: attempt.FirstText, FirstReasoning: attempt.FirstReasoning, ReasoningHidden: attempt.ReasoningHidden}
Millis: time.Since(attempt.Start).Milliseconds(), Status: attempt.Status, TTFT: attempt.TTFT, FirstText: attempt.FirstText, FirstReasoning: attempt.FirstReasoning, ReasoningHidden: attempt.ReasoningHidden, CallerKeyName: o.keyName}
canceledAs(&rec, attempt.Status, attempt.Error)
if wanted := usage.ObservedBodies(); wanted != usage.NoBodies {
reply, cut := capture.body.text(), capture.body.truncated
+88
View File
@@ -327,6 +327,94 @@ func TestOTelExportsGatewayUsageWithoutContent(t *testing.T) {
}
}
// A request with a gateway key carries the key's name on its root span,
// each attempt span and their metrics (magpie.gateway_key.name), never the
// key's id or secret; one without a key carries no such attribute.
func TestOTelExportsGatewayKeyName(t *testing.T) {
for _, keyed := range []bool{true, false} {
t.Run(fmt.Sprint(keyed), func(t *testing.T) {
plan := &fake{ctype: "application/json", code: 429, reply: `{"error":{"message":"busy"}}`}
spare := &fake{ctype: "application/json", reply: `{"id":"ok","choices":[],"usage":{"prompt_tokens":10,"completion_tokens":5}}`}
twoProviders(t, plan, spare)
received := make(chan []byte, 64)
collector := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
b, _ := io.ReadAll(r.Body)
received <- b
io.WriteString(w, `{}`)
}))
defer collector.Close()
t.Setenv("MAGPIE_OTEL_ENABLED", "true")
t.Setenv("MAGPIE_OTEL_ENDPOINT", collector.URL)
t.Setenv("MAGPIE_OTEL_HEADERS", "")
t.Setenv("MAGPIE_OTEL_METRICS", "true")
t.Setenv("MAGPIE_OTEL_BODIES", "false")
fastOTel(t)
stop := startOTel()
t.Cleanup(stop)
req := httptest.NewRequest("POST", "/v1/chat/completions", strings.NewReader(chatReq))
req.RemoteAddr = "192.168.1.5:1234"
if keyed {
req = req.WithContext(access.WithIdentity(req.Context(), access.Identity{KeyID: "PRIVATE-KEY-ID", KeyName: "alice-laptop"}))
}
response := httptest.NewRecorder()
New().Handler().ServeHTTP(response, req)
if response.Code != 200 {
t.Fatalf("gateway: %d %s", response.Code, response.Body.String())
}
stop()
traces, metricExports := otelExports(received)
if len(metricExports) == 0 {
t.Fatal("no metrics exported")
}
type attr struct {
Key string
Value map[string]string
}
var spans [][]attr
for _, exported := range traces {
var wire struct {
ResourceSpans []struct {
ScopeSpans []struct{ Spans []struct{ Attributes []attr } }
}
}
if err := json.Unmarshal(exported, &wire); err != nil {
t.Fatal(err)
}
for _, rs := range wire.ResourceSpans {
for _, ss := range rs.ScopeSpans {
for _, s := range ss.Spans {
spans = append(spans, s.Attributes)
}
}
}
}
if len(spans) != 3 {
t.Fatalf("want two attempts and a root, got %d spans", len(spans))
}
for i, attrs := range spans {
name, n := "", 0
for _, a := range attrs {
if a.Key == "magpie.gateway_key.name" {
name, n = a.Value["stringValue"], n+1
}
}
if keyed && (n != 1 || name != "alice-laptop") || !keyed && n != 0 {
t.Fatalf("span %d: gateway key name %q seen %d times, keyed=%v: %+v", i, name, n, keyed, attrs)
}
}
all := string(bytes.Join(append(traces, metricExports...), []byte("\n")))
if strings.Contains(all, "PRIVATE-KEY-ID") {
t.Fatalf("gateway key id exported: %s", all)
}
points := strings.Count(all, `"key":"magpie.gateway_key.name","value":{"stringValue":"alice-laptop"}`)
if keyed && points < 5 || !keyed && points != 0 {
// 3 spans, plus the duration and token metrics' points
t.Fatalf("gateway key name in %d places, keyed=%v: %s", points, keyed, all)
}
})
}
}
// with bodies on (#538) the span carries the request and the reply as
// Langfuse's observation input and output — a stream's text put together,
// a secret in the request still masked — and with it off neither
+11 -4
View File
@@ -51,7 +51,8 @@ func TestOTelBatchWireAndPrivacy(t *testing.T) {
stop := StartOTel()
t.Cleanup(stop)
r := Record{RouteID: 42, Time: time.Now(), Agent: "pi", Provider: "deepseek", Model: "deepseek-chat", Requested: "group/mine", Served: "deepseek-v4", Input: 10, CacheRead: 3, CacheWrite: 2, Output: 4, Reasoning: 1, Millis: 1200, TTFT: 200, Status: 200,
ProviderKeyName: "PRIVATE-ACCOUNT", ProviderKeyID: "PRIVATE-KEY", Session: "PRIVATE-SESSION", Via: "PRIVATE-HOST"}
ProviderKeyName: "PRIVATE-ACCOUNT", ProviderKeyID: "PRIVATE-KEY", Session: "PRIVATE-SESSION", Via: "PRIVATE-HOST",
CallerKeyID: "PRIVATE-CALLER-KEY", CallerKeyName: "team-ci"}
usage.Append(r)
r.Error, r.ErrType = "PRIVATE-ERROR", "PRIVATE-ERROR-TYPE"
usage.Append(r) // an error in a stream whose HTTP status is already 200
@@ -119,7 +120,7 @@ func TestOTelBatchWireAndPrivacy(t *testing.T) {
for _, a := range spans[0].Attributes {
values[a.Key] = a.Value["stringValue"] + a.Value["intValue"]
}
if values["gen_ai.usage.input_tokens"] != "15" || values["gen_ai.usage.output_tokens"] != "4" || values["magpie.route.id"] != "42" || values["magpie.ttft_ms"] != "200" {
if values["gen_ai.usage.input_tokens"] != "15" || values["gen_ai.usage.output_tokens"] != "4" || values["magpie.route.id"] != "42" || values["magpie.ttft_ms"] != "200" || values["magpie.gateway_key.name"] != "team-ci" {
t.Fatalf("attributes: %v", values)
}
var metrics struct {
@@ -157,12 +158,18 @@ func TestOTelBatchWireAndPrivacy(t *testing.T) {
if p.Count != "1" || p.Sum != 1.2 || len(p.Buckets) != len(p.Bounds)+1 {
t.Errorf("point: %+v", p)
}
errType := ""
errType, keyName := "", ""
for _, a := range p.Attributes {
if a.Key == "error.type" {
switch a.Key {
case "error.type":
errType = a.Value["stringValue"]
case "magpie.gateway_key.name":
keyName = a.Value["stringValue"]
}
}
if keyName != "team-ci" {
t.Errorf("point's gateway key name: %q, want team-ci", keyName)
}
categories[errType]++
}
if len(categories) != 3 || categories[""] != 1 || categories["stream_error"] != 1 || categories["502"] != 1 {
+18 -4
View File
@@ -25,16 +25,19 @@ func otelInt(key string, value int64) otelAttribute {
return otelAttribute{key, map[string]any{"intValue": strconv.FormatInt(value, 10)}}
}
// Only this allowlist leaves the machine: never record JSON, account/key
// names, session titles, raw errors, prompts, completions or tool arguments.
// The one exception is traces' input and output, sent only when the user
// turned bodies on (#538).
// Only this allowlist leaves the machine: never record JSON, provider
// account/key names, session titles, raw errors, prompts, completions or
// tool arguments. The one exception is traces' input and output, sent only
// when the user turned bodies on (#538). The gateway key a call came with
// goes by the name the user gave it (gatewayKeyAttr), never its id or
// secret.
func otelAttributes(r Record) []otelAttribute {
op := r.Operation
if op == "" {
op = "chat"
}
a := []otelAttribute{otelString("gen_ai.operation.name", op), otelString("gen_ai.provider.name", r.Provider), otelString("gen_ai.request.model", r.Model), otelString("magpie.agent", r.Agent)}
a = gatewayKeyAttr(a, r)
if r.Served != "" {
a = append(a, otelString("gen_ai.response.model", r.Served))
}
@@ -48,6 +51,16 @@ func otelAttributes(r Record) []otelAttribute {
return a
}
// gatewayKeyAttr adds the name of the gateway key a call came with
// (Record.CallerKeyName) as magpie.gateway_key.name; a call without one
// has no such attribute.
func gatewayKeyAttr(a []otelAttribute, r Record) []otelAttribute {
if r.CallerKeyName == "" {
return a
}
return append(a, otelString("magpie.gateway_key.name", r.CallerKeyName))
}
func otelEnvelope(signal string, data any) map[string]any {
return map[string]any{"resource" + signal: []any{map[string]any{
"resource": map[string]any{"attributes": otelResourceAttributes()},
@@ -130,6 +143,7 @@ func (e *otelExporter) traces(items []otelItem) any {
if sp.Root {
span["name"], span["kind"] = "gateway "+r.Model, 2
a = []otelAttribute{otelString("magpie.agent", r.Agent), otelString("magpie.requested_model", r.Model), otelInt("http.response.status_code", int64(r.Status))}
a = gatewayKeyAttr(a, r)
if r.RouteID != 0 {
a = append(a, otelInt("magpie.route.id", r.RouteID))
}
+1 -1
View File
@@ -196,7 +196,7 @@
<p>モデルの価格と名前のために <a href="https://models.dev">models.dev</a> のカタログ(<code>models.dev/api.json</code>)を、あなたの通貨で価格を表示するために <code>open.er-api.com</code> から米ドルの為替レート(12 時間保持)を取得します。プラグインとその更新は npm レジストリから、ライブラリの項目は GitHub から取得します。どれも公開データの単なるダウンロードで、あなた、あなたのプロバイダー、使用量については何も送りません。ただし、どのリクエストとも同じく、これらのホストにはあなた(またはプロキシ)の IP アドレスが見えます。magpie は各プロバイダーにも、あなた自身のキーやサインインで残量とモデル一覧を尋ねます。<span class="ui">設定</span> → <span class="ui">利用枠</span> → <span class="ui">利用枠の読み込み</span> → <span class="ui">手動のみ</span> で、頼んだときに限れます。</p>
<h2 id="otel"><a class="anchor" href="#otel">OTLP エクスポート</a></h2>
<p>magpie はゲートウェイの各リクエストを、あなたの OpenTelemetry コレクター(Langfuse など)へエクスポートできます。<b>既定ではオフ</b>で、送り先はあなたが設定したエンドポイントだけです。私たちには送りません。オンにすると、リクエストごとのスパン(エージェント、プロバイダー、モデル、トークン数、ステータス、時間、推定コスト)を送ります。別のスイッチで、メトリクス、ローカルのエージェント会話、リクエストと返答の本文(シークレットはマスク)を加えられます。<span class="ui">設定</span> → <span class="ui">オブザーバビリティ</span> でオンにするか、<code>magpie serve</code> では <code>MAGPIE_OTEL_ENABLED</code>、<code>MAGPIE_OTEL_ENDPOINT</code>、<code>MAGPIE_OTEL_HEADERS</code>、<code>MAGPIE_OTEL_METRICS</code>、<code>MAGPIE_OTEL_SESSIONS</code>、<code>MAGPIE_OTEL_BODIES</code>、<code>MAGPIE_OTEL_BODIES_WHOLE</code> を使います。エンドポイントだけではオンになりません。Langfuse なら、そこで <span class="ui">Langfuse</span> を選び、ホストとプロジェクトの 2 つのキーを入力すると、magpie がエンドポイントと認証を作ります。各エクスポートの resource は <code>service.name=magpie</code> と、あなたが <code>OTEL_RESOURCE_ATTRIBUTES</code> と <code>OTEL_SERVICE_NAME</code> に自分で設定した値(サーバー名など)だけです。マシンの情報は調べません。詳しくは<a href="https://github.com/yetone/magpie/blob/main/docs/reference.md#otlp-export">リファレンス</a>を。</p>
<p>magpie はゲートウェイの各リクエストを、あなたの OpenTelemetry コレクター(Langfuse など)へエクスポートできます。<b>既定ではオフ</b>で、送り先はあなたが設定したエンドポイントだけです。私たちには送りません。オンにすると、リクエストごとのスパン(エージェント、プロバイダー、モデル、リクエストに使われたゲートウェイキーの名前(あなたが付けた名前で、キーそのものは送りません)、トークン数、ステータス、時間、推定コスト)を送ります。別のスイッチで、メトリクス、ローカルのエージェント会話、リクエストと返答の本文(シークレットはマスク)を加えられます。<span class="ui">設定</span> → <span class="ui">オブザーバビリティ</span> でオンにするか、<code>magpie serve</code> では <code>MAGPIE_OTEL_ENABLED</code>、<code>MAGPIE_OTEL_ENDPOINT</code>、<code>MAGPIE_OTEL_HEADERS</code>、<code>MAGPIE_OTEL_METRICS</code>、<code>MAGPIE_OTEL_SESSIONS</code>、<code>MAGPIE_OTEL_BODIES</code>、<code>MAGPIE_OTEL_BODIES_WHOLE</code> を使います。エンドポイントだけではオンになりません。Langfuse なら、そこで <span class="ui">Langfuse</span> を選び、ホストとプロジェクトの 2 つのキーを入力すると、magpie がエンドポイントと認証を作ります。各エクスポートの resource は <code>service.name=magpie</code> と、あなたが <code>OTEL_RESOURCE_ATTRIBUTES</code> と <code>OTEL_SERVICE_NAME</code> に自分で設定した値(サーバー名など)だけです。マシンの情報は調べません。詳しくは<a href="https://github.com/yetone/magpie/blob/main/docs/reference.md#otlp-export">リファレンス</a>を。</p>
<h2 id="masking"><a class="anchor" href="#masking">プロバイダに送る内容のマスク</a></h2>
<p>ここまでの節は magpie が自分で送るものです。エージェントが送る内容は選んだプロバイダに届きますが、<b>プライバシーマスク</b>はその中の秘密をこのコンピュータに留めます。<b>既定ではオフ</b>で、<span class="ui">設定</span> → <span class="ui">プライバシー</span> でオンにします。</p>
+1 -1
View File
@@ -196,7 +196,7 @@
<p>To price and name models magpie fetches the <a href="https://models.dev">models.dev</a> catalog (<code>models.dev/api.json</code>), and for prices in your currency the USD exchange rate from <code>open.er-api.com</code> (kept 12 hours). Plugins and their updates come from the npm registry, and the library’s items from GitHub. These are plain downloads of public data: nothing about you, your providers or your usage is sent, though, as with any request, those hosts see your IP address (or your proxy’s). magpie also asks each of your providers for your allowance and model list, with your own key or sign-in; <span class="ui">Settings</span> → <span class="ui">Allowances</span> → <span class="ui">Allowance reads</span> → <span class="ui">When I ask</span> limits those to when you ask.</p>
<h2 id="otel"><a class="anchor" href="#otel">OTLP export</a></h2>
<p>magpie can export each gateway request to an OpenTelemetry collector of yours (Langfuse, for example). It is <b>off by default</b>, and goes only to the endpoint you set, never to us. When on, it sends per-request spans: agent, provider, model, token counts, status, timing and estimated cost. Optional switches add metrics, local agent conversations, and the request and reply bodies (secrets masked). Turn it on in <span class="ui">Settings</span> → <span class="ui">Observability</span>, or for <code>magpie serve</code> with <code>MAGPIE_OTEL_ENABLED</code>, <code>MAGPIE_OTEL_ENDPOINT</code>, <code>MAGPIE_OTEL_HEADERS</code>, <code>MAGPIE_OTEL_METRICS</code>, <code>MAGPIE_OTEL_SESSIONS</code>, <code>MAGPIE_OTEL_BODIES</code> and <code>MAGPIE_OTEL_BODIES_WHOLE</code>. An endpoint alone doesn’t turn it on. For Langfuse, pick <span class="ui">Langfuse</span> there and give its host and your project’s two keys; magpie makes the endpoint and sign-in from them. Each export’s resource is <code>service.name=magpie</code>, plus only what you set yourself in <code>OTEL_RESOURCE_ATTRIBUTES</code> and <code>OTEL_SERVICE_NAME</code> (a server name, for example); nothing about your machine is looked up. The <a href="https://github.com/yetone/magpie/blob/main/docs/reference.md#otlp-export">reference</a> has the details.</p>
<p>magpie can export each gateway request to an OpenTelemetry collector of yours (Langfuse, for example). It is <b>off by default</b>, and goes only to the endpoint you set, never to us. When on, it sends per-request spans: agent, provider, model, the name you gave the gateway key it came with (never the key itself), token counts, status, timing and estimated cost. Optional switches add metrics, local agent conversations, and the request and reply bodies (secrets masked). Turn it on in <span class="ui">Settings</span> → <span class="ui">Observability</span>, or for <code>magpie serve</code> with <code>MAGPIE_OTEL_ENABLED</code>, <code>MAGPIE_OTEL_ENDPOINT</code>, <code>MAGPIE_OTEL_HEADERS</code>, <code>MAGPIE_OTEL_METRICS</code>, <code>MAGPIE_OTEL_SESSIONS</code>, <code>MAGPIE_OTEL_BODIES</code> and <code>MAGPIE_OTEL_BODIES_WHOLE</code>. An endpoint alone doesn’t turn it on. For Langfuse, pick <span class="ui">Langfuse</span> there and give its host and your project’s two keys; magpie makes the endpoint and sign-in from them. Each export’s resource is <code>service.name=magpie</code>, plus only what you set yourself in <code>OTEL_RESOURCE_ATTRIBUTES</code> and <code>OTEL_SERVICE_NAME</code> (a server name, for example); nothing about your machine is looked up. The <a href="https://github.com/yetone/magpie/blob/main/docs/reference.md#otlp-export">reference</a> has the details.</p>
<h2 id="masking"><a class="anchor" href="#masking">Masking what goes to providers</a></h2>
<p>The sections above are what magpie sends by itself. What your agents send goes to the providers you chose, and <b>privacy masking</b> keeps the secrets in it on this computer. It is <b>off by default</b>; turn it on in <span class="ui">Settings</span> → <span class="ui">Privacy</span>.</p>
+1 -1
View File
@@ -196,7 +196,7 @@
<p>为了给模型定价和命名,magpie 会拉取 <a href="https://models.dev">models.dev</a> 的模型目录(<code>models.dev/api.json</code>);为了用你的货币显示价格,会从 <code>open.er-api.com</code> 拉取美元汇率(缓存 12 小时)。插件及其更新来自 npm 仓库,库里的内容来自 GitHub。这些都是公开数据的普通下载,不发送任何关于你、你的供应商或用量的信息;和任何请求一样,这些主机能看到你的 IP(或代理的 IP)。magpie 还会用你自己的密钥或登录向各个供应商读取额度和模型列表;<span class="ui">设置</span> → <span class="ui">额度</span> → <span class="ui">额度刷新</span> → <span class="ui">仅手动</span> 可以只在你要求时才读。</p>
<h2 id="otel"><a class="anchor" href="#otel">OTLP 导出</a></h2>
<p>magpie 可以把每个网关请求导出到你自己的 OpenTelemetry 收集器(比如 Langfuse)。它<b>默认关闭</b>,只发到你设置的地址,从不发给我们。开启后发送每个请求的 span:agent、供应商、模型、token 数、状态、耗时和估算费用。另有开关可以加上指标、本地 agent 对话,以及请求和回复正文(密钥已遮盖)。在 <span class="ui">设置</span> → <span class="ui">可观测性</span> 里开启,<code>magpie serve</code> 也可以用 <code>MAGPIE_OTEL_ENABLED</code>、<code>MAGPIE_OTEL_ENDPOINT</code>、<code>MAGPIE_OTEL_HEADERS</code>、<code>MAGPIE_OTEL_METRICS</code>、<code>MAGPIE_OTEL_SESSIONS</code>、<code>MAGPIE_OTEL_BODIES</code> 和 <code>MAGPIE_OTEL_BODIES_WHOLE</code>。只设地址不会开启导出。用 Langfuse 的话,在那里选 <span class="ui">Langfuse</span>,填上地址和项目的两个密钥,magpie 会据此生成地址和认证头。每次导出的 resource 是 <code>service.name=magpie</code>,再加上你自己在 <code>OTEL_RESOURCE_ATTRIBUTES</code> 和 <code>OTEL_SERVICE_NAME</code> 里设置的值(比如服务器名),不会读取你机器上的任何信息。细节见<a href="https://github.com/yetone/magpie/blob/main/docs/reference.md#otlp-export">参考文档</a>。</p>
<p>magpie 可以把每个网关请求导出到你自己的 OpenTelemetry 收集器(比如 Langfuse)。它<b>默认关闭</b>,只发到你设置的地址,从不发给我们。开启后发送每个请求的 span:agent、供应商、模型、请求所用网关密钥的名称(你起的名字,从不发送密钥本身)、token 数、状态、耗时和估算费用。另有开关可以加上指标、本地 agent 对话,以及请求和回复正文(密钥已遮盖)。在 <span class="ui">设置</span> → <span class="ui">可观测性</span> 里开启,<code>magpie serve</code> 也可以用 <code>MAGPIE_OTEL_ENABLED</code>、<code>MAGPIE_OTEL_ENDPOINT</code>、<code>MAGPIE_OTEL_HEADERS</code>、<code>MAGPIE_OTEL_METRICS</code>、<code>MAGPIE_OTEL_SESSIONS</code>、<code>MAGPIE_OTEL_BODIES</code> 和 <code>MAGPIE_OTEL_BODIES_WHOLE</code>。只设地址不会开启导出。用 Langfuse 的话,在那里选 <span class="ui">Langfuse</span>,填上地址和项目的两个密钥,magpie 会据此生成地址和认证头。每次导出的 resource 是 <code>service.name=magpie</code>,再加上你自己在 <code>OTEL_RESOURCE_ATTRIBUTES</code> 和 <code>OTEL_SERVICE_NAME</code> 里设置的值(比如服务器名),不会读取你机器上的任何信息。细节见<a href="https://github.com/yetone/magpie/blob/main/docs/reference.md#otlp-export">参考文档</a>。</p>
<h2 id="masking"><a class="anchor" href="#masking">发给供应商的内容脱敏</a></h2>
<p>上面几节讲的是 magpie 自己发出的东西。你的 Agent 发出的内容会去往你选的供应商,<b>隐私脱敏</b>让其中的密钥留在这台电脑上。它<b>默认关闭</b>,在 <span class="ui">设置</span> → <span class="ui">隐私</span> 里打开。</p>