Now liveThe Skillselion MCP - thousands of ranked skills, loaded into your agent mid-task. No install.Get it →
ant-design avatar

Use X Chat

  • 66 installs
  • 4.7k repo stars
  • Updated August 4, 2026
  • ant-design/x

use-x-chat is a skill that explains the @ant-design/x-sdk useXChat hook for building AI conversation apps with provider integration, message management, and multi-conversation support.

About

This skill explains how to use the @ant-design/x-sdk useXChat hook to build AI conversation applications. A developer uses it for custom Provider integration, message state management, error and abort handling, and multi-conversation management. It shows how to map the hook's MessageInfo array into Bubble.List items and wire the Sender component for sending and cancelling requests.

  • Explains the useXChat hook for building AI conversation apps
  • Covers custom Provider integration, message management, and multi-conversation handling
  • Shows mapping MessageInfo to Bubble.List items and error/abort fallbacks

Use X Chat by the numbers

  • 66 all-time installs (skills.sh)
  • Ranked #5,985 of 16,546 AI & Agent Building skills by installs in the Skillselion catalog
  • Data as of Aug 5, 2026 (Skillselion catalog sync)
At a glance

use-x-chat capabilities & compatibility

Capabilities
ant design x · x card
Use cases
frontend · ui design · orchestration
From the docs

What use-x-chat says it does

Use the `useXChat` Hook to build professional AI conversation applications.
SKILL.md
`messages` is `MessageInfo<ChatMessage>[]` and cannot be passed directly to `Bubble.List`. It must be mapped to `{ key, role, content, loading }` format.
SKILL.md
npx skills add https://github.com/ant-design/x --skill use-x-chat

Add your badge

Show developers this skill is listed on Skillselion. Paste this into your README.

Listed on Skillselion
Installs66
repo stars4.7k
Last updatedAugust 4, 2026
Repositoryant-design/x

What it does

Build AI chat apps with the useXChat hook: provider integration, message state, and Bubble.List rendering.

Who is it for?

Developers building AI conversation UIs with @ant-design/x-sdk once a custom Chat Provider exists.

Skip if: Building the Chat Provider itself (use the x-chat-provider skill) or non-x chat stacks.

When should I use this skill?

The user is integrating useXChat, managing chat messages, handling errors, or building multi-conversation UIs with @ant-design/x-sdk.

What you get

A working useXChat integration with mapped Bubble.List rendering, placeholders, and error/abort fallbacks.

  • useXChat integration code
  • Bubble.List message mapping

By the numbers

  • requires @ant-design/x-sdk 2.2.2+
  • three-step integration (provider, usage, UI)

Files

SKILL.mdMarkdownGitHub ↗

🎯 Skill Positioning

Core Positioning: Use the useXChat Hook to build professional AI conversation applications. Prerequisite: Already have a custom Chat Provider (refer to x-chat-provider skill)

Table of Contents

🚀 Quick Start

1. Dependency Management

  • @ant-design/x-sdk: 2.2.2+
  • @ant-design/x: latest version (UI components)
npm install @ant-design/x-sdk@latest @ant-design/x@latest

2. Three-step Integration

Step 1: Prepare Provider

Handled by the x-chat-provider skill. Note XRequest must pass manual: true:

import { MyChatProvider } from './MyChatProvider';
import { XRequest } from '@ant-design/x-sdk';

// ⚠️ manual: true is required
const provider = new MyChatProvider({
  request: XRequest('https://your-api.com/chat', { manual: true }),
});

Step 2: Basic Usage

import { useXChat } from '@ant-design/x-sdk';

const ChatComponent = () => {
  const { messages, onRequest, isRequesting } = useXChat({
    provider,
    requestPlaceholder: (_, { messages }) => ({
      content: 'Thinking...',
      role: 'assistant',
    }),
    requestFallback: (_, { error, messageInfo }) => {
      if (error.name === 'AbortError') {
        return { content: messageInfo?.message?.content || 'Reply cancelled', role: 'assistant' };
      }
      return { content: 'Network error, please try again later', role: 'assistant' };
    },
  });

  return (
    <div>
      {messages.map((msg) => (
        <div key={msg.id}>
          {msg.message.role}: {msg.message.content}
        </div>
      ))}
      <button onClick={() => onRequest({ query: 'Hello' })}>Send</button>
    </div>
  );
};

Step 3: UI Integration

⚠️ messages is MessageInfo<ChatMessage>[] and cannot be passed directly to Bubble.List. It must be mapped to { key, role, content, loading } format. `Bubble.List` uses the `role` prop (not roles) to configure role styles.
import { Bubble, Sender } from '@ant-design/x';

