mirror of
https://github.com/CJackHwang/ds2api.git
synced 2026-05-05 00:45:29 +08:00
Unify Claude count_tokens, legacy stream accounting, and legacy render usage with preserved prompt text so Claude stops falling back to lossy message formatting.
35 lines
934 B
Go
35 lines
934 B
Go
package claude
|
|
|
|
import (
|
|
"encoding/json"
|
|
"net/http"
|
|
)
|
|
|
|
func (h *Handler) CountTokens(w http.ResponseWriter, r *http.Request) {
|
|
a, err := h.Auth.Determine(r)
|
|
if err != nil {
|
|
writeClaudeError(w, http.StatusUnauthorized, err.Error())
|
|
return
|
|
}
|
|
defer h.Auth.Release(a)
|
|
|
|
var req map[string]any
|
|
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
|
|
writeClaudeError(w, http.StatusBadRequest, "invalid json")
|
|
return
|
|
}
|
|
model, _ := req["model"].(string)
|
|
messages, _ := req["messages"].([]any)
|
|
if model == "" || len(messages) == 0 {
|
|
writeClaudeError(w, http.StatusBadRequest, "Request must include 'model' and 'messages'.")
|
|
return
|
|
}
|
|
normalized, err := normalizeClaudeRequest(h.Store, req)
|
|
if err != nil {
|
|
writeClaudeError(w, http.StatusBadRequest, err.Error())
|
|
return
|
|
}
|
|
inputTokens := countClaudeInputTokens(normalized.Standard)
|
|
writeJSON(w, http.StatusOK, map[string]any{"input_tokens": inputTokens})
|
|
}
|