Files
magpie/internal/gateway/tokenhub_test.go
T
yetone e60b721532 providers: Tencent Cloud TokenHub pay as you go is a preset, its global endpoint and China's one row in the add sheet (Jorben on Discord: magpie's Tencent Cloud is TokenHub's Token Plan subscription, whose endpoints pay-as-you-go keys can't use; TokenHub's pay as you go is at tokenhub.tencentmaas.com and tokenhub-intl.tencentmaas.com and speaks Chat Completions, Responses and Anthropic Messages) — the only Tencent preset was tencent-token-plan, at the plan's own api.lkeap.cloud.tencent.com/plan/v3 and /plan/anthropic, where a pay-as-you-go key is no good, so such a key could only go in a custom provider by hand. Now tencent-tokenhub ("Tencent Cloud TokenHub", Singapore, tokenhub-intl.tencentmaas.com) and tencent-tokenhub-cn ("Tencent Cloud TokenHub (China)", Guangzhou, tokenhub.tencentmaas.com) are presets, as TokenHub's language-model API page (1823/130079) gives them: chat completions and Responses at <host>/v1 (Responses converted from chat on TokenHub's side for the models that speak chat alone, 1823/133813), Anthropic messages at <host>/v1/messages with the key as x-api-key, the OpenAI APIs with it as a Bearer, and the model list at /v1/models. Being id and id-cn they pair into one row in the add sheet, its editor switching between them with the key kept, beside the plan's Tencent Cloud row, with the plan's icon (tencentcloud-color), the note "Pay as you go" (按量付费), and models.dev's tencent-tokenhub entry for names and prices; Hosts, as it serves DeepSeek, GLM, Kimi, MiniMax and Qwen besides Hy, so its list is no maker's word on theirs. Keys are made at console.tencentcloud.com/tokenhub/apikey and console.cloud.tencent.com/tokenhub/apikey. An entry imported from another app at either host, on any of the three APIs, is the preset. The plan's preset, its endpoints, models and saved providers are untouched; its note "TokenHub · subscription" now has its Chinese (TokenHub · 订阅). TestTencentTokenHub (endpoints, pair, import from each API, the plan unmoved), TestTencentTokenHubList (its /v1/models as its docs show it, asked with a Bearer, an embedding model left out) and TestTencentTokenHubRoutes (both presets at a fake TokenHub: chat, Responses and messages each reach /v1/chat/completions, /v1/responses and /v1/messages untranslated, Bearer on the first two, x-api-key on messages) are new and fail without the change (no such preset). No request was made to Tencent and no real key used. add-sheet.test.cjs passes in WebKit. go vet ./internal/..., go build -tags nogui (darwin, GOOS=linux), GOOS=windows go build, go test -tags nogui -count=1 ./... under a temp HOME pass (TestFXInState's known TempDir cleanup flake aside).
2026-10-02 21:11:03 +08:00

144 lines
5.2 KiB
Go

