-
Notifications
You must be signed in to change notification settings - Fork 8.4k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
feat: implement mintlify AI search into CMD+K #18749
Open
Amit91848
wants to merge
1
commit into
calcom:main
Choose a base branch
from
Amit91848:feat/mintlify_ai_cmdk
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+326
−2
Open
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -399,6 +399,12 @@ BLACKLISTED_GUEST_EMAILS= | |
NEXT_PUBLIC_VAPID_PUBLIC_KEY= | ||
VAPID_PRIVATE_KEY= | ||
|
||
# Mintlify chat api | ||
# Power AI chat in for docs | ||
NEXT_PUBLIC_MINTLIFY_CHAT_API_KEY= | ||
NEXT_PUBLIC_CHAT_API_URL= | ||
NEXT_PUBLIC_DOCS_URL= | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Sometimes api request does not return |
||
|
||
# Custom privacy policy / terms URLs (for self-hosters: change to your privacy policy / terms URLs) | ||
NEXT_PUBLIC_WEBSITE_PRIVACY_POLICY_URL= | ||
NEXT_PUBLIC_WEBSITE_TERMS_URL= | ||
|
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,100 @@ | ||
/* eslint-disable react/no-danger */ | ||
import type { Dispatch, SetStateAction } from "react"; | ||
import { useState } from "react"; | ||
|
||
import { classNames } from "@calcom/lib"; | ||
import { useLocale } from "@calcom/lib/hooks/useLocale"; | ||
import { markdownToSafeHTML } from "@calcom/lib/markdownToSafeHTML"; | ||
import { Icon, SkeletonContainer, SkeletonText } from "@calcom/ui"; | ||
|
||
import { getFormattedCitations, handleAiChat, optionallyAddBaseUrl } from "../mintlify-chat/util"; | ||
|
||
interface MintlifyChatProps { | ||
searchText: string; | ||
aiResponse: string; | ||
setAiResponse: Dispatch<SetStateAction<string>>; | ||
} | ||
|
||
export const MintlifyChat = ({ searchText, aiResponse, setAiResponse }: MintlifyChatProps) => { | ||
const { t } = useLocale(); | ||
const [topicId, setTopicId] = useState(""); | ||
const [baseUrl, setBaseUrl] = useState(process.env.NEXT_PUBLIC_DOCS_URL ?? ""); | ||
const [isGenerating, setIsGenerating] = useState(false); | ||
const [error, setError] = useState(""); | ||
|
||
const onChunkReceived = (chunk: string, baseUrl?: string, finalChunk?: boolean) => { | ||
setAiResponse((prev) => { | ||
return prev + chunk; | ||
}); | ||
if (baseUrl) { | ||
setBaseUrl(baseUrl); | ||
} | ||
if (finalChunk) { | ||
setIsGenerating(false); | ||
} | ||
}; | ||
|
||
const citations = getFormattedCitations(aiResponse.split("||")[1]) ?? []; | ||
const answer = aiResponse.split("||")[0] ?? ""; | ||
|
||
return ( | ||
<> | ||
<div | ||
onClick={async () => { | ||
if (isGenerating) return; | ||
setIsGenerating(true); | ||
setAiResponse(""); | ||
setError(""); | ||
const { id, error } = await handleAiChat(onChunkReceived, searchText, topicId); | ||
if (id) { | ||
setTopicId(id); | ||
} else if (error) { | ||
setIsGenerating(false); | ||
setError(error); | ||
} | ||
}} | ||
className={classNames( | ||
"hover:bg-subtle flex items-center gap-3 px-4 py-2 transition", | ||
isGenerating ? "cursor-not-allowed" : "cursor-pointer" | ||
)}> | ||
<div> | ||
<Icon name="star" /> | ||
</div> | ||
<div> | ||
<div> | ||
{t("can_you_tell_me_about")} <span className="font-bold">{searchText}</span> | ||
</div> | ||
<div className="text-subtle text-sm">{t("use_ai_to_answer_your_questions")}</div> | ||
</div> | ||
</div> | ||
<div className="px-2 px-4 text-sm"> | ||
{error && <p className="mt-1 text-xs text-red-500">{error}</p>} | ||
{isGenerating && aiResponse === "" ? ( | ||
<SkeletonContainer> | ||
<SkeletonText className="h-12 w-full" /> | ||
</SkeletonContainer> | ||
) : ( | ||
<> | ||
<div dangerouslySetInnerHTML={{ __html: markdownToSafeHTML(answer) }} /> | ||
<div className="my-1 flex flex-wrap gap-2"> | ||
{baseUrl && | ||
citations.map((citation) => { | ||
if (citation.title) { | ||
const url = optionallyAddBaseUrl(baseUrl, citation.url); | ||
return ( | ||
<a key={url} href={url} target="_blank"> | ||
<div className="flex h-6 items-center gap-1 rounded-md bg-gray-100 px-1.5 text-xs text-gray-700 hover:bg-gray-200 dark:bg-gray-800 dark:text-gray-300 dark:hover:bg-gray-700"> | ||
{citation.title} | ||
</div> | ||
</a> | ||
); | ||
} | ||
return null; | ||
})} | ||
</div> | ||
</> | ||
)} | ||
</div> | ||
</> | ||
); | ||
}; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,197 @@ | ||
/** | ||
* This file contains utility functions for interacting with the Mintlify chat API. | ||
* The code was adapted from https://mintlify.com/docs/advanced/rest-api/overview#getting-started. The original source can be found at https://github.com/mintlify/discovery-api-example/tree/main/src/utils. | ||
*/ | ||
|
||
const API_KEY = process.env.NEXT_PUBLIC_MINTLIFY_CHAT_API_KEY; | ||
const apiBaseUrl = process.env.NEXT_PUBLIC_CHAT_API_URL; | ||
|
||
export const createChat = async () => { | ||
if (!API_KEY || !apiBaseUrl) return; | ||
|
||
const topicResponse = await fetch(`${apiBaseUrl}/topic`, { | ||
method: "POST", | ||
headers: { | ||
"Content-Type": "application/json", | ||
Authorization: `Bearer ${API_KEY}`, | ||
}, | ||
}); | ||
|
||
if (!topicResponse.ok) { | ||
return; | ||
} | ||
|
||
const topic: unknown = await topicResponse.json(); | ||
|
||
if (topic && typeof topic === "object" && "topicId" in topic && typeof topic.topicId === "string") { | ||
return topic.topicId; | ||
} else { | ||
return undefined; | ||
} | ||
}; | ||
|
||
export const generateResponse = async ({ | ||
topicId, | ||
userQuery, | ||
onChunkReceived, | ||
}: { | ||
topicId: string; | ||
userQuery: string; | ||
onChunkReceived: (chunk: string, baseUrl?: string, finalChunk?: boolean) => void; | ||
}) => { | ||
if (!API_KEY || !apiBaseUrl) return; | ||
|
||
const queryResponse = await fetch( | ||
` | ||
${apiBaseUrl}/message`, | ||
{ | ||
method: "POST", | ||
headers: { | ||
"Content-Type": "application/json", | ||
Authorization: `Bearer ${API_KEY}`, | ||
}, | ||
body: JSON.stringify({ message: userQuery, topicId }), | ||
} | ||
); | ||
|
||
if (!queryResponse.ok || !queryResponse.body) { | ||
throw Error(queryResponse.statusText); | ||
} | ||
const streamReader = queryResponse.body.getReader(); | ||
|
||
for (;;) { | ||
const { done, value } = await streamReader.read(); | ||
if (done) { | ||
const newValue = new TextDecoder().decode(value); | ||
|
||
onChunkReceived(newValue, queryResponse.headers.get("X-Mintlify-Base-Url") ?? "", true); | ||
return; | ||
} | ||
|
||
const newValue = new TextDecoder().decode(value); | ||
onChunkReceived(newValue); | ||
} | ||
}; | ||
|
||
export const handleAiChat = async ( | ||
onChunkReceived: (chunk: string, baseUrl?: string, finalChunk?: boolean) => void, | ||
userQuery: string, | ||
topicId?: string | ||
) => { | ||
let id = null; | ||
let error = ""; | ||
try { | ||
if (!topicId) { | ||
id = await createChat(); | ||
} | ||
|
||
if (!id) | ||
return { | ||
id, | ||
error: "Error creating topic. Please try again later", | ||
}; | ||
|
||
await generateResponse({ | ||
topicId: id, | ||
onChunkReceived, | ||
userQuery, | ||
}); | ||
} catch (err) { | ||
if (err instanceof Error) { | ||
error = err.message; | ||
} else { | ||
error = "k_bar_ai_error"; | ||
} | ||
} | ||
|
||
return { | ||
id, | ||
error, | ||
}; | ||
}; | ||
|
||
type ChunkMetadata = { | ||
id: string; | ||
link?: string; | ||
metadata?: Record<string, unknown>; | ||
chunk_html?: string; | ||
}; | ||
|
||
export const generateDeeplink = (chunkMetadata: ChunkMetadata) => { | ||
if ( | ||
!( | ||
"metadata" in chunkMetadata && | ||
!!chunkMetadata.metadata && | ||
"title" in chunkMetadata.metadata && | ||
"link" in chunkMetadata && | ||
typeof chunkMetadata.link === "string" | ||
) | ||
) | ||
return ""; | ||
const section = chunkMetadata.metadata.title; | ||
const link = optionallyAddLeadingSlash(chunkMetadata.link); | ||
if (section && typeof section === "string") { | ||
const sectionSlug = section | ||
.toLowerCase() | ||
.replaceAll(" ", "-") | ||
.replaceAll(/[^a-zA-Z0-9-_#]/g, ""); | ||
|
||
return `${link}#${sectionSlug}`; | ||
} | ||
|
||
return link; | ||
}; | ||
|
||
type UnformattedCitation = { | ||
id: string; | ||
link: string; | ||
chunk_html: string; | ||
metadata: Record<string, string>; | ||
}; | ||
|
||
export type Citation = { | ||
citationNumber: number; | ||
title: string; | ||
url: string; | ||
rootRecordId?: number; | ||
rootRecordType?: string; | ||
}; | ||
|
||
export function getFormattedCitations(rawContent?: string): Citation[] { | ||
try { | ||
const citations: UnformattedCitation[] = JSON.parse(rawContent ?? "[]"); | ||
|
||
const uniqueCitations = new Map( | ||
citations.map((citation, index) => { | ||
const title = citation.metadata.title ?? ""; | ||
const formattedCitation = { | ||
citationNumber: index, | ||
title: citation.metadata.title ?? "", | ||
url: generateDeeplink(citation), | ||
}; | ||
|
||
return [title, formattedCitation]; | ||
}) | ||
); | ||
|
||
return Array.from(uniqueCitations.values()); | ||
} catch { | ||
return []; | ||
} | ||
} | ||
|
||
export function optionallyRemoveLeadingSlash(path: string) { | ||
return path.startsWith("/") ? path.substring(1) : path; | ||
} | ||
|
||
export function optionallyAddLeadingSlash(path: string) { | ||
return path.startsWith("/") ? path : `/${path}`; | ||
} | ||
|
||
export function optionallyAddBaseUrl(baseUrl: string, url: string) { | ||
// absolute urls | ||
if (url.startsWith("https://")) return url; | ||
|
||
const urlWithLeadingSlash = optionallyAddLeadingSlash(url); | ||
return `${baseUrl}${urlWithLeadingSlash}`; | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
https://leaves.mintlify.com/api/chat/calcomhelp
you can add this in the .env. The one present on mintlify docs website doesn't seem to be working