0.0.4 • Published 4 months ago

ax-sdk-chatbot v0.0.4

Weekly downloads
-
License
MIT
Repository
-
Last release
4 months ago

ax-sdk-chatbot

version: 0.0.4

installation

npm

npm i ax-sdk-chatbot

yarn

yarn add ax-sdk-chatbot

Quick Use

vite

Dependency

  • React ver: 18.x.x

Use In Root

  • main.tsx
import { createRoot } from "react-dom/client";

import CoxwaveChatSDK from "ax-sdk-chatbot";

import App from "./App.tsx";

import "./index.css";

const coxwaveSDK = new CoxwaveChatSDK({
  clientUrl: `${import.meta.env.VITE_BACKEND_URL}`,
  apiKey: `${import.meta.env.VITE_COXWAVE_HEADER_KEY}`,
  isProd?: boolean;
});

createRoot(document.getElementById("root")!).render(<App />);

coxwaveSDK.renderChat({
  chatApiParams: {
    userId: "user_id",
    courseId: "course_id",
    courseName: "course_name",
    courseCategory: "course_category",
    courseSubCategory: "course_sub_category",
    clipId: "clip_id",
    clipPlayHead: clip_play_head_number,
    commandId: "command_id",
  },
  shortcutKey: {
    openChat: { key: "/", modifier: "" },
    sendChat: { key: "Enter", modifier: "" },
  },
});

Use Custom Hook

  • main.tsx
import { createRoot } from "react-dom/client";

import CoxWaveChatSDK from "ax-sdk-chatbot";

import App from "./App.tsx";

import "./index.css";

const coxwaveSDK = new CoxwaveChatSDK({
  clientUrl: `${import.meta.env.VITE_BACKEND_URL}`,
  apiKey: `${import.meta.env.VITE_COXWAVE_HEADER_KEY}`,
});
// isProd는 false가 default


createRoot(document.getElementById("root")!).render(
  <App coxwaveSDK={coxwaveSDK} />
);
  • App.tsx (can use any component)
    import { useEffect, useRef } from "react";

import CoxwaveChatSDK from "ax-sdk-chatbot";

import "./App.css";

const renderChatConfig = { chatApiParams: { userId: "user_id", courseId: "course_id", courseName: "course_name", courseCategory: "course_category", courseSubCategory: "course_sub_category", clipId: "clip_id", clipPlayHead: clip_play_head_number, commandId: "command_id", }, shortcutKey: { openChat: { key: "/", modifier: "" as "" | "ctrlKey" | "altKey" | "shiftKey" | "metaKey", }, sendChat: { key: "Enter", modifier: "" as "" | "ctrlKey" | "altKey" | "shiftKey" | "metaKey", }, }, };

function App({ coxwaveSDK }: { coxwaveSDK: CoxwaveChatSDK }) { const isDeletedRef = useRef(false); const sdkRef = useRef(coxwaveSDK);

useEffect(() => { if (isDeletedRef.current) { sdkRef.current.destroyChat(); } else { sdkRef.current.renderChat(renderChatConfig); }

return () => {
  sdkRef.current.destroyChat();
};

}, []);

return ( <>

  <div>
    <button
      onClick={() => {
        isDeletedRef.current = !isDeletedRef.current;
        if (isDeletedRef.current) {
          sdkRef.current.destroyChat();
        } else {
          sdkRef.current.renderChat(renderChatConfig);
        }
      }}
    >
      {isDeletedRef.current ? "삭제" : "생성"}
    </button>
  </div>
</>

); }

export default App;

### vite 
#### Dependency
- Next ver: 13.x.x
- React ver: 18.x.x

