fix: normalize tool history and improve health checks

This commit is contained in:
Jason Xu committed 2026-08-14 16:17:36 +08:00
1 parent 66e1ef176e
commit efbdb6e7d1
5 files changed
+261 -5

No files matched your search

+5 -1
View File
@@ -14,7 +14,7 @@
- 将 key 自动均衡绑定到代理,保持连接亲和性
- 使用无锁轮询分配并发请求
- 代理失败后自动迁移绑定,key 失败后进行短时冷却
- 启动时及每 60 秒通过 Cloudflare trace 并行检查代理可用性
- 根据真实上游流量识别代理故障,并每 15 分钟通过 Cloudflare trace 并行复查异常代理
- 为不同会话生成不同的 OpenCode 会话 ID
## API 路径
@@ -27,6 +27,10 @@
| `POST` | `/v1/messages` | Anthropic Messages |
| `GET` | `/healthz` | 健康检查 |
`/healthz` 无需 API key,返回服务版本以及模型目录、Zen/Go key 和代理池的汇总状态,不会暴露 key 或代理地址。模型目录尚未完成首次刷新、已经过期、没有可暴露模型或没有健康代理时返回 HTTP `503`;其余情况返回 `200`。
模型目录的过期阈值为 `models.refresh_seconds` 的两倍,且不低于 60 秒。刚启动时短暂返回 `503 starting` 属于正常现象,模型列表首次刷新成功后会变为 `200 ok`。
## 编译
需要 Go 1.24 或更高版本。
+116 -1
View File
@@ -195,7 +195,7 @@ func encodeRequest(protocol Protocol, request canonicalRequest) map[string]any {
for _, message := range request.Messages {
messages = append(messages, encodeChatMessages(message)...)
}
output["messages"] = messages
output["messages"] = normalizeChatToolMessages(messages)
put(output, "max_tokens", request.MaxTokens)
put(output, "stop", request.Stop)
if effort := reasoningEffort(request.Reasoning); effort != nil {
@@ -355,6 +355,121 @@ func encodeChatMessages(message canonicalMessage) []any {
return messages
}
// normalizeChatToolMessages adapts tool history to the stricter ordering used
// by OpenAI-compatible Chat APIs. Anthropic clients can put tool results and
// text in one user message, while persisted or compacted agent histories may
// spread parallel results across multiple messages. Chat requires every
// assistant tool_calls message to be followed immediately by all matching tool
// messages.
//
// Results are paired globally by tool_call_id and emitted in call order. Tool
// calls without a result are removed from converted history, because forwarding
// an unresolved historical call makes the entire request invalid. An orphaned
// result is retained as ordinary user content instead of an invalid tool
// message.
func normalizeChatToolMessages(messages []any) []any {
type toolResult struct {
message map[string]any
used bool
}
type toolPair struct {
call any
result *toolResult
}
resultsByID := make(map[string][]*toolResult)
resultAt := make(map[int]*toolResult)
for i, raw := range messages {
message, _ := raw.(map[string]any)
if stringAt(message, "role") != "tool" {
continue
}
result := &toolResult{message: message}
resultAt[i] = result
if id := stringAt(message, "tool_call_id"); id != "" {
resultsByID[id] = append(resultsByID[id], result)
}
}
pairsAt := make(map[int][]toolPair)
toolCallAt := make(map[int]bool)
for i, raw := range messages {
message, _ := raw.(map[string]any)
calls := sliceAt(message, "tool_calls")
if stringAt(message, "role") != "assistant" || len(calls) == 0 {
continue
}
toolCallAt[i] = true
for _, rawCall := range calls {
call, _ := rawCall.(map[string]any)
id := stringAt(call, "id")
for _, result := range resultsByID[id] {
if result.used {
continue
}
result.used = true
pairsAt[i] = append(pairsAt[i], toolPair{call: rawCall, result: result})
break
}
}
}
out := make([]any, 0, len(messages))
for i, raw := range messages {
if result := resultAt[i]; result != nil {
if !result.used {
out = append(out, map[string]any{
"role": "user",
"content": contentString(result.message["content"]),
})
}
continue
}
if !toolCallAt[i] {
out = append(out, raw)
continue
}
message, _ := raw.(map[string]any)
converted := make(map[string]any, len(message))
for key, value := range message {
converted[key] = value
}
pairs := pairsAt[i]
if len(pairs) == 0 {
delete(converted, "tool_calls")
if hasChatContent(converted["content"]) {
out = append(out, converted)
}
continue
}
calls := make([]any, 0, len(pairs))
for _, pair := range pairs {
calls = append(calls, pair.call)
}
converted["tool_calls"] = calls
out = append(out, converted)
for _, pair := range pairs {
out = append(out, pair.result.message)
}
}
return out
}
func hasChatContent(value any) bool {
switch value := value.(type) {
case nil:
return false
case string:
return strings.TrimSpace(value) != ""
case []any:
return len(value) > 0
default:
return true
}
}
func encodeChatContent(blocks []canonicalBlock) any {
if len(blocks) == 1 && blocks[0].Type == "text" {
return blocks[0].Text
+95 -3
View File
@@ -32,6 +32,38 @@ type Gateway struct {
catalog *modelCatalog
}
type healthResponse struct {
Status string `json:"status"`
Ready bool `json:"ready"`
Version string `json:"version"`
Models healthModels `json:"models"`
Keys healthKeys `json:"keys"`
Proxies healthProxies `json:"proxies"`
Issues []string `json:"issues,omitempty"`
}
type healthModels struct {
Status string `json:"status"`
Total int `json:"total"`
Exposed int `json:"exposed"`
Zen int `json:"zen"`
Go int `json:"go"`
LastRefresh *time.Time `json:"last_refresh,omitempty"`
StaleAfterSeconds int `json:"stale_after_seconds"`
}
type healthKeys struct {
Zen int `json:"zen"`
Go int `json:"go"`
Total int `json:"total"`
}
type healthProxies struct {
Total int `json:"total"`
Healthy int `json:"healthy"`
Unhealthy int `json:"unhealthy"`
}
func NewGateway(cfg Config, logger *slog.Logger) (*Gateway, error) {
transports, err := newTransportPool(cfg.Proxies, cfg.Performance, time.Duration(cfg.Retry.TimeoutSeconds)*time.Second)
if err != nil {
@@ -62,12 +94,72 @@ func (g *Gateway) Handler() http.Handler {
mux.HandleFunc("POST /v1/chat/completions", g.authenticate(g.handleInference(ProtocolChat)))
mux.HandleFunc("POST /v1/responses", g.authenticate(g.handleInference(ProtocolResponses)))
mux.HandleFunc("POST /v1/messages", g.authenticate(g.handleInference(ProtocolAnthropic)))
mux.HandleFunc("GET /healthz", func(w http.ResponseWriter, _ *http.Request) {
writeJSON(w, http.StatusOK, map[string]any{"status": "ok"})
})
mux.HandleFunc("GET /healthz", g.handleHealth)
return recoveryMiddleware(g.logger, mux)
}
func (g *Gateway) handleHealth(w http.ResponseWriter, _ *http.Request) {
models := g.catalog.Snapshot()
proxyTotal, proxyHealthy := g.transports.healthCounts()
zenKeys, goKeys := g.zenNodes.Len(), g.goNodes.Len()
staleAfter := max(2*time.Duration(g.cfg.Models.RefreshSeconds)*time.Second, time.Minute)
modelStatus := "ready"
var lastRefresh *time.Time
issues := make([]string, 0, 3)
if models.UpdatedAt.IsZero() {
modelStatus = "pending"
issues = append(issues, "model_catalog_pending")
} else {
updatedAt := models.UpdatedAt.UTC()
lastRefresh = &updatedAt
if models.Exposed == 0 {
modelStatus = "empty"
issues = append(issues, "model_catalog_empty")
} else if time.Since(models.UpdatedAt) > staleAfter {
modelStatus = "stale"
issues = append(issues, "model_catalog_stale")
}
}
if zenKeys+goKeys == 0 {
issues = append(issues, "no_upstream_keys")
}
if proxyHealthy == 0 {
issues = append(issues, "no_healthy_proxies")
}
status := "ok"
httpStatus := http.StatusOK
if len(issues) > 0 {
status = "degraded"
httpStatus = http.StatusServiceUnavailable
if modelStatus == "pending" {
status = "starting"
}
}
writeJSON(w, httpStatus, healthResponse{
Status: status,
Ready: len(issues) == 0,
Version: version,
Models: healthModels{
Status: modelStatus,
Total: models.Total,
Exposed: models.Exposed,
Zen: models.Zen,
Go: models.Go,
LastRefresh: lastRefresh,
StaleAfterSeconds: int(staleAfter / time.Second),
},
Keys: healthKeys{Zen: zenKeys, Go: goKeys, Total: zenKeys + goKeys},
Proxies: healthProxies{
Total: proxyTotal,
Healthy: proxyHealthy,
Unhealthy: proxyTotal - proxyHealthy,
},
Issues: issues,
})
}
func (g *Gateway) authenticate(next http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
candidates := []string{strings.TrimSpace(r.Header.Get("x-api-key"))}
+33
View File
@@ -47,6 +47,14 @@ type modelCatalog struct {
prefer Tier
}
type modelCatalogSnapshot struct {
Zen int
Go int
Total int
Exposed int
UpdatedAt time.Time
}
func newModelCatalog(prefer Tier, overrides map[string]string) *modelCatalog {
protocols := make(map[string]Protocol, len(overrides))
for model, protocol := range overrides {
@@ -118,6 +126,31 @@ func (c *modelCatalog) List() []string {
return models
}
func (c *modelCatalog) Snapshot() modelCatalogSnapshot {
c.mu.RLock()
defer c.mu.RUnlock()
seen := make(map[string]bool, len(c.zen)+len(c.goModels))
for model := range c.zen {
seen[model] = true
}
for model := range c.goModels {
seen[model] = true
}
exposed := 0
for model := range seen {
if supportedModel(model) {
exposed++
}
}
return modelCatalogSnapshot{
Zen: len(c.zen),
Go: len(c.goModels),
Total: len(seen),
Exposed: exposed,
UpdatedAt: c.updatedAt,
}
}
func toSet(items []string) map[string]bool {
out := make(map[string]bool, len(items))
for _, item := range items {
+12
View File
@@ -38,6 +38,18 @@ func (p *transportPool) hasHealthy() bool {
return false
}
func (p *transportPool) healthCounts() (total, healthy int) {
if p == nil {
return 0, 0
}
for _, proxy := range p.items {
if proxy.healthy.Load() {
healthy++
}
}
return len(p.items), healthy
}
func newTransportPool(proxies []string, cfg PerformanceConfig, responseHeaderTimeout time.Duration) (*transportPool, error) {
p := &transportPool{items: make([]*proxyTransport, 0, len(proxies))}
for _, raw := range proxies {