Skip to content

🪢 Open source agent evals & observability: Trace, evaluate, and improve LLM applications with one open platform.

feat(topics): be transparent about content filtered topics (#19056)

Nimar5c9bc845e55f
diff --git a/packages/shared/src/server/llm/llmText.ts b/packages/shared/src/server/llm/llmText.ts
index 6894ddd216..36f4128ba6 100644
--- a/packages/shared/src/server/llm/llmText.ts
+++ b/packages/shared/src/server/llm/llmText.ts
@@ -8,6 +8,7 @@ import {
streamText,
tool,
type GenerateTextAbortEvent,
+ type GenerateTextInclude,
type GenerateTextOnAbortCallback,
type GenerateTextOnEndCallback,
type GenerateTextResult,
@@ -136,7 +137,9 @@ type BaseLLMTextOptions<TOOLS extends ToolSet, OUTPUT extends Output.Output> = {
export type GenerateLLMTextOptions<
TOOLS extends ToolSet = {},
OUTPUT extends Output.Output = Output.Output<string, string, never>,
-> = BaseLLMTextOptions<TOOLS, OUTPUT>;
+> = BaseLLMTextOptions<TOOLS, OUTPUT> & {
+ include?: GenerateTextInclude;
+};
export type StreamLLMTextOptions<
TOOLS extends ToolSet = {},
@@ -193,6 +196,7 @@ export async function generateLLMText<
model: prepared.languageModel,
...prepared.callOptions,
output: options.output,
+ include: options.include,
onEnd: options.onEnd,
}),
);
@@ -385,6 +389,7 @@ export async function embedLLMText(options: {
model: LLMModelRef;
connection: LLMConnection;
values: string[];
+ dimensions?: number;
providerOptions?: ProviderOptions;
maxRetries?: number;
maxParallelCalls?: number;
@@ -412,6 +417,7 @@ export async function embedLLMText(options: {
return embedMany({
model: embeddingModel,
values: options.values,
+ dimensions: options.dimensions,
providerOptions: options.providerOptions,
maxRetries: options.maxRetries,
maxParallelCalls: options.maxParallelCalls,
diff --git a/packages/shared/src/server/topics/embeddings.ts b/packages/shared/src/server/topics/embeddings.ts
index 16a60bde4f..e1aec587be 100644
--- a/packages/shared/src/server/topics/embeddings.ts
+++ b/packages/shared/src/server/topics/embeddings.ts
@@ -26,7 +26,8 @@ async function embedWithSizeFallback(
model: { adapter: params.model.adapter, id: params.model.model },
connection: params.model.connection,
values: params.summaries,
- providerOptions: embeddingProviderOptions(params.model, dimensions),
+ dimensions,
+ providerOptions: embeddingProviderOptions(params.model),
maxRetries: 2,
// Single-text models (Bedrock Titan, Nova) split a batch into one request per text.
maxParallelCalls: 10,
@@ -43,38 +44,27 @@ async function embedWithSizeFallback(
}
/** Keeps discovery and centroid assignment in the same clustering vector space. */
-function embeddingProviderOptions(
- model: TopicsModel,
- dimensions: number | undefined,
-): LLMProviderOptions {
+function embeddingProviderOptions(model: TopicsModel): LLMProviderOptions {
if (model.adapter === LLMAdapter.Bedrock)
- return { amazonBedrock: bedrockEmbeddingOptions(model.model, dimensions) };
+ return { amazonBedrock: bedrockEmbeddingOptions(model.model) };
const google = {
taskType: "CLUSTERING",
- ...(dimensions && { outputDimensionality: dimensions }),
};
return {
- openai: dimensions ? { dimensions } : {},
google,
vertex: google,
};
}
-/** The Bedrock SDK validates all options, so send only the model family's size field. */
-function bedrockEmbeddingOptions(
- modelId: string,
- dimensions: number | undefined,
-): Record<string, string | number> {
+function bedrockEmbeddingOptions(modelId: string): Record<string, string> {
if (modelId.includes("nova"))
return {
embeddingPurpose: "CLUSTERING",
- ...(dimensions && { embeddingDimension: dimensions }),
};
if (modelId.includes("cohere"))
return {
inputType: "clustering",
truncate: "NONE",
- ...(dimensions && { outputDimension: dimensions }),
};
- return dimensions ? { dimensions } : {};
+ return {};
}
diff --git a/packages/shared/src/server/topics/text.test.ts b/packages/shared/src/server/topics/text.test.ts
index 5eaf98b2b1..5fa85f76cb 100644
--- a/packages/shared/src/server/topics/text.test.ts
+++ b/packages/shared/src/server/topics/text.test.ts
@@ -32,6 +32,14 @@ vi.mock("../llm/secureLlmFetch", () => ({
createSecureLlmFetch: () => globalThis.fetch,
}));
+vi.mock("google-auth-library", () => ({
+ GoogleAuth: class {
+ getClient = async () => ({
+ getAccessToken: async () => ({ token: "fake-gcp-token" }),
+ });
+ },
+}));
+
vi.mock("../logger", () => ({
logger: { error: vi.fn(), warn: vi.fn(), info: vi.fn(), debug: vi.fn() },
}));
@@ -102,6 +110,90 @@ function bedrockModel(slot: TopicsModel["slot"], model: string): TopicsModel {
}
describe("generateTopicText", () => {
+ it.each([
+ ["chat", true],
+ ["responses", true],
+ ["chat", false],
+ ["bedrock-cache", true],
+ ] as const)(
+ "classifies only explicit wire refusals (%s, refused: %s)",
+ async (api, refused) => {
+ const message = {
+ role: "assistant",
+ content: null,
+ refusal: "private refusal",
+ };
+ // Application data can resemble a provider response without being a refusal.
+ const invalidOutput = JSON.stringify({ choices: [{ message }] });
+ vi.stubGlobal(
+ "fetch",
+ vi.fn(async () =>
+ Response.json(
+ api === "responses"
+ ? {
+ output: [
+ {
+ id: "msg-refusal",
+ type: "message",
+ role: "assistant",
+ content: [
+ { type: "refusal", refusal: "private refusal" },
+ ],
+ },
+ ],
+ }
+ : {
+ choices: [
+ {
+ index: 0,
+ finish_reason: "stop",
+ message: refused
+ ? message
+ : {
+ role: "assistant",
+ content: invalidOutput,
+ refusal: null,
+ },
+ },
+ ],
+ },
+ ),
+ ),
+ );
+ const error = await generateTopicText({
+ model:
+ api === "bedrock-cache"
+ ? bedrockModel("clustering", "us.openai.gpt-6-luna")
+ : {
+ slot: "clustering",
+ provider: "openai-topics",
+ adapter: LLMAdapter.OpenAI,
+ model: "gpt-6-luna",
+ connection: {
+ secretKey: encrypt("sk-test"),
+ config: { useResponsesApi: api === "responses" },
+ },
+ },
+ system: [
+ { text: "private system prompt", cache: api === "bedrock-cache" },
+ ],
+ input: "private input",
+ schema: z.object({ name: z.string() }),
+ maxOutputTokens: 256,
+ }).catch((error: unknown) => error);
+
+ expect(error).toBeInstanceOf(Error);
+ const metadata = getTopicTextResponseMetadata(error);
+ expect(metadata).toMatchObject({
+ "langfuse.topics.response.finish_reason": refused
+ ? "content-filter"
+ : "stop",
+ });
+ expect(JSON.stringify(metadata)).not.toContain("private");
+ expect(fetch).toHaveBeenCalledTimes(1);
+ },
+ );
+
it.each([
["max_tokens", "length", "", "AI_NoOutputGeneratedError"],
["refusal", "other", "", "AI_NoOutputGeneratedError"],
@@ -631,6 +723,129 @@ describe("generateTopicText", () => {
});
describe("generateTopicEmbeddings", () => {
+ it("preserves clustering and dimensions in Google batch embeddings", async () => {
+ const summaries = ["Account access", "Refund request"];
+ const embeddings = summaries.map((_, index) =>
+ Array.from({ length: 768 }, () => index + 1),
+ );
+ const fetch = vi.fn<typeof globalThis.fetch>(async () =>
+ Response.json({ embeddings: embeddings.map((values) => ({ values })) }),
+ );
+ vi.stubGlobal("fetch", fetch);
+
+ const result = await generateTopicEmbeddings({
+ model: {
+ slot: "embedding",
+ provider: "google-topics",
+ adapter: LLMAdapter.GoogleAIStudio,
+ model: "gemini-embedding-001",
+ connection: { secretKey: encrypt("google-key") },
+ },
+ summaries,
+ dimensions: 768,
+ });
+
+ expect(fetch).toHaveBeenCalledTimes(1);
+ const request = new Request(...fetch.mock.calls[0]);
+ expect(request.url).toBe(
+ "https://generativelanguage.googleapis.com/v1beta/models/gemini-embedding-001:batchEmbedContents",
+ );
+ expect(await request.json()).toEqual({
+ requests: summaries.map((text) => ({
+ model: "models/gemini-embedding-001",
+ content: { role: "user", parts: [{ text }] },
+ outputDimensionality: 768,
+ taskType: "CLUSTERING",
+ })),
+ });
+ expect(result.embeddings).toEqual(embeddings);
+ });
+
+ it("preserves clustering and dimensions in Vertex embeddings", async () => {
+ const vector = Array.from({ length: 768 }, () => 0.5);
+ const fetch = vi.fn<typeof globalThis.fetch>(async () =>
+ Response.json({
+ predictions: [
+ { embeddings: { values: vector, statistics: { token_count: 3 } } },
+ ],
+ }),
+ );
+ vi.stubGlobal("fetch", fetch);
+
+ const result = await generateTopicEmbeddings({
+ model: {
+ slot: "embedding",
+ provider: "vertex-topics",
+ adapter: LLMAdapter.VertexAI,
+ model: "text-embedding-005",
+ connection: {
+ secretKey: encrypt(
+ JSON.stringify({
+ type: "service_account",
+ project_id: "topics-project",
+ private_key_id: "fake-key-id",
+ private_key: "fake-private-key",
+ client_email: "[email protected]",
+ client_id: "123456789",
+ auth_uri: "https://accounts.google.com/o/oauth2/auth",
+ token_uri: "https://oauth2.googleapis.com/token",
+ auth_provider_x509_cert_url:
+ "https://www.googleapis.com/oauth2/v1/certs",
+ client_x509_cert_url:
+ "https://www.googleapis.com/robot/v1/metadata/x509/topics",
+ }),
+ ),
+ config: { location: "us-east5" },
+ },
+ },
+ summaries: ["Account access"],
+ dimensions: 768,
+ });
+
+ expect(fetch).toHaveBeenCalledTimes(1);
+ const request = new Request(...fetch.mock.calls[0]);
+ expect(request.url).toBe(
+ "https://us-east5-aiplatform.googleapis.com/v1beta1/projects/topics-project/locations/us-east5/publishers/google/models/text-embedding-005:predict",
+ );
+ expect(await request.json()).toEqual({
+ instances: [{ content: "Account access", task_type: "CLUSTERING" }],
+ parameters: { outputDimensionality: 768 },
+ });
+ expect(result).toEqual({ embeddings: [vector], tokens: 3 });
+ });
+
+ it("preserves clustering and dimensions in Bedrock Nova embeddings", async () => {
+ const vector = Array.from({ length: 384 }, () => 0.5);
+ const fetch = vi.fn<typeof globalThis.fetch>(async () =>
+ Response.json({
+ embeddings: [{ embeddingType: "float", embedding: vector }],
+ inputTokenCount: 3,
+ }),
+ );
+ vi.stubGlobal("fetch", fetch);
+
+ const result = await generateTopicEmbeddings({
+ model: bedrockModel(
+ "embedding",
+ "amazon.nova-2-multimodal-embeddings-v1:0",
+ ),
+ summaries: ["Account access"],
+ dimensions: 384,
+ });
+
+ expect(fetch).toHaveBeenCalledTimes(1);
+ const request = new Request(...fetch.mock.calls[0]);
+ expect(await request.json()).toEqual({
+ taskType: "SINGLE_EMBEDDING",
+ singleEmbeddingParams: {
+ embeddingPurpose: "CLUSTERING",
+ embeddingDimension: 384,
+ text: { truncationMode: "END", value: "Account access" },
+ },
+ });
+ expect(result).toEqual({ embeddings: [vector], tokens: 3 });
+ });
+
it("embeds every summary in one Cohere request on Bedrock", async () => {
const vector = Array.from({ length: 512 }, (_, index) => index + 1);
const other = vector.map((value) => -value);
@@ -698,43 +913,57 @@ describe("generateTopicEmbeddings", () => {
expect(result.embeddings[0]).toHaveLength(768);
});
- it("retries without the size option when a fixed-size model rejects it", async () => {
- const vector = Array.from({ length: 1536 }, () => 0.5);
- const fetch = vi.fn<typeof globalThis.fetch>(async (_url, init) =>
- JSON.parse(String(init?.body)).dimensions
- ? Response.json(
- {
- error: {
+ it.each(["OpenAI", "Bedrock Titan v1"])(
+ "retries without the size option when %s rejects it",
+ async (provider) => {
+ const vector = Array.from({ length: 1536 }, () => 0.5);
+ const fetch = vi.fn<typeof globalThis.fetch>(async (url, init) => {
+ const { dimensions } = (await new Request(url, init).json()) as {
+ dimensions?: number;
+ };
+ return dimensions
+ ? Response.json(
+ {
message: "This model does not support specifying dimensions.",
+ error: {
+ message: "This model does not support specifying dimensions.",
+ },
},
- },
- { status: 400 },
- )
- : Response.json({
- data: [{ embedding: vector, index: 0 }],
- usage: { prompt_tokens: 3 },
- }),
- );
- vi.stubGlobal("fetch", fetch);
+ { status: 400 },
+ )
+ : Response.json(
+ provider === "OpenAI"
+ ? {
+ data: [{ embedding: vector, index: 0 }],
+ usage: { prompt_tokens: 3 },
+ }
+ : { embedding: vector, inputTextTokenCount: 3 },
+ );
+ });
+ vi.stubGlobal("fetch", fetch);
- const result = await generateTopicEmbeddings({
- model: {
- slot: "embedding",
- provider: "openai-topics",
- adapter: LLMAdapter.OpenAI,
- model: "text-embedding-ada-002",
- connection: { secretKey: encrypt("sk-test") },
- },
- summaries: ["Account access"],
- dimensions: 1536,
- });
+ const result = await generateTopicEmbeddings({
+ model:
+ provider === "Bedrock Titan v1"
+ ? bedrockModel("embedding", "amazon.titan-embed-text-v1")
+ : {
+ slot: "embedding",
+ provider: "openai-topics",
+ adapter: LLMAdapter.OpenAI,
+ model: "text-embedding-ada-002",
+ connection: { secretKey: encrypt("sk-test") },
+ },
+ summaries: ["Account access"],
+ dimensions: 1536,
+ });
- expect(fetch).toHaveBeenCalledTimes(2);
- expect(await new Request(...fetch.mock.calls[1]).json()).not.toHaveProperty(
- "dimensions",
- );
- expect(result.embeddings[0]).toHaveLength(1536);
- });
+ expect(fetch).toHaveBeenCalledTimes(2);
+ expect(
+ await new Request(...fetch.mock.calls[1]).json(),
+ ).not.toHaveProperty("dimensions");
+ expect(result.embeddings[0]).toHaveLength(1536);
+ },
+ );
it("falls back when a rate-limit retry precedes the size rejection", async () => {
const vector = Array.from({ length: 1536 }, () => 0.5);
diff --git a/packages/shared/src/server/topics/text.ts b/packages/shared/src/server/topics/text.ts
index 72070b41d1..4ea9e670f3 100644
--- a/packages/shared/src/server/topics/text.ts
+++ b/packages/shared/src/server/topics/text.ts
@@ -1,8 +1,10 @@
import { Sha256 } from "@aws-crypto/sha256-js";
import { SignatureV4 } from "@smithy/signature-v4";
import {
+ APICallError,
NoObjectGeneratedError,
Output,
+ TypeValidationError,
type LanguageModelUsage,
type StepResult,
type ToolSet,
@@ -15,6 +17,7 @@ import {
canUseBedrockDefaultCredentials,
resolveBedrockProviderAuth,
} from "../llm/ai-sdk/providers/bedrock";
+import { isPlainObject } from "../llm/ai-sdk/providers/utils";
import { generateLLMText } from "../llm/llmText";
import { LLMAdapter, type TraceSinkParams } from "../llm/types";
import { logger } from "../logger";
@@ -81,6 +84,17 @@ export async function generateTopicText<T>(
return result;
} catch (error) {
failure = error;
+ // Responses refusal blocks can fail SDK validation before onEnd runs.
+ if (
+ APICallError.isInstance(error) &&
+ error.statusCode === 200 &&
+ TypeValidationError.isInstance(error.cause) &&
+ hasOpenAIRefusal(error.cause.value)
+ ) {
+ responseMetadata = {
+ "langfuse.topics.response.finish_reason": "content-filter",
+ };
+ }
if (responseMetadata && error !== null && typeof error === "object") {
responseMetadataByError.set(error, responseMetadata);
}
@@ -234,6 +248,8 @@ async function generateWithConnection<T>(
// The AI SDK retries 429 and 5xx responses with exponential backoff.
maxRetries: 2,
timeout: params.timeoutMs ?? TIMEOUT_MS,
+ // Retain wire refusal markers in memory; diagnostics only expose their classification.
+ include: { responseBody: true },
// onEnd runs before structured-output parsing and the output getter can throw.
onEnd: ({ finalStep }) => {
const text = finalStep.text;
@@ -256,7 +272,11 @@ function responseAttributes(
maxOutputTokens: number,
): TopicTextResponseMetadata {
return {
- "langfuse.topics.response.finish_reason": step.finishReason,
+ "langfuse.topics.response.finish_reason": hasOpenAIRefusal(
+ step.response.body,
+ )
+ ? "content-filter"
+ : step.finishReason,
"langfuse.topics.response.raw_finish_reason": RAW_FINISH_REASONS.has(
step.rawFinishReason ?? "",
)
@@ -276,6 +296,32 @@ function responseAttributes(
};
}
+/** Inspect wire markers only; generated text and exception messages are not signals. */
+function hasOpenAIRefusal(body: unknown): boolean {
+ if (!isPlainObject(body)) return false;
+ const choice = Array.isArray(body.choices) ? body.choices[0] : undefined;
+ const message = isPlainObject(choice) ? choice.message : undefined;
+ if (
+ isPlainObject(message) &&
+ typeof message.refusal === "string" &&
+ message.refusal.length > 0
+ )
+ return true;
+ return (
+ Array.isArray(body.output) &&
+ body.output.some(
+ (item: unknown) =>
+ isPlainObject(item) &&
+ item.type === "message" &&
+ item.role === "assistant" &&
+ Array.isArray(item.content) &&
+ item.content.some(
+ (part: unknown) => isPlainObject(part) && part.type === "refusal",
+ ),
+ )
+ );
+}
+
function topicReasoning(model: TopicsModel): "none" | "minimal" | undefined {
if (isFirstPartyOpenAI(model)) return openAIReasoning(model.model);
/** Compatible endpoints choose their own supported reasoning settings. */
@@ -394,7 +440,10 @@ async function bedrockRequestHeaders(
async function invokeWithCache(
params: TopicTextParams<unknown>,
- recordResponse: (result: TopicTextResult) => void,
+ recordResponse: (
+ result: TopicTextResult,
+ metadata?: TopicTextResponseMetadata,
+ ) => void,
): Promise<TopicTextResult> {
const { region } = BedrockConfigSchema.parse(params.model.connection.config);
assertValidBedrockRegion(region);
@@ -466,7 +515,12 @@ async function invokeWithCache(
},
};
// Retain paid usage and the original response if parsing or validation fails.
- recordResponse(result);
+ recordResponse(
+ result,
+ hasOpenAIRefusal(json)
+ ? { "langfuse.topics.response.finish_reason": "content-filter" }
+ : undefined,
+ );
if (!message?.content || json.choices?.[0]?.finish_reason === "length")
throw Object.assign(
diff --git a/web/src/features/topics/TopicsPage.tsx b/web/src/features/topics/TopicsPage.tsx
index 01b652eda1..df6ac58436 100644
--- a/web/src/features/topics/TopicsPage.tsx
+++ b/web/src/features/topics/TopicsPage.tsx
@@ -73,7 +73,7 @@ const executionLabels: Record<TopicExecutionStatus, string> = {
queued: "Run queued",
running: "Run in progress",
completed: "Run complete",
- completed_with_errors: "Run finished with errors",
+ completed_with_errors: "Run finished with issues",
failed: "Run failed",
};
const executionPhaseLabels: Record<string, string> = {
@@ -850,7 +850,14 @@ function ExecutionPanel({
configuration.
</p>
)}
- {progress.error && <ErrorMessage message={progress.error} />}
+ {progress.error &&
+ (progress.outcome === "published" ? (
+ <Alert variant="warning">
+ <Alert.Description>{progress.error}</Alert.Description>
+ </Alert>
+ ) : (
+ <ErrorMessage message={progress.error} />
+ ))}
{progress.outcome === "insufficient_data" &&
execution.input.operation === "update" && (
<p className="text-sm">
diff --git a/worker/src/features/topics/README.md b/worker/src/features/topics/README.md
index 7e5460b67f..58447d05d7 100644
--- a/worker/src/features/topics/README.md
+++ b/worker/src/features/topics/README.md
@@ -158,6 +158,10 @@ resume. Old execution history remains readable.
After changing the summary model, start a new **Process traces** execution;
stored-summary reuse cannot reuse results from a different summary model.
Existing topic names remain until their definitions change during **Update topics**.
+If a provider's content filter blocks naming, the cluster is published with an
+unnamed placeholder and a warning; its assignments are preserved and other groups
+and facets continue. **Update topics** retries placeholder names. Other naming
+failures still interrupt the update.
## Trace-batch connection
diff --git a/worker/src/features/topics/models.test.ts b/worker/src/features/topics/models.test.ts
index 48010d3e24..2bc34bf972 100644
--- a/worker/src/features/topics/models.test.ts
+++ b/worker/src/features/topics/models.test.ts
@@ -319,105 +319,115 @@ describe("Topics naming boundary", () => {
expect(state.call).not.toHaveBeenCalled();
});
- it("excludes provider content from failure logs and spans, including echoed error fields", async () => {
- // The AI SDK identifies an APICallError by these markers.
- const rejection = Object.assign(
- new Error("Invalid input: secret transcript"),
- {
- [Symbol.for("vercel.ai.error")]: true,
- [Symbol.for("vercel.ai.error.AI_APICallError")]: true,
- name: "AI_APICallError",
- statusCode: 400,
- isRetryable: false,
- requestBodyValues: { messages: "secret transcript" },
- responseBody: '{"error":{"message":"secret echo"}}',
- data: {
- error: {
- type: "secret error type",
- code: "secret error code",
- param: "secret input value",
+ it.each([
+ ["secret error code", "invalid_input"],
+ ["content_filter", "content_filter"],
+ ])(
+ "classifies HTTP 400 naming errors with code %s without logging provider content",
+ async (code, reason) => {
+ // The AI SDK identifies an APICallError by these markers.
+ const rejection = Object.assign(
+ new Error("Invalid input: secret transcript"),
+ {
+ [Symbol.for("vercel.ai.error")]: true,
+ [Symbol.for("vercel.ai.error.AI_APICallError")]: true,
+ name: "AI_APICallError",
+ statusCode: 400,
+ isRetryable: false,
+ requestBodyValues: { messages: "secret transcript" },
+ responseBody: '{"error":{"message":"secret echo"}}',
+ data: {
+ error: {
+ type: "secret error type",
+ code,
+ param: "secret input value",
+ },
},
},
- },
- );
- state.call.mockRejectedValue(rejection);
- await expect(
- summarizeOne(
- topicsModels(),
- "Trace evidence.",
- topicProcessingConfigSchema.parse({
- summaryModel: "us.openai.gpt-5.6-luna",
- }),
- ),
- ).rejects.toMatchObject({ reason: "invalid_input" });
- const [message, fields] = vi.mocked(logger.warn).mock.calls.at(-1)!;
- expect(message).toBe("Topics model request failed");
- expect(fields).toMatchObject({
- "http.status_code": 400,
- });
- expect(JSON.stringify(fields)).not.toMatch(/secret/);
- expect(JSON.stringify(state.spanAttributes.mock.calls)).not.toMatch(
- /secret/,
- );
- expect(state.increment).toHaveBeenCalledWith(
- "langfuse.topics.llm_calls",
- 1,
- {
- stage: "summary",
- adapter: LLMAdapter.Bedrock,
- status: "400",
- },
- );
- });
+ );
+ state.call.mockRejectedValue(rejection);
+ await expect(
+ nameTopicGroup(topicsModels(), evidence),
+ ).rejects.toMatchObject({ reason });
+ const [message, fields] = vi.mocked(logger.warn).mock.calls.at(-1)!;
+ expect(message).toBe("Topics model request failed");
+ expect(fields).toMatchObject({
+ "http.status_code": 400,
+ });
+ expect(JSON.stringify(fields)).not.toMatch(/secret/);
+ expect(JSON.stringify(state.spanAttributes.mock.calls)).not.toMatch(
+ /secret/,
+ );
+ expect(state.increment).toHaveBeenCalledWith(
+ "langfuse.topics.llm_calls",
+ 1,
+ {
+ stage: "naming",
+ adapter: LLMAdapter.Bedrock,
+ status: "400",
+ },
+ );
+ },
+ );
- it("reports unusable naming output without logging provider content", async () => {
- const rejection = Object.assign(new Error("secret response text"), {
- name: "AI_NoOutputGeneratedError",
- responseBody: "secret response body",
- text: "secret model output",
- });
- const response = {
- "langfuse.topics.response.finish_reason": "other",
- "langfuse.topics.response.raw_finish_reason": "refusal",
- "langfuse.topics.response.text_characters": 0,
- "langfuse.topics.response.output_tokens": 0,
- };
- state.responseMetadata.mockImplementation((error) =>
- error === rejection ? response : undefined,
- );
- state.call.mockRejectedValue(rejection);
+ it.each([
+ ["other", "refusal", "invalid_output"],
+ ["content-filter", "content_filtered", "content_filter"],
+ ])(
+ "reports %s naming output without logging provider content",
+ async (finishReason, rawFinishReason, reason) => {
+ const rejection = Object.assign(new Error("secret response text"), {
+ name: "AI_NoOutputGeneratedError",
+ responseBody: "secret response body",
+ text: "secret model output",
+ });
+ const response = {
+ "langfuse.topics.response.finish_reason": finishReason,
+ "langfuse.topics.response.raw_finish_reason": rawFinishReason,
+ "langfuse.topics.response.text_characters": 0,
+ "langfuse.topics.response.output_tokens": 0,
+ };
+ state.responseMetadata.mockImplementation((error) =>
+ error === rejection ? response : undefined,
+ );
+ state.call.mockRejectedValue(rejection);
- const failure = await nameTopicGroup(topicsModels(), evidence).catch(
- (error: unknown) => error,
- );
- expect(failure).toMatchObject({
- reason: "invalid_output",
- message: expect.stringContaining("returned no usable structured output"),
- });
- expect((failure as Error).message).not.toMatch(/credentials|secret/);
- expect(logger.warn).toHaveBeenCalledOnce();
- const [message, fields] = vi.mocked(logger.warn).mock.calls[0];
- expect(message).toBe("Topics model request failed");
- expect(fields).toMatchObject({
- ...response,
- "langfuse.topics.error.reason": "invalid_output",
- "langfuse.topics.error.type": "AI_NoOutputGeneratedError",
- });
- expect(state.spanAttributes).toHaveBeenCalledWith(fields);
- expect(JSON.stringify(fields)).not.toMatch(/secret/);
- expect(JSON.stringify(state.spanAttributes.mock.calls)).not.toMatch(
- /secret/,
- );
- expect(state.increment).toHaveBeenCalledWith(
- "langfuse.topics.llm_calls",
- 1,
- {
- stage: "naming",
- adapter: LLMAdapter.Bedrock,
- status: "invalid_output",
- },
- );
- });
+ const failure = await nameTopicGroup(topicsModels(), evidence).catch(
+ (error: unknown) => error,
+ );
+ expect(failure).toMatchObject({
+ reason,
+ message: expect.stringMatching(
+ reason === "content_filter"
+ ? /filter/i
+ : /returned no usable structured output/,
+ ),
+ });
+ expect((failure as Error).message).not.toMatch(/credentials|secret/);
+ expect(logger.warn).toHaveBeenCalledOnce();
+ const [message, fields] = vi.mocked(logger.warn).mock.calls[0];
+ expect(message).toBe("Topics model request failed");
+ expect(fields).toMatchObject({
+ ...response,
+ "langfuse.topics.error.reason": reason,
+ "langfuse.topics.error.type": "AI_NoOutputGeneratedError",
+ });
+ expect(state.spanAttributes).toHaveBeenCalledWith(fields);
+ expect(JSON.stringify(fields)).not.toMatch(/secret/);
+ expect(JSON.stringify(state.spanAttributes.mock.calls)).not.toMatch(
+ /secret/,
+ );
+ expect(state.increment).toHaveBeenCalledWith(
+ "langfuse.topics.llm_calls",
+ 1,
+ {
+ stage: "naming",
+ adapter: LLMAdapter.Bedrock,
+ status: reason,
+ },
+ );
+ },
+ );
it.each([
[{}, "ok"],
diff --git a/worker/src/features/topics/processTopicsExecution.test.ts b/worker/src/features/topics/processTopicsExecution.test.ts
index 8522956a2f..963aa38165 100644
--- a/worker/src/features/topics/processTopicsExecution.test.ts
+++ b/worker/src/features/topics/processTopicsExecution.test.ts
@@ -1104,17 +1104,104 @@ describe("Topics execution", () => {
expect(state.name).not.toHaveBeenCalled();
});
- it("fails only the trace whose model output is unusable", async () => {
- state.summarize.mockRejectedValueOnce(
- new TopicsProviderUnavailable("No object generated.", "invalid_output"),
+ it.each(["invalid_output", "content_filter"] as const)(
+ "fails only the trace whose model output is %s",
+ async (reason) => {
+ state.summarize.mockRejectedValueOnce(
+ new TopicsProviderUnavailable("No object generated.", reason),
+ );
+ await processSelection("invalid-output", 3);
+ expect(state.executions.get("invalid-output")?.status).toBe(
+ "completed_with_errors",
+ );
+ expect(
+ state.executions.get("invalid-output")?.facets[0].counts,
+ ).toMatchObject({ complete: 2, failed: 1 });
+ },
+ );
+
+ it("publishes filtered naming groups and later retries their labels without changing membership", async () => {
+ const facets = [facet, { ...facet, facetId: "sibling" }];
+ state.executions.set("source", execution("source", 100, "process", facets));
+ await processTopicsExecution({
+ projectId: "project",
+ executionId: "source",
+ });
+ state.name.mockRejectedValueOnce(
+ new TopicsProviderUnavailable(
+ "The model filtered this response.",
+ "content_filter",
+ ),
);
- await processSelection("invalid-output", 3);
- expect(state.executions.get("invalid-output")?.status).toBe(
- "completed_with_errors",
+ state.executions.set(
+ "filtered",
+ execution("filtered", 0, "update", facets),
);
- expect(
- state.executions.get("invalid-output")?.facets[0].counts,
- ).toMatchObject({ complete: 2, failed: 1 });
+
+ await processTopicsExecution({
+ projectId: "project",
+ executionId: "filtered",
+ });
+
+ const completed = state.executions.get("filtered")!;
+ expect(completed).toMatchObject({
+ status: "completed_with_errors",
+ facets: [
+ {
+ outcome: "published",
+ error: expect.any(String),
+ counts: { assigned: 100, outlier: 0, failed: 0 },
+ },
+ {
+ outcome: "published",
+ error: null,
+ counts: { assigned: 100, outlier: 0, failed: 0 },
+ },
+ ],
+ });
+ expect(state.name).toHaveBeenCalledTimes(4);
+ const published = state.runs.get(completed.facets[0].runId!)!;
+ expect(published.status).toBe("completed");
+ expect(published.topics).toHaveLength(2);
+ const placeholder = published.topics.find(
+ (topic) => topic.metadata.namingFailure === "content_filter",
+ )!;
+ const named = published.topics.find((topic) => topic !== placeholder)!;
+ expect(placeholder).toMatchObject({
+ name: expect.any(String),
+ description: expect.stringMatching(/filter/i),
+ });
+ expect(placeholder.name).not.toBe(named.name);
+ // Definition readback must match after metadata passes through JSON storage.
+ expect(JSON.parse(JSON.stringify(placeholder))).toStrictEqual(placeholder);
+ const assignments = [...state.assignments.values()].filter(
+ (row) => row.runId === published.id,
+ );
+ expect(assignments).toHaveLength(100);
+ for (const topic of published.topics)
+ expect(
+ assignments.filter((row) => row.topicId === topic.topicId),
+ ).toHaveLength(50);
+
+ state.name.mockClear();
+ await updateSelection("retry-label");
+
+ expect(state.name).toHaveBeenCalledOnce();
+ const retried = [...state.runs.values()].at(-1)!;
+ expect(state.executions.get("retry-label")?.status).toBe("completed");
+ expect(retried.topics).toContainEqual(named);
+ const relabeled = retried.topics.find(
+ (topic) => topic.topicId === placeholder.topicId,
+ )!;
+ expect(relabeled.metadata.namingFailure).toBeUndefined();
+ expect(relabeled.topicVersionId).not.toBe(placeholder.topicVersionId);
+ expect(relabeled.centroid).toEqual(placeholder.centroid);
+ expect(relabeled.radius).toBe(placeholder.radius);
+ const membership = (runId: string) =>
+ [...state.assignments.values()]
+ .filter((row) => row.runId === runId)
+ .map(({ traceId, topicId }) => ({ traceId, topicId }));
+ expect(membership(retried.id)).toEqual(membership(published.id));
});
it.each(["summary call", "reuse lookup"])(
@@ -1157,7 +1244,9 @@ describe("Topics execution", () => {
const naming = state.name.getMockImplementation()!;
state.name
.mockImplementationOnce(naming)
- .mockRejectedValueOnce(new Error("Naming unavailable"));
+ .mockRejectedValueOnce(
+ new TopicsProviderUnavailable("Naming unavailable", "invalid_output"),
+ );
await updateSelection("retry");
const failed = [...state.runs.values()].at(-1)!;
expect(failed.status).toBe("failed");
diff --git a/worker/src/features/topics/processTopicsExecution.ts b/worker/src/features/topics/processTopicsExecution.ts
index 18739545ab..185e6d61a0 100644
--- a/worker/src/features/topics/processTopicsExecution.ts
+++ b/worker/src/features/topics/processTopicsExecution.ts
@@ -96,7 +96,9 @@ const isExecutionFailure = (error: unknown) =>
// Like trace-batch, a rejected input or unusable output fails only that trace.
const isTraceModelFailure = (error: unknown) =>
error instanceof TopicsProviderUnavailable &&
- (error.reason === "invalid_output" || error.reason === "invalid_input");
+ (error.reason === "invalid_output" ||
+ error.reason === "invalid_input" ||
+ error.reason === "content_filter");
async function saveProgress(
metrics: TopicMetrics,
@@ -698,7 +700,12 @@ async function clusterFacet(
const old = previous?.topics.find(
(topic) => topic.topicId === candidate.topicId,
);
- if (compatiblePrevious && old && sameTopicGeometry(old, candidate)) {
+ if (
+ compatiblePrevious &&
+ old &&
+ !old.metadata.namingFailure &&
+ sameTopicGeometry(old, candidate)
+ ) {
reused.set(old.topicVersionId, old);
return {
...candidate,
@@ -790,7 +797,14 @@ async function clusterFacet(
};
});
},
- );
+ ).catch((error: unknown) => {
+ if (
+ error instanceof TopicsProviderUnavailable &&
+ error.reason === "content_filter"
+ )
+ return null;
+ throw error;
+ });
const candidate = candidates.find(
(topic) => topic.topicVersionId === group.id,
)!;
@@ -800,18 +814,23 @@ async function clusterFacet(
createdByRunId: run.id,
createdAt: run.createdAt,
tags: [],
- name: label.name,
- description: label.description,
- representativeSummaries: label.representativeSummaries,
+ name: label?.name ?? `Unnamed topic ${topics.length + 1}`,
+ description:
+ label?.description ??
+ "The model's content filter prevented naming this topic. Its traces and assignments were preserved.",
+ representativeSummaries: label?.representativeSummaries ?? [],
metadata: {
...candidate.metadata,
effectiveMemberCount: group.count,
- selectedMemberCount: label.selectedMemberCount,
- namingSampled: label.namingSampled,
+ ...(label && {
+ selectedMemberCount: label.selectedMemberCount,
+ namingSampled: label.namingSampled,
+ }),
namingModel: models.clustering.model,
+ ...(!label && { namingFailure: "content_filter" }),
},
});
- metrics.result("naming", "generated");
+ if (label) metrics.result("naming", "generated");
}
run = await saveTopicRun({ ...run, topics });
// Readback returns the persisted classifier precision before creating any memberships.
@@ -824,12 +843,19 @@ async function clusterFacet(
run,
coordinates,
);
+ const unnamed = run.topics.filter(
+ (topic) => topic.metadata.namingFailure === "content_filter",
+ ).length;
run = await saveTopicRun({
...run,
status: "completed",
+ error: unnamed
+ ? `The model's content filter prevented naming ${unnamed} topic${unnamed === 1 ? "" : "s"}. Traces and assignments were preserved. Choose another clustering model, then run Update topics to retry naming.`
+ : null,
finishedAt: new Date().toISOString(),
});
progress.outcome = "published";
+ progress.error = run.error;
} catch (error) {
await saveTopicRun({
...run,
@@ -1227,6 +1253,7 @@ async function updateTopics(
"Clustering run does not match this facet version.",
);
if (accepted?.status === "completed") {
+ progress.error = accepted.error;
const assignments = await readTopicMapAssignments(
execution.projectId,
{ facetId: facet.facetId, version: facet.version },
@@ -1466,7 +1493,10 @@ export async function processTopicsExecution({
await updateTopics(metrics, models, execution as UpdateExecution);
}
execution.status = execution.facets.some(
- (facet) => facet.outcome === "failed" || facet.counts.failed > 0,
+ (facet) =>
+ facet.outcome === "failed" ||
+ facet.counts.failed > 0 ||
+ facet.error !== null,
)
? "completed_with_errors"
: "completed";
diff --git a/worker/src/features/topics/provider-error.ts b/worker/src/features/topics/provider-error.ts
index 04f373b12a..5b247bf301 100644
--- a/worker/src/features/topics/provider-error.ts
+++ b/worker/src/features/topics/provider-error.ts
@@ -3,8 +3,10 @@ import {
type TopicsModelSlotName,
} from "@langfuse/shared/topics";
import { EvaluatorBlockReason } from "@prisma/client";
+import { z } from "zod";
import { getLLMErrorInfo, logger } from "@langfuse/shared/src/server";
import {
+ getTopicTextResponseMetadata,
pauseTopicsModels,
type TopicsModel,
} from "@langfuse/shared/topics/server";
@@ -16,6 +18,7 @@ type TopicsProviderErrorReason =
| "rate_limit"
| "timeout"
| "invalid_output"
+ | "content_filter"
| "invalid_input"
| "provider_error";
@@ -76,6 +79,20 @@ export function topicProviderError(
current = record.cause;
}
const subject = `The ${TOPICS_MODEL_SLOT_DETAILS[model.slot].label.toLowerCase()} model ${model.model} on LLM connection "${model.provider}"`;
+ if (
+ contentFilterErrorSchema.safeParse(
+ getLLMErrorInfo(error)?.providerError?.data,
+ ).success ||
+ getTopicTextResponseMetadata(error)?.[
+ "langfuse.topics.response.finish_reason"
+ ] === "content-filter"
+ )
+ return new TopicsProviderUnavailable(
+ `${subject} declined the request because of its content filter. You can retry or choose another model.`,
+ "content_filter",
+ model.slot,
+ providerErrorDetails(error, status),
+ );
const failed = `${subject} failed${status ? ` (HTTP ${status})` : ""}.`;
// The message names the actual failure; a generic credentials hint misleads for output or rate-limit errors.
const message = {
@@ -95,6 +112,10 @@ export function topicProviderError(
);
}
+const contentFilterErrorSchema = z.object({
+ error: z.object({ code: z.literal("content_filter") }),
+});
+
/** Provider error strings can echo request/response content; retain only status. */
function providerErrorDetails(
error: unknown,