Skip to content

🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

🐛 fix(goal): retry empty goal plan drafts before failing (#22094)

Rdmclin2e8fb953cc3ee
diff --git a/apps/server/src/services/goal/criteriaGenerator.test.ts b/apps/server/src/services/goal/criteriaGenerator.test.ts
index f68fc84ba27..f56a4ca68fb 100644
--- a/apps/server/src/services/goal/criteriaGenerator.test.ts
+++ b/apps/server/src/services/goal/criteriaGenerator.test.ts
@@ -80,7 +80,7 @@ describe('GoalCriteriaGeneratorService', () => {
);
});
- it('rejects criteria containing evidence values outside the supported enums', async () => {
+ it('drops evidence values outside the supported enums but keeps the criterion', async () => {
generateObject.mockResolvedValue({
criteria: [
{
@@ -101,7 +101,63 @@ describe('GoalCriteriaGeneratorService', () => {
await expect(
new GoalCriteriaGeneratorService({} as any, 'user-1').generate({ goal: 'Ship it' }),
- ).resolves.toEqual([]);
+ ).resolves.toEqual([
+ {
+ description: 'The release is visible',
+ instruction: 'Inspect the release.',
+ onFail: 'auto_repair',
+ required: true,
+ requiredEvidence: [],
+ title: 'Release shipped',
+ verifierType: 'agent',
+ },
+ ]);
+ expect(generateObject).toHaveBeenCalledTimes(1);
+ });
+
+ it('maps modality-style evidence types from an image goal instead of failing the draft', async () => {
+ // Shape the real goal model returned for a goal whose content is only an image.
+ generateObject.mockResolvedValue({
+ criteria: [
+ {
+ requiredEvidence: [
+ { hint: 'Design mockup', modality: 'image', scope: 'task_artifacts', type: 'image' },
+ { hint: 'Spec notes', scope: 'deliverable', type: 'document' },
+ { hint: 'Page DOM', modality: 'structured', type: 'dom_snapshot' },
+ ],
+ title: 'Page matches the mockup',
+ verifierType: 'agent',
+ },
+ ],
+ instruction: 'Build the landing page shown in the mockup.',
+ title: 'Landing page from mockup',
+ });
+
+ await expect(
+ new GoalCriteriaGeneratorService({} as any, 'user-1').generatePlan({
+ goal: '![aquafit-landing-mockup.png](https://example.com/mockup.png)',
+ }),
+ ).resolves.toEqual({
+ criteria: [
+ {
+ requiredEvidence: [
+ {
+ hint: 'Design mockup',
+ modality: 'image',
+ scope: 'task_artifacts',
+ type: 'screenshot',
+ },
+ { hint: 'Spec notes', modality: 'document', scope: 'deliverable', type: 'markdown' },
+ { hint: 'Page DOM', modality: 'structured', type: 'dom_snapshot' },
+ ],
+ title: 'Page matches the mockup',
+ verifierType: 'agent',
+ },
+ ],
+ instruction: 'Build the landing page shown in the mockup.',
+ title: 'Landing page from mockup',
+ });
+ expect(generateObject).toHaveBeenCalledTimes(1);
});
it('keeps the array response for existing callers while exposing the full generated plan', async () => {
@@ -122,6 +178,31 @@ describe('GoalCriteriaGeneratorService', () => {
});
});
+ it('asks again when the model returns an empty structured output', async () => {
+ const plan = {
+ criteria: [{ title: 'Brief is delivered', verifierType: 'agent' }],
+ instruction: 'Write the daily AI news brief, following the attached layout.',
+ title: 'Daily AI news brief',
+ };
+ generateObject.mockResolvedValueOnce({}).mockResolvedValueOnce(plan);
+
+ await expect(
+ new GoalCriteriaGeneratorService({} as any, 'user-1').generatePlan({
+ goal: 'Write the daily AI news brief\n\n![image.png](https://example.com/layout.png)',
+ }),
+ ).resolves.toEqual(plan);
+ expect(generateObject).toHaveBeenCalledTimes(2);
+ });
+
+ it('gives up after a bounded number of empty structured outputs', async () => {
+ generateObject.mockResolvedValue({});
+
+ await expect(
+ new GoalCriteriaGeneratorService({} as any, 'user-1').generatePlan({ goal: 'Ship it' }),
+ ).resolves.toBeUndefined();
+ expect(generateObject).toHaveBeenCalledTimes(3);
+ });
+
it("plans a goal's decomposition on the goal's own planning model", async () => {
const goalConfig = { model: 'gemini-3.8-flash', provider: 'google' };
generateObject.mockResolvedValueOnce({ problemStatement: 'p', tasks: [] });
diff --git a/apps/server/src/services/goal/criteriaGenerator.ts b/apps/server/src/services/goal/criteriaGenerator.ts
index 8edc7af1b10..5a6630c6b5f 100644
--- a/apps/server/src/services/goal/criteriaGenerator.ts
+++ b/apps/server/src/services/goal/criteriaGenerator.ts
@@ -27,6 +27,68 @@ import { resolveGoalModelConfig } from './modelConfig';
const log = debug('lobe-server:goal-criteria-generator');
const DEFAULT_MAX_CRITERIA = 4;
+/**
+ * Structured output occasionally comes back empty (e.g. a `{}` tool input) even
+ * though the same prompt succeeds on the next call. Ask again a bounded number
+ * of times before telling the user the draft failed.
+ */
+const GOAL_PLAN_MAX_ATTEMPTS = 3;
+
+type EvidenceType = (typeof VERIFY_EVIDENCE_TYPES)[number];
+
+/**
+ * Models often put a modality (`image`, `document`, …) where the evidence type
+ * belongs — most of all when the goal itself contains an image. One such tag
+ * used to reject the whole draft, so translate it to the closest evidence type.
+ */
+const EVIDENCE_TYPE_BY_MODALITY: Record<(typeof VERIFY_EVIDENCE_MODALITIES)[number], EvidenceType> =
+ {
+ audio: 'audio',
+ document: 'markdown',
+ image: 'screenshot',
+ structured: 'text',
+ text: 'text',
+ video: 'video',
+ };
+
+const pickEnum = <T extends string>(values: readonly T[], value: unknown): T | undefined =>
+ values.includes(value as T) ? (value as T) : undefined;
+
+/**
+ * Keep a drafted evidence requirement usable instead of failing the plan:
+ * map modality-style types, drop invalid optional tags, and drop an entry whose
+ * type cannot be recognised at all. The criterion itself is kept either way.
+ */
+const normalizeEvidenceItem = (item: unknown) => {
+ if (!item || typeof item !== 'object') return undefined;
+ const { hint, modality, scope, type } = item as Record<string, unknown>;
+ const modalityFromType = pickEnum(VERIFY_EVIDENCE_MODALITIES, type);
+ const evidenceType =
+ pickEnum(VERIFY_EVIDENCE_TYPES, type) ??
+ (modalityFromType ? EVIDENCE_TYPE_BY_MODALITY[modalityFromType] : undefined);
+ if (!evidenceType) return undefined;
+
+ return {
+ hint: typeof hint === 'string' ? hint : undefined,
+ modality: pickEnum(VERIFY_EVIDENCE_MODALITIES, modality) ?? modalityFromType,
+ scope: pickEnum(VERIFY_EVIDENCE_SCOPES, scope),
+ type: evidenceType,
+ };
+};
+
+const requiredEvidenceSchema = z.preprocess(
+ (value) => (Array.isArray(value) ? value.map(normalizeEvidenceItem).filter(Boolean) : value),
+ z
+ .array(
+ z.object({
+ hint: z.string().optional(),
+ modality: z.enum(VERIFY_EVIDENCE_MODALITIES).optional(),
+ scope: z.enum(VERIFY_EVIDENCE_SCOPES).optional(),
+ type: z.enum(VERIFY_EVIDENCE_TYPES),
+ }),
+ )
+ .optional(),
+);
const generatedCriteriaSchema = z.object({
criteria: z.array(
@@ -34,16 +96,7 @@ const generatedCriteriaSchema = z.object({
description: z.string().optional(),
instruction: z.string().optional(),
onFail: z.enum(VERIFY_ON_FAIL_ACTIONS).optional(),
- requiredEvidence: z
- .array(
- z.object({
- hint: z.string().optional(),
- modality: z.enum(VERIFY_EVIDENCE_MODALITIES).optional(),
- scope: z.enum(VERIFY_EVIDENCE_SCOPES).optional(),
- type: z.enum(VERIFY_EVIDENCE_TYPES),
- }),
- )
- .optional(),
+ requiredEvidence: requiredEvidenceSchema,
required: z.boolean().optional(),
title: z.string(),
verifierType: z.enum(VERIFY_VERIFIER_TYPES),
@@ -156,34 +209,46 @@ export class GoalCriteriaGeneratorService {
const maxCriteria = params.maxCriteria ?? DEFAULT_MAX_CRITERIA;
const modelConfig = await resolveGoalModelConfig(this.db, this.userId);
const ai = new AiGenerationService(this.db, this.userId, this.workspaceId);
- const raw = await ai.generateObject(
- {
- ...chainGoalCriteriaDraft({ ...params, maxCriteria }),
- ...modelConfig,
- schema: GOAL_CRITERIA_DRAFT_JSON_SCHEMA,
- thinking: { type: 'disabled' },
- },
- {
- metadata: { trigger: RequestTrigger.Goal },
- tracing: {
- promptVersion: GOAL_CRITERIA_DRAFT_PROMPT_VERSION,
- scenario: TRACING_SCENARIOS.GoalCriteriaGen,
- schemaName: GOAL_CRITERIA_DRAFT_JSON_SCHEMA.name,
- } satisfies TracingOptions,
- },
- );
- const parsed = generatedCriteriaSchema.safeParse(raw);
- if (!parsed.success) {
- log('goal criteria draft did not match schema: %O', parsed.error.flatten());
- return undefined;
+ let plan: z.infer<typeof generatedCriteriaSchema> | undefined;
+ for (let attempt = 1; !plan && attempt <= GOAL_PLAN_MAX_ATTEMPTS; attempt++) {
+ const raw = await ai.generateObject(
+ {
+ ...chainGoalCriteriaDraft({ ...params, maxCriteria }),
+ ...modelConfig,
+ schema: GOAL_CRITERIA_DRAFT_JSON_SCHEMA,
+ thinking: { type: 'disabled' },
+ },
+ {
+ metadata: { trigger: RequestTrigger.Goal },
+ tracing: {
+ promptVersion: GOAL_CRITERIA_DRAFT_PROMPT_VERSION,
+ scenario: TRACING_SCENARIOS.GoalCriteriaGen,
+ schemaName: GOAL_CRITERIA_DRAFT_JSON_SCHEMA.name,
+ } satisfies TracingOptions,
+ },
+ );
+
+ const parsed = generatedCriteriaSchema.safeParse(raw);
+ if (parsed.success) {
+ plan = parsed.data;
+ } else {
+ log(
+ 'goal criteria draft did not match schema (attempt %d/%d): %O',
+ attempt,
+ GOAL_PLAN_MAX_ATTEMPTS,
+ parsed.error.flatten(),
+ );
+ }
}
- const criteria = parsed.data.criteria
+ if (!plan) return undefined;
+
+ const criteria = plan.criteria
.slice(0, maxCriteria)
.filter((criterion) => !isProgrammaticTestCheck(criterion.title, criterion.description));
- return { ...parsed.data, criteria };
+ return { ...plan, criteria };
}
/**