package gateway
import (
"encoding/json"
"io"
"net/http"
"net/http/httptest"
"strings"
"sync"
"testing"
"github.com/yetone/magpie/internal/provider"
)
// tokenhub plays TokenHub's pay-as-you-go endpoints: chat completions,
// Responses and Anthropic messages, all three under /v1 at the host's root.
type tokenhub struct {
mu sync.Mutex
calls []tokenhubCall
}
type tokenhubCall struct {
path, model string
head http.Header
}
func (q *tokenhub) ServeHTTP(w http.ResponseWriter, r *http.Request) {
body, _ := io.ReadAll(r.Body)
var v struct {
Model string `json:"model"`
}
json.Unmarshal(body, &v)
q.mu.Lock()
q.calls = append(q.calls, tokenhubCall{r.URL.Path, v.Model, r.Header.Clone()})
q.mu.Unlock()
w.Header().Set("Content-Type", "text/event-stream")
switch r.URL.Path {
case "/v1/chat/completions":
io.WriteString(w, sse(
`data: {"id":"c1","object":"chat.completion.chunk","choices":[{"index":0,"delta":{"role":"assistant","content":"from chat"}}]}`,
`data: {"id":"c1","object":"chat.completion.chunk","choices":[{"index":0,"delta":{},"finish_reason":"stop"}],"usage":{"prompt_tokens":5,"completion_tokens":2}}`,
`data: [DONE]`))
case "/v1/responses":
io.WriteString(w, sse(
`data: {"type":"response.created","response":{"id":"resp_1"}}`,
`data: {"type":"response.output_item.added","output_index":0,"item":{"id":"msg_1","type":"message","role":"assistant","content":[]}}`,
`data: {"type":"response.output_text.delta","item_id":"msg_1","output_index":0,"content_index":0,"delta":"from responses"}`,
`data: {"type":"response.completed","response":{"id":"resp_1","usage":{"input_tokens":5,"output_tokens":2}}}`))
case "/v1/messages":
io.WriteString(w, sse(
`event: message_start`+"\n"+`data: {"type":"message_start","message":{"id":"msg_1","model":"`+v.Model+`","usage":{"input_tokens":5}}}`,
`data: {"type":"content_block_start","index":0,"content_block":{"type":"text","text":""}}`,
`data: {"type":"content_block_delta","index":0,"delta":{"type":"text_delta","text":"from messages"}}`,
`data: {"type":"content_block_stop","index":0}`,
`data: {"type":"message_delta","delta":{"stop_reason":"end_turn"},"usage":{"output_tokens":2}}`,
`data: {"type":"message_stop"}`))
default:
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusNotFound)
io.WriteString(w, `{"error":{"code":"404000","message":"no such route"}}`)
}
}
func (q *tokenhub) last() tokenhubCall {
q.mu.Lock()
defer q.mu.Unlock()
if len(q.calls) == 0 {
return tokenhubCall{}
}
return q.calls[len(q.calls)-1]
}
// TokenHub pay as you go (Jorben on Discord) at a fake TokenHub, China's
// preset and the global one alike: each client's API reaches TokenHub's own
// path for it, never translated away, with the key as a Bearer on the
// OpenAI APIs and as x-api-key on Anthropic's, which TokenHub's docs ask.
func TestTencentTokenHubRoutes(t *testing.T) {
for _, id := range []string{"tencent-tokenhub-cn", "tencent-tokenhub"} {
t.Run(id, func(t *testing.T) {
fresh(t)
up := &tokenhub{}
srv := httptest.NewServer(up)
t.Cleanup(srv.Close)
p, err := provider.FromPreset(id)
if err != nil {
t.Fatal(err)
}
// the preset's paths kept, its host swapped for the fake's
host := strings.TrimSuffix(p.Chat, "/v1")
if p.Responses != host+"/v1" || p.Anthropic != host {
t.Fatalf("endpoints: %q %q %q", p.Chat, p.Responses, p.Anthropic)
}
p.Chat = strings.Replace(p.Chat, host, srv.URL, 1)
p.Responses = strings.Replace(p.Responses, host, srv.URL, 1)
p.Anthropic = strings.Replace(p.Anthropic, host, srv.URL, 1)
p.Key = "sk-tokenhub-test"
p.Models = []string{"hy3", "deepseek-v4-pro"}
if err := provider.Save(p); err != nil {
t.Fatal(err)
}
for _, tc := range []struct {
name, path, body, path2, model, reply string
bearer bool
}{
{"chat", "/v1/chat/completions",
`{"model":"` + id + `/hy3","stream":true,"messages":[{"role":"user","content":"hi"}]}`,
"/v1/chat/completions", "hy3", "from chat", true},
{"responses", "/v1/responses",
`{"model":"` + id + `/deepseek-v4-pro","input":"hi","stream":true}`,
"/v1/responses", "deepseek-v4-pro", "from responses", true},
{"messages", "/v1/messages",
`{"model":"` + id + `/hy3","max_tokens":20,"stream":true,"messages":[{"role":"user","content":"hi"}]}`,
"/v1/messages", "hy3", "from messages", false},
} {
t.Run(tc.name, func(t *testing.T) {
code, body := post(t, tc.path, tc.body)
if code != 200 || !strings.Contains(body, tc.reply) {
t.Fatalf("status %d: %s", code, body)
}
c := up.last()
if c.path != tc.path2 || c.model != tc.model {
t.Fatalf("upstream: %s %q", c.path, c.model)
}
if tc.bearer {
if c.head.Get("Authorization") != "Bearer sk-tokenhub-test" {
t.Fatalf("headers: %v", c.head)
}
} else if c.head.Get("x-api-key") != "sk-tokenhub-test" || c.head.Get("anthropic-version") == "" {
t.Fatalf("headers: %v", c.head)
}
})
}
up.mu.Lock()
defer up.mu.Unlock()
for _, c := range up.calls {
if c.path != "/v1/chat/completions" && c.path != "/v1/responses" && c.path != "/v1/messages" {
t.Errorf("asked at %s", c.path)
}
}
})
}
}