otlp: OTEL_RESOURCE_ATTRIBUTES and OTEL_SERVICE_NAME name the server a trace or metric came from (#5167)

Several magpie servers exporting to one collector or to Langfuse all sent
the same resource, service.name=magpie alone, so nothing said which server
an event came from. Both signals' resource now merges the standard
OTEL_RESOURCE_ATTRIBUTES over that default, and OTEL_SERVICE_NAME over
that (otelResourceAttributes in internal/otlp/otel_resource.go). Nothing
about the machine is looked up; only what the user set is sent. Neither
variable turns export on.

Ported from reyoung's 7ed03b819 (feat/otel-resource-attributes, base
4ca55c6b6), reviewed line by line; nothing in it reached past its goal.
Changed from it:
- service.name precedence. The resource SDK spec makes code-supplied
  attributes win over OTEL_RESOURCE_ATTRIBUTES, but magpie's "magpie" is
  the fallback in the role the spec gives unknown_service, not identity
  the user supplied, and magpie's default never overrides a value the
  user set (code standards). So a service.name in the variable wins, and
  OTEL_SERVICE_NAME, which the spec's env table puts over the variable's,
  wins over both. An empty service.name or blank OTEL_SERVICE_NAME counts
  as unset (the spec's "empty value = unset"), so the resource never
  carries service.name="".
- Bytes that aren't UTF-8 once decoded (%FF) are a decoding error and
  discard the variable; before, json.Marshal sent U+FFFD.
- The variable was parsed and, when bad, logged on every flush of each
  signal. It is now parsed once per value and logged once, naming the
  entry by position (never its contents).
- otlp tests clear both variables in otelConfig, so a developer's shell
  can't change what the existing wire tests see.
Kept: whole variable discarded on any invalid entry (no '=', empty key,
bad escape, empty entry such as a trailing comma), as the spec says;
keys and values trimmed and percent-decoded with PathUnescape ('+' stays
'+'); last repeated key wins; values are strings.

Docs: reference.md's OTLP export, plugin-runtime.md's internal/otlp row,
and the privacy pages (en, zh, ja) now say the resource carries what the
user sets there.

Verified:
- TestOTelResourceAttributes reads the resource a test collector gets on
  /v1/traces and /v1/metrics, 17 cases. On the old otelEnvelope it FAILs
  (server, override and duplicate, encoding and empty, unencoded UTF-8,
  OTEL_SERVICE_NAME cases: "traces resource attributes =
  map[service.name:magpie]", same for metrics). Broken by hand one at a
  time, each went red: UTF-8 check off (not_UTF-8_once_decoded), no
  OTEL_SERVICE_NAME (3 cases), empty service.name kept (empty_service_
  name_is_unset), valid entries kept from a bad variable (missing equals,
  trailing comma, empty key, ...), and the per-value cache off
  (TestOTelResourceAttributesLoggedOnceWithoutContents: "logged 4 times,
  want once"). All green restored.
- On mote: go test -tags nogui ./internal/otlp ok; go test -race -count=3
  -run TestOTel ./internal/otlp ok; go vet, GOOS=linux go vet -tags nogui,
  GOOS=windows go vet (internal/otlp); go build, GOOS=linux go build -tags
  nogui, GOOS=windows go build; node --test site/*.test.mjs; gofmt -l
  empty.
- Full suite: run after the push (go test -tags nogui -timeout 45m ./...
  on mote); reds, if any, filed separately.

Not tried: a real collector or Langfuse; Windows/Linux runs of the
package (the code has no OS-specific path).

Co-authored-by: reyoung <728699+reyoung@users.noreply.github.com>
This commit is contained in:
yetone
2026-11-04 13:50:09 +08:00
co-authored by reyoung
parent cd83c3147f
commit 83bdfe70d2
9 changed files with 286 additions and 5 deletions
+22
View File
@@ -3358,6 +3358,28 @@ MAGPIE_OTEL_ENABLED=true MAGPIE_OTEL_ENDPOINT=http://localhost:4318 magpie serve
- `MAGPIE_OTEL_BODIES_WHOLE`: `true` or `false`, off by default; with bodies on,
keeps them entire rather than cut at 256 KB. A long reply is written to a
temporary file; a body too large for the collector is still refused.
- `OTEL_RESOURCE_ATTRIBUTES`: the standard OpenTelemetry variable, merged into
the resource of both traces and metrics, for example to tell servers apart:
```sh
OTEL_RESOURCE_ATTRIBUTES='service.instance.id=magpie-prod-01,host.name=server-a,deployment.environment.name=production' \
MAGPIE_OTEL_ENABLED=true MAGPIE_OTEL_ENDPOINT=http://localhost:4318 magpie serve
```
Comma-separated `key=value` pairs, as the
[OTel resource SDK spec](https://github.com/open-telemetry/opentelemetry-specification/blob/main/specification/resource/sdk.md#specifying-resource-information-via-an-environment-variable)
has them: keys and values are trimmed and percent-decoded (write `,` as
`%2C`, `=` as `%3D` and `%` as `%25`; `+` stays a plus), every value is a
string, and the last of a repeated key wins. Any invalid entry (no `=`, an
empty key, a bad escape, bytes that aren't UTF-8 once decoded, an empty
entry such as a trailing comma) discards the whole variable: magpie logs
which entry, never its contents, and exports with the default resource.
Nothing else about the machine is looked up or sent.
- `OTEL_SERVICE_NAME`: the resource's `service.name`, over a `service.name` in
`OTEL_RESOURCE_ATTRIBUTES`. With neither set, or set empty, it is `magpie`.
Neither variable turns export on, and both are read in the process that
exports (the app, or `magpie serve`), so restart it after changing them.
For Langfuse, pick **Collector › Langfuse**, then the host (Cloud EU
`https://cloud.langfuse.com`, Cloud US `https://us.cloud.langfuse.com`, or
+1 -1
View File
@@ -183,7 +183,7 @@ plugin off the gateway does no observing work.
| `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) |
| 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. | [`otlp/`](../../internal/otlp) |
| `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) |
| `plugins/otel` | Requires `window`, `settings` and `gateway`. Apply registers `otlp.New()` and disposes of it when turned off. `InUse` is 1 while `settings.OTelExport` says to send (settings.json or `MAGPIE_OTEL_*`), so a user who exports only through the environment keeps it on under Essentials. | [`otel.go`](../../plugins/otel/otel.go) |
## Gateway extension points (P3): router strategy
+106
View File
@@ -0,0 +1,106 @@
package otlp
import (
"fmt"
"log"
"net/url"
"os"
"sort"
"strings"
"sync"
"unicode/utf8"
)
// otelResource is what both signals' resources were last built from, so an
// export doesn't parse the variables again and a bad value is logged once,
// not on every flush.
var otelResource struct {
sync.Mutex
attrs, name string
built bool
out []otelAttribute
}
// otelResourceAttributes is the resource every export carries:
// service.name=magpie, with the standard OTEL_RESOURCE_ATTRIBUTES merged
// over it and OTEL_SERVICE_NAME over that (#5167). Only what the user set
// is added; nothing about the machine is looked up.
//
// magpie's "magpie" is the fallback the spec gives the SDK
// (unknown_service), not identity the user supplied, so a service.name the
// user set wins. An empty service.name counts as unset, as an empty
// OTEL_SERVICE_NAME does.
func otelResourceAttributes() []otelAttribute {
attrs, name := os.Getenv("OTEL_RESOURCE_ATTRIBUTES"), strings.TrimSpace(os.Getenv("OTEL_SERVICE_NAME"))
otelResource.Lock()
defer otelResource.Unlock()
if otelResource.built && otelResource.attrs == attrs && otelResource.name == name {
return otelResource.out
}
values, err := parseResourceAttributes(attrs)
if err != nil {
// The spec discards the whole value on any error. The message
// never quotes it: the attributes may name private hosts.
log.Printf("otel: OTEL_RESOURCE_ATTRIBUTES ignored: %s", err)
values = map[string]string{}
}
if values["service.name"] == "" {
values["service.name"] = "magpie"
}
if name != "" {
values["service.name"] = name
}
keys := make([]string, 0, len(values))
for key := range values {
keys = append(keys, key)
}
sort.Strings(keys)
out := make([]otelAttribute, 0, len(keys))
for _, key := range keys {
out = append(out, otelString(key, values[key]))
}
otelResource.attrs, otelResource.name, otelResource.built, otelResource.out = attrs, name, true, out
return out
}
// parseResourceAttributes reads key1=value1,key2=value2: keys and values
// trimmed and percent-decoded, every value a string, the last of a
// repeated key kept. An empty or blank value is no attributes. An error
// names the entry by position only.
func parseResourceAttributes(raw string) (map[string]string, error) {
values := map[string]string{}
if strings.TrimSpace(raw) == "" {
return values, nil
}
for i, entry := range strings.Split(raw, ",") {
key, value, found := strings.Cut(entry, "=")
if !found {
return nil, fmt.Errorf("entry %d has no '='", i+1)
}
key, err := decodeResourcePart(key)
if err != nil {
return nil, fmt.Errorf("entry %d's key %s", i+1, err)
}
if key == "" {
return nil, fmt.Errorf("entry %d has an empty key", i+1)
}
if value, err = decodeResourcePart(value); err != nil {
return nil, fmt.Errorf("entry %d's value %s", i+1, err)
}
values[key] = value
}
return values, nil
}
// decodeResourcePart percent-decodes one key or value. PathUnescape leaves
// '+' as it is: this is not form encoding.
func decodeResourcePart(s string) (string, error) {
s, err := url.PathUnescape(strings.TrimSpace(s))
if err != nil {
return "", fmt.Errorf("has a bad percent escape")
}
if !utf8.ValidString(s) {
return "", fmt.Errorf("is not UTF-8 once decoded")
}
return s, nil
}
+150
View File
@@ -0,0 +1,150 @@
package otlp
import (
"bytes"
"encoding/json"
"io"
"log"
"net/http"
"net/http/httptest"
"reflect"
"strings"
"testing"
"time"
"github.com/yetone/magpie/internal/settings"
)
// exportResources flushes one record and returns the resource attributes
// the collector got on /v1/traces and on /v1/metrics, in that order.
func exportResources(t *testing.T, attrs, name string) [2]map[string]string {
t.Helper()
type received struct {
path string
body []byte
}
requests := make(chan received, 2)
collector := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
body, err := io.ReadAll(r.Body)
if err != nil {
t.Error(err)
}
requests <- received{r.URL.Path, body}
io.WriteString(w, `{}`)
}))
defer collector.Close()
otelConfig(t, settings.OTel{Endpoint: collector.URL, Metrics: true})
t.Setenv("OTEL_RESOURCE_ATTRIBUTES", attrs)
t.Setenv("OTEL_SERVICE_NAME", name)
config, err := settings.OTelExport()
if err != nil {
t.Fatal(err)
}
e := newOTelExporter()
defer e.cancel()
defer e.client.CloseIdleConnections()
e.flush([]otelItem{{record: Record{Time: time.Now(), Status: 200, Input: 1}, config: config}})
var out [2]map[string]string
for i, signal := range []string{"Spans", "Metrics"} {
var request received
select {
case request = <-requests:
default:
t.Fatalf("collector received no %s export", signal)
}
if want := map[string]string{"Spans": "/v1/traces", "Metrics": "/v1/metrics"}[signal]; request.path != want {
t.Fatalf("path = %q, want %q", request.path, want)
}
var payload map[string][]struct {
Resource struct {
Attributes []otelAttribute `json:"attributes"`
} `json:"resource"`
}
if err := json.Unmarshal(request.body, &payload); err != nil {
t.Fatal(err)
}
resources := payload["resource"+signal]
if len(resources) != 1 {
t.Fatalf("%s: got %d resources, want 1", signal, len(resources))
}
got := map[string]string{}
for _, attr := range resources[0].Resource.Attributes {
value, ok := attr.Value["stringValue"].(string)
if !ok {
t.Fatalf("%s: attribute %q is not a string: %v", signal, attr.Key, attr.Value)
}
if _, dup := got[attr.Key]; dup {
t.Fatalf("%s: duplicate attribute %q", signal, attr.Key)
}
got[attr.Key] = value
}
out[i] = got
}
return out
}
// A server identity set in OTEL_RESOURCE_ATTRIBUTES reaches the resource
// of both signals, as the collector receives them (#5167).
func TestOTelResourceAttributes(t *testing.T) {
magpie := map[string]string{"service.name": "magpie"}
for _, tc := range []struct {
name, attrs, service string
want map[string]string
}{
{"default", "", "", magpie},
{"whitespace", " \t ", "", magpie},
{"server", "service.instance.id=magpie-prod-01,host.name=server-a,deployment.environment.name=production", "", map[string]string{
"service.name": "magpie", "service.instance.id": "magpie-prod-01", "host.name": "server-a", "deployment.environment.name": "production",
}},
{"override and duplicate", "service.name=first,service.name=custom,host.name=old,host.name=new", "", map[string]string{"service.name": "custom", "host.name": "new"}},
{"encoding and empty", " label%2Ckey = a%2Cb%3Dc%20d+e , empty=,host.name=%E6%9C%BA%E5%99%A8", "", map[string]string{
"service.name": "magpie", "label,key": "a,b=c d+e", "empty": "", "host.name": "机器",
}},
{"unencoded UTF-8 kept", "host.name=机器", "", map[string]string{"service.name": "magpie", "host.name": "机器"}},
{"empty service name is unset", "service.name=,host.name=a", "", map[string]string{"service.name": "magpie", "host.name": "a"}},
{"OTEL_SERVICE_NAME wins", "service.name=from-attrs,host.name=a", " gw-eu ", map[string]string{"service.name": "gw-eu", "host.name": "a"}},
{"OTEL_SERVICE_NAME alone", "", "gw-eu", map[string]string{"service.name": "gw-eu"}},
{"blank OTEL_SERVICE_NAME is unset", "service.name=custom", " ", map[string]string{"service.name": "custom"}},
{"OTEL_SERVICE_NAME over a discarded variable", "host.name=a,broken", "gw-eu", map[string]string{"service.name": "gw-eu"}},
{"missing equals", "host.name=server-a,broken", "", magpie},
{"trailing comma", "host.name=server-a,", "", magpie},
{"empty key", "host.name=server-a, =value", "", magpie},
{"bad key escape", "host.name=server-a,bad%ZZ=value", "", magpie},
{"bad value escape", "host.name=server-a,label=bad%ZZ", "", magpie},
{"not UTF-8 once decoded", "host.name=server-a,label=%FF", "", magpie},
} {
t.Run(tc.name, func(t *testing.T) {
got := exportResources(t, tc.attrs, tc.service)
for i, signal := range []string{"traces", "metrics"} {
if !reflect.DeepEqual(got[i], tc.want) {
t.Errorf("%s resource attributes = %v, want %v", signal, got[i], tc.want)
}
}
})
}
}
// A discarded variable is reported once, by position, never by its
// contents, however many exports read it.
func TestOTelResourceAttributesLoggedOnceWithoutContents(t *testing.T) {
var buf bytes.Buffer
prev, flags := log.Writer(), log.Flags()
log.SetOutput(&buf)
log.SetFlags(0)
defer func() { log.SetOutput(prev); log.SetFlags(flags) }()
attrs := "host.name=secret-host-7731,label=bad%ZZ"
exportResources(t, attrs, "")
exportResources(t, attrs, "")
out := buf.String()
if n := strings.Count(out, "OTEL_RESOURCE_ATTRIBUTES ignored"); n != 1 {
t.Fatalf("logged %d times, want once:\n%s", n, out)
}
if !strings.Contains(out, "entry 2") {
t.Errorf("log doesn't name the entry: %q", out)
}
for _, secret := range []string{"secret-host-7731", "host.name", "bad%ZZ"} {
if strings.Contains(out, secret) {
t.Errorf("log quotes %q: %q", secret, out)
}
}
}
+3
View File
@@ -26,6 +26,9 @@ func otelConfig(t *testing.T, config settings.OTel) {
t.Setenv("MAGPIE_OTEL_ENDPOINT", config.Endpoint)
t.Setenv("MAGPIE_OTEL_HEADERS", "Authorization=Bearer%20collector-test")
t.Setenv("MAGPIE_OTEL_METRICS", "false")
// The shell's own resource variables never reach a test's export.
t.Setenv("OTEL_RESOURCE_ATTRIBUTES", "")
t.Setenv("OTEL_SERVICE_NAME", "")
if config.Metrics {
t.Setenv("MAGPIE_OTEL_METRICS", "true")
}
+1 -1
View File
@@ -50,7 +50,7 @@ func otelAttributes(r Record) []otelAttribute {
func otelEnvelope(signal string, data any) map[string]any {
return map[string]any{"resource" + signal: []any{map[string]any{
"resource": map[string]any{"attributes": []otelAttribute{otelString("service.name", "magpie")}},
"resource": map[string]any{"attributes": otelResourceAttributes()},
"scope" + signal: []any{map[string]any{"scope": map[string]any{"name": "github.com/yetone/magpie"}, map[string]string{"Spans": "spans", "Metrics": "metrics"}[signal]: data}},
}}}
}
+1 -1
View File
@@ -187,7 +187,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 がエンドポイントと認証を作ります。詳しくは<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
@@ -187,7 +187,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. 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, 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
@@ -187,7 +187,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 会据此生成地址和认证头。细节见<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>