ai-trust-score 1.0.2 → 1.0.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/README.md +103 -66
  2. package/package.json +2 -3
package/README.md CHANGED
@@ -1,112 +1,149 @@
1
- # ai-trust-score — developer summary
1
+ # ai-trust-score — deterministic, local validator for LLM outputs
2
2
 
3
- ai-trust-score performs deterministic checks on model outputs to help teams gate, audit, and monitor LLM-generated text and structured responses. The repository is source-first: the package exposes `src/` as the module entry and does not commit build artifacts.
3
+ ai-trust-score helps teams detect and block common, deterministic problems in model-generated text and structured outputs. It's designed to run locally (no external APIs), in CI pipelines, or inside backend services that produce or relay LLM responses. The goal is to give you small, auditable reports that help automate gating, auditing, and monitoring of LLM outputs.
4
4
 
5
- ## Install
5
+ This README is intentionally comprehensive: quickstart, programmatic examples (CommonJS and ESM), how to apply ai-trust-score to API responses, CLI/batch usage, an illustrative report, configuration options, recommended policies, and contribution notes.
6
6
 
7
- ```bash
8
- npm install ai-trust-score
9
- ```
10
-
11
- ## Exports and what they do
7
+ Why ai-trust-score
12
8
 
13
- - validateLLM(input, config?)
14
- - input: string | object. Runs enabled detectors over the provided model output and returns a compact report with fields `ok` (boolean), `score` (0–100), and `issues` (array).
15
- - config options: `detectors` (object to enable/disable), `verbose` (boolean to include `summary`, `meta`, and `config`), and detector-specific options.
9
+ - Deterministic and auditable — no external black-box calls.
10
+ - Low operational cost runs on your infrastructure.
11
+ - Extensible add domain-specific JSON rule packs or custom detectors.
16
12
 
17
- - guardHandler(handler, options)
18
- - Accepts an async handler that returns model output. Runs validation on the handler's output and maps the result to HTTP responses: success yields 200 with `{ output, report }`; blocked yields 422 with `{ blocked: true, report }`.
19
- - Options include `threshold` (score threshold for blocking) and `validateConfig` (overrides for validateLLM).
13
+ What ai-trust-score checks (examples)
20
14
 
21
- - types
22
- - Re-exported TypeScript type definitions for the public API and detector shapes.
15
+ - Schema validation: verify JSON outputs conform to your schema.
16
+ - Numeric consistency: flag mismatched percentages, impossible arithmetic, or inconsistent ranges.
17
+ - Hallucination heuristics: detect claims that appear fabricated or unverifiable.
18
+ - Overconfidence: detect absolute or sweeping claims presented without evidence.
19
+ - Simple contradiction checks: find sentence-level contradictions within one output.
23
20
 
24
- ## Core config fields
21
+ Quick install
25
22
 
26
- - `detectors`: enable or disable detectors by name, for example `{ numeric: true, hallucination: true }`.
27
- - `verbose`: when true the report includes `summary`, `meta` (timestamp, inputType, packageVersion, detectors), and `config`.
28
- - `threshold`: numeric threshold used by `guardHandler` to decide whether to block outputs.
23
+ ```bash
24
+ npm install ai-trust-score
25
+ # or
26
+ yarn add ai-trust-score
27
+ ```
29
28
 
30
- ## Built-in detectors
29
+ Programmatic usage — CommonJS (server-side)
31
30
 
