Skip to content

Commit

Permalink
feature: fully working suggested questions for a single product
Browse files Browse the repository at this point in the history
  • Loading branch information
skeptrunedev committed Dec 16, 2024
1 parent cf431d6 commit 1becbfc
Show file tree
Hide file tree
Showing 15 changed files with 337 additions and 153 deletions.
1 change: 0 additions & 1 deletion clients/search-component/example/src/routes/ecommerce.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@
import { TrieveModalSearch } from "../../../src/index";
import "../../../dist/index.css";
import { useState } from "react";

import { createFileRoute } from "@tanstack/react-router";

export const Route = createFileRoute("/ecommerce")({
Expand Down
6 changes: 3 additions & 3 deletions clients/search-component/src/TrieveModal/Chat/ChatMode.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import React, { Suspense } from "react";
import React, { Suspense, useEffect, useRef } from "react";
import { useModalState } from "../../utils/hooks/modal-context";
import { AIInitialMessage } from "./AIInitalMessage";
import { useChatState } from "../../utils/hooks/chat-context";
Expand Down Expand Up @@ -27,9 +27,9 @@ export const ChatMode = () => {
stopGeneratingMessage,
} = useChatState();

const chatInput = React.useRef<HTMLInputElement>(null);
const chatInput = useRef<HTMLInputElement>(null);

React.useEffect(() => {
useEffect(() => {
if (mode == "chat" && open) {
chatInput.current?.focus();
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -148,7 +148,10 @@ export const ProductItem = ({
</h6>
{group && (
<button
title={`Chat with ${betterGroupName || group.name}`}
title={`Chat with ${(betterGroupName || group.name).replace(
/<[^>]*>/g,
""
)}`}
className="chat-product-button"
onClick={(e) => {
e.preventDefault();
Expand Down
5 changes: 4 additions & 1 deletion clients/search-component/src/TrieveModal/Tags.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,10 @@ export const Tags = () => {
(props.tags?.length ? (
<ul className="tags">
{[ALL_TAG, ...props.tags].map((tag, idx) => (
<li className={currentTag === tag.tag ? "active" : ""} key={tag.tag}>
<li
className={currentTag === tag.tag ? "active" : ""}
key={tag.tag ?? idx}
>
<button onClick={() => setCurrentTag(tag.tag)}>
{tag.iconClassName && <i className={tag.iconClassName}></i>}
{tag.icon && typeof tag.icon === "function" && tag.icon()}
Expand Down
4 changes: 0 additions & 4 deletions clients/search-component/src/TrieveModal/index.css
Original file line number Diff line number Diff line change
Expand Up @@ -253,10 +253,6 @@ body {
}
}

.trieve-footer.ecommerce {
@apply -mx-4;
}

.commands.ecommerce {
visibility: hidden;
}
Expand Down
29 changes: 28 additions & 1 deletion clients/search-component/src/TrieveModal/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -10,14 +10,16 @@ import {
import { useKeyboardNavigation } from "../utils/hooks/useKeyboardNavigation";
import { ModeSwitch } from "./ModeSwitch";
import { OpenModalButton } from "./OpenModalButton";
import { ChatProvider } from "../utils/hooks/chat-context";
import { ChatProvider, useChatState } from "../utils/hooks/chat-context";
import r2wc from "@r2wc/react-to-web-component";
import { setClickTriggers } from "../utils/hooks/setClickTriggers";
import { ChunkGroup } from "trieve-ts-sdk";

const Modal = () => {
useKeyboardNavigation();
setClickTriggers();
const { mode, open, setOpen, setMode, props } = useModalState();
const { askQuestion, chatWithGroup } = useChatState();

useEffect(() => {
const script = document.createElement("script");
Expand All @@ -26,6 +28,31 @@ const Modal = () => {
script.setAttribute("data-auto-replace-svg", "");

document.head.appendChild(script);

const eventListener: EventListener = (e: Event) => {
const customEvent = e as CustomEvent<{
message: string;
group: ChunkGroup;
betterGroupName?: string;
}>;
if (customEvent.detail?.message && customEvent.detail.group) {
setOpen(true);
if (customEvent.detail.betterGroupName) {
customEvent.detail.group.name = customEvent.detail.betterGroupName;
}
chatWithGroup(
customEvent.detail.group,
customEvent.detail.betterGroupName
);
askQuestion(customEvent.detail.message, customEvent.detail.group);
}
};
window.removeEventListener("trieve-start-chat-with-group", eventListener);
window.addEventListener("trieve-start-chat-with-group", eventListener);

return () => {
window.removeEventListener("trieve-start-chat-with-group", eventListener);
};
}, []);

useEffect(() => {
Expand Down
25 changes: 17 additions & 8 deletions clients/search-component/src/utils/hooks/chat-context.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ function removeBrackets(str: string) {
}

const ChatContext = createContext<{
askQuestion: (question?: string) => Promise<void>;
askQuestion: (question?: string, group?: ChunkGroup) => Promise<void>;
isLoading: boolean;
messages: Messages;
currentQuestion: string;
Expand Down Expand Up @@ -167,18 +167,22 @@ function ChatProvider({ children }: { children: React.ReactNode }) {
const createQuestion = async ({
id,
question,
group,
}: {
id?: string;
question?: string;
group?: ChunkGroup;
}) => {
setIsLoading(true);

const curGroup = group || currentGroup;

// Use group search
if (currentGroup) {
if (curGroup) {
// Should already be preloaded when group selected to chat with
const groupChunks = await cached(() => {
return getAllChunksForGroup(currentGroup.id, trieveSDK);
}, `chunk-ids-${currentGroup.id}`);
return getAllChunksForGroup(curGroup.id, trieveSDK);
}, `chunk-ids-${curGroup.id}`);

const { reader, queryId } = await trieveSDK.ragOnChunkReaderWithQueryId(
{
Expand Down Expand Up @@ -220,7 +224,7 @@ function ChatProvider({ children }: { children: React.ReactNode }) {
}
};

const chatWithGroup = async (group: ChunkGroup, betterGroupName?: string) => {
const chatWithGroup = (group: ChunkGroup, betterGroupName?: string) => {
if (betterGroupName) {
group.name = betterGroupName;
}
Expand Down Expand Up @@ -256,7 +260,7 @@ function ChatProvider({ children }: { children: React.ReactNode }) {
clearConversation();
};

const askQuestion = async (question?: string) => {
const askQuestion = async (question?: string, group?: ChunkGroup) => {
isDoneReading.current = false;
setMessages((m) => [
...m,
Expand All @@ -270,10 +274,15 @@ function ChatProvider({ children }: { children: React.ReactNode }) {
],
]);

if (!currentTopic) {
if (!currentGroup && group) {
chatWithGroup(group);
setCurrentGroup(group);
}

if (!currentTopic && !currentGroup && !group) {
await createTopic({ question: question || currentQuestion });
} else {
await createQuestion({ question: question || currentQuestion });
await createQuestion({ question: question || currentQuestion, group });
}

setCurrentQuestion("");
Expand Down
11 changes: 11 additions & 0 deletions clients/ts-sdk/openapi.json
Original file line number Diff line number Diff line change
Expand Up @@ -15287,6 +15287,10 @@
"SingleProductOptions": {
"type": "object",
"properties": {
"groupTrackingId": {
"type": "string",
"nullable": true
},
"productDescriptionHtml": {
"type": "string",
"nullable": true
Expand All @@ -15299,6 +15303,13 @@
"type": "string",
"nullable": true
},
"productQuestions": {
"type": "array",
"items": {
"type": "string"
},
"nullable": true
},
"productTrackingId": {
"type": "string",
"nullable": true
Expand Down
2 changes: 2 additions & 0 deletions clients/ts-sdk/src/types.gen.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2853,9 +2853,11 @@ export type SemanticBoost = {
};

export type SingleProductOptions = {
groupTrackingId?: (string) | null;
productDescriptionHtml?: (string) | null;
productName?: (string) | null;
productPrimaryImageUrl?: (string) | null;
productQuestions?: Array<(string)> | null;
productTrackingId?: (string) | null;
recSearchQuery?: (string) | null;
};
Expand Down
41 changes: 41 additions & 0 deletions frontends/dashboard/src/pages/dataset/PublicPageSettings.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -866,6 +866,7 @@ export const SingleProductOptions = () => {
const { extraParams, setExtraParams } = usePublicPage();
const [defaultDetailOpen] = createSignal(
!!extraParams.singleProductOptions?.productTrackingId ||
!!extraParams.singleProductOptions?.groupTrackingId ||
!!extraParams.singleProductOptions?.productName ||
!!extraParams.singleProductOptions?.productDescriptionHtml ||
!!extraParams.singleProductOptions?.productPrimaryImageUrl,
Expand Down Expand Up @@ -922,6 +923,46 @@ export const SingleProductOptions = () => {
/>
</div>
</div>
<div class="flex gap-4 pb-2 pt-2">
<div class="grow">
<label class="block">Group Tracking ID</label>
<input
placeholder="Tracking ID of the product to display"
value={extraParams.singleProductOptions?.groupTrackingId || ""}
onInput={(e) => {
setExtraParams("singleProductOptions", {
...extraParams.singleProductOptions,
groupTrackingId: e.currentTarget.value,
});
}}
class="block w-full rounded border border-neutral-300 px-3 py-1.5 shadow-sm placeholder:text-neutral-400 focus:outline-magenta-500 sm:text-sm sm:leading-6"
/>
</div>
<div class="grow">
<div class="flex items-center gap-1">
<label class="block" for="">
Product Questions
</label>
<Tooltip
tooltipText="Example AI questions which may be asked about the product"
body={<FaRegularCircleQuestion class="h-3 w-3 text-black" />}
/>
</div>
<MultiStringInput
placeholder="What does it do?..."
value={extraParams.singleProductOptions?.productQuestions || []}
onChange={(e) => {
setExtraParams("singleProductOptions", {
...extraParams.singleProductOptions,
productQuestions: e,
});
}}
addLabel="Add Product Question"
addClass="text-sm"
inputClass="block w-full rounded border border-neutral-300 px-3 py-1.5 shadow-sm placeholder:text-neutral-400 focus:outline-magenta-500 sm:text-sm sm:leading-6"
/>
</div>
</div>
<div class="flex gap-4 pb-2 pt-2">
<div class="grow">
<label class="block">Recommendation Search Query</label>
Expand Down
2 changes: 2 additions & 0 deletions server/src/handlers/page_handler.rs
Original file line number Diff line number Diff line change
Expand Up @@ -140,10 +140,12 @@ pub struct OpenGraphMetadata {
#[serde(rename_all = "camelCase")]
pub struct SingleProductOptions {
product_tracking_id: Option<String>,
group_tracking_id: Option<String>,
product_name: Option<String>,
product_description_html: Option<String>,
product_primary_image_url: Option<String>,
rec_search_query: Option<String>,
product_questions: Option<Vec<String>>,
}

#[derive(Serialize, Deserialize, Debug, Clone, ToSchema, Default)]
Expand Down
4 changes: 2 additions & 2 deletions server/src/public/navbar.html
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
<nav class="bg-white border-b">
<div
class="max-w-screen-2xl mx-auto w-full p-2 flex items-center justify-center flex-col gap-4 sm:justify-between sm:!flex-row"
class="max-w-screen-2xl mx-auto w-full p-2 flex items-center justify-center flex-col gap-2 sm:gap-4 sm:justify-between sm:!flex-row"
>
<a class="flex items-center" href="https://trieve.ai">
<img
Expand Down Expand Up @@ -33,7 +33,7 @@
</a>
</p>
</div>
<div class="sm:flex-1"></div>
<div class="flex-1"></div>
<div
id="nav-links"
class="flex flex-wrap items-center gap-4 justify-center sm:justify-right"
Expand Down
Loading

0 comments on commit 1becbfc

Please sign in to comment.