본문으로 바로가기 본문 바로가기
WIKI 기술 지식 베이스

커스텀 채팅 프로바이더

원문 보기 위키 갱신

커스텀 채팅 프로바이더 (Custom Chat Provider)

내장 Chat Provider로는 요구를 충족할 수 없을 때, 추상 클래스 AbstractChatProvider를 구현해 다양한 모델 프로바이더나 Agentic 서비스의 데이터를 useXChat이 소비할 수 있는 통일된 형식으로 변환해요.

출처: 문서

본문

내장 Chat Provider가 요구를 충족하지 못할 때, 추상 클래스 AbstractChatProvider(추상 메서드 세 개만 포함해요)를 구현하면 서로 다른 모델 프로바이더나 Agentic 서비스의 데이터를 useXChat이 소비할 수 있는 통일된 형식으로 변환할 수 있고, 서로 다른 모델과 에이전트 사이를 매끄럽게 통합하고 전환할 수 있어요.

AbstractChatProvider

AbstractChatProvider는 Chat Provider의 인터페이스를 정의하는 데 쓰이는 추상 클래스예요. 커스텀 데이터 서비스를 사용해야 할 때 AbstractChatProvider를 상속하고 그 메서드들을 구현할 수 있어요. 예제는 Playground - Toolbox를 참고하세요.

type MessageStatus = 'local' | 'loading' | 'updating' | 'success' | 'error';

interface ChatProviderConfig<Input, Output> {
  request: XRequestClass<Input, Output> | (() => XRequestClass<Input, Output>);
}

interface TransformMessage<ChatMessage, Output> {
  originMessage?: ChatMessage;
  chunk: Output;
  chunks: Output[];
  status: MessageStatus;
}

abstract class AbstractChatProvider<ChatMessage, Input, Output> {
  constructor(config: ChatProviderConfig<Input, Output>): void;

  /**
   * Transform parameters passed to onRequest. You can merge or additionally process them with the params in the request configuration when instantiating the Provider
   * @param requestParams Request parameters
   * @param options Request configuration, from the request configuration when instantiating the Provider
   */
  abstract transformParams(
    requestParams: Partial<Input>,
    options: XRequestOptions<Input, Output>,
  ): Input;

  /**
   * Convert parameters passed to onRequest into a local (user-sent) ChatMessage for message rendering
   * @param requestParams Parameters passed to onRequest
   */
  abstract transformLocalMessage(requestParams: Partial<Input>): ChatMessage;

  /**
   * Can transform messages when updating returned data, and will also update messages
   * @param info
   */
  abstract transformMessage(info: TransformMessage<ChatMessage, Output>): ChatMessage;
}

커스텀 Provider의 전체 과정

아래는 Chat Provider를 커스터마이즈하는 방법을 보여 주는 커스텀 Provider 예제예요. 자세한 설명은 코드 예제 뒤에 이어져요.

전체 예제

// Type definitions
type CustomInput = {
  query: string;
};

type CustomOutput = {
  data: {
    content: string; // Text content
    attachments?: {
      // Optional: Document attachments
      name: string; // File name
      url: string; // Download link
      type: string; // File type, e.g., 'pdf', 'docx', 'image'
      size?: number; // File size in bytes, optional
    }[];
  };
};

type CustomMessage = {
  content: string;
  role: 'user' | 'assistant';
  // Optional: Attachment information for displaying download links or previews
  attachments?: {
    name: string;
    url: string;
    type: string;
    size?: number;
  }[];
};

class CustomProvider<
  ChatMessage extends CustomMessage = CustomMessage,
  Input extends CustomInput = CustomInput,
  Output extends CustomOutput = CustomOutput,
> extends AbstractChatProvider<ChatMessage, Input, Output> {
  transformParams(
    requestParams: Partial<Input>,
    options: XRequestOptions<Input, Output, ChatMessage>,
  ): Input {
    if (typeof requestParams !== 'object') {
      throw new Error('requestParams must be an object');
    }
    return {
      ...(options?.params || {}),
      ...(requestParams || {}),
    } as Input;
  }
  transformLocalMessage(requestParams: Partial<Input>): ChatMessage {
    return {
      content: requestParams.query,
      role: 'user',
    } as unknown as ChatMessage;
  }
  transformMessage(info: TransformMessage<ChatMessage, Output>): ChatMessage {
    const { originMessage, chunk } = info || {};
    if (!chunk || !chunk?.data || (chunk?.data && chunk?.data?.includes('[DONE]'))) {
      return {
        content: originMessage?.content || '',
        role: 'assistant',
        attachments: originMessage?.attachments || [],
      } as ChatMessage;
    }

    try {
      const data = JSON.parse(chunk.data);
      const content = originMessage?.content || '';

      // Merge attachment information to avoid data loss
      const existingAttachments = originMessage?.attachments || [];
      const newAttachments = data.attachments || [];
      const mergedAttachments = [...existingAttachments];

      // Only add new attachments to avoid duplicates
      newAttachments.forEach((newAttach) => {
        if (!mergedAttachments.some((existing) => existing.url === newAttach.url)) {
          mergedAttachments.push(newAttach);
        }
      });

      return {
        content: `${content || ''}${data.content || ''}`,
        role: 'assistant',
        attachments: mergedAttachments,
      } as ChatMessage;
    } catch {
      // If not JSON format, treat as plain text
      return {
        content: `${originMessage?.content || ''}${chunk.data || ''}`,
        role: 'assistant',
        attachments: originMessage?.attachments || [],
      } as ChatMessage;
    }
  }
}

