{"record":{"id":"6d2cce72b6f0d841","repo":"micro/go-micro","slug":"failed-to-parse-stream-chunk-w-6d2cce","errorCode":null,"errorMessage":"failed to parse stream chunk: %w","messagePattern":"failed to parse stream chunk: %w","errorType":"exception","errorClass":null,"httpStatus":null,"severity":"error","filePath":"ai/gemini/gemini.go","lineNumber":246,"sourceCode":"\t\t\t\tCode    int    `json:\"code\"`\n\t\t\t\tMessage string `json:\"message\"`\n\t\t\t\tStatus  string `json:\"status\"`\n\t\t\t} `json:\"error\"`\n\t\t\tCandidates []struct {\n\t\t\t\tContent struct {\n\t\t\t\t\tParts []struct {\n\t\t\t\t\t\tText string `json:\"text\"`\n\t\t\t\t\t} `json:\"parts\"`\n\t\t\t\t} `json:\"content\"`\n\t\t\t} `json:\"candidates\"`\n\t\t\tUsageMetadata *struct {\n\t\t\t\tPromptTokenCount     int `json:\"promptTokenCount\"`\n\t\t\t\tCandidatesTokenCount int `json:\"candidatesTokenCount\"`\n\t\t\t\tTotalTokenCount      int `json:\"totalTokenCount\"`\n\t\t\t} `json:\"usageMetadata\"`\n\t\t}\n\t\tif err := json.Unmarshal([]byte(data), &chunk); err != nil {\n\t\t\treturn nil, fmt.Errorf(\"failed to parse stream chunk: %w\", err)\n\t\t}\n\t\tif chunk.Error != nil {\n\t\t\treturn nil, fmt.Errorf(\"gemini stream error (%s): %s\", chunk.Error.Status, chunk.Error.Message)\n\t\t}\n\t\tfor _, candidate := range chunk.Candidates {\n\t\t\tvar parts []string\n\t\t\tfor _, part := range candidate.Content.Parts {\n\t\t\t\tif part.Text != \"\" {\n\t\t\t\t\tparts = append(parts, part.Text)\n\t\t\t\t}\n\t\t\t}\n\t\t\tif len(parts) > 0 {\n\t\t\t\treturn &ai.Response{Reply: strings.Join(parts, \"\")}, nil\n\t\t\t}\n\t\t}\n\t\tif chunk.UsageMetadata != nil {\n\t\t\treturn &ai.Response{Usage: ai.Usage{\n\t\t\t\tInputTokens:  chunk.UsageMetadata.PromptTokenCount,","sourceCodeStart":228,"sourceCodeEnd":264,"githubUrl":"https://github.com/micro/go-micro/blob/24529f140421a11a33b6999ab7944f2021cfd69c/ai/gemini/gemini.go#L228-L264","documentation":"Recv received an SSE data payload from the Gemini stream and json.Unmarshal failed to decode it into the chunk struct. This indicates the stream delivered data that does not match the expected Gemini streaming response schema — an unexpected payload shape, truncation, or a non-Gemini endpoint behind BaseURL.","triggerScenarios":"The SSE 'data:' line's JSON lacked expected fields (candidates/error/usageMetadata shapes changed) or contained invalid/truncated JSON, during a Stream call's Recv loop.","commonSituations":"Proxy that mangles SSE bodies; pointing BaseURL at a Gemini-compatible gateway with slightly different response schema; Gemini API schema evolution; connection cut mid-JSON.","solutions":["Log the raw 'data' payload when this error occurs to see what the endpoint actually sent.","Verify BaseURL points to a genuine Gemini v1beta SSE endpoint, not a shim with divergent schema.","Upgrade the library to pick up schema fixes for newer Gemini API responses.","Recover by closing the stream and retrying the request — truncated chunks are often transient."],"exampleFix":"// before\ntext, err := stream.Recv(ctx)\nif err != nil { return err }\n// after\ntext, err := stream.Recv(ctx)\nif err != nil {\n    if strings.Contains(err.Error(), \"failed to parse stream chunk\") {\n        return fmt.Errorf(\"bad chunk from endpoint; check BaseURL/schema: %w\", err)\n    }\n    return err\n}","handlingStrategy":"try-catch","validationCode":null,"typeGuard":"func isChunkParseErr(err error) bool {\n    return err != nil && strings.Contains(err.Error(), \"failed to parse stream chunk\")\n}","tryCatchPattern":"text, err := stream.Recv(ctx)\nif err != nil {\n    if isChunkParseErr(err) {\n        log.Printf(\"malformed chunk; closing stream and retrying request\")\n        stream.Close()\n        return retryRequest(ctx, req)\n    }\n    return err\n}","preventionTips":["Point BaseURL only at genuine Gemini v1beta SSE endpoints","Keep the library updated for Gemini API schema changes","Bypass SSE-mangling middlewares/proxies for streaming traffic","Treat parse failures as stream-fatal: close and restart the request"],"tags":["json","sse","gemini","streaming","deserialization"],"backgroundTag":"response-parse-failed","analyzedSha":"24529f140421a11a33b6999ab7944f2021cfd69c","analyzedAt":"2026-09-01T02:52:24.923Z","contentChangedAt":null,"schemaVersion":2},"datasetVersion":"2026-09-08T05:18:18.240Z"}