Files
seal-use/src/domains/langfuse/search.ts
T

221 lines
7.7 KiB
TypeScript

import type {
LangfuseObservationSummary,
LangfuseSearchResult,
LangfuseTraceSummary,
SearchField
} from "./types.js";
const DEFAULT_FIELDS: SearchField[] = ["name", "input", "output", "metadata", "userId", "sessionId"];
/**
* Deterministic ranked search inside ONE cached trace (the "qrep" engine).
* Case-insensitive substring matching — no embeddings, no LLM. Matches are
* scored (output > metadata > name; trace scope and review-stage observations
* rank higher) and returned with a hierarchy path plus before/match/after
* context so callers can decide which observation to open next.
*/
export function searchTrace(
projectId: string,
trace: LangfuseTraceSummary,
query: string | string[],
options: {
maxResults: number;
contextChars: number;
fields?: SearchField[];
observationTypes?: string[];
metadata?: Record<string, string | number | boolean>;
}
): LangfuseSearchResult[] {
const terms = normalizeTerms(query);
if (terms.length === 0) return [];
if (!metadataMatches(trace.metadata, options.metadata)) return [];
const fields = options.fields?.length ? options.fields : DEFAULT_FIELDS;
const observations = trace.observations ?? [];
const pathByObservationId = buildObservationPaths(trace, observations);
const allowedTypes = new Set(options.observationTypes?.map((type) => type.toUpperCase()));
const results: Array<LangfuseSearchResult & { score: number }> = [];
for (const field of searchableFields(trace, fields)) {
const match = makeMatch(field.value, terms, options.contextChars);
if (!match) continue;
results.push({
score: scoreMatch("trace", field.name),
projectId,
sessionId: trace.sessionId,
traceId: trace.id,
traceName: trace.name,
timestamp: trace.timestamp,
path: buildTracePath(trace, field.name),
field: field.name,
snippet: formatSnippet(match),
matchedField: field.name,
matchedText: match.match,
context: match,
hierarchy: {
session: trace.sessionId ? { id: trace.sessionId } : undefined,
trace: { id: trace.id, name: trace.name, userId: trace.userId }
}
});
}
for (const observation of observations) {
if (allowedTypes.size > 0 && observation.type && !allowedTypes.has(observation.type.toUpperCase())) {
continue;
}
for (const field of searchableFields(observation, fields)) {
const match = makeMatch(field.value, terms, options.contextChars);
if (!match) continue;
results.push({
score: scoreMatch("observation", field.name, observation.name),
projectId,
sessionId: trace.sessionId ?? observation.sessionId,
traceId: trace.id,
traceName: trace.name,
timestamp: observation.startTime ?? trace.timestamp,
path: [...(pathByObservationId.get(observation.id) ?? buildObservationPath(trace, observation)), field.name],
observationId: observation.id,
observationName: observation.name,
observationType: observation.type,
field: field.name,
snippet: formatSnippet(match),
matchedField: `observations.${observation.id}.${field.name}`,
matchedText: match.match,
context: match,
hierarchy: {
session: trace.sessionId ? { id: trace.sessionId } : undefined,
trace: { id: trace.id, name: trace.name, userId: trace.userId },
observation: {
id: observation.id,
type: observation.type,
name: observation.name
}
}
});
}
}
return results
.sort((left, right) => right.score - left.score)
.slice(0, options.maxResults)
.map(({ score: _score, ...result }) => result);
}
function searchableFields(
entity: Record<string, unknown>,
fields: SearchField[]
): Array<{ name: SearchField; value: string }> {
return fields
.map((field) => ({ name: field, value: stringifyValue(entity[field]) }))
.filter((field) => field.value.length > 0);
}
export function stringifyValue(value: unknown): string {
if (value === undefined || value === null) return "";
if (typeof value === "string") return value;
try {
return JSON.stringify(value);
} catch {
return String(value);
}
}
function normalizeTerms(query: string | string[]): string[] {
const values = Array.isArray(query) ? query : [query];
return values.map((value) => value.trim().toLowerCase()).filter(Boolean);
}
function makeMatch(
text: string,
terms: string[],
contextChars: number
): { before: string; match: string; after: string } | undefined {
const normalizedText = text.toLowerCase();
let best: { term: string; index: number } | undefined;
for (const term of terms) {
const index = normalizedText.indexOf(term);
if (index < 0) continue;
if (!best || index < best.index) best = { term, index };
}
if (!best) return undefined;
const start = Math.max(0, best.index - contextChars);
const end = Math.min(text.length, best.index + best.term.length + contextChars);
return {
before: text.slice(start, best.index),
match: text.slice(best.index, best.index + best.term.length),
after: text.slice(best.index + best.term.length, end)
};
}
function formatSnippet(match: { before: string; match: string; after: string }): string {
return `${match.before}${match.match}${match.after}`;
}
function scoreMatch(scope: "trace" | "observation", fieldName: string, observationName?: string): number {
const fieldWeight = fieldName === "output" ? 30 : fieldName === "metadata" ? 20 : fieldName === "name" ? 10 : 5;
const scopeWeight = scope === "trace" ? 15 : 0;
const finalReviewWeight =
observationName?.includes("approval_review") || observationName?.includes("审核") ? 10 : 0;
return fieldWeight + scopeWeight + finalReviewWeight;
}
function buildTracePath(trace: LangfuseTraceSummary, fieldName: string): string[] {
return [...(trace.sessionId ? [`session:${trace.sessionId}`] : []), `trace:${trace.name ?? trace.id}`, fieldName];
}
function buildObservationPaths(
trace: LangfuseTraceSummary,
observations: LangfuseObservationSummary[]
): Map<string, string[]> {
const byId = new Map(observations.map((observation) => [observation.id, observation]));
const paths = new Map<string, string[]>();
for (const observation of observations) {
paths.set(observation.id, resolveObservationPath(trace, observation, byId, paths));
}
return paths;
}
function resolveObservationPath(
trace: LangfuseTraceSummary,
observation: LangfuseObservationSummary,
byId: Map<string, LangfuseObservationSummary>,
paths: Map<string, string[]>
): string[] {
const cached = paths.get(observation.id);
if (cached) return cached;
const current = `${observation.type?.toLowerCase() ?? "observation"}:${observation.name ?? observation.id}`;
const parent = observation.parentObservationId ? byId.get(observation.parentObservationId) : undefined;
const path = parent
? [...resolveObservationPath(trace, parent, byId, paths), current]
: [...buildTracePath(trace, "observations").slice(0, -1), current];
paths.set(observation.id, path);
return path;
}
function buildObservationPath(trace: LangfuseTraceSummary, observation: LangfuseObservationSummary): string[] {
return [
...(trace.sessionId ? [`session:${trace.sessionId}`] : []),
`trace:${trace.name ?? trace.id}`,
`${observation.type?.toLowerCase() ?? "observation"}:${observation.name ?? observation.id}`
];
}
function metadataMatches(metadata: unknown, filters?: Record<string, string | number | boolean>): boolean {
if (!filters || Object.keys(filters).length === 0) return true;
if (!metadata || typeof metadata !== "object") return false;
const record = metadata as Record<string, unknown>;
return Object.entries(filters).every(([key, expected]) => record[key] === expected);
}