Skip to content

API keys from environment variables with trailing whitespace cause cryptic "expected a cloneable request" error #1480

@alpo

Description

@alpo

When an API key environment variable contains trailing whitespace (commonly a newline character), aichat fails with a confusing error message that doesn't indicate the actual problem.

Error with streaming (default):

Error: Failed to call chat-completions api

 Caused by:
     expected a cloneable request

Error with stream: false:

 Error: Failed to call chat-completions api

 Caused by:
     0: builder error
     1: failed to parse header value

Root Cause

HTTP header values cannot contain newline characters. When an API key with a trailing newline is used in the Authorization: Bearer {key} header, reqwest's RequestBuilder enters an error state. In the streaming code path, reqwest-eventsource calls builder.try_clone() which returns None for error-state builders, resulting in the misleading "expected a cloneable request" error.

How to Reproduce

  1. Set an API key environment variable with a trailing newline:
    export XAI_API_KEY="xai-your-key-here
    "

  2. Configure the provider in config.yaml: clients:

  3. Run aichat:
    aichat -m xai:grok-2-latest "hello"

  4. Observe the cryptic error message

Expected Behavior

Either:

  1. Automatically trim whitespace from environment variable values, or
  2. Provide a clear error message indicating the API key contains invalid characters

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions