{"record":{"id":"5680342dbbca2f13","repo":"linshenkx/prompt-optimizer","slug":"values-index-is-missing-a-valid-reason-field","errorCode":null,"errorMessage":"values[${index}] is missing a valid \"reason\" field.","messagePattern":"values\\[(.+?)\\] is missing a valid \"reason\" field\\.","errorType":"validation","errorClass":"VariableValueGenerationParseError","httpStatus":null,"severity":"error","filePath":"packages/core/src/services/variable-value-generation/service.ts","lineNumber":232,"sourceCode":"    // 🔧 对请求变量名也进行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.`);\n      }\n\n      if (typeof item.name !== 'string' || !item.name.trim()) {\n        throw new VariableValueGenerationParseError(`values[${index}] is missing a valid \"name\" field.`);\n      }\n\n      if (typeof item.value !== 'string') {\n        throw new VariableValueGenerationParseError(`values[${index}] is missing a valid \"value\" field.`);\n      }\n\n      if (typeof item.reason !== 'string') {\n        throw new VariableValueGenerationParseError(`values[${index}] is missing a valid \"reason\" field.`);\n      }\n\n      return {\n        name: item.name.trim(),\n        value: item.value,\n        reason: item.reason,\n        confidence: typeof item.confidence === 'number' ? item.confidence : undefined,\n      };\n    });\n\n    // 🔧 对齐处理：过滤掉不在请求列表中的变量 + 建立Map用于快速查找\n    const valueMap = new Map<string, GeneratedVariableValue>();\n    for (const val of rawValues) {\n      if (requestedNames.has(val.name)) {\n        // 🔧 检测LLM返回的同名重复\n        if (valueMap.has(val.name)) {\n          console.warn(`[VariableValueGeneration] LLM returned a duplicate variable name: ${val.name}. The later value will overwrite the earlier one.`);\n        }","sourceCodeStart":214,"sourceCodeEnd":250,"githubUrl":"https://github.com/linshenkx/prompt-optimizer/blob/3e677b1d9f7e0493c142c175560531e7ae786dce/packages/core/src/services/variable-value-generation/service.ts#L214-L250","documentation":"Each generated value must include a string reason explaining the generated value. normalizeGenerationResponse throws with the item's index when item.reason is missing or not a string, completing the strict per-item contract of { name, value, reason }.","triggerScenarios":"values[i] = { name: 'var1', value: 'x' } with no reason, or reason: 5 / reason: null / reason: { why: '...' }.","commonSituations":"Model drops reason to save tokens on long generations; customized template that removed the reason requirement; truncation cutting trailing fields; model nesting the explanation under a different key ('why', 'explanation').","solutions":["Default-fill reason: '' in pre-processing if explanations are optional for your use case","Remap alternate keys (item.why ?? item.explanation -> item.reason)","Require reason explicitly in the template with an example item","Raise max_tokens if responses end mid-item"],"exampleFix":"// before\nconst out = await gen.generate(req);\n\n// after\nconst parsed = JSON.parse(text);\nfor (const item of parsed.values ?? []) {\n  if (typeof item.reason !== 'string') item.reason = item.why ?? item.explanation ?? '';\n}","handlingStrategy":"validation","validationCode":"for (const item of parsed.values ?? []) { if (typeof item.reason !== 'string') item.reason = item.why ?? item.explanation ?? ''; }","typeGuard":"const hasReason = (item: any) => typeof item?.reason === 'string';","tryCatchPattern":"catch (e) { if (e instanceof VariableValueGenerationParseError && /reason. field/.test(e.message)) { /* default-fill reason and retry */ } throw e; }","preventionTips":["Require a brief reason per item in the template example","Default-fill explanation fields you don't strictly need rather than failing the batch"],"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"}