File size: 4,369 Bytes
9580dce | 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 | import { Client } from "langsmith";
// ---------------------------------------------------------------------------
// Singleton LangSmith client (mirrors claude.ts pattern)
// ---------------------------------------------------------------------------
const globalForLangSmith = globalThis as unknown as { langsmithClient: Client };
export const langsmithClient: Client =
globalForLangSmith.langsmithClient ??
new Client({
apiKey: process.env.LANGSMITH_API_KEY,
});
if (process.env.NODE_ENV !== "production") {
globalForLangSmith.langsmithClient = langsmithClient;
}
// ---------------------------------------------------------------------------
// Run tracer — creates a LangSmith run and returns its ID for feedback
// ---------------------------------------------------------------------------
/**
* Create a traced run in LangSmith and return its run ID.
* The run captures the judge invocation metadata so we can
* attach per-dimension feedback scores after the response is sent.
*/
export async function createRunTracer(opts: {
name: string;
inputs: Record<string, unknown>;
outputs: Record<string, unknown>;
runType?: string;
/** Optional pre-generated run ID. If omitted, a new UUID is generated. */
id?: string;
}): Promise<string> {
const runId = opts.id ?? crypto.randomUUID();
await langsmithClient.createRun({
id: runId,
name: opts.name,
run_type: (opts.runType as "llm") ?? "llm",
inputs: opts.inputs,
outputs: opts.outputs,
end_time: new Date().toISOString(),
});
return runId;
}
// ---------------------------------------------------------------------------
// Feedback — attach per-dimension scores to a run
// ---------------------------------------------------------------------------
/**
* Submit a feedback score for a single dimension on a given run.
*/
export async function submitDimensionFeedback(
runId: string,
dimensionId: string,
score: number,
): Promise<void> {
await langsmithClient.createFeedback(runId, dimensionId, {
score: Math.min(1, Math.max(0, score / 10)), // normalise 0-10 → 0-1
comment: `Auto-scored by judge: ${dimensionId}`,
});
}
/**
* Submit feedback for ALL dimensions of a judgement at once (fire-and-forget safe).
*/
export async function submitAllDimensionFeedback(
runId: string,
dimensionScores: Record<string, number>,
): Promise<void> {
await Promise.all(
Object.entries(dimensionScores).map(([dimId, score]) =>
submitDimensionFeedback(runId, dimId, score),
),
);
}
// ---------------------------------------------------------------------------
// Human feedback — prefixed with "human_" to distinguish from judge scores
// ---------------------------------------------------------------------------
/**
* Submit a human-provided override score for a single dimension.
* Uses the "human_<dimensionId>" key so the reflector can detect divergence
* between the LLM judge's scores and what a human would give.
*
* @param runId LangSmith run ID returned by createRunTracer
* @param dimensionId One of the DIMENSION_IDS (e.g. "argument-structure")
* @param score Human score, 0–10 (will be normalised to 0–1 for LangSmith)
*/
export async function submitHumanFeedback(
runId: string,
dimensionId: string,
score: number,
): Promise<void> {
const key = `human_${dimensionId}`;
await langsmithClient.createFeedback(runId, key, {
score: Math.min(1, Math.max(0, score / 10)), // normalise 0-10 → 0-1
comment: `Human override for ${dimensionId}`,
});
}
/**
* Submit human feedback for multiple dimensions at once.
* Skips any dimensionId whose score is null/undefined.
*/
export async function submitAllHumanFeedback(
runId: string,
overrideScores: Record<string, number>,
): Promise<void> {
await Promise.all(
Object.entries(overrideScores).map(([dimId, score]) =>
submitHumanFeedback(runId, dimId, score),
),
);
}
// ---------------------------------------------------------------------------
// Flush helper (for graceful shutdown / testing)
// ---------------------------------------------------------------------------
export async function flushTraces(): Promise<void> {
// The LangSmith JS client batches requests internally.
// Give it a moment to drain.
await new Promise((resolve) => setTimeout(resolve, 500));
}
|