mirror of
https://github.com/RuoJi6/ARTEX.git
synced 2026-12-02 20:01:51 +08:00
fix: address Jev judge review feedback
This commit is contained in:
1 parent
b0e25d766f
commit
9a1599b96e
17 files changed
+608
-113
No files matched your search
+56
-7
@@ -5,6 +5,7 @@ import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"log"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"regexp"
|
||||
@@ -54,7 +55,12 @@ func (s *Server) wireInterceptReviewer() {
|
||||
return intercept.Decision{ProfileID: profileID}, fmt.Errorf("Jev 判定模型未设置 API Key")
|
||||
}
|
||||
ctx = llmrec.WithWorker(ctx, judgeWorkerLane)
|
||||
return jev.Config{BaseURL: profile.BaseURL, APIKey: profile.APIKey, Model: profile.Model}.Review(ctx, input, prompt, s.m.interceptor.GetJudgeConfig().ConfidenceThreshold, profileID)
|
||||
started := time.Now()
|
||||
decision, usage, reviewErr := (jev.Config{
|
||||
BaseURL: profile.BaseURL, APIKey: profile.APIKey, Model: profile.Model, Proxy: profile.Proxy,
|
||||
}).ReviewWithUsage(ctx, input, prompt, s.m.interceptor.GetJudgeConfig().ConfidenceThreshold, profileID)
|
||||
s.recordJevJudgeUsage(ctx, profile, usage, started, reviewErr)
|
||||
return decision, reviewErr
|
||||
}
|
||||
prov, _, ok := s.providerForProfile(profileID)
|
||||
if !ok {
|
||||
@@ -75,6 +81,32 @@ func (s *Server) wireInterceptReviewer() {
|
||||
})
|
||||
}
|
||||
|
||||
func (s *Server) recordJevJudgeUsage(ctx context.Context, profile *db.LLMProfile, usage jev.Usage, started time.Time, callErr error) {
|
||||
if s == nil || s.m == nil || s.m.PG() == nil || profile == nil {
|
||||
return
|
||||
}
|
||||
status := "ok"
|
||||
if callErr != nil {
|
||||
status = "error"
|
||||
}
|
||||
model := strings.TrimSpace(profile.Model)
|
||||
if model == "" {
|
||||
model = jev.DefaultModel
|
||||
}
|
||||
if err := s.m.PG().InsertLLMUsage(&db.LLMUsage{
|
||||
TaskID: llmrec.TaskIDFrom(ctx),
|
||||
Worker: judgeWorkerLane,
|
||||
Model: model,
|
||||
ProfileName: profile.Name,
|
||||
LatencyMs: int(time.Since(started).Milliseconds()),
|
||||
InputTokens: usage.InputTokens,
|
||||
OutputTokens: usage.OutputTokens,
|
||||
Status: status,
|
||||
}); err != nil {
|
||||
log.Printf("[llmusage] Jev judge insert: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func reviewCompletion(ctx context.Context, prov llm.Provider, prompt string, input intercept.ReviewInput) (string, error) {
|
||||
user, err := json.Marshal(input)
|
||||
if err != nil {
|
||||
@@ -461,11 +493,27 @@ func (s *Server) interceptGetJudgeConfig(w http.ResponseWriter, r *http.Request)
|
||||
|
||||
// interceptSetJudgeConfig persists the judge configuration.
|
||||
func (s *Server) interceptSetJudgeConfig(w http.ResponseWriter, r *http.Request) {
|
||||
var req intercept.JudgeConfig
|
||||
if err := decode(r, &req); err != nil {
|
||||
var raw json.RawMessage
|
||||
if err := decode(r, &raw); err != nil {
|
||||
writeErr(w, 400, err.Error())
|
||||
return
|
||||
}
|
||||
var req intercept.JudgeConfig
|
||||
if err := json.Unmarshal(raw, &req); err != nil {
|
||||
writeErr(w, 400, err.Error())
|
||||
return
|
||||
}
|
||||
var fields map[string]json.RawMessage
|
||||
if err := json.Unmarshal(raw, &fields); err != nil {
|
||||
writeErr(w, 400, err.Error())
|
||||
return
|
||||
}
|
||||
if _, present := fields["confidence_threshold"]; !present {
|
||||
req.ConfidenceThreshold = 0.55
|
||||
} else if req.ConfidenceThreshold < 0 || req.ConfidenceThreshold > 1 {
|
||||
writeErr(w, 400, "confidence_threshold 必须在 0 到 1 之间")
|
||||
return
|
||||
}
|
||||
switch req.FailAction {
|
||||
case "allow", "ask", "deny":
|
||||
default:
|
||||
@@ -490,11 +538,12 @@ func (s *Server) interceptSetJudgeConfig(w http.ResponseWriter, r *http.Request)
|
||||
writeErr(w, 400, err.Error())
|
||||
return
|
||||
}
|
||||
if req.ConfidenceThreshold <= 0 || req.ConfidenceThreshold > 1 {
|
||||
req.ConfidenceThreshold = 0.55
|
||||
}
|
||||
if err := s.m.interceptor.SetJudgeConfig(req); err != nil {
|
||||
writeErr(w, 500, err.Error())
|
||||
if strings.Contains(err.Error(), "confidence_threshold") {
|
||||
writeErr(w, 400, err.Error())
|
||||
} else {
|
||||
writeErr(w, 500, err.Error())
|
||||
}
|
||||
return
|
||||
}
|
||||
writeJSON(w, 200, map[string]any{"ok": true})
|
||||
|
||||
@@ -129,3 +129,41 @@ func TestJudgeConfigRetryRoundTrip(t *testing.T) {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestJudgeConfidenceThresholdKeepsExplicitZeroAndRejectsOutOfRange(t *testing.T) {
|
||||
judgeConfigSQLiteNow.Do(func() {
|
||||
sqlite.MustRegisterDeterministicScalarFunction("now", 0, func(*sqlite.FunctionContext, []driver.Value) (driver.Value, error) {
|
||||
return "2026-01-01 00:00:00", nil
|
||||
})
|
||||
})
|
||||
sqldb, err := sql.Open("sqlite", ":memory:")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { _ = sqldb.Close() })
|
||||
if _, err := sqldb.Exec(`CREATE TABLE settings (key TEXT PRIMARY KEY, value TEXT, updated_at TEXT)`); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
pg := &db.DB{DB: sqldb}
|
||||
s := &Server{m: &Manager{pg: pg, interceptor: intercept.New(pg)}}
|
||||
cfg := s.m.interceptor.GetJudgeConfig()
|
||||
cfg.ConfidenceThreshold = 0
|
||||
body, _ := json.Marshal(cfg)
|
||||
w := httptest.NewRecorder()
|
||||
s.interceptSetJudgeConfig(w, httptest.NewRequest("PUT", "/api/intercept/judge", strings.NewReader(string(body))))
|
||||
if w.Code != 200 || s.m.interceptor.GetJudgeConfig().ConfidenceThreshold != 0 {
|
||||
t.Fatalf("explicit zero status=%d cfg=%+v body=%s", w.Code, s.m.interceptor.GetJudgeConfig(), w.Body.String())
|
||||
}
|
||||
w = httptest.NewRecorder()
|
||||
s.interceptSetJudgeConfig(w, httptest.NewRequest("PUT", "/api/intercept/judge", strings.NewReader(`{"fail_action":"ask","ask_timeout_action":"deny"}`)))
|
||||
if w.Code != 200 || s.m.interceptor.GetJudgeConfig().ConfidenceThreshold != 0.55 {
|
||||
t.Fatalf("missing threshold status=%d cfg=%+v body=%s", w.Code, s.m.interceptor.GetJudgeConfig(), w.Body.String())
|
||||
}
|
||||
for _, value := range []string{"-0.01", "1.01"} {
|
||||
w = httptest.NewRecorder()
|
||||
s.interceptSetJudgeConfig(w, httptest.NewRequest("PUT", "/api/intercept/judge", strings.NewReader(`{"fail_action":"ask","ask_timeout_action":"deny","confidence_threshold":`+value+`}`)))
|
||||
if w.Code != 400 {
|
||||
t.Fatalf("threshold=%s status=%d body=%s", value, w.Code, w.Body.String())
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -477,6 +477,9 @@ func (m *Manager) SetWorkerPools(pools []WorkerPool, legacyWorkers ...int) error
|
||||
if profile == nil {
|
||||
return fmt.Errorf("worker_pools 中 profile_id %d 不存在", pool.ProfileID)
|
||||
}
|
||||
if profile.Format == "jev" {
|
||||
return pgdb.ErrJevProfileJudgeOnly
|
||||
}
|
||||
}
|
||||
}
|
||||
b, err := json.Marshal(pools)
|
||||
|
||||
+54
-7
@@ -136,6 +136,9 @@ type Server struct {
|
||||
type provEntry struct {
|
||||
prov llm.Provider
|
||||
cfg agent.Config
|
||||
// jev is retained in the cache entry so a cached chat provider can be
|
||||
// returned without consulting the DB on every hot-path resolution.
|
||||
jev bool
|
||||
}
|
||||
|
||||
// triggeredRun is one queued P3 trigger fire awaiting its turn for an agent.
|
||||
@@ -364,6 +367,9 @@ func (s *Server) loadLLMConfig() (agent.Config, bool) {
|
||||
if err != nil || p == nil {
|
||||
return agent.Config{}, false
|
||||
}
|
||||
if p.Format == "jev" {
|
||||
return agent.Config{}, false
|
||||
}
|
||||
cfg := agent.ConfigFrom(p.Format, p.Model, p.BaseURL, p.APIKey, p.Proxy)
|
||||
cfg.RatePerSecond, cfg.RatePerMinute = p.RatePerSecond, p.RatePerMinute
|
||||
cfg.ContextWindowK = p.ContextWindowK
|
||||
@@ -384,6 +390,9 @@ func (s *Server) loadLLMConfig() (agent.Config, bool) {
|
||||
|
||||
// saveLLMConfig persists the LLM config as the active "default" profile in PG.
|
||||
func (s *Server) saveLLMConfig(cfg agent.Config) error {
|
||||
if cfg.Jev || cfg.Provider() == "jev" {
|
||||
return db.ErrJevProfileJudgeOnly
|
||||
}
|
||||
// cfg.Provider() returns one of the chat format strings
|
||||
// (anthropic / openai / openai-responses), matching the DB CHECK constraint;
|
||||
// Jev is intentionally handled by the dedicated intercept path.
|
||||
@@ -539,6 +548,13 @@ func (s *Server) loadProfileConfig(id int64) (agent.Config, bool) {
|
||||
if err != nil || p == nil {
|
||||
return agent.Config{}, false
|
||||
}
|
||||
return s.profileConfig(p)
|
||||
}
|
||||
|
||||
func (s *Server) profileConfig(p *db.LLMProfile) (agent.Config, bool) {
|
||||
if p == nil {
|
||||
return agent.Config{}, false
|
||||
}
|
||||
if p.Format == "jev" {
|
||||
return agent.Config{}, false
|
||||
}
|
||||
@@ -607,27 +623,52 @@ func (s *Server) chatUnavailableReason() string {
|
||||
// ok=false when the profile is missing/invalid; pinned callers surface that error
|
||||
// while legacy callers retain their existing fallback behavior.
|
||||
func (s *Server) providerForProfile(id int64) (llm.Provider, agent.Config, bool) {
|
||||
if p, err := s.m.pg.ProfileByID(id); err != nil || p == nil || p.Format == "jev" {
|
||||
return nil, agent.Config{}, false
|
||||
}
|
||||
s.provCacheMu.Lock()
|
||||
if e := s.provByProfile[id]; e != nil {
|
||||
if e.jev {
|
||||
s.provCacheMu.Unlock()
|
||||
return nil, agent.Config{}, false
|
||||
}
|
||||
s.provCacheMu.Unlock()
|
||||
return e.prov, e.cfg, true
|
||||
}
|
||||
generation := s.provCacheGen
|
||||
s.provCacheMu.Unlock()
|
||||
cfg, ok := s.loadProfileConfig(id)
|
||||
// Only a cache miss reaches the DB. This preserves an already-built chat
|
||||
// provider during a transient profile lookup failure and avoids a query for
|
||||
// every agent/task resolution.
|
||||
profile, err := s.m.pg.ProfileByID(id)
|
||||
if err != nil || profile == nil {
|
||||
return nil, agent.Config{}, false
|
||||
}
|
||||
if profile.Format == "jev" {
|
||||
// Cache the negative result too. Profile writes/activation invalidate this
|
||||
// generation, while a transient DB error on a cached chat profile above
|
||||
// still returns that already-built provider.
|
||||
s.provCacheMu.Lock()
|
||||
if generation == s.provCacheGen {
|
||||
if s.provByProfile == nil {
|
||||
s.provByProfile = map[int64]*provEntry{}
|
||||
}
|
||||
s.provByProfile[id] = &provEntry{jev: true}
|
||||
}
|
||||
s.provCacheMu.Unlock()
|
||||
return nil, agent.Config{}, false
|
||||
}
|
||||
cfg, ok := s.profileConfig(profile)
|
||||
if !ok {
|
||||
return nil, agent.Config{}, false
|
||||
}
|
||||
profile, _ := s.m.pg.ProfileByID(id)
|
||||
s.provCacheMu.Lock()
|
||||
if generation != s.provCacheGen {
|
||||
s.provCacheMu.Unlock()
|
||||
return s.providerForProfile(id)
|
||||
}
|
||||
if e := s.provByProfile[id]; e != nil { // lost the race → keep the winner
|
||||
if e.jev {
|
||||
s.provCacheMu.Unlock()
|
||||
return nil, agent.Config{}, false
|
||||
}
|
||||
s.provCacheMu.Unlock()
|
||||
return e.prov, e.cfg, true
|
||||
}
|
||||
@@ -644,7 +685,7 @@ func (s *Server) providerForProfile(id int64) (llm.Provider, agent.Config, bool)
|
||||
prov = llmrec.Wrap(prov, s.m.PG(), cfg.Model, profile.Name, cfg.ThinkingType, cfg.ReasoningEffort, s.m.LLMRecordEnabled)
|
||||
prov = bindSideProvider(prov, cfg, id, profile.Name)
|
||||
}
|
||||
s.provByProfile[id] = &provEntry{prov: prov, cfg: cfg}
|
||||
s.provByProfile[id] = &provEntry{prov: prov, cfg: cfg, jev: false}
|
||||
log.Printf("[engine] built provider for LLM profile %d (%s / %s)", id, cfg.Provider(), cfg.Model)
|
||||
s.provCacheMu.Unlock()
|
||||
return prov, cfg, true
|
||||
@@ -1533,7 +1574,13 @@ func (s *Server) testLLM(w http.ResponseWriter, r *http.Request) {
|
||||
if model == "" {
|
||||
model = jev.DefaultModel
|
||||
}
|
||||
lat, reply, err := (jev.Config{BaseURL: baseURL, APIKey: apiKey, Model: model}).TestConnection(r.Context())
|
||||
proxy := strings.TrimSpace(req.Proxy)
|
||||
if proxy == "" && req.ProfileID != nil {
|
||||
if p, err := s.m.pg.ProfileByID(*req.ProfileID); err == nil && p != nil {
|
||||
proxy = p.Proxy
|
||||
}
|
||||
}
|
||||
lat, reply, err := (jev.Config{BaseURL: baseURL, APIKey: apiKey, Model: model, Proxy: proxy}).TestConnection(r.Context())
|
||||
if err != nil {
|
||||
writeJSON(w, 200, map[string]any{"ok": false, "error": err.Error()})
|
||||
return
|
||||
|
||||
+16
-9
@@ -10,7 +10,6 @@ import (
|
||||
"io"
|
||||
"log"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"os"
|
||||
"path"
|
||||
"path/filepath"
|
||||
@@ -25,6 +24,7 @@ import (
|
||||
|
||||
"github.com/Autumn-27/artex/agent"
|
||||
"github.com/Autumn-27/artex/db"
|
||||
"github.com/Autumn-27/artex/llmhttp"
|
||||
"github.com/Autumn-27/norma/llm"
|
||||
"github.com/Autumn-27/norma/skill"
|
||||
)
|
||||
@@ -1832,6 +1832,10 @@ func (s *Server) pgSaveProfile(w http.ResponseWriter, r *http.Request) {
|
||||
}
|
||||
id, err := pg.SaveProfile(&p)
|
||||
if err != nil {
|
||||
if errors.Is(err, db.ErrJevProfileJudgeOnly) {
|
||||
writeErr(w, http.StatusBadRequest, err.Error())
|
||||
return
|
||||
}
|
||||
writeErr(w, 500, err.Error())
|
||||
return
|
||||
}
|
||||
@@ -2008,6 +2012,11 @@ func (s *Server) pgListModels(w http.ResponseWriter, r *http.Request) {
|
||||
writeErr(w, 400, err.Error())
|
||||
return
|
||||
}
|
||||
provider := strings.TrimSpace(req.Provider)
|
||||
if provider == "jev" {
|
||||
writeErr(w, http.StatusBadRequest, "Jev / System One 不提供模型列表,请直接使用默认模型 jev-latest")
|
||||
return
|
||||
}
|
||||
// Resolve API key: form input > profile stored key.
|
||||
apiKey := strings.TrimSpace(req.APIKey)
|
||||
if apiKey == "" && req.ProfileID != nil {
|
||||
@@ -2021,7 +2030,6 @@ func (s *Server) pgListModels(w http.ResponseWriter, r *http.Request) {
|
||||
}
|
||||
|
||||
baseURL := strings.TrimRight(strings.TrimSpace(req.BaseURL), "/")
|
||||
provider := strings.TrimSpace(req.Provider)
|
||||
|
||||
// Candidate endpoints to try in order. Some Anthropic-compatible providers
|
||||
// (e.g. DeepSeek) implement /v1/messages under an /anthropic path but expose
|
||||
@@ -2069,14 +2077,13 @@ func (s *Server) pgListModels(w http.ResponseWriter, r *http.Request) {
|
||||
}
|
||||
}
|
||||
|
||||
// Build HTTP client with optional proxy.
|
||||
transport := &http.Transport{}
|
||||
if p := strings.TrimSpace(req.Proxy); p != "" {
|
||||
if pu, err := url.Parse(p); err == nil {
|
||||
transport.Proxy = http.ProxyURL(pu)
|
||||
}
|
||||
// Build HTTP client with the same profile proxy semantics as LLM calls.
|
||||
client, err := llmhttp.NewClient(req.Proxy)
|
||||
if err != nil {
|
||||
writeErr(w, http.StatusBadRequest, err.Error())
|
||||
return
|
||||
}
|
||||
client := &http.Client{Transport: transport, Timeout: 30 * time.Second}
|
||||
client.Timeout = 30 * time.Second
|
||||
|
||||
// Try each candidate; return the first that yields a non-empty model list.
|
||||
var lastErr string
|
||||
|
||||
Reference in new issue
Block a user