logoAnt Design X

DesignDevelopmentComponentsX MarkdownX SDKPlayground
  • Introduction
  • Data Flow
    • useXChatConversation Data
      2.0.0
    • useXConversations
      2.0.0
  • Chat Provider
    • Chat Provider
      2.0.0
    • OpenAIChatProvider
      2.0.0
    • DeepSeekChatProvider
      2.0.0
    • Custom Chat Provider
      2.0.0
  • Utilities
    • XRequestRequest
      2.0.0
    • XStreamStream
      2.0.0

XRequest
Request

Universal streaming request utility.
Importimport { XRequest } from "@ant-design/x-sdk";
Sourcex-sdk/src/x-request
Docs
Edit this page
Versionsupported since 2.0.0

When To Use

  • Make requests to backend service APIs to get response data. For OpenAI Compatible LLM services, it's recommended to use XModelAPI.

Code Demo

API

XRequestFunction

ts
type XRequestFunction<Input = Record<PropertyKey, any>, Output = Record<string, string>> = (
baseURL: string,
options: XRequestOptions<Input, Output>,
) => XRequestClass<Input, Output>;

XRequestFunction

PropertyDescriptionTypeDefaultVersion
baseURLAPI endpoint URLstring--
optionsRequest optionsXRequestOptions<Input, Output>--

XRequestOptions

PropertyDescriptionTypeDefaultVersion
callbacksRequest callback handlersXRequestCallbacks<Output>--
paramsRequest parametersInput--
headersAdditional request headersRecord<string, string>--
timeoutRequest timeout configuration (time from sending request to connecting to service), unit: msnumber--
streamTimeoutStream mode data timeout configuration (time interval for each chunk return), unit: msnumber--
fetchCustom fetch objecttypeof fetch--
middlewaresMiddlewares for pre- and post-request processingXFetchMiddlewares--
transformStreamStream processorXStreamOptions<Output>['transformStream'] | ((baseURL: string, responseHeaders: Headers) => XStreamOptions<Output>['transformStream'])--
streamSeparatorStream separator, used to separate different data streams. Does not take effect when transformStream has a valuestring\n\n2.2.0
partSeparatorPart separator, used to separate different parts of data. Does not take effect when transformStream has a valuestring\n2.2.0
kvSeparatorKey-value separator, used to separate keys and values. Does not take effect when transformStream has a valuestring:2.2.0
manualWhether to manually control request sending. When true, need to manually call run methodbooleanfalse-
retryIntervalRetry interval when request is interrupted or fails, in milliseconds. If not set, automatic retry will not occurnumber--
retryTimesMaximum number of retry attempts. No further retries will be attempted after exceeding this limitnumber--

XRequestCallbacks

PropertyDescriptionTypeDefaultVersion
onSuccessSuccess callback. When used with Chat Provider, additionally gets the assembled message(chunks: Output[], responseHeaders: Headers, message: ChatMessage) => void--
onErrorError handling callback. onError can return a number indicating the retry interval (in milliseconds) when a request exception occurs. When both onError return value and options.retryInterval exist, the onError return value takes precedence. When used with Chat Provider, additionally gets the assembled fail back message(error: Error, errorInfo: any, responseHeaders?: Headers, message: ChatMessage) => number | void--
onUpdateMessage update callback. When used with Chat Provider, additionally gets the assembled message(chunk: Output, responseHeaders: Headers, message: ChatMessage) => void--

XRequestClass

PropertyDescriptionTypeDefaultVersion
abortCancel request() => void--
runManually execute request (effective when manual=true)(params?: Input) => void--
isRequestingWhether currently requestingboolean--

setXRequestGlobalOptions

ts
type setXRequestGlobalOptions<Input, Output> = (
options: XRequestGlobalOptions<Input, Output>,
) => void;

XRequestGlobalOptions

ts
type XRequestGlobalOptions<Input, Output> = Pick<
XRequestOptions<Input, Output>,
'headers' | 'timeout' | 'streamTimeout' | 'middlewares' | 'fetch' | 'transformStream' | 'manual'
>;

XFetchMiddlewares

ts
interface XFetchMiddlewares {
onRequest?: (...ags: Parameters<typeof fetch>) => Promise<Parameters<typeof fetch>>;
onResponse?: (response: Response) => Promise<Response>;
}

FAQ

When using transformStream in XRequest, it causes stream locking issues on the second input request. How to solve this?

ts
onError TypeError: Failed to execute 'getReader' on 'ReadableStream': ReadableStreamDefaultReader constructor can only accept readable streams that are not yet locked to a reader

The Web Streams API stipulates that a stream can only be locked by one reader at the same time. Reuse will cause an error. Therefore, when using TransformStream, you need to pay attention to the following points:

  1. Ensure that the transformStream function returns a new ReadableStream object, not the same object.
  2. Ensure that the transformStream function does not perform multiple read operations on response.body.

Recommended Writing

tsx
const [provider] = React.useState(
new CustomProvider({
request: XRequest(url, {
manual: true,
// Recommended: transformStream returns a new instance with a function
transformStream: () =>
new TransformStream({
transform(chunk, controller) {
// Your custom processing logic
controller.enqueue({ data: chunk });
},
}),
// Other configurations...
}),
}),
);
tsx
const request = XRequest(url, {
manual: true,
transformStream: new TransformStream({ ... }), // Do not persist in Provider/useState
});
Basic Usage

Basic request example showing XRequest fundamental usage.

CodeSandbox Icon
codepen icon
External Link Icon
expand codeexpand code
Custom Parameters

Custom parameters and headers configuration for full request customization.

CodeSandbox Icon
codepen icon
External Link Icon
expand codeexpand code
Custom Transformer

Configure a custom transformStream for XRequest. The following example demonstrates how to handle application/x-ndjson data format.

CodeSandbox Icon
codepen icon
External Link Icon
expand codeexpand code
Stream Parsing Configuration

Configure the stream parsing separator streamSeparator for XRequest to customize data stream splitting.

CodeSandbox Icon
codepen icon
External Link Icon
expand codeexpand code
Manual Trigger

Manual trigger request mode with streaming response and abort support.

CodeSandbox Icon
codepen icon
External Link Icon
expand codeexpand code
Timeout Configuration

Configure timeout for XRequest to set the request timeout.

CodeSandbox Icon
codepen icon
External Link Icon
expand codeexpand code
Chunk Timeout Configuration

Configure streamTimeout for XRequest to set the request stream timeout.

CodeSandbox Icon
codepen icon
External Link Icon
expand codeexpand code
Request Log
Status-
Update Times0
Request Log
Status-
Update Times0
Mock Custom Protocol - Log
Mock Custom Protocol - Log
Request Log
request
Status-
Update Times0
Request Log
request
Status-
Mock Custom Protocol - Log