const ChatUI = () => {
  const { messages, onRequest, isRequesting, abort } = useXChat({ provider });

  return (
    <div style={{ height: 600 }}>
      <Bubble.List
        // ✅ Correct: use role (not roles)
        role={{
          user: { placement: 'end' },
          assistant: { placement: 'start' },
        }}
        items={messages.map(({ id, message, status }) => ({
          key: id,
          role: message.role, // matches role config key
          content: message.content, // message content
          loading: status === 'loading', // loading animation
        }))}
      />
      <Sender
        loading={isRequesting}
        onSubmit={(content) => onRequest({ query: content })}
        onCancel={abort}
      />
    </div>
  );
};
When ChatMessage is an object type (not string)

When ChatMessage is a complex object (e.g., with content, attachments fields), use contentRender:

<Bubble.List
  role={{
    assistant: {
      placement: 'start',
      // contentRender receives content param, which is the message field itself
      contentRender(content: MyMessage) {
        return (
          <div>
            <div>{content.content}</div>
            {content.attachments?.map((a) => (
              <FileCard key={a.url} name={a.name} />
            ))}
          </div>
        );
      },
    },
    user: {
      placement: 'end',
      contentRender(content: MyMessage) {
        return content.content;
      },
    },
  }}
  items={messages.map(({ id, message, status }) => ({
    key: id,
    role: message.role,
    content: message, // ⚠️ Pass the entire message object; contentRender handles rendering
    loading: status === 'loading',
  }))}
/>

🧩 Core Concepts

Data Model

⚠️ Important: messages type is MessageInfo<ChatMessage>[]; message content is in msg.message
interface MessageInfo<ChatMessage> {
  id: number | string; // Message unique identifier
  message: ChatMessage; // Actual message content (your ChatMessage type)
  status: MessageStatus; // Message status
  extraInfo?: AnyObject; // Extended info (note: extraInfo, not extra)
}

type MessageStatus = 'local' | 'loading' | 'updating' | 'success' | 'error' | 'abort';
// local: locally sent user message
// loading: AI reply placeholder (corresponds to requestPlaceholder)
// updating: AI streaming output in progress
// success: AI reply complete
// error: request failed
// abort: user actively cancelled

useXChat Configuration Options

OptionTypeDescription
providerAbstractChatProvider<ChatMessage, Input, Output>Required, Provider instance
conversationKeystringConversation unique identifier, required for multi-conversation
defaultMessages`DefaultMessageInfo[] \() => ... \
requestPlaceholder`ChatMessage \(requestParams, { messages }) => ChatMessage`
requestFallback`ChatMessage \(requestParams, { error, errorInfo, messages, messageInfo }) => ChatMessage \
parser`(message: ChatMessage) => BubbleMessage \BubbleMessage[]`
requestFallback's messageInfo type is MessageInfo<ChatMessage>, the message being updated when the request fails. requestFallback handles both network errors (error) and user abort (error.name === 'AbortError').

useXChat Return Values

Return ValueTypeDescription
messagesMessageInfo<ChatMessage>[]Message list; must be mapped before passing to Bubble.List
parsedMessagesMessageInfo<ParsedMessage>[]Message list after parser transform (use this when parser is set)
onRequest(params: Partial<Input>, opts?: { extraInfo: AnyObject }) => voidAdd message and trigger request
isRequestingbooleanWhether request is in progress
abort() => voidAbort current request
setMessages(messages: Partial<MessageInfo<ChatMessage>>[]) => voidDirectly modify message list, no request triggered
setMessage`(id: string \number, info: Partial<MessageInfo<ChatMessage>>) => void`
removeMessage`(id: string \number) => boolean`
onReload`(id: string \number, params: Partial<Input>, opts?: { extraInfo: AnyObject }) => void`
queueRequest`(conversationKey: string \symbol, params: Partial<Input>, opts?: { extraInfo: AnyObject }) => void`
isDefaultMessagesRequestingbooleanWhether default messages are async loading

🔧 Core Function Details

Core functionality reference: CORE.md

🗂️ Multi-conversation Management

useXConversations Hook

useXConversations is a conversation list management Hook provided by @ant-design/x-sdk, used together with useXChat for multi-conversation:

import { useXConversations } from '@ant-design/x-sdk';
import type { ConversationData } from '@ant-design/x-sdk';

const {
  conversations, // ConversationData[]: conversation list
  activeConversationKey, // string: currently active conversation key
  setActiveConversationKey, // (key: string) => void: switch conversation
  addConversation, // (ConversationData, placement?) => boolean
  removeConversation, // (key: string) => boolean
  setConversation, // (key: string,  ConversationData) => boolean
  getConversation, // (key: string) => ConversationData | undefined
  setConversations, // (list: ConversationData[]) => void
  getMessages, // (key: string) => MessageInfo[] | undefined (read messages across components)
} = useXConversations({
  defaultConversations: [
    { key: 'conv-1', label: 'Conversation 1' },
    { key: 'conv-2', label: 'Conversation 2' },
  ],
  defaultActiveConversationKey: 'conv-1',
});

