micro/go-micro · error

failed to create stream request: %w

Error message

failed to create stream request: %w

What it means

Thrown when http.NewRequestWithContext cannot build the streaming POST request to the Ollama OpenAI-compatible stream endpoint in streamOpenAI (called from Stream). The cause is virtually always an invalid composed URL (bad BaseURL), since the body is already-marshalled bytes.

Source

Thrown at ai/ollama/ollama.go:339

	apiReq := map[string]any{
		"model":          p.opts.Model,
		"messages":       messages,
		"stream":         true,
		"stream_options": map[string]any{"include_usage": true},
	}
	if p.opts.MaxTokens > 0 {
		apiReq["max_tokens"] = 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, "/") + p.streamPath()
	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")
	if p.opts.APIKey != "" {
		httpReq.Header.Set("Authorization", "Bearer "+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()
		respBody, _ := io.ReadAll(httpResp.Body)
		return nil, fmt.Errorf("stream API error (%s): %s", httpResp.Status, string(respBody))
	}

	return &sseStream{body: httpResp.Body, scanner: bufio.NewScanner(httpResp.Body)}, nil

View on GitHub (pinned to 24529f1404)

Solutions

  1. Validate and normalize the BaseURL (trim spaces/quotes, ensure scheme+host) with url.Parse before use
  2. Confirm BaseURL matches the running Ollama server, e.g. http://localhost:11434
  3. Log the composed apiURL when this error occurs to spot malformed composition
  4. Fix the env/config source of the BaseURL rather than patching at call time

Example fix

// before
provider, err := ai.NewOllama(ai.Options{BaseURL: os.Getenv("OLLAMA_URL")})
// after
base := strings.TrimSpace(strings.Trim(os.Getenv("OLLAMA_URL"), "\"'"))
if u, err := url.Parse(base); err != nil || u.Scheme == "" || u.Host == "" {
    return fmt.Errorf("invalid OLLAMA_URL %q", os.Getenv("OLLAMA_URL"))
}
provider, err := ai.NewOllama(ai.Options{BaseURL: base})
Defensive patterns

Strategy: validation

Validate before calling

u, err := url.Parse(strings.TrimSpace(opts.BaseURL))
if err != nil || u.Scheme == "" || u.Host == "" {
    return fmt.Errorf("invalid Ollama base URL: %q", opts.BaseURL)
}

Type guard

func isValidURL(raw string) bool {
    u, err := url.Parse(strings.TrimSpace(raw))
    return err == nil && u.Scheme != "" && u.Host != ""
}

Try / catch

stream, err := provider.Stream(ctx, req)
if err != nil {
    if strings.Contains(err.Error(), "failed to create stream request") {
        // BaseURL malformed — fix env/config
    }
    return err
}

Prevention

When it happens

Trigger: http.NewRequestWithContext fails in streamOpenAI (called from Stream) because apiURL = BaseURL + p.streamPath() is unparseable — BaseURL with spaces/control characters, quotes from config, missing scheme, or other malformed URL syntax.

Common situations: OLLAMA base URL env var with stray whitespace/newline or copy-pasted quotes; https scheme against a plain-http local server manifesting as URL/TLS issues; programmatic BaseURL composition bugs.

Understand the failure class

Background: "Invalid URL" / "URL cannot be empty": fix the malformed or missing URL behind request-construction failures — this error's family across 50 libraries.

Related errors


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