RotNot / src /lib /langsmith.ts
deploy
Deploy RotNot
9580dce
Raw History Blame Contribute Delete
4.37 kB
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));
}