Skip to content

ChatXAI: 400 error when AIMessage has tool_calls but no content #34140

@tsh356

Description

@tsh356

Description

When using ChatXAI with LangGraph agents, xAI's API returns a 400 error if an AIMessage contains tool_calls but has empty/null content:

openai.BadRequestError: Error code: 400 - {'code': 'Client specified an invalid argument', 
'error': 'Invalid request content: Each message must have at least one content element.'}

Environment

  • langchain-xai: 1.1.0
  • langchain-core: 1.1.0
  • Model: grok-4-1-fast-reasoning
  • Using LangGraph with tool-calling agents

Reproduction

This occurs when using ChatXAI in a LangGraph agent that makes tool calls. After several tool call rounds, the message history contains AIMessages with only tool_calls and no content field. xAI's API is stricter than OpenAI's and rejects these messages.

Workaround

Subclass ChatXAI and ensure content is always set:

from langchain_xai import ChatXAI
from langchain_core.messages import AIMessage

class ChatXAISanitized(ChatXAI):
    def _convert_messages_to_dicts(self, messages):
        for msg in messages:
            if isinstance(msg, AIMessage) and not msg.content and msg.tool_calls:
                msg.content = ""  # xAI requires content, even if empty
        return super()._convert_messages_to_dicts(messages)

Suggested Fix

ChatXAI._convert_messages_to_dicts (or the underlying message conversion) should ensure all messages have at least an empty content field to satisfy xAI's API requirements.

Metadata

Metadata

Assignees

No one assigned

    Labels

    xai`langchain-xai` package issues & PRs

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions