Skip to content

Job application tracker and AI-powered job search assistant. Helps job seekers manage their search journey with AI resume review, job matching, task logging, and application analytics, all while keeping your data private.

feat(telemetry): add GenAI spans at the five LLM call sites and fix float encoding

Khuram Niaz612e7162b302
diff --git a/__tests__/agentNestedGeneration.spec.ts b/__tests__/agentNestedGeneration.spec.ts
index 1b4c8d5..b495faf 100644
--- a/__tests__/agentNestedGeneration.spec.ts
+++ b/__tests__/agentNestedGeneration.spec.ts
@@ -29,6 +29,8 @@ const args = () => ({
toolCallId: "call-1",
guard: { running: false },
label: "test_tool",
+ provider: "ollama",
+ modelName: "test-model",
});
describe("runNestedGeneration", () => {
diff --git a/__tests__/telemetry/genai.spec.ts b/__tests__/telemetry/genai.spec.ts
new file mode 100644
index 0000000..804a0a7
--- /dev/null
+++ b/__tests__/telemetry/genai.spec.ts
@@ -0,0 +1,102 @@
+import { loadTelemetry } from "./helpers";
+
+const ENDPOINT = "http://homelab:5080/api/default";
+
+const usage = {
+ inputTokens: 1234,
+ inputTokenDetails: {},
+ outputTokens: 567,
+ outputTokenDetails: {},
+ totalTokens: 1801,
+} as any;
+
+describe("genai attribute mapping", () => {
+ afterEach(() => vi.unstubAllEnvs());
+
+ it("maps request fields onto standard and jobsync attributes", async () => {
+ const { genai } = await loadTelemetry({ endpoint: ENDPOINT });
+ const attrs = genai.genAiRequestAttrs({
+ provider: "ollama",
+ model: "qwen3.5:9b",
+ temperature: 0.1,
+ numCtx: 16384,
+ surface: genai.SURFACES.AGENT_CHAT,
+ });
+
+ expect(attrs).toEqual({
+ "gen_ai.system": "ollama",
+ "gen_ai.request.model": "qwen3.5:9b",
+ "gen_ai.request.temperature": 0.1,
+ "jobsync.surface": "agent.chat",
+ "jobsync.ollama.num_ctx": 16384,
+ });
+ });
+
+ it("omits prompt content unless OTEL_CAPTURE_CONTENT is on", async () => {
+ const off = await loadTelemetry({ endpoint: ENDPOINT });
+ const withoutContent = off.genai.genAiRequestAttrs({
+ provider: "ollama",
+ model: "qwen3.5:9b",
+ surface: off.genai.SURFACES.RESUME_REVIEW,
+ system: "you are a reviewer",
+ prompt: "resume text",
+ });
+ expect(withoutContent["gen_ai.prompt"]).toBeUndefined();
+ // Token counts and model survive with content off — that is the point of
+ // the two independent stages.
+ expect(withoutContent["gen_ai.request.model"]).toBe("qwen3.5:9b");
+
+ const on = await loadTelemetry({ endpoint: ENDPOINT, captureContent: true });
+ const withContent = on.genai.genAiRequestAttrs({
+ provider: "ollama",
+ model: "qwen3.5:9b",
+ surface: on.genai.SURFACES.RESUME_REVIEW,
+ system: "you are a reviewer",
+ prompt: "resume text",
+ });
+ expect(withContent["gen_ai.prompt"]).toEqual({
+ system: "you are a reviewer",
+ prompt: "resume text",
+ });
+ });
+
+ it("maps usage and finish reason, and gates the completion", async () => {
+ const off = await loadTelemetry({ endpoint: ENDPOINT });
+ const attrs = off.genai.genAiResponseAttrs({
+ usage,
+ finishReason: "stop",
+ text: "the review",
+ });
+ expect(attrs).toEqual({
+ "gen_ai.usage.input_tokens": 1234,
+ "gen_ai.usage.output_tokens": 567,
+ "gen_ai.usage.total_tokens": 1801,
+ "gen_ai.response.finish_reasons": "stop",
+ });
+
+ const on = await loadTelemetry({ endpoint: ENDPOINT, captureContent: true });
+ expect(
+ on.genai.genAiResponseAttrs({ usage, finishReason: "stop", text: "the review" })[
+ "gen_ai.completion"
+ ],
+ ).toBe("the review");
+ });
+
+ it("omits usage keys entirely when the provider returned none", async () => {
+ const { genai } = await loadTelemetry({ endpoint: ENDPOINT });
+ expect(genai.genAiResponseAttrs({ finishReason: "error" })).toEqual({
+ "gen_ai.response.finish_reasons": "error",
+ });
+ });
+
+ it("reports input sizes and the call site's own truncation flag", async () => {
+ const { genai } = await loadTelemetry({ endpoint: ENDPOINT });
+ expect(
+ genai.inputSizeAttrs({ resumeChars: 14_500, jobChars: 3_200, truncated: true }),
+ ).toEqual({
+ "jobsync.input.resume_chars": 14_500,
+ "jobsync.input.job_chars": 3_200,
+ "jobsync.input.truncated": true,
+ });
+ });
+});
diff --git a/__tests__/telemetry/nestedGenerationSpan.spec.ts b/__tests__/telemetry/nestedGenerationSpan.spec.ts
new file mode 100644
index 0000000..3a8b9e6
--- /dev/null
+++ b/__tests__/telemetry/nestedGenerationSpan.spec.ts
@@ -0,0 +1,111 @@
+import { loadTelemetry, mockFetchOk } from "./helpers";
+
+const ENDPOINT = "http://homelab:5080/api/default";
+
+const writer = { write: () => {} } as any;
+
+function stubStreamText(chunks: string[], finishReason: string) {
+ return {
+ textStream: (async function* () {
+ for (const chunk of chunks) yield chunk;
+ })(),
+ finishReason: Promise.resolve(finishReason),
+ totalUsage: Promise.resolve({
+ inputTokens: 7000,
+ inputTokenDetails: {},
+ outputTokens: 900,
+ outputTokenDetails: {},
+ totalTokens: 7900,
+ }),
+ };
+}
+
+vi.mock("ai", async (importOriginal) => {
+ const actual = await importOriginal<typeof import("ai")>();
+ return { ...actual, streamText: vi.fn() };
+});
+
+describe("agent.nested span", () => {
+ afterEach(() => {
+ vi.unstubAllEnvs();
+ vi.unstubAllGlobals();
+ vi.restoreAllMocks();
+ });
+
+ it("records surface, num_ctx, usage and the caller's input sizes", async () => {
+ mockFetchOk();
+ const { otlp } = await loadTelemetry({ endpoint: ENDPOINT });
+ const { streamText } = await import("ai");
+ (streamText as any).mockReturnValue(stubStreamText(["a", "b"], "stop"));
+ const { runNestedGeneration } = await import("@/lib/agent/nestedGeneration");
+
+ const result = await runNestedGeneration({
+ model: {} as any,
+ system: "sys",
+ prompt: "resume text",
+ temperature: 0.3,
+ numCtx: 8192,
+ timeoutMs: 1000,
+ writer,
+ toolCallId: "call-1",
+ guard: { running: false },
+ label: "review_resume",
+ provider: "ollama",
+ modelName: "qwen3.5:9b",
+ attrs: { "jobsync.input.resume_chars": 14500 },
+ });
+
+ expect(result).toEqual({ status: "ok", text: "ab" });
+ expect(otlp.getTelemetryStats().queuedSpans).toBe(1);
+ });
+
+ it("marks an incomplete generation as an error span", async () => {
+ mockFetchOk();
+ const { otlp } = await loadTelemetry({ endpoint: ENDPOINT });
+ const { streamText } = await import("ai");
+ (streamText as any).mockReturnValue(stubStreamText(["a"], "length"));
+ const { runNestedGeneration } = await import("@/lib/agent/nestedGeneration");
+
+ const result = await runNestedGeneration({
+ model: {} as any,
+ system: "sys",
+ prompt: "p",
+ temperature: 0.3,
+ numCtx: 8192,
+ timeoutMs: 1000,
+ writer,
+ toolCallId: "call-1",
+ guard: { running: false },
+ label: "review_resume",
+ provider: "ollama",
+ modelName: "qwen3.5:9b",
+ });
+
+ expect(result).toEqual({ status: "incomplete" });
+ expect(otlp.getTelemetryStats().queuedSpans).toBe(1);
+ });
+
+ it("still records a span when the guard rejects the call as busy", async () => {
+ mockFetchOk();
+ const { otlp } = await loadTelemetry({ endpoint: ENDPOINT });
+ const { runNestedGeneration } = await import("@/lib/agent/nestedGeneration");
+
+ const result = await runNestedGeneration({
+ model: {} as any,
+ system: "sys",
+ prompt: "p",
+ temperature: 0.3,
+ numCtx: 8192,
+ timeoutMs: 1000,
+ writer,
+ toolCallId: "call-1",
+ guard: { running: true },
+ label: "match_job",
+ provider: "ollama",
+ modelName: "qwen3.5:9b",
+ });
+
+ expect(result).toEqual({ status: "busy" });
+ expect(otlp.getTelemetryStats().queuedSpans).toBe(1);
+ });
+});
diff --git a/__tests__/telemetry/otlpPayload.spec.ts b/__tests__/telemetry/otlpPayload.spec.ts
index b2d9fee..09ba4cb 100644
--- a/__tests__/telemetry/otlpPayload.spec.ts
+++ b/__tests__/telemetry/otlpPayload.spec.ts
@@ -42,7 +42,7 @@ describe("otlp payload shape", () => {
expect(encoded.endTimeUnixNano).toBe("1756500001000000000");
});
- it("types attribute values: string, int, double, bool, and JSON for objects", async () => {
+ it("types attribute values: string, int, float, bool, and JSON for objects", async () => {
const { otlp } = await loadTelemetry({ endpoint: ENDPOINT });
const payload = otlp.buildTracePayload([
span({
@@ -60,7 +60,8 @@ describe("otlp payload shape", () => {
expect(byKey["gen_ai.request.model"]).toEqual({ stringValue: "qwen3.5:9b" });
expect(byKey["gen_ai.usage.input_tokens"]).toEqual({ intValue: "1234" });
- expect(byKey["gen_ai.request.temperature"]).toEqual({ doubleValue: 0.1 });
+ // Not doubleValue: OpenObserve 400s that and drops the entire batch.
+ expect(byKey["gen_ai.request.temperature"]).toEqual({ stringValue: "0.1" });
expect(byKey["jobsync.prefix_changed"]).toEqual({ boolValue: true });
expect(byKey["gen_ai.prompt"]).toEqual({
stringValue: '{"role":"user","content":"hi"}',
diff --git a/__tests__/telemetry/streamParenting.spec.ts b/__tests__/telemetry/streamParenting.spec.ts
index 9b0ed6e..b1471c8 100644
--- a/__tests__/telemetry/streamParenting.spec.ts
+++ b/__tests__/telemetry/streamParenting.spec.ts
@@ -81,3 +81,52 @@ describe("telemetry context propagation through createUIMessageStream", () => {
expect(seenInOnFinish).toBe("turn-span");
});
});
+
+describe("real span parenting through the stream boundary", () => {
+ afterEach(() => {
+ vi.unstubAllEnvs();
+ vi.unstubAllGlobals();
+ });
+
+ it("a span started inside a tool parents under the turn span", async () => {
+ const { loadTelemetry, mockFetchOk } = await import("./helpers");
+ mockFetchOk();
+ const { span: api, otlp } = await loadTelemetry({
+ endpoint: "http://homelab:5080/api/default",
+ });
+
+ const turn = api.startSpan("agent.chat.turn");
+ let childParent: string | undefined;
+
+ const stream = createUIMessageStream({
+ execute: ({ writer }) =>
+ api.runInSpan(turn, () => {
+ const result = streamText({
+ model: toolCallingModel(),
+ prompt: "go",
+ stopWhen: [stepCountIs(1)],
+ tools: {
+ nested_tool: tool({
+ description: "starts a nested span",
+ inputSchema: z.object({}),
+ execute: async () => {
+ const child = api.startSpan("agent.nested.review_resume");
+ childParent = turn.spanId;
+ expect(child.traceId).toBe(turn.traceId);
+ child.end();
+ return { status: "ok" };
+ },
+ }),
+ },
+ });
+ writer.merge(result.toUIMessageStream());
+ }),
+ });
+
+ await drain(stream);
+ turn.end();
+
+ expect(childParent).toBe(turn.spanId);
+ expect(otlp.getTelemetryStats().queuedSpans).toBe(2);
+ });
+});
diff --git a/src/actions/automation/analyze.ts b/src/actions/automation/analyze.ts
index 65f6ab6..51e9d2f 100644
--- a/src/actions/automation/analyze.ts
+++ b/src/actions/automation/analyze.ts
@@ -15,6 +15,14 @@ import { getResumeById } from "@/actions/profile.actions";
import { getJobDetails } from "@/actions/job.actions";
import { defaultUserSettings } from "@/models/userSettings.model";
import { automationLogger } from "@/lib/automation-logger";
+import { APP_CONSTANTS } from "@/lib/constants";
+import {
+ genAiRequestAttrs,
+ genAiResponseAttrs,
+ inputSizeAttrs,
+ SURFACES,
+ withSpan,
+} from "@/lib/telemetry";
import { formatError } from "./shared";
// Runs an on-demand LLM match for an un-analyzed discovered job using the
@@ -76,15 +84,47 @@ export async function analyzeDiscoveredJob(jobId: string): Promise<{
const model = await getModel(ai.provider, ai.model || "llama3.2", user.id);
- const result = await generateText({
- model,
- system: JOB_MATCH_SYSTEM_PROMPT,
- prompt: buildJobMatchPrompt(
- resumePre.data.normalizedText,
- jobPre.data.normalizedText,
- ),
- temperature: 0.3,
- });
+ const promptText = buildJobMatchPrompt(
+ resumePre.data.normalizedText,
+ jobPre.data.normalizedText,
+ );
+
+ const result = await withSpan(
+ "automation.analyze",
+ {
+ ...genAiRequestAttrs({
+ provider: ai.provider,
+ model: ai.model || "llama3.2",
+ temperature: 0.3,
+ numCtx: APP_CONSTANTS.AI_OLLAMA_NUM_CTX,
+ surface: SURFACES.JOB_MATCH,
+ system: JOB_MATCH_SYSTEM_PROMPT,
+ prompt: promptText,
+ }),
+ ...inputSizeAttrs({
+ resumeChars: resumePre.data.normalizedText.length,
+ jobChars: jobPre.data.normalizedText.length,
+ }),
+ "jobsync.user_id": user.id,
+ "jobsync.job_id": jobId,
+ },
+ async (span) => {
+ const generated = await generateText({
+ model,
+ system: JOB_MATCH_SYSTEM_PROMPT,
+ prompt: promptText,
+ temperature: 0.3,
+ });
+ span.setAttrs(
+ genAiResponseAttrs({
+ usage: generated.totalUsage,
+ finishReason: generated.finishReason,
+ text: generated.text,
+ }),
+ );
+ return generated;
+ },
+ );
const { scores, body } = parseJobMatch(result.text);
if (!scores) {
diff --git a/src/app/api/ai/chat/route.ts b/src/app/api/ai/chat/route.ts
index 39b6477..835eda2 100644
--- a/src/app/api/ai/chat/route.ts
+++ b/src/app/api/ai/chat/route.ts
@@ -10,6 +10,7 @@ import {
isToolUIPart,
stepCountIs,
streamText,
+ type LanguageModelUsage,
type StopCondition,
type UIMessage,
} from "ai";
@@ -35,6 +36,13 @@ import { mapAgentError } from "@/lib/agent/errors";
import { getUserSettings } from "@/actions/userSettings.actions";
import { saveChatConversation } from "@/actions/agentChat.actions";
import { AiProvider } from "@/models/ai.model";
+import {
+ genAiRequestAttrs,
+ genAiResponseAttrs,
+ runInSpan,
+ startSpan,
+ SURFACES,
+} from "@/lib/telemetry";
import { addJobSettled, AGENT_CHAT_TERMINAL_TOOLS } from "@/models/agent.model";
// The one terminal tool whose stop condition is not "was it called" — see
@@ -182,55 +190,80 @@ export const POST = async (req: NextRequest) => {
// Written inside execute, read in onFinish, which runs after it.
let prefixMetrics: TurnPrefixMetrics | undefined;
+ // Written by streamText's own onFinish, read in the outer onFinish. Must be
+ // totalUsage, not one step's usage: stopWhen permits AGENT_CHAT_MAX_STEPS.
+ let turnUsage: LanguageModelUsage | undefined;
+ let turnFinishReason: string | undefined;
+
+ const turnSpan = startSpan("agent.chat.turn", {
+ ...genAiRequestAttrs({
+ provider,
+ model: modelName,
+ temperature: TEMPERATURES.ANALYSIS,
+ numCtx: APP_CONSTANTS.AGENT_CHAT_NUM_CTX,
+ surface: SURFACES.AGENT_CHAT,
+ system: AGENT_CHAT_SYSTEM_PROMPT,
+ prompt: modelMessages,
+ }),
+ "jobsync.user_id": userId,
+ });
+
const stream = createUIMessageStream({
originalMessages: messages,
- execute: ({ writer }) => {
- const tools = buildAgentTools({
- userId,
- pastedText,
- pageContext,
- model,
- provider,
- modelName,
- writer,
- });
- prefixMetrics = measureTurnPrefix({
- userId,
- system: AGENT_CHAT_SYSTEM_PROMPT,
- tools,
- modelMessages,
- });
- const result = streamText({
- model,
- system: AGENT_CHAT_SYSTEM_PROMPT,
- messages: modelMessages,
- tools,
- // Which tools end the turn — and why — lives beside the tool metadata
- // in agent.model.ts, where a new tool is registered.
- stopWhen: [
- stepCountIs(APP_CONSTANTS.AGENT_CHAT_MAX_STEPS),
- ...AGENT_CHAT_TERMINAL_TOOLS.map((name) =>
- name === "add_job" ? addJobSettledStop : hasToolCall(name),
- ),
- ],
- // Argument extraction wants determinism.
- temperature: TEMPERATURES.ANALYSIS,
- abortSignal: turnSignal,
- providerOptions: {
- // qwen3.5 is a hybrid-reasoning model and the provider defaults
- // think to false. With the thinking channel shut it deliberates in
- // the content channel, and content and a tool call are mutually
- // exclusive — add_job measured 1/7 with it off, 7/7 with it on.
- ollama: { think: true, options: { num_ctx: APP_CONSTANTS.AGENT_CHAT_NUM_CTX } },
- },
- });
- // createUIMessageStream emits no start/finish of its own — the merged
- // stream carries them, so this is byte-identical to the old response.
- writer.merge(result.toUIMessageStream());
- },
+ execute: ({ writer }) =>
+ runInSpan(turnSpan, () => {
+ const tools = buildAgentTools({
+ userId,
+ pastedText,
+ pageContext,
+ model,
+ provider,
+ modelName,
+ writer,
+ });
+ prefixMetrics = measureTurnPrefix({
+ userId,
+ system: AGENT_CHAT_SYSTEM_PROMPT,
+ tools,
+ modelMessages,
+ });
+ const result = streamText({
+ model,
+ system: AGENT_CHAT_SYSTEM_PROMPT,
+ messages: modelMessages,
+ tools,
+ // Which tools end the turn — and why — lives beside the tool metadata
+ // in agent.model.ts, where a new tool is registered.
+ stopWhen: [
+ stepCountIs(APP_CONSTANTS.AGENT_CHAT_MAX_STEPS),
+ ...AGENT_CHAT_TERMINAL_TOOLS.map((name) =>
+ name === "add_job" ? addJobSettledStop : hasToolCall(name),
+ ),
+ ],
+ // Argument extraction wants determinism.
+ temperature: TEMPERATURES.ANALYSIS,
+ abortSignal: turnSignal,
+ providerOptions: {
+ // qwen3.5 is a hybrid-reasoning model and the provider defaults
+ // think to false. With the thinking channel shut it deliberates in
+ // the content channel, and content and a tool call are mutually
+ // exclusive — add_job measured 1/7 with it off, 7/7 with it on.
+ ollama: { think: true, options: { num_ctx: APP_CONSTANTS.AGENT_CHAT_NUM_CTX } },
+ },
+ // streamText's onFinish, not createUIMessageStream's: result is
+ // scoped inside execute while the span ends in the outer onFinish.
+ onFinish: ({ totalUsage, finishReason }) => {
+ turnUsage = totalUsage;
+ turnFinishReason = finishReason;
+ },
+ });
+ // createUIMessageStream emits no start/finish of its own — the merged
+ // stream carries them, so this is byte-identical to the old response.
+ writer.merge(result.toUIMessageStream());
+ }),
onFinish: async ({ messages: finalMessages, responseMessage, isAborted }) => {
const { tool, state, outcome } = outcomeOf(responseMessage);
- logTurn({
+ const fields = {
provider,
model: modelName,
tool,
@@ -249,6 +282,26 @@ export const POST = async (req: NextRequest) => {
toolChars: prefixMetrics?.toolChars ?? 0,
messageChars: prefixMetrics?.messageChars ?? 0,
prefixChanged: prefixMetrics?.prefixChanged ?? false,
+ };
+ logTurn(fields);
+ // The same curated field set, on the span rather than only in the log,
+ // so it is queryable beside latency, tokens and the tool waterfall.
+ turnSpan.end({
+ ...genAiResponseAttrs({
+ usage: turnUsage,
+ finishReason: turnFinishReason,
+ }),
+ "jobsync.tool": fields.tool,
+ "jobsync.tool_state": fields.toolState,
+ "jobsync.outcome": fields.outcome,
+ "jobsync.aborted": fields.aborted,
+ "jobsync.paste_chars": fields.pasteChars,
+ "jobsync.message_count": fields.messageCount,
+ "jobsync.history_dropped": fields.historyDropped,
+ "jobsync.system_chars": fields.systemChars,
+ "jobsync.tool_chars": fields.toolChars,
+ "jobsync.message_chars": fields.messageChars,
+ "jobsync.prefix_changed": fields.prefixChanged,
});
// A cancelled turn never writes back. Clear deletes the conversation and
// this fires afterwards on the stream's cancel path, so saving here would
diff --git a/src/app/api/ai/resume/import/route.ts b/src/app/api/ai/resume/import/route.ts
index 71cdb29..5251251 100644
--- a/src/app/api/ai/resume/import/route.ts
+++ b/src/app/api/ai/resume/import/route.ts
@@ -18,6 +18,14 @@ import {
RESUME_IMPORT_SYSTEM_PROMPT,
buildResumeImportPrompt,
} from "@/lib/ai/prompts/resume-import";
+import {
+ genAiRequestAttrs,
+ genAiResponseAttrs,
+ inputSizeAttrs,
+ runInSpan,
+ startSpan,
+ SURFACES,
+} from "@/lib/telemetry";
export const POST = async (req: NextRequest) => {
const session = await auth();
@@ -130,30 +138,58 @@ export const POST = async (req: NextRequest) => {
// partialOutputStream is a generic "No output generated".
let streamErrorMessage: string | undefined;
- const result = streamText({
- model,
- output: Output.object({ schema: ResumeImportSchema }),
- system: RESUME_IMPORT_SYSTEM_PROMPT,
- prompt: buildResumeImportPrompt(preprocessResult.data.normalizedText),
- temperature: TEMPERATURES.ANALYSIS,
- abortSignal: controller.signal,
- providerOptions: {
- ollama: { options: { num_ctx: APP_CONSTANTS.AI_OLLAMA_NUM_CTX } },
- // OpenAI (and OpenRouter, same factory) default to strict json_schema,
- // which rejects any object whose `required` omits a key — this schema
- // is optional-by-design throughout. Non-strict passes it as guidance.
- openai: { strictJsonSchema: false },
- },
- onFinish: () => {
- clearTimeout(timer);
- },
- onError: ({ error }) => {
- clearTimeout(timer);
- console.error("Resume import stream error:", error);
- streamErrorMessage = error instanceof Error ? error.message : undefined;
- },
+ const importSpan = startSpan("resume.import", {
+ ...genAiRequestAttrs({
+ provider: selectedModel.provider,
+ model: selectedModel.model,
+ temperature: TEMPERATURES.ANALYSIS,
+ numCtx: APP_CONSTANTS.AI_OLLAMA_NUM_CTX,
+ surface: SURFACES.RESUME_IMPORT,
+ system: RESUME_IMPORT_SYSTEM_PROMPT,
+ prompt: preprocessResult.data.normalizedText,
+ }),
+ ...inputSizeAttrs({
+ resumeChars: preprocessResult.data.normalizedText.length,
+ // The flag extract-text.ts already computes at its 50,000-char and
+ // 5-page limits — did the model see the whole document?
+ truncated,
+ }),
+ "jobsync.user_id": userId,
+ "jobsync.resume_id": resumeId,
});
+ const result = runInSpan(importSpan, () =>
+ streamText({
+ model,
+ output: Output.object({ schema: ResumeImportSchema }),
+ system: RESUME_IMPORT_SYSTEM_PROMPT,
+ prompt: buildResumeImportPrompt(preprocessResult.data.normalizedText),
+ temperature: TEMPERATURES.ANALYSIS,
+ abortSignal: controller.signal,
+ providerOptions: {
+ ollama: { options: { num_ctx: APP_CONSTANTS.AI_OLLAMA_NUM_CTX } },
+ // OpenAI (and OpenRouter, same factory) default to strict
+ // json_schema, which rejects any object whose `required` omits a key
+ // — this schema is optional-by-design throughout. Non-strict passes
+ // it as guidance.
+ openai: { strictJsonSchema: false },
+ },
+ onFinish: ({ totalUsage, finishReason }) => {
+ clearTimeout(timer);
+ importSpan.end(
+ genAiResponseAttrs({ usage: totalUsage, finishReason }),
+ );
+ },
+ onError: ({ error }) => {
+ clearTimeout(timer);
+ console.error("Resume import stream error:", error);
+ streamErrorMessage = error instanceof Error ? error.message : undefined;
+ importSpan.setError(error);
+ importSpan.end();
+ },
+ }),
+ );
+
// Stream partialOutputStream (not textStream): the SDK parses the model's
// output regardless of whether the provider used json or tool-call mode, so
// this is non-empty even when textStream is. Each value is a full snapshot
diff --git a/src/lib/agent/nestedGeneration.ts b/src/lib/agent/nestedGeneration.ts
index 9061599..b51f82e 100644
--- a/src/lib/agent/nestedGeneration.ts
+++ b/src/lib/agent/nestedGeneration.ts
@@ -2,6 +2,14 @@ import "server-only";
import { streamText, type LanguageModel, type UIMessageStreamWriter } from "ai";
import { AGENT_NESTED_STREAM_PART_TYPE } from "@/models/agent.model";
+import {
+ genAiRequestAttrs,
+ genAiResponseAttrs,
+ runInSpan,
+ startSpan,
+ SURFACE_BY_NESTED_LABEL,
+ SURFACES,
+} from "@/lib/telemetry";
export type NestedGenerationResult =
| { status: "ok"; text: string }
@@ -25,6 +33,11 @@ type NestedGenerationArgs = {
abortSignal?: AbortSignal;
guard: NestedGenerationGuard;
label: string;
+ provider: string;
+ modelName: string;
+ // Call-site facts the invariant half cannot know: input sizes and whether
+ // the caller clipped what it sent.
+ attrs?: Record<string, unknown>;
};
/**
@@ -45,52 +58,92 @@ export async function runNestedGeneration({
abortSignal,
guard,
label,
+ provider,
+ modelName,
+ attrs,
}: NestedGenerationArgs): Promise<NestedGenerationResult> {
+ // Started before the guard check so a rejected call is visible too — "busy"
+ // is exactly the outcome you go looking for when a review never appeared.
+ const span = startSpan(`agent.nested.${label}`, {
+ ...genAiRequestAttrs({
+ provider,
+ model: modelName,
+ temperature,
+ numCtx,
+ surface: SURFACE_BY_NESTED_LABEL[label] ?? SURFACES.AGENT_CHAT,
+ system,
+ prompt,
+ }),
+ ...attrs,
+ });
+
// Terminal tools stop the loop after a step, not within one: the model can
// still emit both nested tools in a single step, and two 180s sub-calls
// serialize on Ollama past the 300s turn deadline, losing both.
- if (guard.running) return { status: "busy" };
+ if (guard.running) {
+ span.end({ "jobsync.nested.status": "busy" });
+ return { status: "busy" };
+ }
guard.running = true;
- // Own deadline, plus the outer turn's signal so closing the panel aborts
- // this too.
- const signals: AbortSignal[] = [AbortSignal.timeout(timeoutMs)];
- if (abortSignal) signals.push(abortSignal);
-
- let text = "";
- try {
- const sub = streamText({
- model,
- system,
- prompt,
- temperature,
- abortSignal: AbortSignal.any(signals),
- // Deliberately no think:true. These sub-calls have no tools, so
- // reasoning buys nothing and costs 30s. The chat loop enables it.
- providerOptions: { ollama: { options: { num_ctx: numCtx } } },
- });
+ return runInSpan(span, async () => {
+ // Own deadline, plus the outer turn's signal so closing the panel aborts
+ // this too.
+ const signals: AbortSignal[] = [AbortSignal.timeout(timeoutMs)];
+ if (abortSignal) signals.push(abortSignal);
- for await (const delta of sub.textStream) {
- text += delta;
- writer.write({
- type: AGENT_NESTED_STREAM_PART_TYPE,
- id: toolCallId,
- data: { delta },
- transient: true,
+ let text = "";
+ try {
+ const sub = streamText({
+ model,
+ system,
+ prompt,
+ temperature,
+ abortSignal: AbortSignal.any(signals),
+ // Deliberately no think:true. These sub-calls have no tools, so
+ // reasoning buys nothing and costs 30s. The chat loop enables it.
+ providerOptions: { ollama: { options: { num_ctx: numCtx } } },
});
- }
- // The stream running out is not the generation finishing, and neither
- // case throws: an abort ends textStream cleanly and rejects this promise,
- // and a body that stops without Ollama's done chunk resolves to "other".
- const finishReason = await sub.finishReason;
- if (finishReason !== "stop") return { status: "incomplete" };
- } catch (error) {
- console.error(`[agent-chat] ${label} generation failed:`, error);
- return { status: "failed" };
- } finally {
- guard.running = false;
- }
+ for await (const delta of sub.textStream) {
+ text += delta;
+ writer.write({
+ type: AGENT_NESTED_STREAM_PART_TYPE,
+ id: toolCallId,
+ data: { delta },
+ transient: true,
+ });
+ }
- return { status: "ok", text };
+ // The stream running out is not the generation finishing, and neither
+ // case throws: an abort ends textStream cleanly and rejects this
+ // promise, and a body that stops without Ollama's done chunk resolves
+ // to "other".
+ const finishReason = await sub.finishReason;
+ if (finishReason !== "stop") {
+ span.setError(new Error(`finishReason=${finishReason}`));
+ span.end({
+ "jobsync.nested.status": "incomplete",
+ ...genAiResponseAttrs({ finishReason }),
+ });
+ return { status: "incomplete" };
+ }
+
+ // Only on the ok path, and defensively: an aborted stream rejects this,
+ // the same trap the finishReason guard above exists for.
+ const usage = await Promise.resolve(sub.totalUsage).catch(() => undefined);
+ span.end({
+ "jobsync.nested.status": "ok",
+ ...genAiResponseAttrs({ usage, finishReason, text }),
+ });
+ return { status: "ok", text };
+ } catch (error) {
+ console.error(`[agent-chat] ${label} generation failed:`, error);
+ span.setError(error);
+ span.end({ "jobsync.nested.status": "failed" });
+ return { status: "failed" };
+ } finally {
+ guard.running = false;
+ }
+ });
}
diff --git a/src/lib/agent/tools/generateCoverLetter.ts b/src/lib/agent/tools/generateCoverLetter.ts
index 4916c73..3d812b7 100644
--- a/src/lib/agent/tools/generateCoverLetter.ts
+++ b/src/lib/agent/tools/generateCoverLetter.ts
@@ -111,6 +111,12 @@ export function buildGenerateCoverLetterTool(ctx: CoverLetterContext) {
abortSignal,
guard: ctx.guard,
label: "generate_cover_letter",
+ provider: ctx.provider,
+ modelName: ctx.modelName,
+ attrs: {
+ "jobsync.input.resume_chars": resumePre.data.normalizedText.length,
+ "jobsync.input.job_chars": jobPre.data.normalizedText.length,
+ },
});
if (generation.status === "busy") {
return {
diff --git a/src/lib/agent/tools/matchJob.ts b/src/lib/agent/tools/matchJob.ts
index 911f056..ee4699c 100644
--- a/src/lib/agent/tools/matchJob.ts
+++ b/src/lib/agent/tools/matchJob.ts
@@ -100,6 +100,12 @@ export function buildMatchJobTool(ctx: MatchJobContext) {
abortSignal,
guard: ctx.guard,
label: "match_job",
+ provider: ctx.provider,
+ modelName: ctx.modelName,
+ attrs: {
+ "jobsync.input.resume_chars": resumePre.data.normalizedText.length,
+ "jobsync.input.job_chars": jobPre.data.normalizedText.length,
+ },
});
if (generation.status === "busy") {
return {
diff --git a/src/lib/agent/tools/reviewResume.ts b/src/lib/agent/tools/reviewResume.ts
index d412051..83c841b 100644
--- a/src/lib/agent/tools/reviewResume.ts
+++ b/src/lib/agent/tools/reviewResume.ts
@@ -76,6 +76,11 @@ export function buildReviewResumeTool(ctx: ReviewResumeContext) {
abortSignal,
guard: ctx.guard,
label: "review_resume",
+ provider: ctx.provider,
+ modelName: ctx.modelName,
+ attrs: {
+ "jobsync.input.resume_chars": pre.data.normalizedText.length,
+ },
});
if (generation.status === "busy") {
return {
diff --git a/src/lib/scraper/runner.ts b/src/lib/scraper/runner.ts
index 02672c5..edd4ac7 100644
--- a/src/lib/scraper/runner.ts
+++ b/src/lib/scraper/runner.ts
@@ -42,6 +42,13 @@ import {
import { resolveApiKey } from "@/lib/api-key-resolver";
import { PROVIDER_VERIFIERS } from "@/lib/ai/provider-registry.server";
import { getOllamaBaseUrl } from "@/actions/apiKey.actions";
+import {
+ genAiRequestAttrs,
+ genAiResponseAttrs,
+ inputSizeAttrs,
+ SURFACES,
+ withSpan,
+} from "@/lib/telemetry";
const MAX_JOBS_PER_RUN = APP_CONSTANTS.MAX_JOBS_PER_RUN;
@@ -1148,13 +1155,45 @@ ${removeHtmlTags(job.description)}
const modelName = aiSettings.model || getDefaultModelForProvider(provider);
const model = await getModel(provider, modelName, userId);
- const result = await generateText({
- model,
- system: AUTOMATION_JOB_MATCH_SYSTEM_PROMPT,
- prompt: buildAutomationJobMatchPrompt(resumeText, jobText),
- temperature: 0.3,
- abortSignal: signal,
- });
+ const promptText = buildAutomationJobMatchPrompt(resumeText, jobText);
+
+ const result = await withSpan(
+ "scraper.match",
+ {
+ ...genAiRequestAttrs({
+ provider,
+ model: modelName,
+ temperature: 0.3,
+ numCtx: APP_CONSTANTS.AI_OLLAMA_NUM_CTX,
+ surface: SURFACES.AUTOMATION_MATCH,
+ system: AUTOMATION_JOB_MATCH_SYSTEM_PROMPT,
+ prompt: promptText,
+ }),
+ ...inputSizeAttrs({
+ resumeChars: resumeText.length,
+ jobChars: jobText.length,
+ }),
+ "jobsync.job_board": sourceBoard,
+ "jobsync.user_id": userId,
+ },
+ async (span) => {
+ const generated = await generateText({
+ model,
+ system: AUTOMATION_JOB_MATCH_SYSTEM_PROMPT,
+ prompt: promptText,
+ temperature: 0.3,
+ abortSignal: signal,
+ });
+ span.setAttrs(
+ genAiResponseAttrs({
+ usage: generated.totalUsage,
+ finishReason: generated.finishReason,
+ text: generated.text,
+ }),
+ );
+ return generated;
+ },
+ );
const { scores, body } = parseJobMatch(result.text);
if (!scores) {
diff --git a/src/lib/telemetry/genai.ts b/src/lib/telemetry/genai.ts
index 2a80e56..49adc3b 100644
--- a/src/lib/telemetry/genai.ts
+++ b/src/lib/telemetry/genai.ts
@@ -1,2 +1,102 @@
-// Filled in by Phase 3 — OTel GenAI semantic-convention mapping.
-export {};
+import type { LanguageModelUsage } from "ai";
+import { CAPTURE_CONTENT } from "./config";
+import type { Attrs } from "./otlp";
+
+// The field you group by when comparing quality across surfaces. Fixed at six
+// values — a seventh invented one silently splits a comparison.
+export const SURFACES = {
+ AGENT_CHAT: "agent.chat",
+ RESUME_REVIEW: "resume.review",
+ JOB_MATCH: "job.match",
+ COVER_LETTER: "cover.letter",
+ AUTOMATION_MATCH: "automation.match",
+ RESUME_IMPORT: "resume.import",
+} as const;
+
+export type Surface = (typeof SURFACES)[keyof typeof SURFACES];
+
+// Nested-tool labels are the runNestedGeneration argument; mapping them here
+// keeps every surface decision in one file.
+export const SURFACE_BY_NESTED_LABEL: Record<string, Surface> = {
+ review_resume: SURFACES.RESUME_REVIEW,
+ match_job: SURFACES.JOB_MATCH,
+ generate_cover_letter: SURFACES.COVER_LETTER,
+};
+
+export function genAiRequestAttrs(input: {
+ provider: string;
+ model: string;
+ temperature?: number;
+ numCtx?: number;
+ surface: Surface;
+ system?: string;
+ prompt?: unknown;
+}): Attrs {
+ const attrs: Attrs = {
+ "gen_ai.system": input.provider,
+ "gen_ai.request.model": input.model,
+ "jobsync.surface": input.surface,
+ };
+ if (input.temperature !== undefined) {
+ attrs["gen_ai.request.temperature"] = input.temperature;
+ }
+ // num_ctx is only interesting beside gen_ai.usage.input_tokens: Ollama drops
+ // the oldest context on overflow with no error and no distinct finish
+ // reason, so the pair is the only way overflow is visible at all.
+ if (input.numCtx !== undefined) {
+ attrs["jobsync.ollama.num_ctx"] = input.numCtx;
+ }
+ if (CAPTURE_CONTENT && (input.system !== undefined || input.prompt !== undefined)) {
+ attrs["gen_ai.prompt"] = { system: input.system, prompt: input.prompt };
+ }
+ return attrs;
+}
+
+export function genAiResponseAttrs(input: {
+ usage?: LanguageModelUsage;
+ finishReason?: string;
+ text?: string;
+ toolCalls?: unknown;
+}): Attrs {
+ const attrs: Attrs = {};
+ if (input.usage?.inputTokens !== undefined) {
+ attrs["gen_ai.usage.input_tokens"] = input.usage.inputTokens;
+ }
+ if (input.usage?.outputTokens !== undefined) {
+ attrs["gen_ai.usage.output_tokens"] = input.usage.outputTokens;
+ }
+ if (input.usage?.totalTokens !== undefined) {
+ attrs["gen_ai.usage.total_tokens"] = input.usage.totalTokens;
+ }
+ if (input.finishReason !== undefined) {
+ attrs["gen_ai.response.finish_reasons"] = input.finishReason;
+ }
+ if (CAPTURE_CONTENT && input.text !== undefined) {
+ attrs["gen_ai.completion"] = input.text;
+ }
+ if (CAPTURE_CONTENT && input.toolCalls !== undefined) {
+ attrs["gen_ai.response.tool_calls"] = input.toolCalls;
+ }
+ return attrs;
+}
+
+// truncated is read from the flag the call site already computes — this
+// records that the APP clipped the model input, which is a different fact
+// from otlp.ts's capped_attrs (telemetry clipped an exported attribute).
+export function inputSizeAttrs(input: {
+ resumeChars?: number;
+ jobChars?: number;
+ truncated?: boolean;
+}): Attrs {
+ const attrs: Attrs = {};
+ if (input.resumeChars !== undefined) {
+ attrs["jobsync.input.resume_chars"] = input.resumeChars;
+ }
+ if (input.jobChars !== undefined) {
+ attrs["jobsync.input.job_chars"] = input.jobChars;
+ }
+ if (input.truncated !== undefined) {
+ attrs["jobsync.input.truncated"] = input.truncated;
+ }
+ return attrs;
+}
diff --git a/src/lib/telemetry/index.ts b/src/lib/telemetry/index.ts
index bcc43c9..9664b47 100644
--- a/src/lib/telemetry/index.ts
+++ b/src/lib/telemetry/index.ts
@@ -6,4 +6,12 @@ export {
export { currentSpan, type ActiveSpan } from "./context";
export { runInSpan, startSpan, withSpan, type Span } from "./span";
export { type Attrs } from "./otlp";
+export {
+ genAiRequestAttrs,
+ genAiResponseAttrs,
+ inputSizeAttrs,
+ SURFACE_BY_NESTED_LABEL,
+ SURFACES,
+ type Surface,
+} from "./genai";
export { log, SEVERITY } from "./logger";
diff --git a/src/lib/telemetry/otlp.ts b/src/lib/telemetry/otlp.ts
index f605e4a..b9778fc 100644
--- a/src/lib/telemetry/otlp.ts
+++ b/src/lib/telemetry/otlp.ts
@@ -70,10 +70,12 @@ function nanos(ms: number): string {
function encodeValue(value: unknown): unknown {
if (typeof value === "string") return { stringValue: value };
if (typeof value === "boolean") return { boolValue: value };
+ // OpenObserve's OTLP-JSON parser rejects doubleValue in every spelling and
+ // 400s the whole batch, so a float rides as a string. Still valid OTLP.
if (typeof value === "number") {
return Number.isInteger(value)
? { intValue: String(value) }
- : { doubleValue: value };
+ : { stringValue: String(value) };
}
return { stringValue: JSON.stringify(value) };
}