#### Use Dynamic import
- page.tsx
```ts
import dynamic from "next/dynamic";

const ChatComponent = dynamic(() => import("./ChatComponent"), {
  ssr: false,
});

export default function Home() {
  return (
    <div>
      <ChatComponent />
    </div>
  );
}
  • ChatComponent.tsx
"use client";

import { useEffect, useState } from "react";

import CoxwaveChatSDK from "ax-sdk-chatbot";

const coxwaveChatSDKInstance = new CoxwaveChatSDK({
  clientUrl: YOUR_API_BASE_URL,
  apiKey: YOUR_API_KEY,
});

const ChatComponent = () => {
  const [isDelelted, setIsDelelted] = useState(false);

  useEffect(() => {
    if (isDelelted) {
      coxwaveChatSDKInstance.destroyChat();
    } else {
      coxwaveChatSDKInstance.renderChat({
        chatApiParams: {
          userId: "user_id",
          courseId: "course_id",
          courseName: "course_name",
          courseCategory: "course_category",
          courseSubCategory: "course_sub_category",
          clipId: "clip_id",
          clipPlayHead: clip_play_head_number,
          commandId: "command_id",
        },
        shortcutKey: {
          openChat: { key: "/", modifier: "" },
          sendChat: { key: "Enter", modifier: "" },
        },
      });
    }

    return () => {
      coxwaveChatSDKInstance.destroyChat(); // 클린업 함수
    };
  }, [isDelelted]);


  return (
    <div onClick={() => setIsDelelted((prev) => !prev)}>
      {isDelelted ? "챗봇 생성" : "챗봇 제거"}
    </div>
  );
};

export default ChatComponent;

Use await import

  • ChatComponent.tsx
"use client";

import { useEffect, useState } from "react";

const ChatComponent = () => {
  const [isDelelted, setIsDelelted] = useState(false);

  useEffect(() => {
    const loadChatSdk = async () => {
      try {
        const chatSdkModule = await import("ax-sdk-chatbot");
        const CoxwaveChatSDK = chatSdkModule.default ?? chatSdkModule; // default 없을 경우 대비

        const coxwaveChatSDKInstance = new CoxwaveChatSDK({
          clientUrl: YOUR_API_BASE_URL,
          apiKey: YOUR_API_KEY,
        });

        coxwaveChatSDKInstance.renderChat({
          chatApiParams: {
            userId: "user_id",
            courseId: "course_id",
            courseName: "course_name",
            courseCategory: "course_category",
            courseSubCategory: "course_sub_category",
            clipId: "clip_id",
            clipPlayHead: clip_play_head_number,
            commandId: "command_id",
          },
          shortcutKey: {
            openChat: { key: "/", modifier: "" },
            sendChat: { key: "Enter", modifier: "" },
          },
        });

        // coxwaveChatSdkInstance.destroyChat();
        return () => {
          console.log("ChatComponent unmounted");
          coxwaveChatSDKInstance.destroyChat();
        };
      } catch (error) {
        console.error("Failed to initialize chat SDK:", error);
      }
    };

    loadChatSdk();
  }, []);

  return (
    <div onClick={() => setIsDelelted((prev) => !prev)}>
      {isDelelted ? "챗봇 생성" : "챗봇 제거"}
    </div>
  );
};

export default ChatComponent;

Trouble Shooting

StrickMode

  app-index.js:
  32 Warning: Attempted to synchronously unmount a root while React was already rendering. 
  React cannot finish unmounting the root until the current render has completed, which may lead to a race condition.
  • solution: turn off React strickMode

If you use, Next 14, 15 & React 19 Ver

  • ReactCurrentOwner issue occurred: This error originates from React Fiber and is likely due to a version mismatch between the SDK and the internal React logic after React 19.
  • If you upgrade to Next.js 14 or 15, you may encounter this issue. In the case of Next.js 15, it requires compatibility with React 19.

When you use useState instead useRef in Vite

  index.ts:
  167 Warning: Attempted to synchronously unmount a root while React was already rendering.
  React cannot finish unmounting the root until the current render has completed, which may lead to a race condition.
  • If the SDK's lifecycle is not managed through Ref, a Fiber Sync~ warning will occur.
  • React Fiber acts like an operating system, autonomously determining the priority of the virtual DOM's lifecycle. However, if this priority system is unexpectedly disrupted (e.g., by calling root.unmount();), a warning is triggered.
  • In the case of coxwaveChatSdkInstance.destroyChat(), it removes React by calling root.unmount(). Therefore, if another React root dynamically manages this instance, it may cause a warning to appear.

Types

SDK Class

type CoxwaveChatSDKType = {
  clientUrl: string;
  apiKey: string;
  isProd?: boolean;
};

const coxwaveChatSDKInstance = new CoxwaveChatSDK({
  clientUrl: "~",
  apiKey: "~",
});

renderChat Method

type ShortcutKeyPropertiesType = {
  key: string;
  modifier: "ctrlKey" | "altKey" | "shiftKey" | "metaKey" | "";
};

type ShortcutKeyType = {
  openChat: ShortcutKeyPropertiesType;
  sendChat: ShortcutKeyPropertiesType;
};

type ChatApiParamsType = {
  userId: string;
  courseId: string;
  courseName: string;
  courseCategory: string;
  courseSubCategory: string;
  clipId: string | null;
  clipPlayHead: number | null;
  commandId: string;
};

async renderChat({
    chatApiParams,
    shortcutKey,
  }: {
    chatApiParams: ChatApiParamsType;
    shortcutKey?: ShortcutKeyType;
  })

license

MIT

Copyright (c) 2025-present, Coxwave