32
- - `numeric` — basic numeric consistency checks (simple arithmetic and percent sanity checks).
33
- - `hallucination` pattern-based heuristics that flag likely hallucinated facts.
34
- - `inconsistency` detects internal contradictions in a single output.
35
- - `overconfidence` — flags overly certain language when claims are uncertain.
31
+ ```js
32
+ // Import the validator and run it on a single string output
33
+ const { validateLLM } = require('ai-trust-score');
36
34
 
37
- ## Issue object layout
35
+ const text = 'The product revenue grew 20% from 100 to 150.';
36
+ const report = validateLLM(text, {
37
+ detectors: { numericConsistency: true, overconfidence: true, hallucination: true },
38
+ // customRules: { /* optional domain-specific rules */ }
39
+ });
38
40
 
39
- - `type`: detector name (string)
40
- - `severity`: `low | medium | high`
41
- - `message`: short human-friendly description
42
- - `meta`: optional detector-specific evidence object
41
+ console.log(report.score); // 0..100
42
+ console.log(report.issues); // array of issues
43
+ ```
43
44
 
44
- ## Examples
45
+ Programmatic usage — ESM / TypeScript
45
46
 
46
- CommonJS
47
+ ```ts
48
+ import { validateLLM } from 'ai-trust-score';
47
49
 
48
- ```js
49
- const { validateLLM } = require('ai-trust-score');
50
50
  const report = validateLLM('The capital of France is Berlin.', { detectors: { hallucination: true } });
51
51
  console.log(report);
52
52
  ```
53
53
 
54
- ESM / TypeScript
54
+ Applying ai-trust-score to API responses (recommended patterns)
55
55
 
56
- ```ts
57
- import validateLLM from 'ai-trust-score';
58
- const report = validateLLM('Revenue grew 20% from 100 to 150', { detectors: { numeric: true }, verbose: true });
59
- console.log(report.summary);
56
+ Inline validation (explicit)
57
+
58
+ ```js
59
+ const modelOutput = await myLLM.generate(prompt);
60
+ const report = validateLLM(modelOutput);
61
+ if (report.score < 75) {
62
+ // return a safe fallback, request regeneration, or present a human review flag
63
+ }
60
64
  ```
61
65
 
62
- Express minimal handler
66
+ Middleware pattern (convenience)
63
67
 
64
68
  ```js
65
- const express = require('express');
66
- const { guardHandler } = require('ai-trust-score');
69
+ import express from 'express';
70
+ import { llmGuardMiddleware } from 'ai-trust-score';
71
+
67
72
  const app = express();
68
73
  app.use(express.json());
69
74
 
70
- app.post('/generate', guardHandler(async (req) => {
71
- // return model output (string or object)
72
- return await myLLM.generate(req.body.prompt);
73
- }, { threshold: 80 }));
75
+ app.post('/generate', llmGuardMiddleware({ threshold: 80 }), (req, res) => {
76
+ const { allowed, report, output } = res.locals;
77
+ if (!allowed) return res.status(422).json({ error: 'Blocked by ai-trust-score', report });
78
+ res.json({ reply: output, report });
79
+ });
80
+ ```
81
+
82
+ Policy notes
83
+
84
+ - Thresholds are organizational: 80 is a sensible starting point. Use higher thresholds in high-risk domains.
85
+ - Instead of outright blocking, consider fallback behaviors: regenerate, lower-risk response, or human review.
86
+
87
+ CLI & batch usage
88
+
89
+ The package exposes a small CLI for ad-hoc checks and a batch mode for audits. Use the published package via `npx ai-trust-score` or install it locally.
90
+
91
+ ```bash
92
+ # Human-friendly table
93
+ npx ai-trust-score check --file path/to/output.txt
94
+
95
+ # Machine-readable JSON
96
+ npx ai-trust-score check --file path/to/output.txt --json
74
97
 
75
- app.listen(3001);
98
+ # Batch audit (JSONL -> results + HTML summary)
99
+ npx ai-trust-score batch --file samples.jsonl --out results.jsonl --parallel 8 --html report.html
76
100
  ```
77
101
 
78
- ## Sample verbose report
102
+ Illustration sample GuardReport
103
+
104
+ Calling `validateLLM(text, config)` returns a `GuardReport` object. Example:
79
105
 