Multi-conversation Full Pattern

import { useXChat, useXConversations } from '@ant-design/x-sdk';
import { OpenAIChatProvider, XRequest } from '@ant-design/x-sdk';
import { Bubble, Conversations, Sender } from '@ant-design/x';
import React, { useEffect, useRef } from 'react';

// ⚠️ Each conversation must have its own Provider instance, otherwise state mixes
const providerCache = new Map<string, OpenAIChatProvider>();

function getProvider(key: string): OpenAIChatProvider {
  if (!providerCache.has(key)) {
    providerCache.set(
      key,
      new OpenAIChatProvider({
        request: XRequest(BASE_URL, { manual: true, params: { model: 'gpt-4o', stream: true } }),
      }),
    );
  }
  return providerCache.get(key)!;
}

const App = () => {
  const senderRef = useRef<any>(null);

  const { conversations, activeConversationKey, setActiveConversationKey, addConversation } =
    useXConversations({
      defaultConversations: [{ key: 'conv-1', label: 'New Conversation' }],
      defaultActiveConversationKey: 'conv-1',
    });

  const { messages, onRequest, isRequesting, abort, queueRequest } = useXChat({
    provider: getProvider(activeConversationKey),
    conversationKey: activeConversationKey,
    // Async load default messages
    defaultMessages: async ({ conversationKey }) => {
      // Load history from server based on conversationKey
      return [];
    },
    requestFallback: (_, { error, messageInfo }) => {
      if (error.name === 'AbortError') {
        return { content: messageInfo?.message?.content || 'Cancelled', role: 'assistant' };
      }
      return { content: 'Request failed', role: 'assistant' };
    },
  });

  // Clear input on conversation switch
  useEffect(() => {
    senderRef.current?.clear?.();
  }, [activeConversationKey]);

  const handleNewConversation = () => {
    const newKey = `conv-${Date.now()}`;
    addConversation({ key: newKey, label: `New Conversation ${conversations.length + 1}` });
    setActiveConversationKey(newKey);
  };

  return (
    <div style={{ display: 'flex', height: '100vh' }}>
      <Conversations
        items={conversations}
        activeKey={activeConversationKey}
        onActiveChange={setActiveConversationKey}
        creation={{ onClick: handleNewConversation }}
      />
      <div style={{ flex: 1, display: 'flex', flexDirection: 'column' }}>
        <Bubble.List
          role={{ assistant: { placement: 'start' }, user: { placement: 'end' } }}
          items={messages.map(({ id, message, status }) => ({
            key: id,
            role: message.role,
            content: message.content,
            loading: status === 'loading',
          }))}
        />
        <Sender
          ref={senderRef}
          loading={isRequesting}
          onCancel={abort}
          onSubmit={(val) => {
            onRequest({ messages: [{ role: 'user', content: val }] });
          }}
        />
      </div>
    </div>
  );
};

queueRequest: Delayed Send After Conversation Switch

// Scenario: user switches to a new conversation and triggers an initial message simultaneously
// queueRequest waits for defaultMessages async loading to complete, then sends the request

const handleNewConversationWithFirstMessage = () => {
  const newKey = `conv-${Date.now()}`;
  addConversation({ key: newKey, label: 'New Conversation' });
  setActiveConversationKey(newKey);

  // Queue the message; sent automatically after newKey conversation's defaultMessages finish loading
  queueRequest(newKey, {
    messages: [{ role: 'user', content: 'Hello! Please introduce yourself.' }],
  });
};

📋 Prerequisites and Dependencies

Usage ScenarioRequired Skill/ProviderOrder
Private API Adaptationx-chat-provider → use-x-chatCreate Provider first
Standard APIBuilt-in Provider + use-x-chatDirect use
Multi-conversationProvider factory + useXConversations + useXChatUse together

🚨 Development Rules

Before using use-x-chat, confirm:

  • [ ] Has Provider (custom or built-in Provider)
  • [ ] Provider's XRequest is configured with manual: true
  • [ ] Understands MessageInfo data structure (message content is in msg.message)
  • [ ] Bubble.List uses role prop (not `roles`)
  • [ ] Multi-conversation scenario: each conversation has its own Provider instance

Test Case Rules

  • If the user does not explicitly need test cases, do not add test files

Code Quality Rules

  • After completion, must check types: Run tsc --noEmit to ensure no type errors
  • Keep code clean: Remove all unused variables and imports

🔗 Reference Resources

📚 Core Reference Documentation

  • API.md - Complete API reference documentation
  • CORE.md - Core function details
  • EXAMPLES.md - Practical example code

🌐 SDK Official Documentation

💻 Example Code

Related skills

This week in AI coding

Five minutes, every Monday - the tools, releases and tactics for developers.

unsubscribe anytime.