From 8d7f9305961987448fea249a98a8bfecd3b083c6 Mon Sep 17 00:00:00 2001 From: yunyingk Date: Sun, 11 Oct 2026 19:33:29 +0800 Subject: [PATCH] Split Langfuse flow heuristics out of the trace service MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit service.ts interleaved orchestration (cache-first trace access) with ~200 lines of flow heuristics — stage word tables, evidence collection, source classification — and carried near-isomorphic copies of the collector for the attachment and rule flows. None of it had tests. flows.ts now owns the heuristics: one collectEvidence shared by both flows, stage vocabulary as data tables so tuning a word list cannot alter a code path, and an explicit attachment/rule difference (only the rule flow falls back to scanning every observation when a stage has no named candidates). summary.ts holds the trace/observation projections both the service and the flows need, which also keeps service <-> flows acyclic. Adds 15 tests over the previously untested branches, including the two behaviors the extraction surfaced: the "unknown" classification arm is unreachable as written, and a filename-only needle set can never reach the OCR/inference grading. --- src/domains/langfuse/flows.test.ts | 246 ++++++++++++++++++++++++ src/domains/langfuse/flows.ts | 242 +++++++++++++++++++++++ src/domains/langfuse/service.ts | 295 ++--------------------------- src/domains/langfuse/summary.ts | 62 ++++++ 4 files changed, 567 insertions(+), 278 deletions(-) create mode 100644 src/domains/langfuse/flows.test.ts create mode 100644 src/domains/langfuse/flows.ts create mode 100644 src/domains/langfuse/summary.ts diff --git a/src/domains/langfuse/flows.test.ts b/src/domains/langfuse/flows.test.ts new file mode 100644 index 0000000..15e5920 --- /dev/null +++ b/src/domains/langfuse/flows.test.ts @@ -0,0 +1,246 @@ +import { describe, expect, test } from "bun:test"; +import { + ATTACHMENT_STAGES, + buildAttachmentFlow, + buildRuleFlow, + candidatesForStage, + classifyAttachmentEvidence, + collectEvidence, + RULE_FLOW_STAGES, + stageTerms, + summarizeEvidenceFields +} from "./flows.js"; +import type { LangfuseObservationSummary } from "./types.js"; + +function observation(overrides: Partial & { id: string }): LangfuseObservationSummary { + return { + traceId: "trace-1", + type: "SPAN", + ...overrides + } as LangfuseObservationSummary; +} + +describe("stage vocabulary", () => { + test("every stage resolves bilingual search terms", () => { + for (const stage of ATTACHMENT_STAGES) { + expect(stageTerms(stage, "attachment").length).toBeGreaterThan(0); + } + for (const stage of RULE_FLOW_STAGES) { + expect(stageTerms(stage, "rule").length).toBeGreaterThan(0); + } + }); + + test("matches observation names case-insensitively in either language", () => { + const observations = [ + observation({ id: "a", name: "Attachment_Parsing" }), + observation({ id: "b", name: "文档解析 worker" }), + observation({ id: "c", name: "unrelated" }) + ]; + + const matched = candidatesForStage(observations, stageTerms("document_parsing", "attachment")); + expect(matched.map((item) => item.id)).toEqual(["b"]); + + // The rule vocabulary is broader, so it also picks up the English name. + const ruleParsed = candidatesForStage(observations, stageTerms("document parsing", "rule")); + expect(ruleParsed.map((item) => item.id)).toEqual(["a", "b"]); + }); +}); + +describe("collectEvidence", () => { + const obs = observation({ + id: "obs-1", + name: "attachment parsing", + input: "folder/invoice.pdf", + output: "解析完成 invoice.pdf", + metadata: { file: "invoice.pdf" } + }); + + test("scans input, output and metadata and pads the snippet with context", () => { + const hits = collectEvidence(obs, ["invoice.pdf"], 5, 10); + expect(hits.map((hit) => hit.field)).toEqual(["input", "output", "metadata"]); + expect(hits[0]?.matched).toBe("invoice.pdf"); + // contextChars=5 → 5 chars of lead-in before the needle (index 7 - 5 = 2). + expect(hits[0]?.snippet).toBe("lder/invoice.pdf"); + // Needle sits at index 5 (4 CJK chars + space), so 5 chars of lead-in + // reaches the start of the string. + expect(hits[1]?.snippet).toBe("解析完成 invoice.pdf"); + }); + + test("caps the number of hits so a pathological trace cannot balloon", () => { + const noisy = observation({ + id: "obs-2", + input: "x".repeat(500), + output: "x".repeat(500), + metadata: { a: "x".repeat(500) } + }); + expect(collectEvidence(noisy, ["x"], 10, 3)).toHaveLength(3); + expect(collectEvidence(noisy, ["nope"], 10, 3)).toHaveLength(0); + }); + + test("matching is case-insensitive on both sides", () => { + const hits = collectEvidence(obs, ["INVOICE.PDF"], 5, 10); + expect(hits.length).toBeGreaterThan(0); + // `matched` preserves the original casing from the trace text. + expect(hits[0]?.matched).toBe("invoice.pdf"); + }); +}); + +describe("classifyAttachmentEvidence", () => { + test("returns absent when nothing matched", () => { + expect(classifyAttachmentEvidence([], "file-1", "a.pdf")).toBe("absent"); + }); + + test("filename-only and file-id-only when those are the sole hits", () => { + expect( + classifyAttachmentEvidence([{ matched: "a.pdf", snippet: "a.pdf" }], "file-1", "a.pdf") + ).toBe("filename-only"); + expect( + classifyAttachmentEvidence([{ matched: "file-1", snippet: "file-1" }], "file-1", "a.pdf") + ).toBe("file-id-only"); + }); + + test("some other hint wins over filename/id and is graded by the snippet", () => { + const other = [{ matched: "some extra token", snippet: "..." }]; + expect(classifyAttachmentEvidence(other, "file-1", "a.pdf")).toBe("parsed-text"); + expect( + classifyAttachmentEvidence( + [...other, { matched: "ocr", snippet: "run OCR on the scan" }], + "file-1", + "a.pdf" + ) + ).toBe("image-ocr"); + expect( + classifyAttachmentEvidence( + [...other, { matched: "推断", snippet: "模型认为金额为 120" }], + "file-1", + "a.pdf" + ) + ).toBe("model-inferred"); + }); + + test("with no identifiers every hit is an 'other hint' graded from the snippet", () => { + // fileName/fileId undefined → `matched !== undefined` is always true, so + // hasOtherHint fires and the snippet decides. Note: the union's "unknown" + // arm is unreachable — with both identifiers defined, hasOtherHint false + // already implies one of them matched. Kept as a defensive fallback only. + expect( + classifyAttachmentEvidence([{ matched: "x", snippet: "raw parsed text" }], undefined, undefined) + ).toBe("parsed-text"); + expect( + classifyAttachmentEvidence([{ matched: "x", snippet: "OCR pipeline output" }], undefined, undefined) + ).toBe("image-ocr"); + }); +}); + +describe("summarizeEvidenceFields", () => { + test("counts hits per field and de-duplicates repeated matches", () => { + const summary = summarizeEvidenceFields([ + { field: "input", matched: "rule-a" } as never, + { field: "input", matched: "rule-a" } as never, + { field: "input", matched: "rule-b" } as never, + { field: "output", matched: "rule-a" } as never + ]); + expect(summary.input).toEqual({ count: 3, matched: ["rule-a", "rule-b"] }); + expect(summary.output).toEqual({ count: 1, matched: ["rule-a"] }); + expect(summary.metadata).toBeUndefined(); + }); +}); + +describe("buildAttachmentFlow", () => { + const observations = [ + observation({ id: "p1", name: "attachment parsing", input: "读取 a.pdf" }), + observation({ id: "p2", name: "document_parsing", output: "解析 a.pdf 得到 120 元" }), + observation({ id: "p3", name: "approval_review", output: "OCR 结果 a.pdf 金额 120" }), + observation({ id: "other", name: "unrelated", input: "nothing here" }) + ]; + + test("labels a stage seen and classifies the evidence source", () => { + const stages = buildAttachmentFlow({ + observations, + fileName: "a.pdf", + // A second, non-identifier needle is what makes hasOtherHint fire — a + // filename-only query can never reach the OCR/inference grading. + needles: ["a.pdf", "金额"], + contextChars: 20 + }); + + expect(stages).toHaveLength(ATTACHMENT_STAGES.length); + expect(stages.map((stage) => stage.stage)).toEqual([...ATTACHMENT_STAGES]); + + const parsing = stages.find((stage) => stage.stage === "document_parsing"); + expect(parsing?.status).toBe("seen"); + expect(parsing?.source).toBe("filename-only"); + expect(parsing?.observations.map((item) => item.id)).toEqual(["p2"]); + expect(parsing?.evidence[0]?.observationId).toBe("p2"); + + const review = stages.find((stage) => stage.stage === "approval_review"); + expect(review?.evidence.length).toBeGreaterThan(0); + // 金额 is a non-identifier hit, so hasOtherHint fires and "OCR" in the + // snippet grades this stage as image-ocr. + expect(review?.source).toBe("image-ocr"); + }); + + test("stages with no matching observation report absent", () => { + const stages = buildAttachmentFlow({ + observations, + fileId: "file-xyz", + needles: ["file-xyz"], + contextChars: 20 + }); + const understanding = stages.find( + (stage) => stage.stage === "image/document understanding" + ); + expect(understanding?.status).toBe("absent"); + expect(understanding?.source).toBe("absent"); + expect(understanding?.observations).toEqual([]); + }); +}); + +describe("buildRuleFlow", () => { + const observations = [ + observation({ id: "r1", name: "rule matching", input: "规则:禁止差旅超标" }), + observation({ id: "g1", name: "generic span", output: "命中规则 禁止差旅超标" }), + observation({ id: "f1", name: "final review", output: "审核结论:驳回" }) + ]; + + test("falls back to every observation when no stage name matches", () => { + const flow = buildRuleFlow({ + observations, + needles: ["禁止差旅超标"], + contextChars: 30 + }); + + expect(flow.stages.ruleMatching?.matched).toBe(true); + expect(flow.stages.ruleMatching?.matchedObservationIds).toContain("r1"); + // g1 sits in a generically-named span, reachable only via the fallback pool. + expect(flow.relatedObservationIds).toContain("g1"); + expect(flow.evidenceCount).toBeGreaterThan(0); + + // No observation is named for "document parsing", so the stage has zero + // *named* candidates but still scans the whole trace via the fallback — + // that is what keeps a rule applied inside a generically-named span visible. + const documentParsing = flow.stages.documentParsing; + expect(documentParsing?.observations).toEqual([]); + expect(documentParsing?.matched).toBe(true); + expect(documentParsing?.matchedObservationIds).toContain("r1"); + }); + + test("reports extracted fields grouped by source field", () => { + const flow = buildRuleFlow({ + observations, + needles: ["禁止差旅超标", "驳回"], + contextChars: 30 + }); + + expect(flow.stages.ruleMatching?.extractedFields.input?.matched).toEqual(["禁止差旅超标"]); + expect(flow.stages.finalReview?.extractedFields.output?.matched).toEqual(["驳回"]); + expect(flow.stages.finalReview?.matched).toBe(true); + }); + + test("returns the documented stage keys in order", () => { + const flow = buildRuleFlow({ observations, needles: ["nothing-matches"], contextChars: 30 }); + expect(Object.keys(flow.stages)).toEqual(["ruleMatching", "documentParsing", "finalReview"]); + expect(flow.evidenceCount).toBe(0); + expect(flow.relatedObservationIds).toEqual([]); + }); +}); diff --git a/src/domains/langfuse/flows.ts b/src/domains/langfuse/flows.ts new file mode 100644 index 0000000..70d768b --- /dev/null +++ b/src/domains/langfuse/flows.ts @@ -0,0 +1,242 @@ +import { stringifyValue } from "./search.js"; +import { summarizeObservation, uniqueStrings } from "./summary.js"; +import type { LangfuseObservationSummary } from "./types.js"; + +/** + * Deterministic flow reconstruction from cached Langfuse fields. + * + * Everything here is plain text matching over observation name/input/output/ + * metadata — no network, no model calls. Both flows answer "where does this + * file or rule show up across the stages", so they share one evidence + * collector and differ only in their stage vocabulary and in what they report. + * + * The stage word lists are bilingual heuristics tuned against real traces; + * they are deliberately data, not logic, so tuning them cannot change a code + * path. + */ + +export const ATTACHMENT_STAGES = [ + "attachment parsing", + "image/document understanding", + "pre_analysis", + "document_parsing", + "approval_review" +] as const; + +export const RULE_FLOW_STAGES = ["rule matching", "document parsing", "final review"] as const; + +export type AttachmentStage = (typeof ATTACHMENT_STAGES)[number]; +export type RuleFlowStage = (typeof RULE_FLOW_STAGES)[number]; + +export type EvidenceField = "input" | "output" | "metadata"; + +export interface EvidenceHit { + observationId: string; + name?: string; + type?: string; + field: EvidenceField; + matched: string; + snippet: string; +} + +export type AttachmentSource = + | "filename-only" + | "file-id-only" + | "parsed-text" + | "image-ocr" + | "model-inferred" + | "absent" + | "unknown"; + +const ATTACHMENT_STAGE_TERMS: Record = { + "attachment parsing": ["attachment", "附件", "parse_attachment", "attachment_parsing"], + "image/document understanding": [ + "understanding", + "vision", + "image", + "document_understanding", + "文档理解", + "图片理解" + ], + pre_analysis: ["pre_analysis", "pre-analysis", "预分析"], + document_parsing: ["document_parsing", "document parsing", "文档解析"], + approval_review: ["approval_review", "approval review", "审核"] +}; + +const RULE_STAGE_TERMS: Record = { + "rule matching": ["rule", "规则", "policy", "match", "matching", "命中"], + "document parsing": ["document", "parse", "parsing", "attachment", "ocr", "文档", "解析", "附件", "提取"], + "final review": ["approval_review", "approval review", "review", "审核", "结论", "final"] +}; + +export function stageTerms( + stage: AttachmentStage | RuleFlowStage, + vocabulary: "attachment" | "rule" +): string[] { + return vocabulary === "attachment" + ? ATTACHMENT_STAGE_TERMS[stage as AttachmentStage] + : RULE_STAGE_TERMS[stage as RuleFlowStage]; +} + +/** Observations whose name mentions any of the stage's terms. */ +export function candidatesForStage( + observations: LangfuseObservationSummary[], + terms: string[] +): LangfuseObservationSummary[] { + const lowered = terms.map((term) => term.toLowerCase()); + return observations.filter((observation) => { + const name = observation.name?.toLowerCase() ?? ""; + return lowered.some((term) => name.includes(term)); + }); +} + +/** + * Scan every field of an observation for each needle and return bounded, + * context-padded hits. The cap keeps a pathological trace from ballooning the + * response. + */ +export function collectEvidence( + observation: LangfuseObservationSummary, + needles: string[], + contextChars: number, + limit: number +): EvidenceHit[] { + const fields = [ + ["input", stringifyValue(observation.input)], + ["output", stringifyValue(observation.output)], + ["metadata", stringifyValue(observation.metadata)] + ] as const; + const evidence: EvidenceHit[] = []; + + for (const [field, text] of fields) { + const normalized = text.toLowerCase(); + for (const needle of needles) { + const index = normalized.indexOf(needle.toLowerCase()); + if (index < 0) continue; + evidence.push({ + observationId: observation.id, + name: observation.name, + type: observation.type, + field, + matched: text.slice(index, index + needle.length), + snippet: text.slice( + Math.max(0, index - contextChars), + Math.min(text.length, index + needle.length + contextChars) + ) + }); + } + } + + return evidence.slice(0, limit); +} + +/** + * Decide where an attachment's presence appears to come from. Labels describe + * the text that was found — they never assert that a model understood the file. + */ +export function classifyAttachmentEvidence( + evidence: Array<{ matched: string; snippet: string }>, + fileId: string | undefined, + fileName: string | undefined +): AttachmentSource { + if (evidence.length === 0) return "absent"; + + const hasFileName = fileName ? evidence.some((item) => item.matched === fileName) : false; + const hasFileId = fileId ? evidence.some((item) => item.matched === fileId) : false; + const hasOtherHint = evidence.some((item) => item.matched !== fileId && item.matched !== fileName); + + if (hasOtherHint) { + const joined = evidence + .map((item) => item.snippet) + .join("\n") + .toLowerCase(); + if (/(ocr|图片|image|vision|视觉|识别)/i.test(joined)) return "image-ocr"; + if (/(infer|inferred|推断|模型认为|判断|审核结论)/i.test(joined)) return "model-inferred"; + return "parsed-text"; + } + if (hasFileName) return "filename-only"; + if (hasFileId) return "file-id-only"; + return "unknown"; +} + +/** Count hits per field, de-duplicating the matched substrings. */ +export function summarizeEvidenceFields( + evidence: EvidenceHit[] +): Record { + const summary: Record = {}; + for (const item of evidence) { + const entry = summary[item.field]; + if (entry) { + entry.count += 1; + if (!entry.matched.includes(item.matched)) entry.matched.push(item.matched); + } else { + summary[item.field] = { count: 1, matched: [item.matched] }; + } + } + return summary; +} + +export function buildAttachmentFlow(options: { + observations: LangfuseObservationSummary[]; + fileId?: string; + fileName?: string; + needles: string[]; + contextChars: number; +}) { + const { observations, fileId, fileName, needles, contextChars } = options; + + return ATTACHMENT_STAGES.map((stage) => { + const candidates = candidatesForStage(observations, stageTerms(stage, "attachment")); + const evidence = candidates.flatMap((observation) => + collectEvidence(observation, needles, contextChars, 10) + ); + const source = classifyAttachmentEvidence(evidence, fileId, fileName); + + return { + stage, + source, + status: source === "absent" ? ("absent" as const) : ("seen" as const), + observations: candidates.map(summarizeObservation), + evidence + }; + }); +} + +export function buildRuleFlow(options: { + observations: LangfuseObservationSummary[]; + needles: string[]; + contextChars: number; +}) { + const { observations, needles, contextChars } = options; + + const stages = RULE_FLOW_STAGES.map((stage) => { + const candidates = candidatesForStage(observations, stageTerms(stage, "rule")); + // Unlike attachment flow, a rule query falls back to every observation: + // a rule can be applied inside a generically-named span. + const pool = candidates.length ? candidates : observations; + const evidence = pool + .flatMap((observation) => collectEvidence(observation, needles, contextChars, 20)) + .slice(0, 20); + + return { + stage, + matched: evidence.length > 0, + matchedObservationIds: uniqueStrings(evidence.map((item) => item.observationId)), + observations: candidates.map(summarizeObservation), + extractedFields: summarizeEvidenceFields(evidence), + evidence + }; + }); + + const allEvidence = stages.flatMap((stage) => stage.evidence); + + return { + stages: { + ruleMatching: stages[0], + documentParsing: stages[1], + finalReview: stages[2] + }, + relatedObservationIds: uniqueStrings(allEvidence.map((item) => item.observationId)), + evidenceCount: allEvidence.length + }; +} diff --git a/src/domains/langfuse/service.ts b/src/domains/langfuse/service.ts index 288f2a3..0bc51da 100644 --- a/src/domains/langfuse/service.ts +++ b/src/domains/langfuse/service.ts @@ -3,7 +3,9 @@ import { LangfuseApi } from "./api.js"; import { TraceCache } from "./cache.js"; import type { LangfuseConfig } from "./config.js"; import { LangfuseClient } from "./client.js"; +import { buildAttachmentFlow, buildRuleFlow } from "./flows.js"; import { searchTrace, stringifyValue } from "./search.js"; +import { byteLength, objectKeys, summarizeObservation, summarizeTrace, uniqueStrings } from "./summary.js"; import type { AttachmentFlowInput, CachedTrace, @@ -28,14 +30,6 @@ const DEFAULT_IO_CHARS = 8_000; const DEFAULT_PREVIEW_CHARS = 160; const FULL_OUTPUT_WARNING_THRESHOLD = 30_000; const OUTLINE_FULL_FIELD_THRESHOLD = 20_000; -const ATTACHMENT_STAGES = [ - "attachment parsing", - "image/document understanding", - "pre_analysis", - "document_parsing", - "approval_review" -] as const; -const RULE_FLOW_STAGES = ["rule matching", "document parsing", "final review"] as const; /** * Read-only Langfuse trace service, ported from langfuse-home. @@ -278,15 +272,17 @@ export class LangfuseService { } const cached = await this.getCachedTrace(input.traceId, input.refreshIfMissing ?? false); - const trace = cached.trace; const contextChars = clamp(input.contextChars ?? DEFAULT_CONTEXT_CHARS, 20, 500); const needles = [input.fileId, input.fileName, ...(input.contentHints ?? [])].filter( (value): value is string => Boolean(value?.trim()) ); - const observations = trace.observations ?? []; - const stages = ATTACHMENT_STAGES.map((stage) => - inspectAttachmentStage(stage, observations, needles, input.fileId, input.fileName, contextChars) - ); + const stages = buildAttachmentFlow({ + observations: cached.trace.observations ?? [], + fileId: input.fileId, + fileName: input.fileName, + needles, + contextChars + }); return { traceId: input.traceId, @@ -304,27 +300,20 @@ export class LangfuseService { async getTraceRuleFlow(input: TraceRuleFlowInput) { const cached = await this.getCachedTrace(input.traceId, input.refreshIfMissing ?? false); - const trace = cached.trace; const contextChars = clamp(input.contextChars ?? 300, 20, 500); - const needles = uniqueStrings([input.rule, ...(input.ruleHints ?? [])]); - const observations = trace.observations ?? []; - const stageResults = RULE_FLOW_STAGES.map((stage) => - inspectRuleStage(stage, observations, needles, contextChars) - ); - const allEvidence = stageResults.flatMap((stage) => stage.evidence); - const relatedObservationIds = uniqueStrings(allEvidence.map((item) => item.observationId)); + const flow = buildRuleFlow({ + observations: cached.trace.observations ?? [], + needles: uniqueStrings([input.rule, ...(input.ruleHints ?? [])]), + contextChars + }); return { traceId: input.traceId, rule: input.rule, ruleHints: input.ruleHints, - stages: { - ruleMatching: stageResults[0], - documentParsing: stageResults[1], - finalReview: stageResults[2] - }, - relatedObservationIds, - evidenceCount: allEvidence.length, + stages: flow.stages, + relatedObservationIds: flow.relatedObservationIds, + evidenceCount: flow.evidenceCount, note: "Rule flow is deterministic text evidence extraction from cached Langfuse fields. It reports where the rule or hints appear; it does not infer hidden model reasoning or prove causality beyond the recorded trace text.", cache: { @@ -436,45 +425,6 @@ function buildOutlineWarnings( return warnings.slice(0, 20); } -function summarizeTrace(trace: LangfuseTraceSummary) { - return { - id: trace.id, - name: trace.name, - projectId: trace.projectId, - sessionId: trace.sessionId, - userId: trace.userId, - timestamp: trace.timestamp, - environment: trace.environment, - tags: trace.tags, - inputLength: stringifyValue(trace.input).length, - outputLength: stringifyValue(trace.output).length, - metadata: trace.metadata, - latency: trace.latency, - totalCost: trace.totalCost - }; -} - -function summarizeObservation(observation: LangfuseObservationSummary) { - return { - id: observation.id, - traceId: observation.traceId, - parentObservationId: observation.parentObservationId, - type: observation.type, - name: observation.name, - startTime: observation.startTime, - endTime: observation.endTime, - model: observation.providedModelName ?? observation.model, - inputLength: stringifyValue(observation.input).length, - outputLength: stringifyValue(observation.output).length, - inputBytes: byteLength(stringifyValue(observation.input)), - outputBytes: byteLength(stringifyValue(observation.output)), - metadataKeys: objectKeys(observation.metadata), - usageDetails: observation.usageDetails, - costDetails: observation.costDetails, - totalCost: observation.totalCost - }; -} - function buildTraceUrl(baseUrl: string, projectId: string, traceId: string): string { const url = new URL( `/project/${encodeURIComponent(projectId)}/traces/${encodeURIComponent(traceId)}`, @@ -545,209 +495,6 @@ function parsePath(path: string): Array { return segments; } -function inspectAttachmentStage( - stage: (typeof ATTACHMENT_STAGES)[number], - observations: LangfuseObservationSummary[], - needles: string[], - fileId: string | undefined, - fileName: string | undefined, - contextChars: number -) { - const stageTerms = stageSearchTerms(stage); - const candidates = observations.filter((observation) => { - const name = observation.name?.toLowerCase() ?? ""; - return stageTerms.some((term) => name.includes(term)); - }); - const evidence = candidates.flatMap((observation) => - collectAttachmentEvidence(observation, needles, contextChars) - ); - const source = classifyAttachmentEvidence(evidence, fileId, fileName); - - return { - stage, - source, - status: source === "absent" ? "absent" : "seen", - observations: candidates.map(summarizeObservation), - evidence - }; -} - -function stageSearchTerms(stage: (typeof ATTACHMENT_STAGES)[number]): string[] { - switch (stage) { - case "attachment parsing": - return ["attachment", "附件", "parse_attachment", "attachment_parsing"]; - case "image/document understanding": - return ["understanding", "vision", "image", "document_understanding", "文档理解", "图片理解"]; - case "pre_analysis": - return ["pre_analysis", "pre-analysis", "预分析"]; - case "document_parsing": - return ["document_parsing", "document parsing", "文档解析"]; - case "approval_review": - return ["approval_review", "approval review", "审核"]; - } -} - -function collectAttachmentEvidence( - observation: LangfuseObservationSummary, - needles: string[], - contextChars: number -): Array<{ - observationId: string; - name?: string; - field: "input" | "output" | "metadata"; - matched: string; - snippet: string; -}> { - const fields = [ - ["input", stringifyValue(observation.input)], - ["output", stringifyValue(observation.output)], - ["metadata", stringifyValue(observation.metadata)] - ] as const; - const evidence: ReturnType = []; - - for (const [field, text] of fields) { - const normalized = text.toLowerCase(); - for (const needle of needles) { - const index = normalized.indexOf(needle.toLowerCase()); - if (index < 0) continue; - evidence.push({ - observationId: observation.id, - name: observation.name, - field, - matched: text.slice(index, index + needle.length), - snippet: text.slice( - Math.max(0, index - contextChars), - Math.min(text.length, index + needle.length + contextChars) - ) - }); - } - } - - return evidence.slice(0, 10); -} - -function classifyAttachmentEvidence( - evidence: Array<{ matched: string; snippet: string; field?: string }>, - fileId: string | undefined, - fileName: string | undefined -): "filename-only" | "file-id-only" | "parsed-text" | "image-ocr" | "model-inferred" | "absent" | "unknown" { - if (evidence.length === 0) return "absent"; - const hasFileName = fileName ? evidence.some((item) => item.matched === fileName) : false; - const hasFileId = fileId ? evidence.some((item) => item.matched === fileId) : false; - const hasOtherHint = evidence.some((item) => item.matched !== fileId && item.matched !== fileName); - if (hasOtherHint) { - const joined = evidence - .map((item) => item.snippet) - .join("\n") - .toLowerCase(); - if (/(ocr|图片|image|vision|视觉|识别)/i.test(joined)) return "image-ocr"; - if (/(infer|inferred|推断|模型认为|判断|审核结论)/i.test(joined)) return "model-inferred"; - return "parsed-text"; - } - if (hasFileName && !hasOtherHint) return "filename-only"; - if (hasFileId && !hasOtherHint) return "file-id-only"; - return "unknown"; -} - -function inspectRuleStage( - stage: (typeof RULE_FLOW_STAGES)[number], - observations: LangfuseObservationSummary[], - needles: string[], - contextChars: number -) { - const stageTerms = ruleStageSearchTerms(stage); - const candidates = observations.filter((observation) => { - const name = observation.name?.toLowerCase() ?? ""; - return stageTerms.some((term) => name.includes(term)); - }); - const candidatePool = candidates.length ? candidates : observations; - const evidence = candidatePool - .flatMap((observation) => collectRuleEvidence(observation, needles, contextChars)) - .slice(0, 20); - const matchedObservationIds = uniqueStrings(evidence.map((item) => item.observationId)); - - return { - stage, - matched: evidence.length > 0, - matchedObservationIds, - observations: candidates.map(summarizeObservation), - extractedFields: summarizeEvidenceFields(evidence), - evidence - }; -} - -function ruleStageSearchTerms(stage: (typeof RULE_FLOW_STAGES)[number]): string[] { - switch (stage) { - case "rule matching": - return ["rule", "规则", "policy", "match", "matching", "命中"]; - case "document parsing": - return ["document", "parse", "parsing", "attachment", "ocr", "文档", "解析", "附件", "提取"]; - case "final review": - return ["approval_review", "approval review", "review", "审核", "结论", "final"]; - } -} - -function collectRuleEvidence( - observation: LangfuseObservationSummary, - needles: string[], - contextChars: number -): Array<{ - observationId: string; - name?: string; - type?: string; - field: "input" | "output" | "metadata"; - matched: string; - snippet: string; -}> { - const fields = [ - ["input", stringifyValue(observation.input)], - ["output", stringifyValue(observation.output)], - ["metadata", stringifyValue(observation.metadata)] - ] as const; - const evidence: ReturnType = []; - - for (const [field, text] of fields) { - const normalized = text.toLowerCase(); - for (const needle of needles) { - const index = normalized.indexOf(needle.toLowerCase()); - if (index < 0) continue; - evidence.push({ - observationId: observation.id, - name: observation.name, - type: observation.type, - field, - matched: text.slice(index, index + needle.length), - snippet: text.slice( - Math.max(0, index - contextChars), - Math.min(text.length, index + needle.length + contextChars) - ) - }); - } - } - - return evidence; -} - -function summarizeEvidenceFields( - evidence: Array<{ field: "input" | "output" | "metadata"; matched: string }> -): Record { - const summary: Record = {}; - for (const item of evidence) { - const entry = summary[item.field]; - if (entry) { - entry.count += 1; - if (!entry.matched.includes(item.matched)) entry.matched.push(item.matched); - } else { - summary[item.field] = { count: 1, matched: [item.matched] }; - } - } - return summary; -} - -function uniqueStrings(values: Array): string[] { - return [...new Set(values.filter((value): value is string => Boolean(value?.trim())))]; -} - function hasValue(value: unknown): boolean { return stringifyValue(value).length > 0; } @@ -759,14 +506,6 @@ function truncateMiddle(text: string, maxChars: number): string { return `${text.slice(0, head)}\n......\n${text.slice(text.length - tail)}`; } -function objectKeys(value: unknown): string[] { - return value && typeof value === "object" && !Array.isArray(value) ? Object.keys(value) : []; -} - -function byteLength(value: string): number { - return Buffer.byteLength(value, "utf8"); -} - function clamp(value: number, min: number, max: number): number { return Math.max(min, Math.min(max, value)); } diff --git a/src/domains/langfuse/summary.ts b/src/domains/langfuse/summary.ts new file mode 100644 index 0000000..994ec48 --- /dev/null +++ b/src/domains/langfuse/summary.ts @@ -0,0 +1,62 @@ +import { stringifyValue } from "./search.js"; +import type { LangfuseObservationSummary, LangfuseTraceSummary } from "./types.js"; + +/** + * Size-before-content projections of a cached trace. + * + * Both the outline/search responses and the flow evidence builders need these + * (a stage reports its candidate observations in summary form), so they live + * here rather than in `service.ts` — otherwise `flows.ts` would have to import + * the service that imports it back. + */ + +export function summarizeTrace(trace: LangfuseTraceSummary) { + return { + id: trace.id, + name: trace.name, + projectId: trace.projectId, + sessionId: trace.sessionId, + userId: trace.userId, + timestamp: trace.timestamp, + environment: trace.environment, + tags: trace.tags, + inputLength: stringifyValue(trace.input).length, + outputLength: stringifyValue(trace.output).length, + metadata: trace.metadata, + latency: trace.latency, + totalCost: trace.totalCost + }; +} + +export function summarizeObservation(observation: LangfuseObservationSummary) { + return { + id: observation.id, + traceId: observation.traceId, + parentObservationId: observation.parentObservationId, + type: observation.type, + name: observation.name, + startTime: observation.startTime, + endTime: observation.endTime, + model: observation.providedModelName ?? observation.model, + inputLength: stringifyValue(observation.input).length, + outputLength: stringifyValue(observation.output).length, + inputBytes: byteLength(stringifyValue(observation.input)), + outputBytes: byteLength(stringifyValue(observation.output)), + metadataKeys: objectKeys(observation.metadata), + usageDetails: observation.usageDetails, + costDetails: observation.costDetails, + totalCost: observation.totalCost + }; +} + +export function objectKeys(value: unknown): string[] { + return value && typeof value === "object" && !Array.isArray(value) ? Object.keys(value) : []; +} + +export function byteLength(value: string): number { + return Buffer.byteLength(value, "utf8"); +} + +export function uniqueStrings(values: Array): string[] { + return [...new Set(values.filter((value): value is string => Boolean(value?.trim())))]; +}