{"record":{"id":"95ba93534d1a7bcf","repo":"linshenkx/prompt-optimizer","slug":"generation-result-is-not-a-valid-object","errorCode":null,"errorMessage":"Generation result is not a valid object.","messagePattern":"Generation result is not a valid object\\.","errorType":"validation","errorClass":"VariableValueGenerationParseError","httpStatus":null,"severity":"error","filePath":"packages/core/src/services/variable-value-generation/service.ts","lineNumber":202,"sourceCode":"        return this.normalizeGenerationResponse(parsed, requestedVariables);\n      } catch (fallbackError) {\n        throw new VariableValueGenerationParseError(\n          `Failed to parse LLM response: ${error instanceof Error ? error.message : String(error)}`\n        );\n      }\n    }\n  }\n\n  /**\n   * 标准化并验证生成响应\n   * 🔧 修复：添加变量对齐校验，确保返回的变量与请求一致\n   */\n  private normalizeGenerationResponse(\n    data: any,\n    requestedVariables: VariableToGenerate[]\n  ): VariableValueGenerationResponse {\n    if (!data || typeof data !== 'object') {\n      throw new VariableValueGenerationParseError('Generation result is not a valid object.');\n    }\n\n    if (!Array.isArray(data.values)) {\n      throw new VariableValueGenerationParseError('Generation result must have a \"values\" array.');\n    }\n\n    if (typeof data.summary !== 'string') {\n      throw new VariableValueGenerationParseError('Generation result must have a \"summary\" string.');\n    }\n\n    // 构建请求变量名集合（用于快速查找）\n    // 🔧 对请求变量名也进行trim，避免首尾空格导致匹配失败\n    const requestedNames = new Set(requestedVariables.map(v => v.name.trim()));\n\n    // 标准化每个生成的值\n    const rawValues: GeneratedVariableValue[] = data.values.map((item: any, index: number) => {\n      if (!item || typeof item !== 'object') {\n        throw new VariableValueGenerationParseError(`values[${index}] is not a valid object.`);","sourceCodeStart":184,"sourceCodeEnd":220,"githubUrl":"https://github.com/linshenkx/prompt-optimizer/blob/3e677b1d9f7e0493c142c175560531e7ae786dce/packages/core/src/services/variable-value-generation/service.ts#L184-L220","documentation":"After successfully JSON-parsing the model output, normalizeGenerationResponse requires the top level to be an object. If the parsed value is an array, string, number, or null, VariableValueGenerationParseError is thrown. The model returned valid JSON but the wrong shape.","triggerScenarios":"Model returns a bare array of values ([{name, value, reason}, ...]) or a bare string instead of the expected { values: [...], summary: \"...\" } envelope.","commonSituations":"Models that 'simplify' the requested schema and return an array; template instruction ambiguous about the envelope; few-shot examples in a customized template showing a bare array; model returning just the JSON string of values.","solutions":["If you control the output, wrap bare arrays: { values: arr, summary: '' } before passing onward (or re-run generation)","Fix the template to show the exact envelope with a one-shot example","Log the parsed type (Array.isArray, typeof) to confirm the mismatch","Prefer models with structured-output/JSON-schema enforcement"],"exampleFix":"// before\nconst out = await gen.generate(req);\n\n// after\n// if you post-process raw model text yourself:\nlet parsed = JSON.parse(text);\nif (Array.isArray(parsed)) parsed = { values: parsed, summary: '' };\nif (typeof parsed !== 'object' || parsed === null) throw new Error('unexpected LLM shape');","handlingStrategy":"type-guard","validationCode":"const parsed = JSON.parse(text);\nif (Array.isArray(parsed)) parsed = { values: parsed, summary: '' };","typeGuard":"function isEnvelope(d: any): d is { values: unknown[]; summary: string } { return !!d && typeof d === 'object' && !Array.isArray(d); }","tryCatchPattern":"catch (e) { if (e instanceof VariableValueGenerationParseError && /not a valid object/.test(e.message)) { /* wrap arrays and retry normalize */ } throw e; }","preventionTips":["Show the exact envelope shape in the template's example","Check Array.isArray on parsed LLM JSON before assuming object shape"],"tags":["llm-output","schema-validation","json","variable-value-generation"],"backgroundTag":"llm-response-schema-invalid","analyzedSha":"3e677b1d9f7e0493c142c175560531e7ae786dce","analyzedAt":"2026-08-27T21:29:16.709Z","schemaVersion":2},"datasetVersion":"2026-08-28T00:17:15.603Z"}