Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,132 @@
/** @jsx createElement */
import { cx } from '../../lib';
import { createButtonComponent } from '../Button';

import type { Renderer } from '../../types';
import type { ChatStatus } from './types';

export type PromptSuggestionsClassNames = {
/**
* Class name for the root element
*/
root?: string;
/**
* Class name for the header element
*/
header?: string;
/**
* Class name for the suggestions list
*/
suggestionsList?: string;
/**
* Class name for each suggestion item
*/
suggestionItem?: string;
/**
* Class name for the loading state
*/
loading?: string;
};

export type PromptSuggestionsTranslations = {
/**
* Text for the suggestions header
*/
suggestionsHeaderText?: string;
};

export type PromptSuggestionsProps = {
/**
* Status of the chat
*/
status: ChatStatus;
/**
* List of prompt suggestions
*/
suggestions?: string[];
/**
* Callback when a suggestion is clicked
*/
onSuggestionClick?: (suggestion: string) => void;
/**
* Custom loading component
*/
loadingComponent?: () => JSX.Element;
/**
* Optional class names
*/
classNames?: PromptSuggestionsClassNames;
/**
* Optional translations
*/
translations?: PromptSuggestionsTranslations;
};

export function createPromptSuggestionsComponent({
createElement,
}: Pick<Renderer, 'createElement'>) {
const Button = createButtonComponent({ createElement });

return function PromptSuggestions(userProps: PromptSuggestionsProps) {
const {
status,
suggestions,
onSuggestionClick,
loadingComponent: LoadingComponent,
classNames = {},
translations: userTranslations,
} = userProps;

const cssClasses = {
root: cx('ais-PromptSuggestions', classNames.root),
header: cx('ais-PromptSuggestions-header', classNames.header),
suggestionsList: cx(
'ais-PromptSuggestions-list',
classNames.suggestionsList
),
suggestionItem: cx(
'ais-PromptSuggestions-item',
classNames.suggestionItem
),
loading: cx('ais-PromptSuggestions-loading', classNames.loading),
};

const translations: Required<PromptSuggestionsTranslations> = {
suggestionsHeaderText: 'Suggestions',
...userTranslations,
};

if (status === 'streaming') {
return LoadingComponent ? (
<LoadingComponent />
) : (
<span className={cssClasses.loading}>Loading suggestions...</span>
);
}

if (status === 'ready' && suggestions && suggestions.length > 0) {
return (
<div className={cssClasses.root}>
<h3 className={cssClasses.header}>
{translations.suggestionsHeaderText}
</h3>

<ul className={cssClasses.suggestionsList}>
{suggestions.map((suggestion, index) => (
<li key={index} className={cssClasses.suggestionItem}>
<Button
variant="ghost"
onClick={() => onSuggestionClick?.(suggestion)}
>
{suggestion}
</Button>
</li>
))}
</ul>
</div>
);
}

return null;
};
}
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ export * from './chat/ChatMessageLoader';
export * from './chat/ChatMessageError';
export * from './chat/ChatPrompt';
export * from './chat/ChatToggleButton';
export * from './chat/PromptSuggestions';
export * from './chat/icons';
export * from './chat/types';
export * from './FrequentlyBoughtTogether';
Expand Down
23 changes: 22 additions & 1 deletion packages/instantsearch.js/src/connectors/chat/connectChat.ts
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,10 @@ export type ChatRenderState<TUiMessage extends UIMessage = UIMessage> = {
* Tools configuration with addToolResult bound, ready to be used by the UI.
*/
tools: ClientSideTools;
/**
* Suggestions received from the AI model.
*/
suggestions?: string[];
} & Pick<
AbstractChat<TUiMessage>,
| 'addToolResult'
Expand Down Expand Up @@ -113,6 +117,10 @@ export type ChatConnectorParams<TUiMessage extends UIMessage = UIMessage> = (
* Whether to resume an ongoing chat generation stream.
*/
resume?: boolean;
/**
* Whether to enable caching of chat messages.
*/
enableCaching?: boolean;
/**
* Configuration for client-side tools.
*/
Expand Down Expand Up @@ -146,7 +154,12 @@ export default (function connectChat<TWidgetParams extends UnknownWidgetParams>(
) => {
warning(false, 'Chat is not yet stable and will change in the future.');

const { resume = false, tools = {}, ...options } = widgetParams || {};
const {
resume = false,
enableCaching = true,
tools = {},
...options
} = widgetParams || {};

let _chatInstance: Chat<TUiMessage>;
let input = '';
Expand All @@ -156,6 +169,7 @@ export default (function connectChat<TWidgetParams extends UnknownWidgetParams>(
let setInput: ChatRenderState<TUiMessage>['setInput'];
let setOpen: ChatRenderState<TUiMessage>['setOpen'];
let setIsClearing: (value: boolean) => void;
let suggestions: string[] | undefined;

const setMessages = (
messagesParam: TUiMessage[] | ((m: TUiMessage[]) => TUiMessage[])
Expand Down Expand Up @@ -216,7 +230,13 @@ export default (function connectChat<TWidgetParams extends UnknownWidgetParams>(
return new Chat({
...options,
transport,
enableCaching,
sendAutomaticallyWhen: lastAssistantMessageIsCompleteWithToolCalls,
onData: ({ data }) => {
if (data && typeof data === 'object' && 'suggestions' in data) {
suggestions = (data as any).suggestions as string[] | undefined;
}
},
onToolCall({ toolCall }) {
const tool = tools[toolCall.toolName];

Expand Down Expand Up @@ -356,6 +376,7 @@ export default (function connectChat<TWidgetParams extends UnknownWidgetParams>(
setInput,
setOpen,
setMessages,
suggestions,
isClearing,
clearMessages,
onClearTransitionEnd,
Expand Down
34 changes: 29 additions & 5 deletions packages/instantsearch.js/src/lib/chat/chat.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,11 +33,26 @@ export class ChatState<TUiMessage extends UIMessage>

constructor(
id: string | undefined = undefined,
initialMessages: TUiMessage[] = getDefaultInitialMessages<TUiMessage>(id)
initialMessages: TUiMessage[] = [],
enableCaching: boolean = true
) {
this._messages = initialMessages;
this._messages =
enableCaching && initialMessages.length === 0
? getDefaultInitialMessages<TUiMessage>(id)
: [];
const saveMessagesInLocalStorage = () => {
if (this.status === 'ready') {
if (this.status === 'ready' && enableCaching) {
// We remove data-* parts before saving as it causes validation errors on the API side
this.messages.forEach((message) => {
if (message.role === 'assistant') {
const newParts = message.parts.filter(
(part) => !part.type.includes('data-')
);

message.parts = newParts;
}
});

try {
sessionStorage.setItem(CACHE_KEY + id, JSON.stringify(this.messages));
} catch (e) {
Expand Down Expand Up @@ -76,6 +91,10 @@ export class ChatState<TUiMessage extends UIMessage>
this._callMessagesCallbacks();
}

get data(): unknown {
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is an alternative approach that would be similar to the dashboard POC. I've left it here in case the integration with the backend requires this approach instead of the onData one.

return this.data;
}

pushMessage = (message: TUiMessage) => {
this._messages = this._messages.concat(message);
this._callMessagesCallbacks();
Expand Down Expand Up @@ -143,13 +162,18 @@ export class Chat<
constructor({
messages,
agentId,
enableCaching = true,
...init
}: ChatInit<TUiMessage> & { agentId?: string }) {
const state = new ChatState(agentId, messages);
}: ChatInit<TUiMessage> & { agentId?: string; enableCaching?: boolean }) {
const state = new ChatState(agentId, messages, enableCaching);
super({ ...init, state });
this._state = state;
}

get data() {
return this._state.data;
}

'~registerMessagesCallback' = (onChange: () => void): (() => void) =>
this._state['~registerMessagesCallback'](onChange);

Expand Down
1 change: 1 addition & 0 deletions packages/instantsearch.js/src/widgets/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -60,3 +60,4 @@ export { default as voiceSearch } from './voice-search/voice-search';
export { default as frequentlyBoughtTogether } from './frequently-bought-together/frequently-bought-together';
export { default as lookingSimilar } from './looking-similar/looking-similar';
export { default as chat } from './chat/chat';
export { default as promptSuggestions } from './prompt-suggestions/prompt-suggestions';
Loading