@asgard-js/react v0.0.24
AsgardJs React
This package provides React components and hooks for integrating with the Asgard AI platform, allowing you to build interactive chat interfaces.
Installation
To install the React package, use the following command:
yarn add @asgard-js/core @asgard-js/reactUsage
Here's a basic example of how to use the React components:
import React, { useRef } from 'react';
import { Chatbot } from '@asgard-js/react';
const chatbotRef = useRef(null);
const App = () => {
return (
<div style={{ width: '800px', position: 'relative' }}>
<button
style={{
position: 'absolute',
top: '80px',
right: '50%',
transform: 'translateX(50%)',
zIndex: 10,
border: '1px solid white',
borderRadius: '5px',
color: 'white',
backgroundColor: 'transparent',
cursor: 'pointer',
padding: '0.5rem 1rem',
}}
onClick={() =>
chatbotRef.current?.serviceContext?.sendMessage?.({ text: 'Hello' })
}
>
Send a message from outside of chatbot
</button>
<Chatbot
ref={chatbotRef}
title="Asgard AI Chatbot"
config={{
apiKey: 'your-api-key',
endpoint:
'https://api.asgard-ai.com/ns/{namespace}/bot-provider/{botProviderId}/message/sse',
botProviderEndpoint:
'https://api.asgard-ai.com/ns/{namespace}/bot-provider/{botProviderId}',
onExecutionError: (error) => {
console.error('Execution error:', error);
},
transformSsePayload: (payload) => {
return payload;
},
}}
enableLoadConfigFromService={true}
customChannelId="your-channel-id"
initMessages={[]}
debugMode={false}
fullScreen={false}
avatar="https://example.com/avatar.png"
botTypingPlaceholder="Bot is typing..."
onReset={() => {
console.log('Chat reset');
}}
onClose={() => {
console.log('Chat closed');
}}
onSseMessage={(response, ctx) => {
if (response.eventType === 'asgard.run.done') {
console.log('onSseMessage', response, ctx.conversation);
setTimeout(() => {
// delay some time to wait for the serviceContext to be available
chatbotRef.current?.serviceContext?.sendMessage?.({
text: 'Say hi after 5 seconds',
});
}, 5000);
}
}}
/>
</div>
);
};
export default App;Chatbot Component Props
- title:
string- The title of the chatbot. - config:
ClientConfig- Configuration object for the Asgard service client, including:apiKey:string(required) - API key for authenticationendpoint:string(required) - API endpoint URLbotProviderEndpoint?:string- Bot provider endpoint URLtransformSsePayload?:(payload: FetchSsePayload) => FetchSsePayload- SSE payload transformerdebugMode?:boolean- Enable debug mode, defaults tofalseonRunInit?:InitEventHandler- Handler for run initialization eventsonMessage?:MessageEventHandler- Handler for message eventsonToolCall?:ToolCallEventHandler- Handler for tool call eventsonProcess?:ProcessEventHandler- Handler for process eventsonRunDone?:DoneEventHandler- Handler for run completion eventsonRunError?:ErrorEventHandler- Error handler for execution errors
- customActions?:
ReactNode[]- Custom actions to display on the chatbot header - enableLoadConfigFromService?:
boolean- Enable loading configuration from service - maintainConnectionWhenClosed?:
boolean- Maintain connection when chat is closed, defaults tofalse - loadingComponent?:
ReactNode- Custom loading component - asyncInitializers?:
Record<string, () => Promise<unknown>>- Asynchronous initializers for app initialization before rendering any component. Good for loading data or other async operations as the initial state. It only works whenenableLoadConfigFromServiceis set totrue. - customChannelId:
string- Custom channel identifier for the chat session - initMessages:
ConversationMessage[]- Initial messages to display in the chat - fullScreen:
boolean- Display chatbot in full screen mode, defaults tofalse - avatar:
string- URL for the chatbot's avatar image - botTypingPlaceholder:
string- Text to display while the bot is typing - theme:
Partial<AsgardThemeContextValue>- Custom theme configuration - onReset:
() => void- Callback function when chat is reset - onClose:
() => void- Callback function when chat is closed - onSseMessage:
(response: SseResponse, ctx: AsgardServiceContextValue) => void- Callback function when SSE message is received. It would be helpful if using with the ref to provide some context and conversation data and do some proactively actions like sending messages to the bot. - ref:
ForwardedRef<ChatbotRef>- Forwarded ref to access the chatbot instance. It can be used to access the chatbot instance and do some actions like sending messages to the bot. ChatbotRef extends the ref of the chatbot instance and provides some additional methods likeserviceContext.sendMessageto interact with the chatbot instance.
Theme Configuration
The theme configuration can be obtained from the bot provider metadata of annotations field and theme props.
The priority of themes is as follows (high to low):
- Theme from props
- Theme from annotations from bot provider metadata
- Default theme
export interface AsgardThemeContextValue {
chatbot: Pick<
CSSProperties,
| 'width'
| 'height'
| 'maxWidth'
| 'minWidth'
| 'maxHeight'
| 'minHeight'
| 'backgroundColor'
| 'borderColor'
| 'borderRadius'
> & {
contentMaxWidth?: CSSProperties['maxWidth'];
style?: CSSProperties;
header?: Partial<{
style: CSSProperties;
title: {
style: CSSProperties;
};
}>;
body?: Partial<{
style: CSSProperties;
}>;
footer?: Partial<{
style: CSSProperties;
textArea: {
style: CSSProperties;
};
submitButton: {
style: CSSProperties;
};
speechInputButton: {
style: CSSProperties;
};
}>;
};
botMessage: Pick<CSSProperties, 'color' | 'backgroundColor'>;
userMessage: Pick<CSSProperties, 'color' | 'backgroundColor'>;
template?: Partial<{
/**
* first level for common/shared properties.
* Check MessageTemplate type for more details (packages/core/src/types/sse-response.ts).
*/
quickReplies?: Partial<{
style: CSSProperties;
button: {
style: CSSProperties;
};
}>;
TextMessageTemplate: Partial<{ style: CSSProperties }>;
HintMessageTemplate: Partial<{ style: CSSProperties }>;
ImageMessageTemplate: Partial<{ style: CSSProperties }>;
ChartMessageTemplate: Partial<{ style: CSSProperties }>;
ButtonMessageTemplate: Partial<{ style: CSSProperties }>;
CarouselMessageTemplate: Partial<{ style: CSSProperties }>;
// Didn't implement yet
VideoMessageTemplate: Partial<{ style: CSSProperties }>;
AudioMessageTemplate: Partial<{ style: CSSProperties }>;
LocationMessageTemplate: Partial<{ style: CSSProperties }>;
}>;
}Default Theme
The default theme uses CSS variables for consistent styling:
const defaultTheme = {
chatbot: {
width: '375px',
height: '640px',
backgroundColor: 'var(--asg-color-bg)',
borderColor: 'var(--asg-color-border)',
borderRadius: 'var(--asg-radius-md)',
contentMaxWidth: '1200px',
style: {},
header: {
style: {},
title: {
style: {},
},
},
body: {
style: {},
},
footer: {
style: {},
textArea: {
style: {},
},
submitButton: {
style: {},
},
speechInputButton: {
style: {},
},
},
},
botMessage: {
color: 'var(--asg-color-text)',
backgroundColor: 'var(--asg-color-secondary)',
},
userMessage: {
color: 'var(--asg-color-text)',
backgroundColor: 'var(--asg-color-primary)',
},
template: {
quickReplies: {
style: {},
button: {
style: {},
},
},
TextMessageTemplate: {
style: {},
},
HintMessageTemplate: {
style: {},
},
ImageMessageTemplate: {
style: {},
},
VideoMessageTemplate: {
style: {},
},
AudioMessageTemplate: {
style: {},
},
LocationMessageTemplate: {
style: {},
},
ChartMessageTemplate: {
style: {},
},
ButtonMessageTemplate: {
style: {},
},
CarouselMessageTemplate: {
style: {},
},
},
};Usage Example
const App = () => {
const customTheme = {
chatbot: {
width: '400px',
height: '600px',
backgroundColor: '#ffffff',
borderRadius: '12px',
},
botMessage: {
backgroundColor: '#f0f0f0',
},
userMessage: {
backgroundColor: '#007bff',
color: '#ffffff',
},
};
return (
<Chatbot
// ... other props
theme={customTheme}
/>
);
};Note: When fullScreen prop is set to true, the chatbot's width and height will be set to 100vw and 100vh respectively, and borderRadius will be set to zero, regardless of theme settings.
Development
To develop the React package locally, follow these steps:
Clone the repository and navigate to the project root directory.
Install dependencies:
yarn install- Start development:
You can use the following commands to work with the React package:
# Lint the React package
yarn lint:react
# Run tests
yarn test:react
# Build the package
yarn build:react
# Watch mode for development
yarn watch:react
# Run the demo application
yarn serve:react-demoFor working with both core and React packages:
# Lint both packages
yarn lint:packages
# Build core package (required for React package)
yarn build:core
# Release packages
yarn release:core # Release core package
yarn release:react # Release React packageAll builds will be available in the dist directory of their respective packages.
Contributing
We welcome contributions! Please read our contributing guide to get started.
License
This project is licensed under the MIT License - see the LICENSE file for details.
6 months ago
7 months ago
7 months ago
7 months ago
7 months ago
8 months ago
8 months ago
8 months ago
8 months ago
8 months ago
8 months ago
8 months ago
8 months ago
8 months ago
8 months ago
9 months ago
9 months ago
9 months ago
10 months ago
10 months ago
11 months ago
11 months ago
11 months ago
11 months ago