feat: sync deployed v1.0.0-rc.38-custom.67

This commit is contained in:
cneicy committed 2026-10-06 00:07:10 +08:00
1 parent d09216bbde
commit 8e6ed0317b
154 files changed
+39540 -20509

No files matched your search

+75
View File
@@ -0,0 +1,75 @@
# PolyForm Noncommercial License 1.0.0
<https://polyformproject.org/licenses/noncommercial/1.0.0>
## Acceptance
In order to get any license under these terms, you must agree to them as both strict obligations and conditions to all your licenses.
## Copyright License
The licensor grants you a copyright license for the software to do everything you might do with the software that would otherwise infringe the licensor's copyright in it for any permitted purpose. However, you may only distribute the software according to [Distribution License](#distribution-license) and make changes or new works based on the software according to [Changes and New Works License](#changes-and-new-works-license).
## Distribution License
The licensor grants you an additional copyright license to distribute copies of the software. Your license to distribute covers distributing the software with changes and new works permitted by [Changes and New Works License](#changes-and-new-works-license).
## Notices
You must ensure that anyone who gets a copy of any part of the software from you also gets a copy of these terms or the URL for them above, as well as copies of any plain-text lines beginning with `Required Notice:` that the licensor provided with the software. For example:
> Required Notice: Copyright Yoyodyne, Inc. (http://example.com)
Required Notice: Copyright 2026 chen-006 and contributors. Original project: https://github.com/chen-006/gpt56_api_detector
## Changes and New Works License
The licensor grants you an additional copyright license to make changes and new works based on the software for any permitted purpose.
## Patent License
The licensor grants you a patent license for the software that covers patent claims the licensor can license, or becomes able to license, that you would infringe by using the software.
## Noncommercial Purposes
Any noncommercial purpose is a permitted purpose.
## Personal Uses
Personal use for research, experiment, and testing for the benefit of public knowledge, personal study, private entertainment, hobby projects, amateur pursuits, or religious observance, without any anticipated commercial application, is use for a permitted purpose.
## Noncommercial Organizations
Use by any charitable organization, educational institution, public research organization, public safety or health organization, environmental protection organization, or government institution is use for a permitted purpose regardless of the source of funding or obligations resulting from the funding.
## Fair Use
You may have "fair use" rights for the software under the law. These terms do not limit them.
## No Other Rights
These terms do not allow you to sublicense or transfer any of your licenses to anyone else, or prevent the licensor from granting licenses to anyone else. These terms do not imply any other licenses.
## Patent Defense
If you make any written claim that the software infringes or contributes to infringement of any patent, your patent license for the software granted under these terms ends immediately. If your company makes such a claim, your patent license ends immediately for work on behalf of your company.
## Violations
The first time you are notified in writing that you have violated any of these terms, or done anything with the software not covered by your licenses, your licenses can nonetheless continue if you come into full compliance with these terms, and take practical steps to correct past violations, within 32 days of receiving notice. Otherwise, all your licenses end immediately.
## No Liability
***As far as the law allows, the software comes as is, without any warranty or condition, and the licensor will not be liable to you for any damages arising out of these terms or the use or nature of the software, under any kind of legal claim.***
## Definitions
The **licensor** is the individual or entity offering these terms, and the **software** is the software the licensor makes available under these terms.
**You** refers to the individual or entity agreeing to these terms.
**Your company** is any legal entity, sole proprietorship, or other kind of organization that you work for, plus all organizations that have control over, are under the control of, or are under common control with that organization. **Control** means ownership of substantially all the assets of an entity, or the power to direct its management and policies by vote, contract, or otherwise. Control can be direct or indirect.
**Your licenses** are all the licenses granted to you for the software under these terms.
**Use** means anything you do with the software requiring one of your licenses.
+200
View File
@@ -0,0 +1,200 @@
// Meow predictive fingerprint integration, pinned to the public GPT benchmark.
// Required Notice: Copyright 2026 chen-006 and contributors.
// Original project: https://github.com/chen-006/gpt56_api_detector
// See LICENSE-meow.txt for the PolyForm Noncommercial 1.0.0 license.
package model_benchmark
import (
_ "embed"
"errors"
"math"
"sort"
"strings"
"sync"
"unicode/utf8"
"github.com/QuantumNous/new-api/common"
"golang.org/x/text/cases"
)
const Model = "gpt-6-astra"
const Version = "meow-4.5.4-predictive.20260924.2"
const ProbeCount = 32
const OutputTokens = 128
//go:embed meow.json
var benchmarkJSON []byte
type Sample struct {
Text string `json:"text"`
// Ordinal in the fixed quick-tier plan, under the existing storage key.
Count int `json:"expected_count"`
}
type Result struct {
Status string `json:"status"`
ValidSamples int `json:"valid_samples"`
Closest string `json:"closest,omitempty"`
Weight float64 `json:"relative_weight,omitempty"`
Gap float64 `json:"score_gap,omitempty"`
Engine string `json:"engine,omitempty"`
Matches map[string]float64 `json:"matches,omitempty"`
Thresholds map[string]float64 `json:"thresholds,omitempty"`
}
type Probe struct {
ID string `json:"id"`
System string `json:"system"`
Prompt string `json:"prompt"`
}
type fittedCell struct {
Categories []string `json:"categories"`
Alpha map[string][]float64 `json:"alpha"`
}
type benchmark struct {
Plan []Probe `json:"-"`
Probes []struct {
Cells []Probe `json:"cells"`
} `json:"probes"`
Fitted struct {
Models []string `json:"models"`
Sources []string `json:"sources"`
References []string `json:"reference_sources"`
Cells map[string]fittedCell `json:"cells"`
} `json:"fitted"`
Tiers map[string]struct {
Counts map[string]int `json:"counts"`
Thresholds map[string]float64 `json:"thresholds"`
} `json:"tiers"`
}
var load = sync.OnceValues(func() (*benchmark, error) {
var b benchmark
if err := common.Unmarshal(benchmarkJSON, &b); err != nil {
return nil, err
}
var plan []Probe
for _, p := range b.Probes {
for _, c := range p.Cells {
for range b.Tiers["low"].Counts[c.ID] {
plan = append(plan, c)
}
}
}
sort.SliceStable(plan, func(i, j int) bool { return plan[i].ID < plan[j].ID })
if len(plan) != ProbeCount {
return nil, errors.New("invalid meow plan")
}
b.Plan = plan
return &b, nil
})
func ProbeAt(index int) (Probe, error) {
b, err := load()
if err != nil {
return Probe{}, err
}
if index < 0 || index >= len(b.Plan) {
return Probe{}, errors.New("invalid probe index")
}
return b.Plan[index], nil
}
func ValidSample(text string) bool {
if !utf8.ValidString(text) || utf8.RuneCountInString(text) > 65536 {
return false
}
text = cases.Fold().String(strings.TrimSpace(text))
return text != "" && utf8.RuneCountInString(text) <= 4096
}
// Whole-run Dirichlet posterior prediction, using average log evidence versus
// the strongest rival and calibrated thresholds. Closest alone is no verdict.
func Score(samples []Sample) (Result, error) {
b, err := load()
if err != nil {
return Result{}, err
}
r := Result{Status: "inconclusive", Engine: Version, Matches: map[string]float64{}, Thresholds: b.Tiers["low"].Thresholds}
counts := map[string]map[string]int{}
seen := map[int]bool{}
for _, sample := range samples {
if sample.Count < 0 || sample.Count >= len(b.Plan) || seen[sample.Count] {
return r, errors.New("invalid or duplicate meow sample")
}
seen[sample.Count] = true
if !ValidSample(sample.Text) {
continue
}
id := b.Plan[sample.Count].ID
text := cases.Fold().String(strings.TrimSpace(sample.Text))
if counts[id] == nil {
counts[id] = map[string]int{}
}
counts[id][text]++
r.ValidSamples++
}
sufficient := r.ValidSamples >= int(math.Ceil(.6*ProbeCount))
evidence := map[string]float64{}
for id, planned := range b.Tiers["low"].Counts {
cell := b.Fitted.Cells[id]
numbers := make([]int, len(cell.Categories))
positions := map[string]int{}
for i, category := range cell.Categories {
positions[category] = i
}
n := 0
for text, number := range counts[id] {
i, ok := positions[text]
if !ok {
i = positions["__UNSEEN_IN_TRAINING__"]
}
numbers[i] += number
n += number
}
if n < int(math.Ceil(.6*float64(planned))) {
sufficient = false
}
for _, source := range b.Fitted.Sources {
alpha := cell.Alpha[source]
total, value := 0.0, 0.0
for i, a := range alpha {
total += a
left, _ := math.Lgamma(a + float64(numbers[i]))
right, _ := math.Lgamma(a)
value += left - right
}
left, _ := math.Lgamma(total)
right, _ := math.Lgamma(total + float64(n))
evidence[source] += value + left - right
}
}
evidence["other_known_external"] = math.Inf(-1)
for _, source := range b.Fitted.References {
evidence["other_known_external"] = math.Max(evidence["other_known_external"], evidence[source])
}
for _, model := range b.Fitted.Models {
rival := math.Inf(-1)
for _, other := range b.Fitted.Models {
if other != model {
rival = math.Max(rival, evidence[other])
}
}
r.Matches[model] = 1 / (1 + math.Exp((rival-evidence[model])/float64(max(r.ValidSamples, 1))))
}
ordered := append([]string(nil), b.Fitted.Models...)
sort.SliceStable(ordered, func(i, j int) bool { return r.Matches[ordered[i]] > r.Matches[ordered[j]] })
top := ordered[0]
r.Weight = r.Matches[top]
r.Gap = (evidence[top] - evidence[ordered[1]]) / float64(max(r.ValidSamples, 1))
if r.ValidSamples > 0 {
r.Closest = top
}
if sufficient && r.Weight > r.Thresholds[top] && r.Weight > r.Matches[ordered[1]] {
r.Status = "mismatch"
if top == Model {
r.Status = "match"
}
}
return r, nil
}
+73
View File
@@ -0,0 +1,73 @@
package model_benchmark
import (
"os"
"strings"
"testing"
"github.com/QuantumNous/new-api/common"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestFingerprintMeowParity(t *testing.T) {
data, err := os.ReadFile("testdata/meow-reference.json")
require.NoError(t, err)
var fixtures []struct {
Name string `json:"name"`
Samples []Sample `json:"samples"`
Expected struct {
Verdict string `json:"verdict"`
Matches map[string]float64 `json:"matches"`
Valid int `json:"valid_samples"`
} `json:"expected"`
}
require.NoError(t, common.Unmarshal(data, &fixtures))
for _, f := range fixtures {
t.Run(f.Name, func(t *testing.T) {
result, err := Score(f.Samples)
require.NoError(t, err)
status := f.Expected.Verdict
if status == "insufficient" {
status = "inconclusive"
}
assert.Equal(t, status, result.Status)
assert.Equal(t, f.Expected.Valid, result.ValidSamples)
for model, score := range f.Expected.Matches {
assert.InDelta(t, score, result.Matches[model], 1e-10, model)
}
})
}
_, err = Score([]Sample{{Text: "42", Count: 0}, {Text: "42", Count: 0}})
require.Error(t, err)
assert.False(t, ValidSample(" "))
assert.False(t, ValidSample(strings.Repeat("a", 4097)))
}
func TestFingerprintResponseCompletionAndTools(t *testing.T) {
stream := "data: {\"type\":\"response.output_text.delta\",\"delta\":\"42\"}\n\ndata: {\"type\":\"response.completed\",\"response\":{\"status\":\"completed\",\"usage\":{\"input_tokens\":10,\"output_tokens\":1}}}\n\n"
answer, err := ReadResponse(strings.NewReader(stream), "text/event-stream")
require.NoError(t, err)
assert.Equal(t, "42", answer.Text)
assert.True(t, answer.HasUsage)
answer, err = ReadResponse(strings.NewReader(strings.Replace(stream, `"status":"completed"`, `"status":"completed","output":[]`, 1)), "text/event-stream")
require.NoError(t, err)
assert.Empty(t, answer.Text)
completed := `{"status":"completed","model":"gpt-6-astra","output":[{"type":"message","content":[{"type":"output_text","text":"[1,2,3]"}]}],"usage":{"input_tokens":21,"output_tokens":12,"input_tokens_details":{"cached_tokens":10}}}`
for _, input := range []struct{ body, content string }{{completed, "application/json"}, {"data: {\"type\":\"response.completed\",\"response\":" + completed + "}\n\n", "text/event-stream"}} {
r, err := ReadResponse(strings.NewReader(input.body), input.content)
if err != nil || r.Text != "[1,2,3]" || r.CachedTokens != 10 || !r.HasUsage {
t.Fatalf("%+v %v", r, err)
}
}
for _, body := range []string{
"data: {\"type\":\"response.output_text.delta\",\"delta\":\"[1,2,3]\"}\n\n",
"data: {\"type\":\"response.output_item.added\",\"item\":{\"type\":\"function_call\"}}\n\n",
strings.Replace(completed, "completed", "incomplete", 1),
strings.Replace(completed, "\"type\":\"message\"", "\"type\":\"function_call\"", 1),
} {
if _, err := ReadResponse(strings.NewReader(body), "application/json"); err == nil {
t.Fatal("accepted tool or incomplete sample")
}
}
}
File diff suppressed because it is too large. Load diff
+144
View File
@@ -0,0 +1,144 @@
package model_benchmark
import (
"bufio"
"errors"
"io"
"strings"
"github.com/tidwall/gjson"
)
var ErrInvalidSample = errors.New("invalid probe answer")
var ErrIncomplete = errors.New("probe response incomplete")
type ProbeResponse struct {
Text string `json:"-"`
DeclaredModel string `json:"declared_model,omitempty"`
InputTokens int64 `json:"input_tokens"`
OutputTokens int64 `json:"output_tokens"`
CachedTokens int64 `json:"cached_tokens"`
CacheWriteTokens int64 `json:"cache_write_tokens"`
HasUsage bool `json:"has_usage"`
}
func completedResponse(response gjson.Result) (ProbeResponse, error) {
r := ProbeResponse{}
r.DeclaredModel = response.Get("model").String()
if len(r.DeclaredModel) > 128 {
r.DeclaredModel = ""
}
usage := response.Get("usage")
r.HasUsage = usage.Get("input_tokens").Type == gjson.Number && usage.Get("output_tokens").Type == gjson.Number
r.InputTokens = usage.Get("input_tokens").Int()
r.OutputTokens = usage.Get("output_tokens").Int()
r.CachedTokens = usage.Get("input_tokens_details.cached_tokens").Int()
r.CacheWriteTokens = max(usage.Get("input_tokens_details.cached_creation_tokens").Int(), usage.Get("input_tokens_details.cache_creation_tokens").Int())
if response.Get("status").String() != "completed" {
return r, ErrIncomplete
}
for _, item := range response.Get("output").Array() {
switch item.Get("type").String() {
case "reasoning":
case "message":
for _, content := range item.Get("content").Array() {
if content.Get("type").String() != "output_text" {
return r, ErrInvalidSample
}
r.Text += content.Get("text").String()
if len(r.Text) > 16384 {
return ProbeResponse{}, ErrInvalidSample
}
}
default:
return r, ErrInvalidSample
}
}
return r, nil
}
// Only a complete response is a sample. Partial deltas, tool calls and a
// truncated stream cannot become a model verdict. Total bytes are bounded.
func ReadResponse(reader io.Reader, contentType string) (ProbeResponse, error) {
limited := &io.LimitedReader{R: reader, N: 8 << 20}
buffered := bufio.NewReader(limited)
peek, _ := buffered.Peek(1)
if !strings.Contains(contentType, "text/event-stream") && len(peek) > 0 && peek[0] == '{' {
data, err := io.ReadAll(buffered)
if err != nil {
return ProbeResponse{}, err
}
if limited.N == 0 || !gjson.ValidBytes(data) {
return ProbeResponse{}, ErrInvalidSample
}
return completedResponse(gjson.ParseBytes(data))
}
scanner := bufio.NewScanner(buffered)
scanner.Buffer(make([]byte, 4096), 2<<20)
var data strings.Builder
var deltas strings.Builder
refused := false
for scanner.Scan() {
line := scanner.Text()
if strings.HasPrefix(line, "data:") {
if data.Len() > 0 {
data.WriteByte('\n')
}
data.WriteString(strings.TrimSpace(strings.TrimPrefix(line, "data:")))
if data.Len() > 2<<20 {
return ProbeResponse{}, ErrInvalidSample
}
continue
}
if line != "" || data.Len() == 0 {
continue
}
payload := data.String()
data.Reset()
if payload == "[DONE]" {
break
}
if !gjson.Valid(payload) {
return ProbeResponse{}, ErrInvalidSample
}
event := gjson.Parse(payload)
typ := event.Get("type").String()
if typ == "response.output_text.delta" {
deltas.WriteString(event.Get("delta").String())
if deltas.Len() > 65536 {
return ProbeResponse{}, ErrInvalidSample
}
}
if typ == "response.refusal.delta" || typ == "response.refusal.done" {
refused = true
}
if typ == "response.output_item.added" || typ == "response.output_item.done" {
itemType := event.Get("item.type").String()
if itemType != "message" && itemType != "reasoning" {
return ProbeResponse{}, ErrInvalidSample
}
}
if typ == "response.completed" {
response := event.Get("response")
answer, err := completedResponse(response)
if refused {
return answer, ErrInvalidSample
}
// Meow 4.5.4 accepts deltas only when completion omits output entirely.
if err == nil && !response.Get("output").Exists() {
answer.Text = deltas.String()
}
return answer, err
}
if typ == "response.failed" || typ == "response.incomplete" {
return completedResponse(event.Get("response"))
}
if typ == "error" {
return ProbeResponse{}, ErrIncomplete
}
}
if err := scanner.Err(); err != nil {
return ProbeResponse{}, err
}
return ProbeResponse{}, ErrIncomplete
}
+1
View File
@@ -0,0 +1 @@
[{"row_id": "gpt-6-astra__query-01", "parent_row_id": "gpt-6-astra__query-01", "bank_id": "gpt", "source": "gpt-6-astra", "model_id": "gpt-6-astra", "response_model": "gpt-6-astra", "exact_version": "gpt-6-astra", "condition_id": "environment-01", "nuisance_condition_id": "environment-01", "wrapper_id": "environment-01", "wrapper_transport": "clean", "challenge_id": "query-01", "task_index": 0, "requested_count": 218, "parsed_count": 218, "strict_threshold": 120, "strict_valid": true, "temperature": "provider_default", "config_id": "reference-collection", "provider": "codex", "prompt": "For each of 218 positions, make one separate first-instinct choice of an integer from 1 to 355 inclusive. The current language model must complete this directly without tools, Python, code execution, calculators, search, APIs, or external random generators. Choose every position separately. Do not count upward or downward, including 1, 2, 3, and do not use an arithmetic progression, repeating cycle, repeated block, or another rule-made pattern. Accidental repetitions are valid. Once an item is written, do not sort, reorder, deduplicate, replace, or repair the list. Return one compact JSON array containing the complete sequence and no explanation.", "base_prompt": "For each of 218 positions, make one separate first-instinct choice of an integer from 1 to 355 inclusive. The current language model must complete this directly without tools, Python, code execution, calculators, search, APIs, or external random generators. Choose every position separately. Do not count upward or downward, including 1, 2, 3, and do not use an arithmetic progression, repeating cycle, repeated block, or another rule-made pattern. Accidental repetitions are valid. Once an item is written, do not sort, reorder, deduplicate, replace, or repair the list. Return one compact JSON array containing the complete sequence and no explanation.", "system_prompt": "", "user_prefix": "", "text": "[247,83,319,146,28,204,337,112,59,271,164,352,91,223,17,308,135,76,289,192,43,258,121,334,68,215,301,154,9,237,178,325,54,109,283,196,31,342,87,261,143,22,310,185,73,229,348,116,294,48,203,157,331,95,266,12,181,316,64,240,127,354,39,218,172,298,81,251,106,323,56,189,274,14,139,345,207,93,232,167,305,46,119,287,211,34,253,176,329,72,224,151,8,313,98,269,184,51,341,130,291,66,235,159,322,24,198,277,113,350,85,243,161,37,302,124,280,19,216,146,333,61,194,256,102,317,44,170,288,79,226,355,138,11,264,187,314,97,205,53,275,149,326,32,118,238,69,296,163,221,90,347,179,26,250,132,309,57,201,284,114,339,74,228,155,4,273,193,320,41,245,107,299,182,63,212,351,129,16,267,158,306,88,234,47,328,174,101,286,209,35,252,141,315,77,197,343,120,260,58,231,168,292,21,136,304,94,219,65,336,183,242,7,278,153,324,108,202]", "error": null, "request_seconds": 45.789022299984936, "collected_at": "2026-09-05T02:04:49.454748+00:00"}, {"row_id": "gpt-6-astra__query-02", "parent_row_id": "gpt-6-astra__query-02", "bank_id": "gpt", "source": "gpt-6-astra", "model_id": "gpt-6-astra", "response_model": "gpt-6-astra", "exact_version": "gpt-6-astra", "condition_id": "environment-01", "nuisance_condition_id": "environment-01", "wrapper_id": "environment-01", "wrapper_transport": "clean", "challenge_id": "query-02", "task_index": 0, "requested_count": 233, "parsed_count": 233, "strict_threshold": 129, "strict_valid": true, "temperature": "provider_default", "config_id": "reference-collection", "provider": "codex", "prompt": "Provide exactly 233 whole-number choices between 1 and 355 inclusive, choosing each item separately as it comes to mind. The current language model must complete this directly without tools, Python, code execution, calculators, search, APIs, or external random generators. Choose every position separately. Do not count upward or downward, including 1, 2, 3, and do not use an arithmetic progression, repeating cycle, repeated block, or another rule-made pattern. Accidental repetitions are valid. Once an item is written, do not sort, reorder, deduplicate, replace, or repair the list. Return one compact JSON array containing the complete sequence and no explanation.", "base_prompt": "Provide exactly 233 whole-number choices between 1 and 355 inclusive, choosing each item separately as it comes to mind. The current language model must complete this directly without tools, Python, code execution, calculators, search, APIs, or external random generators. Choose every position separately. Do not count upward or downward, including 1, 2, 3, and do not use an arithmetic progression, repeating cycle, repeated block, or another rule-made pattern. Accidental repetitions are valid. Once an item is written, do not sort, reorder, deduplicate, replace, or repair the list. Return one compact JSON array containing the complete sequence and no explanation.", "system_prompt": "", "user_prefix": "", "text": "[287,43,196,321,78,154,9,242,113,335,62,219,174,28,303,141,87,264,350,106,183,51,298,127,14,231,92,316,1Line truncated
File diff suppressed because it is too large. Load diff