micro/go-micro · error

failed to marshal request: %w

Error message

failed to marshal request: %w

What it means

This error wraps json.Marshal failure when encoding the OpenAI-compatible chat request map in the Ollama provider's callOpenAI. The request is built as map[string]any, so marshalling should rarely fail, but non-JSON-serializable values (channels, funcs, invalid float NaN/Inf) in the map would trigger it.

Source

Thrown at ai/ollama/ollama.go:229

				"content":    followUpRaw.content,
				"tool_calls": followUpRaw.toolCalls,
			})
			continue
		}

		if followUpResp.Reply != "" {
			resp.Answer = followUpResp.Reply
		}
		break
	}

	return resp, nil
}

func (p *Provider) callOpenAI(ctx context.Context, req map[string]any) (*ai.Response, *rawChatMessage, error) {
	reqBody, err := json.Marshal(req)
	if err != nil {
		return nil, nil, fmt.Errorf("failed to marshal request: %w", err)
	}

	apiURL := strings.TrimRight(p.opts.BaseURL, "/") + p.chatPath()
	httpReq, err := http.NewRequestWithContext(ctx, http.MethodPost, apiURL, bytes.NewReader(reqBody))
	if err != nil {
		return nil, nil, fmt.Errorf("failed to create request: %w", err)
	}
	httpReq.Header.Set("Content-Type", "application/json")
	if p.opts.APIKey != "" {
		httpReq.Header.Set("Authorization", "Bearer "+p.opts.APIKey)
	}

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

View on GitHub (pinned to 24529f1404)

Solutions

  1. Inspect the request map for values not JSON-serializable (channels, funcs, cycles, NaN/Inf floats)
  2. Sanitize floats (temperature, top_p) to avoid NaN/Inf before building the map
  3. Log the req map keys and value types to identify the offending entry
  4. Build the request as a typed struct instead of map[string]any to catch this at compile time

Example fix

// before
reqBody, err := json.Marshal(req)
if err != nil {
    return nil, nil, fmt.Errorf("failed to marshal request: %w", err)
}
// after
reqBody, err := json.Marshal(req)
if err != nil {
    return nil, nil, fmt.Errorf("failed to marshal request: %w (keys: %v)", err, mapKeys(req))
}
Defensive patterns

Strategy: validation

Validate before calling

// validate options before building the request
for k, v := range opts {
    if err := json.Unmarshal(mustJSON(v), new(json.RawMessage)); err != nil {
        return fmt.Errorf("option %q is not JSON-serializable: %w", k, err)
    }
}
if math.IsNaN(opts.Temperature) || math.IsInf(opts.Temperature, 0) {
    return fmt.Errorf("temperature must be a finite number")
}

Type guard

func isJSONSerializable(v any) bool {
    _, err := json.Marshal(v)
    return err == nil
}

Try / catch

resp, err := provider.Generate(ctx, req)
if err != nil {
    if strings.Contains(err.Error(), "failed to marshal request") {
        // inspect request fields for channels/funcs/cycles/NaN
    }
    return err
}

Prevention

When it happens

Trigger: json.Marshal(req) in callOpenAI (called from generateOpenAI) fails because the request map contains a value json cannot encode — e.g. a caller-supplied option value inserted into the map that is a channel, function, cyclic reference, or NaN/Inf number.

Common situations: Passing options like tools or messages built with unsupported types; NaN/Inf token or temperature values from computed defaults; cyclic structures in user-supplied metadata.

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/b4a98aabcc5165ff. Report an issue: GitHub.