micro/go-micro · error

failed to marshal stream request: %w

Error message

failed to marshal stream request: %w

What it means

Gemini provider's Stream method failed to json.Marshal the assembled request map into the HTTP body. Marshal errors on map[string]any are rare and indicate values that are not JSON-encodable (channels, funcs, unsupported types) sneaked into the request construction. The wrapped error identifies the offending value.

Source

Thrown at ai/gemini/gemini.go:181

// piece of multi-step work reaches it.
const maxToolRounds = 12

func (p *Provider) Stream(ctx context.Context, req *ai.Request, opts ...ai.GenerateOption) (ai.Stream, error) {
	apiReq := map[string]any{
		"contents": geminiContents(req),
	}
	if req.SystemPrompt != "" {
		apiReq["system_instruction"] = map[string]any{
			"parts": []map[string]any{{"text": req.SystemPrompt}},
		}
	}
	if p.opts.MaxTokens > 0 {
		apiReq["generationConfig"] = map[string]any{"maxOutputTokens": p.opts.MaxTokens}
	}

	reqBody, err := json.Marshal(apiReq)
	if err != nil {
		return nil, fmt.Errorf("failed to marshal stream request: %w", err)
	}

	apiURL := strings.TrimRight(p.opts.BaseURL, "/") +
		"/v1beta/models/" + p.opts.Model + ":streamGenerateContent?alt=sse"
	httpReq, err := http.NewRequestWithContext(ctx, http.MethodPost, apiURL, bytes.NewReader(reqBody))
	if err != nil {
		return nil, fmt.Errorf("failed to create stream request: %w", err)
	}
	httpReq.Header.Set("Content-Type", "application/json")
	httpReq.Header.Set("Accept", "text/event-stream")
	httpReq.Header.Set("x-goog-api-key", p.opts.APIKey)

	httpResp, err := http.DefaultClient.Do(httpReq)
	if err != nil {
		return nil, fmt.Errorf("stream API request failed: %w", err)
	}
	if httpResp.StatusCode != http.StatusOK {
		defer httpResp.Body.Close()

View on GitHub (pinned to 24529f1404)

Solutions

  1. Inspect the wrapped %w error to identify the non-marshalable value and fix where it enters the request.
  2. Ensure all option/prompt values passed to the provider are plain JSON-safe types (string, number, bool, slice, map, struct).
  3. Upgrade the library version if this occurs with standard usage, as it likely indicates an internal regression.
  4. Marshal a copy of the request yourself before calling Stream to isolate the bad value.

Example fix

// before
apiReq["contents"] = myCustomContent
// after
b, err := json.Marshal(myCustomContent)
if err != nil {
    return nil, fmt.Errorf("unsupported content type: %w", err)
}
var safe any
json.Unmarshal(b, &safe)
apiReq["contents"] = safe
Defensive patterns

Strategy: validation

Validate before calling

if _, err := json.Marshal(req); err != nil {
    return fmt.Errorf("request not JSON-serializable: %w", err)
}

Type guard

func isJSONSafe(v any) bool {
    b, err := json.Marshal(v)
    return err == nil && json.Valid(b)
}

Try / catch

stream, err := provider.Stream(ctx, req)
if err != nil {
    if strings.Contains(err.Error(), "failed to marshal stream request") {
        return fmt.Errorf("client bug: non-serializable value in request: %w", err)
    }
    return err
}

Prevention

When it happens

Trigger: Calling Stream when the internally-built apiReq map contains a value json.Marshal cannot encode (e.g. a non-marshalable type inserted via options or prompt content).

Common situations: Passing custom types implementing MarshalJSON incorrectly through prompt/options plumbing; embedding channel/func values via configuration; a code regression in request construction.

Understand the failure class

Background: json.Marshal / "failed to marshal" errors in Go: why "unsupported type" happens and how to fix it — this error's family across 22 libraries.

Related errors


AI-assisted analysis of micro/go-micro@24529f1404 (2026-09-01). Data as JSON: /api/errors/74b433deeef81ef7. Report an issue: GitHub.