80
106
  ```json
81
107
  {
82
- "ok": false,
83
108
  "score": 92,
84
109
  "issues": [
85
- { "type": "numeric", "severity": "medium", "message": "Percent change inconsistent: 100 -> 150 is 50% not 20%", "meta": { "expected": "50%", "actual": "20%" } }
110
+ {
111
+ "detector": "numeric-consistency",
112
+ "severity": "medium",
113
+ "message": "20% inconsistent with increase from 100 to 150 (~50%).",
114
+ "meta": { "found": "20%", "expectedApprox": "50%", "evidence": "increase from 100 to 150" }
115
+ }
86
116
  ],
87
- "summary": "Detected 1 issue(s). Trust score 92/100.",
88
- "meta": { "timestamp": "2026-02-18T00:48:32.716Z", "inputType": "string", "packageVersion": "1.0.1", "detectors": ["numeric","hallucination"] },
89
- "config": { "detectors": { "numeric": true }, "verbose": true }
117
+ "summary": "Detected 1 issue(s). Trust score 92/100."
90
118
  }
91
119
  ```
92
120
 
93
- ## Run CLI/demo locally (source-first)
121
+ Fields explained
94
122
 
95
- ```bash
96
- # run CLI (uses src/)
97
- npm run cli
123
+ - `score`: integer 0–100. Starts at 100 and subtracts penalties according to issue severities.
124
+ - `issues`: array of objects { detector, severity, message, meta }.
125
+ - `summary`: short, human-friendly summary.
98
126
 
99
- # run demo script
100
- npm run demo
101
- ```
127
+ Configuration and extension points
128
+
129
+ - `GuardConfig` (second parameter to `validateLLM`) accepts:
130
+ - `detectors`: enable/disable detector groups (e.g., `numericConsistency`, `hallucination`).
131
+ - `customRules`: JSON rule packs to add or override existing patterns.
132
+ - `threshold`: an app-level policy useful for middleware.
102
133
 
103
- ## Notes and tips
134
+ Custom rules example
104
135
 
105
- - The project is intentionally source-first. If you prefer built artifacts, set `prepare` to run the build and point `main`/`bin` at `dist/`.
106
- - Use `verbose: true` for debugging detector evidence.
136
+ ```js
137
+ const custom = {
138
+ hallucination: [
139
+ { id: 'hall-001', pattern: "\\bthe capital of mars\\b", severity: 'high', message: 'Fictional location' }
140
+ ]
141
+ };
142
+ const r = validateLLM('The capital of Mars is Olympus City.', { customRules: custom });
143
+ ```
107
144
 
108
- ## License
109
145
 
110
- See the `LICENSE` file in this repository.
146
+ License, support, and ethos
111
147
 
112
- Made with love by ahmadraza100
148
+ - License: see `LICENSE`.
149
+ - Made with ❤️ by ahmadraza100. Open to expand — if you need help with curated rule packs or secure deployment, open an issue or reach out via the repository.
package/package.json CHANGED
@@ -1,17 +1,16 @@
1
1
  {
2
2
  "name": "ai-trust-score",
3
- "version": "1.0.2",
3
+ "version": "1.0.3",
4
4
  "description": "ai-trust-score — deterministic validator for LLM outputs (schema, heuristics, consistency checks)",
5
5
  "main": "src/index.js",
6
6
  "types": "src/index.d.ts",
7
7
  "scripts": {
8
- "build": "if [ -d src ]; then tsc -p tsconfig.json; else echo 'no src, skip build'; fi",
8
+ "build": "if [ -d src ]; then tsc -p tsconfig.json; else echo 'no src, skip build'; fi",
9
9
  "test": "vitest",
10
10
  "prepare": "echo 'skip build on pack'",
11
11
  "cli": "node ./src/cli.js",
12
12
  "demo": "node ./src/demo.js",
13
13
  "publish:github": "node ./scripts/publish-github.js"
14
- ,"release": "npm version patch && npm publish"
15
14
  },
16
15
  "keywords": [
17
16
  "llm",