상세 설명

  1. Agentic 서비스 스트리밍 인터페이스는 https://xxx.agent.com/api/stream이에요.

요청 파라미터:

{
  "query": "Help me summarize today's tech news"
}

응답 데이터:

id:1
data: {"content":"Okay,"}

id:2
data: {"content":"I'll help you"}

id:3
data: {"content":"summarize today's"}

id:4
data: {"content":"tech news,"}

id:5
data: {"content":"Report has been generated","attachments":[{"name":"Tech News Summary.pdf","url":"https://example.com/download/report.pdf","type":"pdf","size":102400}]}
  1. 인터페이스를 바탕으로 CustomInput과 CustomOutput 타입을 정의할 수 있어요.

CustomInput 타입:

{
  query: string;
}

JSON 문자열을 파싱해 content 필드를 추출해 이어 붙이고, 첨부 정보가 있으면 함께 처리해야 하므로 CustomOutput 타입은 다음과 같아요:

{
  data: {
    content: string;   // Text content
    attachments?: {    // Optional: Document attachments
      name: string;    // File name
      url: string;     // Download link
      type: string;    // File type, e.g., 'pdf', 'docx', 'image'
      size?: number;   // File size in bytes, optional
    }[];
  };
}

모든 응답은 텍스트 내용에 통일된 data.content 필드를, 첨부 정보에 옵션인 data.attachments 필드를 사용해요.

  1. useXChat이 생성한 messages 데이터를 Bubble.List가 바로 소비할 수 있기를 기대하므로, CustomMessage를 다음과 같이 정의할 수 있어요:
{
  content: string;
  role: 'user' | 'assistant';
  // Optional: Attachment information for displaying download links or previews
  attachments?: {
    name: string;
    url: string;
    type: string;
    size?: number;
  }[];
}
  1. 그다음 AbstractChatProvider를 상속하고 그 메서드들을 구현해 CustomProvider를 얻어요. AbstractChatProvider는 세 가지 메서드만 구현하면 돼요.
  • transformParams는 onRequest에 전달되는 파라미터를 변환해요. Provider를 인스턴스화할 때의 요청 설정에 있는 파라미터와 병합하거나 추가로 처리할 수 있어요.
  • transformLocalMessage는 onRequest에 전달된 파라미터를 로컬(사용자가 보낸) ChatMessage로 변환해 사용자 메시지 렌더링에 쓰고, 메시지 목록 렌더링을 위해 메시지도 함께 갱신해요.
  • transformMessage는 반환 데이터를 갱신할 때 데이터를 ChatMessage 데이터 타입으로 변환할 수 있고, 메시지 목록 렌더링을 위해 메시지도 함께 갱신해요.
  1. 마지막으로 CustomProvider를 인스턴스화해 useXChat에 전달하면 커스텀 Provider 사용이 완성돼요.
const [provider] = React.useState(
  new CustomProvider({
    request: XRequest<CustomInput, CustomOutput>('https://xxx.agent.com/api/stream', {
      manual: true,
    }),
  }),
);

const { onRequest, messages, setMessages, setMessage, isRequesting, abort, onReload } = useXChat({
  provider,
});
  1. 요청 보내기:
onRequest({
  query: "Help me summarize today's tech news",
});

첨부 파일을 포함한 전체 예제

서비스가 문서 첨부 반환을 지원한다면 다음처럼 사용할 수 있어요:

// Send request and handle responses with attachments
onRequest({
  query: 'Generate a project summary report',
});

// The response will include attachment information, which can be displayed as download links in message bubbles
// The messages data will include the attachments field

주의 사항:

  • 첨부 정보는 옵션이고, 모든 응답이 반드시 포함해야 하는 건 아니에요
  • 파일 타입은 pdf, docx, xlsx, png, jpg 등 일반적인 문서 형식이 될 수 있어요
  • 사용자 경험을 개선하려면 파일 크기 정보를 함께 제공하는 게 좋아요
  • 다운로드 링크는 사용자가 접근 권한을 갖도록 보장해야 해요

사용 예제

Chat Provider 기여하기

새로운 Chat Provider에 대한 커뮤니티 기여를 환영해요! Chat Provider 개발 시 다음 스펙을 따라 주세요.

기여 가이드

이 가이드는 Ant Design에 기여하는 데 도움을 줘요. 이슈나 pull request를 제출하기 전에 이 기여 가이드를 몇 분 읽어 주세요.

기여 표준

Chat Provider는 다음 스펙을 따라야 해요:

  • Chat Provider는 packages/x-sdk/src/chat-providers 디렉터리에 포함되어야 해요.
  • Chat Provider 타입은 packages/x-sdk/src/chat-providers/type 디렉터리에 포함되어야 해요.

네이밍 규칙

Chat Provider 테마 파일은 다음 네이밍 규칙을 따라야 해요:

  • Chat Provider 테마 파일은 camelCase 형식으로 [Vendor][Type][Version].ts처럼 이름 지어야 해요.
  • 특정 모델은 camelCase 형식으로 [Vendor][ModelName].ts처럼 바로 이름 지을 수 있어요.

더 알아보기

Provider가 만들어 낸 메시지를 그리는 컴포넌트가 궁금하면 말풍선(Bubble) 문서를 함께 보세요. useXChat 훅 자체의 상세 스펙은 X SDK 문서에서 확인할 수 있어요.