-
Notifications
You must be signed in to change notification settings - Fork 694
Expand file tree
/
Copy pathchain-of-thought.js
More file actions
368 lines (320 loc) · 11.1 KB
/
Copy pathchain-of-thought.js
File metadata and controls
368 lines (320 loc) · 11.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
/**
* Example 14: Chain of Thought (CoT) - Return decision
*
* Run:
* node examples/14_chain-of-thought/chain-of-thought.js
*/
import { getLlama, LlamaChatSession } from "node-llama-cpp";
import { fileURLToPath } from "url";
import path from "path";
import { JsonParser } from "../../helper/json-parser.js";
import { writeCoTReturnVisualization } from "../../helper/visualization-writers.js";
const __dirname = path.dirname(fileURLToPath(import.meta.url));
const debug = false;
const RETURN_CASE = {
request_id: "RET-2026-0414",
customer_id: "CUST-90871",
product: "Wireless Noise Cancelling Headphones X2",
order_date: "2026-03-29",
delivery_date: "2026-04-01",
request_date: "2026-04-24",
claimed_reason: "Right ear cup has intermittent sound dropouts",
claim_timing_days_after_delivery: 23,
order_value_eur: 189.0,
return_count_last_12_months: 3,
previous_high_value_returns: 2,
account_age_months: 46,
payment_method: "credit_card_verified",
shipping_address_matches_payment: true,
diagnostic_log_uploaded: true,
photo_evidence_uploaded: false,
replacement_requested: true
};
const RETURN_POLICY = {
return_window_days: 30,
max_high_value_returns_12m_before_manual_review: 2,
mandatory_manual_review_amount_eur: 250,
allowed_outcomes: ["approve", "reject", "manual_review"]
};
const systemPrompt = `You are a careful e-commerce risk analyst.
You must follow the requested phase exactly and return valid JSON only.
No markdown, no code fences, no text outside JSON.`;
const factsSchema = {
type: "object",
properties: {
extracted_facts: {
type: "array",
items: { type: "string" },
minItems: 6
},
missing_information: {
type: "array",
items: { type: "string" }
}
},
required: ["extracted_facts", "missing_information"]
};
const redFlagsSchema = {
type: "object",
properties: {
checkpoints: {
type: "array",
items: {
type: "object",
properties: {
check: { type: "string" },
status: { type: "string", enum: ["present", "not_present", "unclear"] },
evidence: { type: "string" }
},
required: ["check", "status", "evidence"]
},
minItems: 5
},
fraud_score: { type: "number" },
fraud_rationale: { type: "string" }
},
required: ["checkpoints", "fraud_score", "fraud_rationale"]
};
const legitimacySchema = {
type: "object",
properties: {
customer_supporting_points: {
type: "array",
items: {
type: "object",
properties: {
point: { type: "string" },
strength: { type: "string", enum: ["high", "medium", "low"] },
evidence: { type: "string" }
},
required: ["point", "strength", "evidence"]
},
minItems: 4
},
legitimacy_score: { type: "number" },
legitimacy_rationale: { type: "string" }
},
required: ["customer_supporting_points", "legitimacy_score", "legitimacy_rationale"]
};
const policySchema = {
type: "object",
properties: {
policy_checks: {
type: "array",
items: {
type: "object",
properties: {
rule: { type: "string" },
status: { type: "string", enum: ["pass", "fail", "manual_review_trigger"] },
reason: { type: "string" }
},
required: ["rule", "status", "reason"]
},
minItems: 4
},
policy_outcome: {
type: "string",
enum: ["approve", "reject", "manual_review"]
}
},
required: ["policy_checks", "policy_outcome"]
};
const decisionSchema = {
type: "object",
properties: {
final_decision: {
type: "string",
enum: ["approve", "reject", "manual_review"]
},
confidence: { type: "number" },
decision_reasoning: { type: "string" },
customer_message: { type: "string" },
internal_note: { type: "string" }
},
required: ["final_decision", "confidence", "decision_reasoning", "customer_message", "internal_note"]
};
const llama = await getLlama({ debug });
const model = await llama.loadModel({
modelPath: path.join(__dirname, "..", "..", "models", "Qwen3-1.7B-Q8_0.gguf")
});
const context = await model.createContext({ contextSize: 8192 });
const session = new LlamaChatSession({
contextSequence: context.getSequence(),
systemPrompt
});
async function promptJson(schema, userText) {
session.resetChatHistory();
const grammar = await llama.createGrammarForJsonSchema(schema);
const raw = await session.prompt(userText, {
grammar,
maxTokens: 1400,
temperature: 0.2
});
return JsonParser.parse(raw, { debug, expectObject: true, repairAttempts: true });
}
async function extractFacts(returnCase) {
return promptJson(
factsSchema,
`Phase 1 of 5: FACTS ONLY.
Extract facts from the return request without evaluation, suspicion, or judgment.
Do not infer intent. Do not score. Just capture what is explicitly known.
Return request JSON:
${JSON.stringify(returnCase, null, 2)}
Return JSON:
{
"extracted_facts": ["fact 1", "fact 2", "fact 3"],
"missing_information": ["missing point 1", "missing point 2"]
}`
);
}
async function screenRedFlags(returnCase, facts) {
return promptJson(
redFlagsSchema,
`Phase 2 of 5: RED FLAG SCREENING.
Evaluate potential fraud indicators one by one.
Be explicit for each checkpoint whether it is present, not present, or unclear.
Use these checkpoints:
1) Frequent recent return behavior
2) High-value return pattern
3) Inconsistent payment/shipping identity
4) Weak or missing defect evidence
5) Timing pattern that looks strategic
6) Account behavior anomaly
Known case data:
${JSON.stringify(returnCase, null, 2)}
Facts from phase 1:
${JSON.stringify(facts.extracted_facts, null, 2)}
Return JSON:
{
"checkpoints": [
{ "check": "Frequent recent return behavior", "status": "present", "evidence": "..." }
],
"fraud_score": 6.0,
"fraud_rationale": "..."
}`
);
}
async function assessLegitimacy(returnCase, facts) {
return promptJson(
legitimacySchema,
`Phase 3 of 5: LEGITIMACY VIEW.
Now build the customer-side case.
List reasons why this may be a legitimate return.
Do not reference fraud score. Focus on fairness and plausible product failure.
Known case data:
${JSON.stringify(returnCase, null, 2)}
Facts from phase 1:
${JSON.stringify(facts.extracted_facts, null, 2)}
Return JSON:
{
"customer_supporting_points": [
{ "point": "point text", "strength": "high", "evidence": "..." }
],
"legitimacy_score": 7.0,
"legitimacy_rationale": "..."
}`
);
}
async function checkPolicy(returnCase, policy, redFlags, legitimacy) {
return promptJson(
policySchema,
`Phase 4 of 5: POLICY CHECK.
Apply policy strictly. Do not invent rules.
Use both risk and legitimacy context, but final status must be policy-compliant.
Policy JSON:
${JSON.stringify(policy, null, 2)}
Case JSON:
${JSON.stringify(returnCase, null, 2)}
Fraud score: ${redFlags.fraud_score}
Legitimacy score: ${legitimacy.legitimacy_score}
Return JSON:
{
"policy_checks": [
{ "rule": "Return window <= 30 days", "status": "pass", "reason": "..." }
],
"policy_outcome": "manual_review"
}`
);
}
async function makeDecision(returnCase, phase1Facts, redFlags, legitimacy, policyResult) {
return promptJson(
decisionSchema,
`Phase 5 of 5: FINAL DECISION.
You can decide only now. Use all prior phases.
Explain trade-offs clearly. If conflict exists (e.g., fraud 6/10 vs legitimacy 7/10), show how policy resolves it.
Case:
${JSON.stringify(returnCase, null, 2)}
Phase 1 facts:
${JSON.stringify(phase1Facts, null, 2)}
Phase 2 red flags:
${JSON.stringify(redFlags, null, 2)}
Phase 3 legitimacy:
${JSON.stringify(legitimacy, null, 2)}
Phase 4 policy:
${JSON.stringify(policyResult, null, 2)}
Return JSON:
{
"final_decision": "manual_review",
"confidence": 0.79,
"decision_reasoning": "...",
"customer_message": "...",
"internal_note": "..."
}`
);
}
async function runChainOfThoughtReturnDecision(returnCase, policy) {
console.log("\nChain of Thought: Return decision (fraud vs legitimate)");
console.log(`Case ID: ${returnCase.request_id}`);
console.log(`Reason: "${returnCase.claimed_reason}"\n`);
console.log("Phase 1: Facts - extract only, no judgment");
const facts = await extractFacts(returnCase);
(facts.extracted_facts || []).slice(0, 6).forEach((fact) => {
console.log(` - ${fact}`);
});
console.log("\nPhase 2: Red Flags - explicit fraud screening");
const redFlags = await screenRedFlags(returnCase, facts);
console.log(` Fraud score: ${Number(redFlags.fraud_score).toFixed(1)}/10`);
(redFlags.checkpoints || []).slice(0, 6).forEach((cp) => {
console.log(` - ${cp.check}: ${cp.status}`);
});
console.log("\nPhase 3: Legitimacy - customer-side balancing");
const legitimacy = await assessLegitimacy(returnCase, facts);
console.log(` Legitimacy score: ${Number(legitimacy.legitimacy_score).toFixed(1)}/10`);
(legitimacy.customer_supporting_points || []).slice(0, 4).forEach((p) => {
console.log(` - ${p.point} (${p.strength})`);
});
console.log("\nPhase 4: Policy Check - rule-constrained outcome");
const policyResult = await checkPolicy(returnCase, policy, redFlags, legitimacy);
console.log(` Policy outcome: ${policyResult.policy_outcome}`);
(policyResult.policy_checks || []).slice(0, 4).forEach((r) => {
console.log(` - ${r.rule}: ${r.status}`);
});
console.log("\nPhase 5: Decision - final judgment with full chain");
const decision = await makeDecision(returnCase, facts, redFlags, legitimacy, policyResult);
console.log("\n" + "=".repeat(72));
console.log("RETURN DECISION (Chain of Thought)");
console.log("=".repeat(72));
console.log(`\nFraud score: ${Number(redFlags.fraud_score).toFixed(1)}/10`);
console.log(`Legitimacy score: ${Number(legitimacy.legitimacy_score).toFixed(1)}/10`);
console.log(`Policy outcome: ${policyResult.policy_outcome}`);
console.log(`Final decision: ${decision.final_decision}`);
console.log(`Confidence: ${Number(decision.confidence).toFixed(2)}`);
console.log(`\nDecision reasoning:\n${decision.decision_reasoning}`);
console.log(`\nCustomer message:\n${decision.customer_message}`);
console.log(`\nInternal note:\n${decision.internal_note}`);
writeCoTReturnVisualization(__dirname, {
returnCase,
policy,
facts,
redFlags,
legitimacy,
policyResult,
decision
});
return { returnCase, policy, facts, redFlags, legitimacy, policyResult, decision };
}
await runChainOfThoughtReturnDecision(RETURN_CASE, RETURN_POLICY);
session.dispose();
context.dispose();
model.dispose();
llama.dispose();