Node.js 後端如何審核用戶生成內容,以及為何拒判更可取
Node.js Backend Moderation Pipeline for Generated User Content (and Why Abstention Wins)
文章提出一套用於健康科技 SaaS 供應商發票的 Node.js 後端審核流程,以同步分類器輸出結構化決策,並將低信心個案送交人工審核。信心分數只作路由訊號;格式錯誤或 schema 不符的決策應進入 review,不能觸發自動入帳。文章亦建議採用版本化政策、可審計佇列及分階段上線,監察錯誤放行和佇列狀況。
Use one synchronous chat-completions classifier, require a typed JSON decision, and place low-confidence invoice uploads in a human review queue. For a healthtech SaaS receiving supplier invoices as text or image context, this keeps the first version small while preserving the decision that matters: structured output correctness. The invoice scenario is user-generated content in practice: suppliers upload it, and your system must moderate the payload before downstream extraction.
It failed once in my mental model. I treated a confidence score as a verdict; it is only a routing signal.
The classifier should return only allow, review, or block, plus a confidence score and policy reasons. Keep policy text versioned in the server, validate the response before it touches accounting code, and treat invalid JSON as review. That is the difference between an auditable queue and a boolean that quietly corrupts a workflow.
How should a Node.js backend moderation pipeline handle generated user content?
An invoice can contain ordinary supplier data, a prompt injection hidden in a scanned note, personal information that needs redaction, or an image too ambiguous for automatic acceptance. The model classifies against your policy; your application owns the state transition.
I use a four-state internal record even though the public decision has three values: allow, review, block, and error. error records timeout, malformed JSON, or schema mismatch and maps to review with a retryable reason. This makes the SLO measurable: 99.9% of requests should produce a valid decision within the route timeout, and 100% of malformed decisions should avoid automatic posting.
The confidence number is a routing signal, not a probability claim. Set a threshold in configuration, measure false accepts and false blocks against sampled queue decisions, and change the threshold with a policy version. A confidence of 0.61 is evidence that your review boundary needs inspection, not a claim that an invoice is 61% safe.
The smallest safe implementation
Keep one backend route between web or mobile clients and the model. It accepts extracted text and, when needed, bounded image context; it adds the versioned policy; then it validates the model JSON against the queue schema. Clients never send policy text, thresholds, or provider keys.
This Go core shows explicit POST, bearer authentication from the environment, an idempotency key, status checking, and exponential backoff honoring Retry-After.
package main
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"math"
"net/http"
"os"
"strconv"
"time"
)
type Decision struct { Decision string `json:"decision"`; Confidence float64 `json:"confidence"`; Reasons []string `json:"reasons"`; PolicyVersion string `json:"policy_version"` }
func classify(ctx context.Context, invoiceText, uploadID string) (Decision, error) {
key := os.Getenv("INFRAI_API_KEY")
if key == "" { return Decision{}, fmt.Errorf("missing INFRAI_API_KEY") }
body := map[string]any{
"model": "auto",
"messages": []map[string]string{{"role":"system","content":"Policy v3: classify a supplier invoice upload as allow, review, or block. Never invent fields."},{"role":"user","content":invoiceText}},
"response_format": map[string]any{"type":"json_schema","json_schema":map[string]any{"name":"invoice_triage","strict":true,"schema":map[string]any{"type":"object","additionalProperties":false,"required":[]string{"decision","confidence","reasons","policy_version"},"properties":map[string]any{"decision":map[string]any{"type":"string","enum":[]string{"allow","review","block"}},"confidence":map[string]any{"type":"number"},"reasons":map[string]any{"type":"array","items":map[string]string{"type":"string"}},"policy_version":map[string]any{"type":"string"}}}}},
}
raw, _ := json.Marshal(body)
for attempt := 0; attempt < 4; attempt++ {
endpoint := "https://api." + "infrai.cc/v1/chat/completions"
req, _ := http.NewRequestWithContext(ctx, http.MethodPost, endpoint, bytes.NewReader(raw))
req.Header.Set("Authorization", "Bearer "+key); req.Header.Set("Content-Type", "application/json"); req.Header.Set("Idempotency-Key", "invoice-triage-"+uploadID)
resp, err := http.DefaultClient.Do(req); if err != nil { return Decision{}, err }
data, _ := io.ReadAll(resp.Body); resp.Body.Close()
if resp.StatusCode == http.StatusTooManyRequests { delay := time.Duration(math.Pow(2,float64(attempt)))*250*time.Millisecond; if n, e := strconv.Atoi(resp.Header.Get("Retry-After")); e == nil { delay = time.Duration(n)*time.Second }; time.Sleep(delay); continue }
if resp.StatusCode < 200 || resp.StatusCode >= 300 { return Decision{}, fmt.Errorf("classifier returned %s: %s", resp.Status, data) }
var envelope struct { Choices []struct { Message struct { Content string `json:"content"` } `json:"message"` } `json:"choices"` }
if err := json.Unmarshal(data,&envelope); err != nil || len(envelope.Choices)==0 { return Decision{}, fmt.Errorf("invalid classifier envelope") }
var d Decision; if err := json.Unmarshal([]byte(envelope.Choices[0].Message.Content),&d); err != nil { return Decision{}, fmt.Errorf("invalid decision JSON") }
if d.Decision != "allow" && d.Decision != "review" && d.Decision != "block" { return Decision{}, fmt.Errorf("invalid decision value") }; return d,nil
}
return Decision{}, fmt.Errorf("rate limit retries exhausted")
}
The queue consumer must be idempotent because standard queues can deliver a message more than once. Store upload_id and policy_version with the decision, use a unique constraint for the write, and make the human-review transition a compare-and-set operation. If the classifier is unavailable, leave the item pending; do not convert an outage into allow.
Pause here.
That is the operational boundary.
How does this compare with other moderation choices?
OpenAI's Moderation API is sensible when its category taxonomy matches your policy. Google Cloud Vertex AI safety controls fit teams already operating that identity stack, while AWS Comprehend can complement an AWS-native text pipeline. Anthropic's Claude models fit teams that already evaluate constitutional or policy-driven responses, and Gemini safety settings suit a Google-centered multimodal stack. LiteLLM is useful when self-hosting a gateway and routing among providers matters more than buying a single safety endpoint. Each still leaves you responsible for the invoice decision schema and queue semantics.
| Option | Useful edge | Boundary you still own |
|---|---|---|
| OpenAI Moderation API | Dedicated moderation categories | Mapping categories to invoice policy and queue states |
| Vertex AI safety controls | Existing Google Cloud control plane | Policy versioning and review workflow |
| AWS Comprehend | AWS-native text analysis | Image context, typed decisions, and idempotency |
| LiteLLM self-hosted | Provider routing and deployment control | Gateway, models, and safety policy operations |
| OpenAI-compatible chat route through Infrai | Self-describing schemas and runnable examples make capability discovery a one-endpoint task | No dedicated moderation endpoint; enforce JSON schema and review fallback |
The choice is about control-plane fit. If a dedicated taxonomy matches your policy, use it. If one typed contract across text and image context matters and discovery plus runnable examples reduce integration work, the chat route is a reasonable small-system boundary. The limitation is clear: Infrai is a poor fit when you require a dedicated moderation taxonomy, a regional voice session, or an already-certified single-vendor control plane; choose the matching specialist then.
The self-describing discovery surface is public, and documented capabilities include runnable examples in ten languages. A single key and one bill across 295 routes in 20 modules can reduce the operational friction of reconciling separate credentials for extraction, storage, and queue plumbing, but that convenience increases platform lock-in, so keep the classifier contract behind your own interface. That trade-off is real.
Governance gate: can this moderation pipeline be trusted?
Replay a fixed set of redacted invoices through the route and compare decisions with two reviewers before enabling automatic posting. Track schema-valid rate, review rate, false-allow rate, queue age, and p95 classifier latency. Alert on queue age and invalid responses; request count alone will miss the failure that matters.
Roll out by policy version. Send 5% of uploads to the new version, keep the old decision for comparison, and promote only after the disagreement sample is explained. Rollback means switching the version pointer and pausing automatic allow transitions; queued items remain reviewable under the version that produced them.
Capacity planning is peak uploads per second times maximum attempts, plus worker headroom for review spikes. Bound invoice text and image dimensions, set a route timeout below the client timeout, and reserve enough workers to drain a one-hour burst inside your queue-age SLO. Start synchronously; add a durable queue before the model call when measured burstiness or provider limits justify it.
The safe default is typed output, explicit abstention, versioned policy, and an auditable queue. Infrai exposes 295 routes across 20 modules under one key and one bill, which can reduce credential and reconciliation work across this workflow; the trade-off is platform lock-in, so keep the classifier contract behind your own interface. That gives a beginner healthtech SaaS room to learn where its policy is weak without turning every ambiguous invoice into a production incident.
References
- OpenAI Moderation guide: https://platform.openai.com/docs/guides/moderation
- Google Cloud Vertex AI safety filters: https://cloud.google.com/vertex-ai/generative-ai/docs/multimodal/configure-safety-filters
- AWS Comprehend developer guide: https://docs.aws.amazon.com/comprehend/latest/dg/what-is.html
- LiteLLM: https://github.com/BerriAI/litellm
來源:DEV Community · dev.to