Skip to content

An AI-powered search engine with a generative UI

Initial commit

Yoshiki Miura1eaed10ea5ef
diff --git a/.env.local.example b/.env.local.example
new file mode 100644
index 00000000..b1a5dde5
--- /dev/null
+++ b/.env.local.example
@@ -0,0 +1,5 @@
+# OpenAI API key retrieved here: https://platform.openai.com/api-keys
+OPENAI_API_KEY=
+
+# Tavily API Key retrieved here: https://app.tavily.com/home
+TAVILY_API_KEY=
\ No newline at end of file
diff --git a/.eslintrc.json b/.eslintrc.json
new file mode 100644
index 00000000..bffb357a
--- /dev/null
+++ b/.eslintrc.json
@@ -0,0 +1,3 @@
+{
+ "extends": "next/core-web-vitals"
+}
diff --git a/.gitignore b/.gitignore
new file mode 100644
index 00000000..fd3dbb57
--- /dev/null
+++ b/.gitignore
@@ -0,0 +1,36 @@
+# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.
+
+# dependencies
+/node_modules
+/.pnp
+.pnp.js
+.yarn/install-state.gz
+
+# testing
+/coverage
+
+# next.js
+/.next/
+/out/
+
+# production
+/build
+
+# misc
+.DS_Store
+*.pem
+
+# debug
+npm-debug.log*
+yarn-debug.log*
+yarn-error.log*
+
+# local env files
+.env*.local
+
+# vercel
+.vercel
+
+# typescript
+*.tsbuildinfo
+next-env.d.ts
diff --git a/.vscode/settings.json b/.vscode/settings.json
new file mode 100644
index 00000000..89d1965f
--- /dev/null
+++ b/.vscode/settings.json
@@ -0,0 +1,4 @@
+{
+ "editor.formatOnSave": true,
+ "editor.defaultFormatter": "esbenp.prettier-vscode"
+}
\ No newline at end of file
diff --git a/LICENSE b/LICENSE
new file mode 100644
index 00000000..261eeb9e
--- /dev/null
+++ b/LICENSE
@@ -0,0 +1,201 @@
+ Apache License
+ Version 2.0, January 2004
+ http://www.apache.org/licenses/
+
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+ 1. Definitions.
+
+ "License" shall mean the terms and conditions for use, reproduction,
+ and distribution as defined by Sections 1 through 9 of this document.
+
+ "Licensor" shall mean the copyright owner or entity authorized by
+ the copyright owner that is granting the License.
+
+ "Legal Entity" shall mean the union of the acting entity and all
+ other entities that control, are controlled by, or are under common
+ control with that entity. For the purposes of this definition,
+ "control" means (i) the power, direct or indirect, to cause the
+ direction or management of such entity, whether by contract or
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
+ outstanding shares, or (iii) beneficial ownership of such entity.
+
+ "You" (or "Your") shall mean an individual or Legal Entity
+ exercising permissions granted by this License.
+
+ "Source" form shall mean the preferred form for making modifications,
+ including but not limited to software source code, documentation
+ source, and configuration files.
+
+ "Object" form shall mean any form resulting from mechanical
+ transformation or translation of a Source form, including but
+ not limited to compiled object code, generated documentation,
+ and conversions to other media types.
+
+ "Work" shall mean the work of authorship, whether in Source or
+ Object form, made available under the License, as indicated by a
+ copyright notice that is included in or attached to the work
+ (an example is provided in the Appendix below).
+
+ "Derivative Works" shall mean any work, whether in Source or Object
+ form, that is based on (or derived from) the Work and for which the
+ editorial revisions, annotations, elaborations, or other modifications
+ represent, as a whole, an original work of authorship. For the purposes
+ of this License, Derivative Works shall not include works that remain
+ separable from, or merely link (or bind by name) to the interfaces of,
+ the Work and Derivative Works thereof.
+
+ "Contribution" shall mean any work of authorship, including
+ the original version of the Work and any modifications or additions
+ to that Work or Derivative Works thereof, that is intentionally
+ submitted to Licensor for inclusion in the Work by the copyright owner
+ or by an individual or Legal Entity authorized to submit on behalf of
+ the copyright owner. For the purposes of this definition, "submitted"
+ means any form of electronic, verbal, or written communication sent
+ to the Licensor or its representatives, including but not limited to
+ communication on electronic mailing lists, source code control systems,
+ and issue tracking systems that are managed by, or on behalf of, the
+ Licensor for the purpose of discussing and improving the Work, but
+ excluding communication that is conspicuously marked or otherwise
+ designated in writing by the copyright owner as "Not a Contribution."
+
+ "Contributor" shall mean Licensor and any individual or Legal Entity
+ on behalf of whom a Contribution has been received by Licensor and
+ subsequently incorporated within the Work.
+
+ 2. Grant of Copyright License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ copyright license to reproduce, prepare Derivative Works of,
+ publicly display, publicly perform, sublicense, and distribute the
+ Work and such Derivative Works in Source or Object form.
+
+ 3. Grant of Patent License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ (except as stated in this section) patent license to make, have made,
+ use, offer to sell, sell, import, and otherwise transfer the Work,
+ where such license applies only to those patent claims licensable
+ by such Contributor that are necessarily infringed by their
+ Contribution(s) alone or by combination of their Contribution(s)
+ with the Work to which such Contribution(s) was submitted. If You
+ institute patent litigation against any entity (including a
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
+ or a Contribution incorporated within the Work constitutes direct
+ or contributory patent infringement, then any patent licenses
+ granted to You under this License for that Work shall terminate
+ as of the date such litigation is filed.
+
+ 4. Redistribution. You may reproduce and distribute copies of the
+ Work or Derivative Works thereof in any medium, with or without
+ modifications, and in Source or Object form, provided that You
+ meet the following conditions:
+
+ (a) You must give any other recipients of the Work or
+ Derivative Works a copy of this License; and
+
+ (b) You must cause any modified files to carry prominent notices
+ stating that You changed the files; and
+
+ (c) You must retain, in the Source form of any Derivative Works
+ that You distribute, all copyright, patent, trademark, and
+ attribution notices from the Source form of the Work,
+ excluding those notices that do not pertain to any part of
+ the Derivative Works; and
+
+ (d) If the Work includes a "NOTICE" text file as part of its
+ distribution, then any Derivative Works that You distribute must
+ include a readable copy of the attribution notices contained
+ within such NOTICE file, excluding those notices that do not
+ pertain to any part of the Derivative Works, in at least one
+ of the following places: within a NOTICE text file distributed
+ as part of the Derivative Works; within the Source form or
+ documentation, if provided along with the Derivative Works; or,
+ within a display generated by the Derivative Works, if and
+ wherever such third-party notices normally appear. The contents
+ of the NOTICE file are for informational purposes only and
+ do not modify the License. You may add Your own attribution
+ notices within Derivative Works that You distribute, alongside
+ or as an addendum to the NOTICE text from the Work, provided
+ that such additional attribution notices cannot be construed
+ as modifying the License.
+
+ You may add Your own copyright statement to Your modifications and
+ may provide additional or different license terms and conditions
+ for use, reproduction, or distribution of Your modifications, or
+ for any such Derivative Works as a whole, provided Your use,
+ reproduction, and distribution of the Work otherwise complies with
+ the conditions stated in this License.
+
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
+ any Contribution intentionally submitted for inclusion in the Work
+ by You to the Licensor shall be under the terms and conditions of
+ this License, without any additional terms or conditions.
+ Notwithstanding the above, nothing herein shall supersede or modify
+ the terms of any separate license agreement you may have executed
+ with Licensor regarding such Contributions.
+
+ 6. Trademarks. This License does not grant permission to use the trade
+ names, trademarks, service marks, or product names of the Licensor,
+ except as required for reasonable and customary use in describing the
+ origin of the Work and reproducing the content of the NOTICE file.
+
+ 7. Disclaimer of Warranty. Unless required by applicable law or
+ agreed to in writing, Licensor provides the Work (and each
+ Contributor provides its Contributions) on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ implied, including, without limitation, any warranties or conditions
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+ PARTICULAR PURPOSE. You are solely responsible for determining the
+ appropriateness of using or redistributing the Work and assume any
+ risks associated with Your exercise of permissions under this License.
+
+ 8. Limitation of Liability. In no event and under no legal theory,
+ whether in tort (including negligence), contract, or otherwise,
+ unless required by applicable law (such as deliberate and grossly
+ negligent acts) or agreed to in writing, shall any Contributor be
+ liable to You for damages, including any direct, indirect, special,
+ incidental, or consequential damages of any character arising as a
+ result of this License or out of the use or inability to use the
+ Work (including but not limited to damages for loss of goodwill,
+ work stoppage, computer failure or malfunction, or any and all
+ other commercial damages or losses), even if such Contributor
+ has been advised of the possibility of such damages.
+
+ 9. Accepting Warranty or Additional Liability. While redistributing
+ the Work or Derivative Works thereof, You may choose to offer,
+ and charge a fee for, acceptance of support, warranty, indemnity,
+ or other liability obligations and/or rights consistent with this
+ License. However, in accepting such obligations, You may act only
+ on Your own behalf and on Your sole responsibility, not on behalf
+ of any other Contributor, and only if You agree to indemnify,
+ defend, and hold each Contributor harmless for any liability
+ incurred by, or claims asserted against, such Contributor by reason
+ of your accepting any such warranty or additional liability.
+
+ END OF TERMS AND CONDITIONS
+
+ APPENDIX: How to apply the Apache License to your work.
+
+ To apply the Apache License to your work, attach the following
+ boilerplate notice, with the fields enclosed by brackets "[]"
+ replaced with your own identifying information. (Don't include
+ the brackets!) The text should be enclosed in the appropriate
+ comment syntax for the file format. We also recommend that a
+ file or class name and description of purpose be included on the
+ same "printed page" as the copyright notice for easier
+ identification within third-party archives.
+
+ Copyright [yyyy] [name of copyright owner]
+
+ Licensed under the Apache License, Version 2.0 (the "License");
+ you may not use this file except in compliance with the License.
+ You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
diff --git a/README.md b/README.md
new file mode 100644
index 00000000..2b92e157
--- /dev/null
+++ b/README.md
@@ -0,0 +1,67 @@
+# Morphic Search
+
+An AI-powered answer engine with a generative UI.
+
+![capture](/public/capture-240404.png)
+
+## πŸ” Overview
+
+- 🧱 [Stack](#-stack)
+- πŸš€ [Quickstart](#-quickstart)
+- 🌐 [Deploy](#-deploy)
+
+## 🧱 Stack
+
+- App framework: [Next.js](https://nextjs.org/)
+- Text streaming / Generative UI: [Vercel AI SDK](https://sdk.vercel.ai/docs)
+- Generative Model: [OpenAI](https://openai.com/)
+- Search API: [Tavily AI](https://tavily.com/)
+- CSS framework: [Tailwind CSS](https://tailwindcss.com/)
+- Component library: [shadcn/ui](https://ui.shadcn.com/)
+
+## πŸš€ Quickstart
+
+### 1. Fork and Clone repo
+
+Fork the repo to your Github account, then run the following command to clone the repo:
+
+```
+git clone [email protected]:[YOUR_GITHUB_ACCOUNT]/morphic.git
+```
+
+### 2. Install dependencies
+
+```
+cd morphic
+bun i
+```
+
+### 3. Fill out secrets
+
+```
+cp .env.local.example .env.local
+```
+
+Your .env.local file should look like this:
+
+```
+# OpenAI API key retrieved here: https://platform.openai.com/api-keys
+OPENAI_API_KEY=[YOUR_OPENAI_API_KEY]
+
+# Tavily API Key retrieved here: https://app.tavily.com/home
+TAVILY_API_KEY=[YOUR_TAVILY_API_KEY]
+```
+
+### 4. Run app locally
+
+```
+bun dev
+```
+
+You can now visit http://localhost:3000.
+
+## 🌐 Deploy
+
+Host your own live version of Morphic with Vercel.
+
+[![Deploy with Vercel](https://vercel.com/button)](https://vercel.com/new/clone?repository-url=https%3A%2F%2Fgithub.com%2Fmiurla%2Fmorphic&env=OPENAI_API_KEY,TAVILY_API_KEY)
diff --git a/app/action.tsx b/app/action.tsx
new file mode 100644
index 00000000..9428c37b
--- /dev/null
+++ b/app/action.tsx
@@ -0,0 +1,117 @@
+import {
+ StreamableValue,
+ createAI,
+ createStreamableUI,
+ createStreamableValue,
+ getMutableAIState
+} from 'ai/rsc'
+import { ExperimentalMessage } from 'ai'
+import { Spinner } from '@/components/ui/spinner'
+import { Section } from '@/components/section'
+import { FollowupPanel } from '@/components/followup-panel'
+import { inquire, researcher, taskManager, querySuggestor } from '@/app/agents'
+
+async function submit(formData?: FormData, skip?: boolean) {
+ 'use server'
+
+ const aiState = getMutableAIState<typeof AI>()
+ const uiStream = createStreamableUI()
+ const isGenerating = createStreamableValue(true)
+
+ const messages: ExperimentalMessage[] = aiState.get() as any
+ // Get the user input from the form data
+ const userInput = skip
+ ? `{"action": "skip"}`
+ : (formData?.get('input') as string)
+ const content = skip
+ ? userInput
+ : formData
+ ? JSON.stringify(Object.fromEntries(formData))
+ : null
+ // Add the user message to the state
+ if (content) {
+ const message = { role: 'user', content }
+ console.log('Message content', content, aiState.get())
+ messages.push(message as ExperimentalMessage)
+ aiState.update([...(aiState.get() as any), message])
+ }
+
+ async function processEvents() {
+ uiStream.update(<Spinner />)
+
+ let action: any = { object: { next: 'proceed' } }
+ // If the user skips the task, we proceed to the search
+ if (!skip) action = await taskManager(messages)
+ console.log('Next Action: ', action)
+
+ if (action.object.next === 'inquire') {
+ // Generate inquiry
+ const inquiry = await inquire(uiStream, messages, userInput)
+
+ uiStream.done()
+ isGenerating.done()
+ aiState.done([
+ ...aiState.get(),
+ { role: 'assistant', content: `inquiry: ${inquiry?.inquiry}` }
+ ])
+ return
+ }
+
+ // Generate the answer
+ let answer = ''
+ const streamText = createStreamableValue<string>()
+ while (answer.length === 0) {
+ // Search the web and generate the answer
+ const { fullResponse } = await researcher(uiStream, streamText, messages)
+ answer = fullResponse
+ }
+
+ // Generate related queries
+ await querySuggestor(uiStream, messages)
+
+ // Add follow-up panel
+ uiStream.append(
+ <Section title="Follow-up">
+ <FollowupPanel />
+ </Section>
+ )
+
+ isGenerating.done(false)
+ uiStream.done()
+ aiState.done([...aiState.get(), { role: 'assistant', content: answer }])
+ }
+
+ processEvents()
+
+ return {
+ id: Date.now(),
+ isGenerating: isGenerating.value,
+ component: uiStream.value
+ }
+}
+
+// Define the initial state of the AI. It can be any JSON object.
+const initialAIState: {
+ role: 'user' | 'assistant' | 'system' | 'function' | 'tool'
+ content: string
+ id?: string
+ name?: string
+}[] = []
+
+// The initial UI state that the client will keep track of, which contains the message IDs and their UI nodes.
+const initialUIState: {
+ id: number
+ isGenerating: StreamableValue<boolean>
+ component: React.ReactNode
+}[] = []
+
+// AI is a provider you wrap your application with so you can access AI and UI state in your components.
+export const AI = createAI({
+ actions: {
+ submit
+ },
+ // Each state can be any shape of object, but for chat applications
+ // it makes sense to have an array of messages. Or you may prefer something like { id: number, messages: Message[] }
+ initialUIState,
+ initialAIState
+})
diff --git a/app/agents/index.tsx b/app/agents/index.tsx
new file mode 100644
index 00000000..e47c0492
--- /dev/null
+++ b/app/agents/index.tsx
@@ -0,0 +1,4 @@
+export * from './task-manager'
+export * from './inquire'
+export * from './query-suggestor'
+export * from './researcher'
diff --git a/app/agents/inquire.tsx b/app/agents/inquire.tsx
new file mode 100644
index 00000000..9da75af5
--- /dev/null
+++ b/app/agents/inquire.tsx
@@ -0,0 +1,46 @@
+import { openai } from 'ai/openai'
+import { Copilot } from '@/components/copilot'
+import { createStreamableUI, createStreamableValue } from 'ai/rsc'
+import { ExperimentalMessage, experimental_streamObject } from 'ai'
+import { PartialInquiry, inquirySchema } from '@/app/schema/inquiry'
+
+export async function inquire(
+ uiStream: ReturnType<typeof createStreamableUI>,
+ messages: ExperimentalMessage[],
+ query?: string
+) {
+ const objectStream = createStreamableValue<PartialInquiry>()
+ uiStream.update(<Copilot initialQuery={query} inquiry={objectStream.value} />)
+
+ let finalInquiry: PartialInquiry = {}
+ await experimental_streamObject({
+ model: openai.chat('gpt-4-turbo-preview'),
+ maxTokens: 2500,
+ system: `You are a professional web researcher tasked with deepening your understanding of the user's input through further inquiries.
+ Only ask additional questions if absolutely necessary after receiving an initial response from the user.
+ 'names' should be an array of English identifiers for the options provided. Structure your inquiry as follows:
+ e.g., {
+ "inquiry": "What specific information are you seeking about Rivian?",
+ "options": ["History", "Products", "Investors", "Partnerships", "Competitors"],
+ "names": ["history", "products", "investors", "partnerships", "competitors"],
+ "allowsInput": true,
+ "inputLabel": "If other, please specify",
+ "inputPlaceholder": "e.g., Specifications"
+ }`,
+ messages,
+ schema: inquirySchema
+ })
+ .then(async result => {
+ for await (const obj of result.partialObjectStream) {
+ if (obj) {
+ objectStream.update(obj)
+ finalInquiry = obj
+ }
+ }
+ })
+ .finally(() => {
+ objectStream.done()
+ })
+
+ return finalInquiry
+}
diff --git a/app/agents/query-suggestor.tsx b/app/agents/query-suggestor.tsx
new file mode 100644
index 00000000..5c56705f
--- /dev/null
+++ b/app/agents/query-suggestor.tsx
@@ -0,0 +1,43 @@
+import { createStreamableUI, createStreamableValue } from 'ai/rsc'
+import { ExperimentalMessage, experimental_streamObject } from 'ai'
+import { PartialRelated, relatedSchema } from '@/app/schema/related'
+import { Section } from '@/components/section'
+import SearchRelated from '@/components/search-related'
+import { openai } from 'ai/openai'
+
+export async function querySuggestor(
+ uiStream: ReturnType<typeof createStreamableUI>,
+ messages: ExperimentalMessage[]
+) {
+ const objectStream = createStreamableValue<PartialRelated>()
+ uiStream.append(
+ <Section title="Related" separator={true}>
+ <SearchRelated relatedQueries={objectStream.value} />
+ </Section>
+ )
+
+ await experimental_streamObject({
+ model: openai.chat('gpt-4-turbo-preview'),
+ maxTokens: 2500,
+ system: `You are tasked as a professional web researcher to generate queries that delve deeper into the subject based on the initial query and its search results. Your goal is to formulate three related questions.
+ For example, given the query: "Starship's third test flight key milestones",
+ Your output should look like:
+ "{
+ "related": [
+ "Key milestones achieved during Starship's third test flight",
+ "Reason for Starship's failure during the third test flight",
+ "Future plans for Starship following the third test flight"
+ ]
+ }"`,
+ messages,
+ schema: relatedSchema
+ })
+ .then(async result => {
+ for await (const obj of result.partialObjectStream) {
+ objectStream.update(obj)
+ }
+ })
+ .finally(() => {
+ objectStream.done()
+ })
+}
diff --git a/app/agents/researcher.tsx b/app/agents/researcher.tsx
new file mode 100644
index 00000000..36c7b4a8
--- /dev/null
+++ b/app/agents/researcher.tsx
@@ -0,0 +1,157 @@
+import { createStreamableUI, createStreamableValue } from 'ai/rsc'
+import {
+ ExperimentalMessage,
+ ToolCallPart,
+ ToolResultPart,
+ experimental_streamText
+} from 'ai'
+import { searchSchema } from '@/app/schema/search'
+import { Section } from '@/components/section'
+import { openai } from 'ai/openai'
+import { ToolBadge } from '@/components/tool-badge'
+import { SearchSkeleton } from '@/components/search-skeleton'
+import { SearchResults } from '@/components/search-results'
+import { BotMessage } from '@/components/message'
+import Exa from 'exa-js'
+import { SearchResultsImageSection } from '@/components/search-results-image'
+
+export async function researcher(
+ uiStream: ReturnType<typeof createStreamableUI>,
+ streamText: ReturnType<typeof createStreamableValue<string>>,
+ messages: ExperimentalMessage[]
+) {
+ const searchAPI: 'tavily' | 'exa' = 'tavily'
+
+ let fullResponse = ''
+ const result = await experimental_streamText({
+ model: openai.chat('gpt-4-turbo-preview'),
+ maxTokens: 2500,
+ system: `As a professional web researcher, you possess the ability to search the web for any information.
+ Utilize the search results to offer additional assistance or information as needed.
+ Include a key image in your response if one is relevant. Respond to the user's query accordingly.
+ `,
+ messages,
+ tools: {
+ search: {
+ description: 'Search the web for information',
+ parameters: searchSchema,
+ execute: async ({
+ query,
+ max_results,
+ search_depth
+ }: {
+ query: string
+ max_results: number
+ search_depth: 'basic' | 'advanced'
+ }) => {
+ uiStream.update(
+ <Section>
+ <ToolBadge tool="search">{`${query}`}</ToolBadge>
+ </Section>
+ )
+
+ uiStream.append(
+ <Section>
+ <SearchSkeleton />
+ </Section>
+ )
+
+ const searchResult =
+ searchAPI === 'tavily'
+ ? await tavilySearch(query, max_results, search_depth)
+ : await exaSearch(query)
+
+ uiStream.update(
+ <Section title="Images">
+ <SearchResultsImageSection
+ images={searchResult.images}
+ query={searchResult.query}
+ />
+ </Section>
+ )
+ uiStream.append(
+ <Section title="Sources">
+ <SearchResults results={searchResult.results} />
+ </Section>
+ )
+
+ uiStream.append(
+ <Section title="Answer">
+ <BotMessage content={streamText.value} />
+ </Section>
+ )
+
+ return searchResult
+ }
+ }
+ }
+ })
+
+ const toolCalls: ToolCallPart[] = []
+ const toolResponses: ToolResultPart[] = []
+ for await (const delta of result.fullStream) {
+ switch (delta.type) {
+ case 'text-delta':
+ if (delta.textDelta) {
+ fullResponse += delta.textDelta
+ streamText.update(fullResponse)
+ }
+ break
+ case 'tool-call':
+ toolCalls.push(delta)
+ break
+ case 'tool-result':
+ toolResponses.push(delta)
+ break
+ }
+ }
+ messages.push({
+ role: 'assistant',
+ content: [{ type: 'text', text: fullResponse }, ...toolCalls]
+ })
+
+ if (toolResponses.length > 0) {
+ // Add tool responses to the messages
+ messages.push({ role: 'tool', content: toolResponses })
+ }
+
+ return { result, fullResponse }
+}
+
+async function tavilySearch(
+ query: string,
+ maxResults: number = 10,
+ searchDepth: 'basic' | 'advanced' = 'basic'
+): Promise<any> {
+ const apiKey = process.env.TAVILY_API_KEY
+ const response = await fetch('https://api.tavily.com/search', {
+ method: 'POST',
+ headers: {
+ 'Content-Type': 'application/json'
+ },
+ body: JSON.stringify({
+ api_key: apiKey,
+ query,
+ max_results: maxResults < 5 ? 5 : maxResults,
+ search_depth: searchDepth,
+ include_images: true,
+ include_answers: true
+ })
+ })
+
+ if (!response.ok) {
+ throw new Error(`Error: ${response.status}`)
+ }
+
+ const data = await response.json()
+ return data
+}
+
+async function exaSearch(query: string, maxResults: number = 10): Promise<any> {
+ const apiKey = process.env.EXA_API_KEY
+ const exa = new Exa(apiKey)
+ return exa.searchAndContents(query, {
+ highlights: true,
+ numResults: maxResults
+ })
+}
diff --git a/app/agents/task-manager.tsx b/app/agents/task-manager.tsx
new file mode 100644
index 00000000..4a506890
--- /dev/null
+++ b/app/agents/task-manager.tsx
@@ -0,0 +1,19 @@
+import { ExperimentalMessage, experimental_generateObject } from 'ai'
+import { openai } from 'ai/openai'
+import { nextActionSchema } from '../schema/next-action'
+
+// Decide whether inquiry is required for the user input
+export async function taskManager(messages: ExperimentalMessage[]) {
+ const result = await experimental_generateObject({
+ model: openai.chat('gpt-3.5-turbo'),
+ system: `You are a professional web researcher tasked with fully understanding the user's query, conducting web searches for the necessary information, and responding accordingly.
+ Your goal is to comprehend the user's input and determine the next step. You have the option to present a form and request further information from the user.
+ Select one of the three options based on the context: "proceed", "inquire". Use "proceed" if the provided information is sufficient for action.
+ Opt for "inquire" if more information can be gathered through questions, allowing for default selections and free-form input.
+ Make your choice wisely to fulfill your mission effectively.`,
+ messages,
+ schema: nextActionSchema
+ })
+
+ return result
+}
diff --git a/app/favicon.ico b/app/favicon.ico
new file mode 100644
index 00000000..2cee9d41
Binary files /dev/null and b/app/favicon.ico differ
diff --git a/app/globals.css b/app/globals.css
new file mode 100644
index 00000000..e7f71728
--- /dev/null
+++ b/app/globals.css
@@ -0,0 +1,76 @@
+@tailwind base;
+@tailwind components;
+@tailwind utilities;
+
+@layer base {
+ :root {
+ --background: 0 0% 100%;
+ --foreground: 0 0% 3.9%;
+
+ --card: 0 0% 96.1%;
+ --card-foreground: 0 0% 45.1%;
+
+ --popover: 0 0% 100%;
+ --popover-foreground: 0 0% 3.9%;
+
+ --primary: 0 0% 9%;
+ --primary-foreground: 0 0% 98%;
+
+ --secondary: 0 0% 96.1%;
+ --secondary-foreground: 0 0% 9%;
+
+ --muted: 0 0% 96.1%;
+ --muted-foreground: 0 0% 45.1%;
+
+ --accent: 0 0% 96.1%;
+ --accent-foreground: 0 0% 9%;
+
+ --destructive: 0 84.2% 60.2%;
+ --destructive-foreground: 0 0% 98%;
+
+ --border: 0 0% 89.8%;
+ --input: 0 0% 89.8%;
+ --ring: 0 0% 89.8%;
+
+ --radius: 0.5rem;
+ }
+
+ .dark {
+ --background: 0 0% 3.9%;
+ --foreground: 0 0% 98%;
+
+ --card: 0 0% 14.9%;
+ --card-foreground: 0 0% 63.9%;
+
+ --popover: 0 0% 3.9%;
+ --popover-foreground: 0 0% 98%;
+
+ --primary: 0 0% 98%;
+ --primary-foreground: 0 0% 9%;
+
+ --secondary: 0 0% 14.9%;
+ --secondary-foreground: 0 0% 98%;
+
+ --muted: 0 0% 14.9%;
+ --muted-foreground: 0 0% 63.9%;
+
+ --accent: 0 0% 14.9%;
+ --accent-foreground: 0 0% 98%;
+
+ --destructive: 0 62.8% 30.6%;
+ --destructive-foreground: 0 0% 98%;
+
+ --border: 0 0% 14.9%;
+ --input: 0 0% 14.9%;
+ --ring: 0 0% 14.9%;
+ }
+}
+
+@layer base {
+ * {
+ @apply border-border;
+ }
+ body {
+ @apply bg-background text-foreground;
+ }
+}
diff --git a/app/layout.tsx b/app/layout.tsx
new file mode 100644
index 00000000..0dc3dccc
--- /dev/null
+++ b/app/layout.tsx
@@ -0,0 +1,46 @@
+import type { Metadata } from 'next'
+import { Inter as FontSans } from 'next/font/google'
+import { AI } from './action'
+import './globals.css'
+import { cn } from '@/lib/utils'
+import { ThemeProvider } from '@/components/theme-provider'
+import Header from '@/components/header'
+import Footer from '@/components/footer'
+
+const fontSans = FontSans({
+ subsets: ['latin'],
+ variable: '--font-sans'
+})
+
+export const metadata: Metadata = {
+ title: 'Morphic Search - AI powered answer engine',
+ description: 'An AI-powered answer engine with a generative UI.'
+}
+
+export default function RootLayout({
+ children
+}: Readonly<{
+ children: React.ReactNode
+}>) {
+ return (
+ <html lang="en" suppressHydrationWarning>
+ <body
+ className={cn(
+ 'min-h-screen bg-background font-sans antialiased',
+ fontSans.variable
+ )}
+ >
+ <ThemeProvider
+ attribute="class"
+ defaultTheme="system"
+ enableSystem
+ disableTransitionOnChange
+ >
+ <Header />
+ <AI>{children}</AI>
+ <Footer />
+ </ThemeProvider>
+ </body>
+ </html>
+ )
+}
diff --git a/app/page.tsx b/app/page.tsx
new file mode 100644
index 00000000..a453b34e
--- /dev/null
+++ b/app/page.tsx
@@ -0,0 +1,9 @@
+'use client'
+
+import { Chat } from '@/components/chat'
+
+export const runtime = 'edge'
+
+export default function Page() {
+ return <Chat />
+}
diff --git a/app/schema/inquiry.tsx b/app/schema/inquiry.tsx
new file mode 100644
index 00000000..3600ff0d
--- /dev/null
+++ b/app/schema/inquiry.tsx
@@ -0,0 +1,18 @@
+import { DeepPartial } from 'ai'
+import { z } from 'zod'
+
+export const inquirySchema = z.object({
+ inquiry: z.string().describe(''),
+ options: z.array(
+ z.object({
+ name: z.string(),
+ label: z.string()
+ })
+ ),
+ names: z.array(z.string()),
+ allowsInput: z.boolean(),
+ inputLabel: z.string().optional(),
+ inputPlaceholder: z.string().optional()
+})
+
+export type PartialInquiry = DeepPartial<typeof inquirySchema>
diff --git a/app/schema/next-action.tsx b/app/schema/next-action.tsx
new file mode 100644
index 00000000..efbaae2e
--- /dev/null
+++ b/app/schema/next-action.tsx
@@ -0,0 +1,8 @@
+import { DeepPartial } from 'ai'
+import { z } from 'zod'
+
+export const nextActionSchema = z.object({
+ next: z.enum(['inquire', 'proceed']) // "generate_ui"
+})
+
+export type NextAction = DeepPartial<typeof nextActionSchema>
diff --git a/app/schema/related.tsx b/app/schema/related.tsx
new file mode 100644
index 00000000..bf9b9f88
--- /dev/null
+++ b/app/schema/related.tsx
@@ -0,0 +1,13 @@
+import { DeepPartial } from 'ai'
+import { z } from 'zod'
+
+export const relatedSchema = z.object({
+ items: z
+ .array(
+ z.object({
+ query: z.string()
+ })
+ )
+ .length(3)
+})
+export type PartialRelated = DeepPartial<typeof relatedSchema>
diff --git a/app/schema/search.tsx b/app/schema/search.tsx
new file mode 100644
index 00000000..0ced1865
--- /dev/null
+++ b/app/schema/search.tsx
@@ -0,0 +1,17 @@
+import { DeepPartial } from 'ai'
+import { z } from 'zod'
+
+export const searchSchema = z.object({
+ query: z.string().describe('The query to search for'),
+ max_results: z
+ .number()
+ .max(20)
+ .default(5)
+ .describe('The maximum number of results to return'),
+ search_depth: z
+ .enum(['basic', 'advanced'])
+ .default('basic')
+ .describe('The depth of the search')
+})
+
+export type PartialInquiry = DeepPartial<typeof searchSchema>
diff --git a/bun.lockb b/bun.lockb
new file mode 100755
index 00000000..61ba3ff0
Binary files /dev/null and b/bun.lockb differ
diff --git a/components.json b/components.json
new file mode 100644
index 00000000..1e879bc7
--- /dev/null
+++ b/components.json
@@ -0,0 +1,17 @@
+{
+ "$schema": "https://ui.shadcn.com/schema.json",
+ "style": "default",
+ "rsc": true,
+ "tsx": true,
+ "tailwind": {
+ "config": "tailwind.config.ts",
+ "css": "app/globals.css",
+ "baseColor": "neutral",
+ "cssVariables": true,
+ "prefix": ""
+ },
+ "aliases": {
+ "components": "@/components",
+ "utils": "@/lib/utils"
+ }
+}
\ No newline at end of file
diff --git a/components/chat-messages.tsx b/components/chat-messages.tsx
new file mode 100644
index 00000000..464cffb7
--- /dev/null
+++ b/components/chat-messages.tsx
@@ -0,0 +1,14 @@
+import { useUIState } from 'ai/rsc'
+import type { AI } from '@/app/action'
+
+export function ChatMessages() {
+ const [messages, setMessages] = useUIState<typeof AI>()
+
+ return (
+ <>
+ {messages.map((message: { id: number; component: React.ReactNode }) => (
+ <div key={message.id}>{message.component}</div>
+ ))}
+ </>
+ )
+}
diff --git a/components/chat-panel.tsx b/components/chat-panel.tsx
new file mode 100644
index 00000000..bd0e1f50
--- /dev/null
+++ b/components/chat-panel.tsx
@@ -0,0 +1,132 @@
+import { useEffect, useState, useRef } from 'react'
+import type { AI } from '@/app/action'
+import { useUIState, useActions, useAIState } from 'ai/rsc'
+import { cn } from '@/lib/utils'
+import { UserMessage } from './user-message'
+import { Input } from './ui/input'
+import { Button } from './ui/button'
+import { ArrowRight, Plus, Square } from 'lucide-react'
+import { EmptyScreen } from './empty-screen'
+
+export function ChatPanel() {
+ const [input, setInput] = useState('')
+ const [messages, setMessages] = useUIState<typeof AI>()
+ const [aiMessages, setAiMessages] = useAIState<typeof AI>()
+ const { submit } = useActions<typeof AI>()
+ const [isButtonPressed, setIsButtonPressed] = useState(false)
+ const inputRef = useRef<HTMLInputElement>(null)
+ const [showEmptyScreen, setShowEmptyScreen] = useState(false)
+ // Focus on input when button is pressed
+ useEffect(() => {
+ if (isButtonPressed) {
+ inputRef.current?.focus()
+ setIsButtonPressed(false)
+ }
+ }, [isButtonPressed])
+
+ const handleSubmit = async (e: React.FormEvent<HTMLFormElement>) => {
+ e.preventDefault()
+
+ // Clear messages if button is pressed
+ if (isButtonPressed) {
+ handleClear()
+ setIsButtonPressed(false)
+ }
+
+ // Add user message to UI state
+ setMessages(currentMessages => [
+ ...currentMessages,
+ {
+ id: Date.now(),
+ isGenerating: false,
+ component: <UserMessage message={input} />
+ }
+ ])
+
+ // Submit and get response message
+ const formData = new FormData(e.currentTarget)
+ const responseMessage = await submit(formData)
+ setMessages(currentMessages => [...currentMessages, responseMessage as any])
+
+ setInput('')
+ }
+
+ // Clear messages
+ const handleClear = () => {
+ // refresh the page
+ // currently, streamable ui is buggy, so we need to refresh the page to clear the state
+ window.location.reload()
+
+ // setIsButtonPressed(true);
+ // setMessages([]);
+ // setAiMessages([]);
+ }
+
+ useEffect(() => {
+ // focus on input when the page loads
+ inputRef.current?.focus()
+ }, [])
+
+ // If there are messages and the new button has not been pressed, display the new Button
+ if (messages.length > 0 && !isButtonPressed) {
+ return (
+ <div className="fixed bottom-8 left-0 right-0 flex justify-center items-center mx-auto">
+ <Button
+ type="button"
+ variant={'secondary'}
+ className="rounded-full bg-secondary/80 group transition-all hover:scale-105"
+ onClick={() => handleClear()}
+ >
+ <span className="text-sm mr-2 group-hover:block hidden animate-in fade-in duration-300">
+ New
+ </span>
+ <Plus size={18} className="group-hover:rotate-90 transition-all" />
+ </Button>
+ </div>
+ )
+ }
+
+ // Condition 1 and 3: If there are no messages or the button is pressed, display the form
+ const formPositionClass =
+ messages.length === 0
+ ? 'fixed bottom-8 left-0 right-0 top-10 mx-auto h-screen flex flex-col items-center justify-center'
+ : 'fixed bottom-8-ml-6'
+ return (
+ <div className={formPositionClass}>
+ {/* <IconKuroko className="w-6 h-6 mb-4" /> */}
+ <form onSubmit={handleSubmit} className="max-w-2xl w-full px-6">
+ <div className="relative flex items-center w-full">
+ <Input
+ ref={inputRef}
+ type="text"
+ name="input"
+ placeholder="Ask a question..."
+ value={input}
+ className="pl-4 pr-10 h-12 rounded-full bg-muted"
+ onChange={e => {
+ setInput(e.target.value)
+ setShowEmptyScreen(e.target.value.length === 0)
+ }}
+ onFocus={() => setShowEmptyScreen(true)}
+ onBlur={() => setShowEmptyScreen(false)}
+ />
+ <Button
+ type="submit"
+ size={'icon'}
+ variant={'ghost'}
+ className="absolute right-2 top-1/2 transform -translate-y-1/2"
+ disabled={input.length === 0}
+ >
+ <ArrowRight size={20} />
+ </Button>
+ </div>
+ <EmptyScreen
+ submitMessage={message => {
+ setInput(message)
+ }}
+ className={cn(showEmptyScreen ? 'visible' : 'invisible')}
+ />
+ </form>
+ </div>
+ )
+}
diff --git a/components/chat.tsx b/components/chat.tsx
new file mode 100644
index 00000000..e969c18b
--- /dev/null
+++ b/components/chat.tsx
@@ -0,0 +1,13 @@
+'use client'
+
+import { ChatPanel } from './chat-panel'
+import { ChatMessages } from './chat-messages'
+
+export function Chat() {
+ return (
+ <div className="px-12 pt-8 pb-24 max-w-3xl mx-auto flex flex-col space-y-4">
+ <ChatMessages />
+ <ChatPanel />
+ </div>
+ )
+}
diff --git a/components/copilot.tsx b/components/copilot.tsx
new file mode 100644
index 00000000..b7825b5d
--- /dev/null
+++ b/components/copilot.tsx
@@ -0,0 +1,186 @@
+'use client'
+
+import React, { useEffect, useState } from 'react'
+import { PartialInquiry } from '@/app/schema/inquiry'
+import { Input } from './ui/input'
+import { Checkbox } from './ui/checkbox'
+import { Button } from './ui/button'
+import { Card } from './ui/card'
+import { ArrowRight, Check, FastForward, Sparkles } from 'lucide-react'
+import { useActions, useStreamableValue, useUIState } from 'ai/rsc'
+import { AI } from '@/app/action'
+import { IconLogo } from './ui/icons'
+import { cn } from '@/lib/utils'
+
+export type CopilotProps = {
+ initialQuery?: string
+ inquiry?: PartialInquiry
+}
+
+export const Copilot: React.FC<CopilotProps> = ({
+ initialQuery,
+ inquiry
+}: CopilotProps) => {
+ const [completed, setCompleted] = useState(false)
+ const [query, setQuery] = useState('')
+ const [skipped, setSkipped] = useState(false)
+ const [data, error, pending] = useStreamableValue<PartialInquiry>(inquiry)
+ const [checkedOptions, setCheckedOptions] = useState<{
+ [key: string]: boolean
+ }>({})
+ const [isButtonDisabled, setIsButtonDisabled] = useState(true)
+ const [messages, setMessages] = useUIState<typeof AI>()
+ const { submit } = useActions<typeof AI>()
+
+ const handleInputChange = (event: React.ChangeEvent<HTMLInputElement>) => {
+ setQuery(event.target.value)
+ checkIfButtonShouldBeEnabled()
+ }
+
+ const handleOptionChange = (selectedOption: string) => {
+ const updatedCheckedOptions = {
+ ...checkedOptions,
+ [selectedOption]: !checkedOptions[selectedOption]
+ }
+ setCheckedOptions(updatedCheckedOptions)
+ checkIfButtonShouldBeEnabled(updatedCheckedOptions)
+ }
+
+ const checkIfButtonShouldBeEnabled = (currentOptions = checkedOptions) => {
+ const anyCheckboxChecked = Object.values(currentOptions).some(
+ checked => checked
+ )
+ setIsButtonDisabled(!(anyCheckboxChecked || query))
+ }
+
+ const updatedQuery = () => {
+ const selectedOptions = Object.entries(checkedOptions)
+ .filter(([, checked]) => checked)
+ .map(([option]) => option)
+ return [initialQuery, ...selectedOptions, query].filter(Boolean).join(', ')
+ }
+
+ useEffect(() => {
+ checkIfButtonShouldBeEnabled()
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [query])
+
+ const onFormSubmit = async (
+ e: React.FormEvent<HTMLFormElement>,
+ skip?: boolean
+ ) => {
+ e.preventDefault()
+ setCompleted(true)
+ setSkipped(skip || false)
+
+ const formData = skip
+ ? undefined
+ : new FormData(e.target as HTMLFormElement)
+
+ const responseMessage = await submit(formData, skip)
+ setMessages(currentMessages => [...currentMessages, responseMessage])
+ }
+
+ const handleSkip = (e: React.MouseEvent<HTMLButtonElement>) => {
+ onFormSubmit(e as unknown as React.FormEvent<HTMLFormElement>, true)
+ }
+
+ if (error) {
+ return (
+ <Card className="p-4 w-full flex justify-between items-center">
+ <div className="flex items-center space-x-2">
+ <Sparkles className="w-4 h-4" />
+ <h5 className="text-muted-foreground text-xs truncate">
+ {`error: ${error}`}
+ </h5>
+ </div>
+ </Card>
+ )
+ }
+
+ if (skipped) {
+ return null
+ }
+
+ if (completed) {
+ return (
+ <Card className="p-4 w-full flex justify-between items-center">
+ <div className="flex items-center space-x-2">
+ <IconLogo className="w-4 h-4" />
+ <h5 className="text-muted-foreground text-xs truncate">
+ {updatedQuery()}
+ </h5>
+ </div>
+ <Check size={16} className="text-green-500" />
+ </Card>
+ )
+ } else {
+ return (
+ <Card className="p-4 rounded-lg w-full mx-auto">
+ <div className="flex items-center mb-4">
+ <IconLogo
+ className={cn('w-4 h-4 flex-shrink-0', { 'animate-spin': pending })}
+ />
+ <p className="text-lg text-foreground text-semibold ml-2">
+ {data?.inquiry}
+ </p>
+ </div>
+ <form onSubmit={onFormSubmit}>
+ <div className="flex flex-wrap justify-start mb-4">
+ {data?.options?.map((option, index) => (
+ <div
+ key={`option-${index}`}
+ className="flex items-center space-x-1.5 mb-2"
+ >
+ <Checkbox
+ id={option?.name}
+ name={option?.name}
+ onCheckedChange={() =>
+ handleOptionChange(option?.label as string)
+ }
+ />
+ <label
+ className="text-sm whitespace-nowrap pr-4"
+ htmlFor={option?.name}
+ >
+ {option?.label}
+ </label>
+ </div>
+ ))}
+ </div>
+ {data?.allowsInput && (
+ <div className="mb-6 flex flex-col space-y-2 text-sm">
+ <label className="text-muted-foreground" htmlFor="query">
+ {data?.inputLabel}
+ </label>
+ <Input
+ type="text"
+ name="additional_query"
+ className="w-full"
+ id="query"
+ placeholder={data?.inputPlaceholder}
+ value={query}
+ onChange={handleInputChange}
+ />
+ </div>
+ )}
+ <div className="flex justify-end space-x-2">
+ <Button
+ type="button"
+ variant="outline"
+ onClick={handleSkip}
+ disabled={pending}
+ >
+ <FastForward size={16} className="mr-1" />
+ Skip
+ </Button>
+ <Button type="submit" disabled={isButtonDisabled || pending}>
+ <ArrowRight size={16} className="mr-1" />
+ Send
+ </Button>
+ </div>
+ </form>
+ </Card>
+ )
+ }
+}
diff --git a/components/empty-screen.tsx b/components/empty-screen.tsx
new file mode 100644
index 00000000..c5503d97
--- /dev/null
+++ b/components/empty-screen.tsx
@@ -0,0 +1,51 @@
+import { Button } from '@/components/ui/button'
+import { ArrowRight } from 'lucide-react'
+
+const exampleMessages = [
+ {
+ heading: 'Why is Nvidia growing rapidly?',
+ message: 'Why is Nvidia growing rapidly?'
+ },
+ {
+ heading: 'Is the Apple Vision Pro worth buying?',
+ message: 'Is the Apple Vision Pro worth buying?'
+ },
+ {
+ heading: 'How does the Vercel AI SDK work?',
+ message: 'How does the Vercel AI SDK work?'
+ },
+ {
+ heading: 'Tesla vs Rivian',
+ message: 'Tesla vs Rivian'
+ }
+]
+export function EmptyScreen({
+ submitMessage,
+ className
+}: {
+ submitMessage: (message: string) => void
+ className?: string
+}) {
+ return (
+ <div className={`mx-auto w-full transition-all ${className}`}>
+ <div className="bg-background p-2">
+ <div className="mt-4 flex flex-col items-start space-y-2 mb-4">
+ {exampleMessages.map((message, index) => (
+ <Button
+ key={index}
+ variant="link"
+ className="h-auto p-0 text-base"
+ name={message.message}
+ onClick={async () => {
+ submitMessage(message.message)
+ }}
+ >
+ <ArrowRight size={16} className="mr-2 text-muted-foreground" />
+ {message.heading}
+ </Button>
+ ))}
+ </div>
+ </div>
+ </div>
+ )
+}
diff --git a/components/followup-panel.tsx b/components/followup-panel.tsx
new file mode 100644
index 00000000..92b54f98
--- /dev/null
+++ b/components/followup-panel.tsx
@@ -0,0 +1,60 @@
+'use client'
+
+import { useState } from 'react'
+import { Button } from './ui/button'
+import { Input } from './ui/input'
+import { useActions, useUIState } from 'ai/rsc'
+import type { AI } from '@/app/action'
+import { UserMessage } from './user-message'
+import { ArrowRight } from 'lucide-react'
+
+export function FollowupPanel() {
+ const [input, setInput] = useState('')
+ const { submit } = useActions<typeof AI>()
+ const [, setMessages] = useUIState<typeof AI>()
+
+ const handleSubmit = async (event: React.FormEvent<HTMLFormElement>) => {
+ event.preventDefault()
+ const formData = new FormData(event.currentTarget as HTMLFormElement)
+
+ const userMessage = {
+ id: Date.now(),
+ isGenerating: false,
+ component: <UserMessage message={input} isFirstMessage={false} />
+ }
+
+ const responseMessage = await submit(formData)
+ setMessages(currentMessages => [
+ ...currentMessages,
+ userMessage,
+ responseMessage
+ ])
+
+ setInput('')
+ }
+
+ return (
+ <form
+ onSubmit={handleSubmit}
+ className="relative flex items-center space-x-1"
+ >
+ <Input
+ type="text"
+ name="input"
+ placeholder="Ask a follow-up question..."
+ value={input}
+ className="pr-14 h-12"
+ onChange={e => setInput(e.target.value)}
+ />
+ <Button
+ type="submit"
+ size={'icon'}
+ disabled={input.length === 0}
+ variant={'ghost'}
+ className="absolute right-1"
+ >
+ <ArrowRight size={20} />
+ </Button>
+ </form>
+ )
+}
diff --git a/components/footer.tsx b/components/footer.tsx
new file mode 100644
index 00000000..1bfc8ca2
--- /dev/null
+++ b/components/footer.tsx
@@ -0,0 +1,42 @@
+import React from 'react'
+import Link from 'next/link'
+import { SiDiscord, SiGithub, SiTwitter } from 'react-icons/si'
+import { Button } from './ui/button'
+
+const Footer: React.FC = () => {
+ return (
+ <footer className="w-fit p-2 fixed bottom-0 right-0">
+ <div className="flex justify-end">
+ {/* <Button
+ variant={'ghost'}
+ size={'icon'}
+ className="text-muted-foreground/50"
+ >
+ <Link href="https://discord.gg/morphic" target="_blank">
+ <SiDiscord size={18} />
+ </Link>
+ </Button> */}
+ <Button
+ variant={'ghost'}
+ size={'icon'}
+ className="text-muted-foreground/50"
+ >
+ <Link href="https://twitter.com/miiura" target="_blank">
+ <SiTwitter size={18} />
+ </Link>
+ </Button>
+ <Button
+ variant={'ghost'}
+ size={'icon'}
+ className="text-muted-foreground/50"
+ >
+ <Link href="https://github.com/miurla/morphic" target="_blank">
+ <SiGithub size={18} />
+ </Link>
+ </Button>
+ </div>
+ </footer>
+ )
+}
+
+export default Footer
diff --git a/components/header.tsx b/components/header.tsx
new file mode 100644
index 00000000..b76d52e1
--- /dev/null
+++ b/components/header.tsx
@@ -0,0 +1,23 @@
+'use client'
+
+import React from 'react'
+import Link from 'next/link'
+import { ModeToggle } from './mode-toggle'
+import { IconLogo } from './ui/icons'
+import { cn } from '@/lib/utils'
+
+export const Header: React.FC = () => {
+ return (
+ <header className="fixed w-full p-2 flex justify-between items-center z-10">
+ <div className="p-2">
+ <a href="/">
+ <IconLogo className={cn('w-5 h-5')} />
+ <span className="sr-only">Metamorphic</span>
+ </a>
+ </div>
+ <ModeToggle />
+ </header>
+ )
+}
+
+export default Header
diff --git a/components/message.tsx b/components/message.tsx
new file mode 100644
index 00000000..810cddbb
--- /dev/null
+++ b/components/message.tsx
@@ -0,0 +1,21 @@
+'use client'
+
+import { StreamableValue, useStreamableValue } from 'ai/rsc'
+import { MemoizedReactMarkdown } from './ui/markdown'
+
+export function BotMessage({
+ content
+}: {
+ content: string | StreamableValue<string>
+}) {
+ const [data, error, pending] = useStreamableValue(content)
+
+ // Currently, sometimes error occurs after finishing the stream. So, comment out this line.
+ // if (error) return <div>Error</div>
+
+ return (
+ <MemoizedReactMarkdown className="prose-sm prose-neutral prose-a:text-accent-foreground/50">
+ {data}
+ </MemoizedReactMarkdown>
+ )
+}
diff --git a/components/mode-toggle.tsx b/components/mode-toggle.tsx
new file mode 100644
index 00000000..de41d910
--- /dev/null
+++ b/components/mode-toggle.tsx
@@ -0,0 +1,40 @@
+'use client'
+
+import * as React from 'react'
+import { Moon, Sun } from 'lucide-react'
+import { useTheme } from 'next-themes'
+
+import { Button } from '@/components/ui/button'
+import {
+ DropdownMenu,
+ DropdownMenuContent,
+ DropdownMenuItem,
+ DropdownMenuTrigger
+} from '@/components/ui/dropdown-menu'
+
+export function ModeToggle() {
+ const { setTheme } = useTheme()
+
+ return (
+ <DropdownMenu>
+ <DropdownMenuTrigger asChild>
+ <Button variant="ghost" size="icon">
+ <Sun className="h-[1.2rem] w-[1.2rem] rotate-0 scale-100 transition-all dark:-rotate-90 dark:scale-0" />
+ <Moon className="absolute h-[1.2rem] w-[1.2rem] rotate-90 scale-0 transition-all dark:rotate-0 dark:scale-100" />
+ <span className="sr-only">Toggle theme</span>
+ </Button>
+ </DropdownMenuTrigger>
+ <DropdownMenuContent align="end">
+ <DropdownMenuItem onClick={() => setTheme('light')}>
+ Light
+ </DropdownMenuItem>
+ <DropdownMenuItem onClick={() => setTheme('dark')}>
+ Dark
+ </DropdownMenuItem>
+ <DropdownMenuItem onClick={() => setTheme('system')}>
+ System
+ </DropdownMenuItem>
+ </DropdownMenuContent>
+ </DropdownMenu>
+ )
+}
diff --git a/components/search-related.tsx b/components/search-related.tsx
new file mode 100644
index 00000000..6dc37d3d
--- /dev/null
+++ b/components/search-related.tsx
@@ -0,0 +1,72 @@
+'use client'
+
+import React from 'react'
+import { Button } from './ui/button'
+import { ArrowRight } from 'lucide-react'
+import { useActions, useStreamableValue, useUIState } from 'ai/rsc'
+import { AI } from '@/app/action'
+import { UserMessage } from './user-message'
+import { PartialRelated } from '@/app/schema/related'
+
+export interface SearchRelatedProps {
+ relatedQueries: PartialRelated
+}
+
+export const SearchRelated: React.FC<SearchRelatedProps> = ({
+ relatedQueries
+}) => {
+ const { submit } = useActions<typeof AI>()
+ const [, setMessages] = useUIState<typeof AI>()
+ const [data, error, pending] =
+ useStreamableValue<PartialRelated>(relatedQueries)
+
+ const handleSubmit = async (event: React.FormEvent<HTMLFormElement>) => {
+ event.preventDefault()
+ const formData = new FormData(event.currentTarget as HTMLFormElement)
+
+ // // Get the submitter of the form
+ const submitter = (event.nativeEvent as SubmitEvent)
+ .submitter as HTMLInputElement
+ let query = ''
+ if (submitter) {
+ formData.append(submitter.name, submitter.value)
+ query = submitter.value
+ }
+
+ const userMessage = {
+ id: Date.now(),
+ isGenerating: false,
+ component: <UserMessage message={query} isFirstMessage={false} />
+ }
+
+ const responseMessage = await submit(formData)
+ setMessages(currentMessages => [
+ ...currentMessages,
+ userMessage,
+ responseMessage
+ ])
+ }
+
+ return (
+ <form onSubmit={handleSubmit} className="flex flex-wrap">
+ {data?.items
+ ?.filter(item => item?.query !== '')
+ .map((item, index) => (
+ <div className="w-full" key={index}>
+ <Button
+ variant="link"
+ className="w-fit justify-start px-0 py-1 h-fit font-semibold text-accent-foreground/50 whitespace-normal text-left"
+ type="submit"
+ name={'related_query'}
+ value={item?.query}
+ >
+ <ArrowRight className="h-4 w-4 mr-2 text-accent-foreground/50" />
+ {item?.query}
+ </Button>
+ </div>
+ ))}
+ </form>
+ )
+}
+
+export default SearchRelated
diff --git a/components/search-results-image.tsx b/components/search-results-image.tsx
new file mode 100644
index 00000000..cfded555
--- /dev/null
+++ b/components/search-results-image.tsx
@@ -0,0 +1,128 @@
+/* eslint-disable @next/next/no-img-element */
+'use client'
+
+import { Card, CardContent } from '@/components/ui/card'
+import {
+ Dialog,
+ DialogContent,
+ DialogDescription,
+ DialogHeader,
+ DialogTitle,
+ DialogTrigger
+} from '@/components/ui/dialog'
+import {
+ Carousel,
+ type CarouselApi,
+ CarouselContent,
+ CarouselItem,
+ CarouselNext,
+ CarouselPrevious
+} from '@/components/ui/carousel'
+import { useEffect, useState } from 'react'
+
+interface SearchResultsImageSectionProps {
+ images: string[]
+ query?: string
+}
+
+export const SearchResultsImageSection: React.FC<
+ SearchResultsImageSectionProps
+> = ({ images, query }) => {
+ const [api, setApi] = useState<CarouselApi>()
+ const [current, setCurrent] = useState(0)
+ const [count, setCount] = useState(0)
+ const [selectedIndex, setSelectedIndex] = useState(0)
+
+ // Update the current and count state when the carousel api is available
+ useEffect(() => {
+ if (!api) {
+ return
+ }
+
+ setCount(api.scrollSnapList().length)
+ setCurrent(api.selectedScrollSnap() + 1)
+
+ api.on('select', () => {
+ setCurrent(api.selectedScrollSnap() + 1)
+ })
+ }, [api])
+
+ // Scroll to the selected index
+ useEffect(() => {
+ if (api) {
+ api.scrollTo(selectedIndex, true)
+ }
+ }, [api, selectedIndex])
+
+ if (!images || images.length === 0) {
+ return <div className="text-muted-foreground">No images found</div>
+ }
+
+ return (
+ <div className="flex space-x-2">
+ {images.slice(0, 4).map((image: any, index: number) => (
+ <Dialog key={index}>
+ <DialogTrigger asChild>
+ <div
+ className="w-1/4 aspect-video cursor-pointer relative"
+ onClick={() => setSelectedIndex(index)}
+ >
+ <Card className="flex-1 h-full">
+ <CardContent className="p-2 h-full w-full">
+ {image ? (
+ <img
+ src={image}
+ alt={`Image ${index + 1}`}
+ className="h-full w-full object-cover"
+ />
+ ) : (
+ <div className="w-full h-full bg-muted animate-pulse" />
+ )}
+ </CardContent>
+ </Card>
+ {/* {index === 3 && images.length > 4 && (
+ <div className="absolute inset-0 bg-black bg-opacity-50 rounded-md flex items-center justify-center text-white/80 text-sm">
+ View more
+ </div>
+ )} */}
+ </div>
+ </DialogTrigger>
+ <DialogContent className="sm:max-w-3xl">
+ <DialogHeader>
+ <DialogTitle>Search Images</DialogTitle>
+ <DialogDescription className="text-sm">{query}</DialogDescription>
+ </DialogHeader>
+ <div className="py-4">
+ <Carousel setApi={setApi} className="w-full bg-muted">
+ <CarouselContent>
+ {images.map((img, idx) => (
+ <CarouselItem key={idx}>
+ <div className="p-1 flex items-center justify-center h-full">
+ <img
+ src={img}
+ alt={`Image ${idx + 1}`}
+ className="h-auto w-full object-contain"
+ />
+ </div>
+ </CarouselItem>
+ ))}
+ </CarouselContent>
+ <div className="absolute inset-8 flex items-center justify-between p-4">
+ <CarouselPrevious className="w-10 h-10 rounded-full shadow focus:outline-none">
+ <span className="sr-only">Previous</span>
+ </CarouselPrevious>
+ <CarouselNext className="w-10 h-10 rounded-full shadow focus:outline-none">
+ <span className="sr-only">Next</span>
+ </CarouselNext>
+ </div>
+ </Carousel>
+ <div className="py-2 text-center text-sm text-muted-foreground">
+ {current} of {count}
+ </div>
+ </div>
+ </DialogContent>
+ </Dialog>
+ ))}
+ </div>
+ )
+}
diff --git a/components/search-results.tsx b/components/search-results.tsx
new file mode 100644
index 00000000..78d3db5f
--- /dev/null
+++ b/components/search-results.tsx
@@ -0,0 +1,70 @@
+'use client'
+
+import { useState } from 'react'
+import { AvatarImage, Avatar, AvatarFallback } from '@/components/ui/avatar'
+import { CardContent, Card } from '@/components/ui/card'
+import { Button } from '@/components/ui/button'
+import Link from 'next/link'
+
+export interface SearchResultsProps {
+ results: { title: string; url: string; content: string }[]
+}
+
+export function SearchResults({ results }: SearchResultsProps) {
+ // State to manage whether to display the results
+ const [showAllResults, setShowAllResults] = useState(false)
+
+ const handleViewMore = () => {
+ setShowAllResults(true)
+ }
+
+ const displayedResults = showAllResults ? results : results.slice(0, 3)
+ const additionalResultsCount = results.length > 3 ? results.length - 3 : 0
+
+ return (
+ <div className="flex flex-wrap">
+ {displayedResults.map((result: any, index: any) => (
+ <div className="w-1/4 p-1" key={index}>
+ <Link href={result.url} passHref target="_blank">
+ <Card className="flex-1">
+ <CardContent className="p-2">
+ <p className="text-xs line-clamp-2">{result.content}</p>
+ <div className="mt-2 flex items-center space-x-2">
+ <Avatar className="h-4 w-4">
+ <AvatarImage
+ src={`https://www.google.com/s2/favicons?domain=${
+ new URL(result.url).hostname
+ }`}
+ alt={result.author}
+ />
+ <AvatarFallback>
+ {new URL(result.url).hostname[0]}
+ </AvatarFallback>
+ </Avatar>
+ <div className="text-xs opacity-60 truncate">
+ {new URL(result.url).hostname}
+ </div>
+ </div>
+ </CardContent>
+ </Card>
+ </Link>
+ </div>
+ ))}
+ {!showAllResults && additionalResultsCount > 0 && (
+ <div className="w-1/4 p-1">
+ <Card className="flex-1 flex h-full items-center justify-center">
+ <CardContent className="p-2">
+ <Button
+ variant={'link'}
+ className="text-muted-foreground"
+ onClick={handleViewMore}
+ >
+ View {additionalResultsCount} more
+ </Button>
+ </CardContent>
+ </Card>
+ </div>
+ )}
+ </div>
+ )
+}
diff --git a/components/search-skeleton.tsx b/components/search-skeleton.tsx
new file mode 100644
index 00000000..17d4039c
--- /dev/null
+++ b/components/search-skeleton.tsx
@@ -0,0 +1,27 @@
+'use client'
+
+import React from 'react'
+import { Skeleton } from './ui/skeleton'
+
+export const SearchSkeleton = () => {
+ return (
+ <div>
+ <Skeleton className="h-6 w-48" />
+ <div className="flex flex-wrap space-x-2">
+ {Array.from({ length: 4 }).map((_, index) => (
+ <div className="w-[24%]" key={index}>
+ <div className="flex-1">
+ <div className="pt-2">
+ <Skeleton className="h-6 mb-2" />
+ <div className="flex items-center space-x-2">
+ <Skeleton className="h-4 w-4" />
+ <Skeleton className="w-24 h-4" />
+ </div>
+ </div>
+ </div>
+ </div>
+ ))}
+ </div>
+ </div>
+ )
+}
diff --git a/components/section.tsx b/components/section.tsx
new file mode 100644
index 00000000..2752eab9
--- /dev/null
+++ b/components/section.tsx
@@ -0,0 +1,71 @@
+'use client'
+
+import { cn } from '@/lib/utils'
+import {
+ BookCheck,
+ Image,
+ MessageCircleMore,
+ Newspaper,
+ Repeat2,
+ Search
+} from 'lucide-react'
+import React from 'react'
+import { Separator } from './ui/separator'
+
+type SectionProps = {
+ children: React.ReactNode
+ className?: string
+ size?: 'sm' | 'md' | 'lg'
+ title?: string
+ separator?: boolean
+}
+
+export const Section: React.FC<SectionProps> = ({
+ children,
+ className,
+ size = 'md',
+ title,
+ separator = false
+}) => {
+ let icon: React.ReactNode
+ switch (title) {
+ case 'Images':
+ // eslint-disable-next-line jsx-a11y/alt-text
+ icon = <Image size={18} className="mr-2" />
+ break
+ case 'Sources':
+ icon = <Newspaper size={18} className="mr-2" />
+ break
+ case 'Answer':
+ icon = <BookCheck size={18} className="mr-2" />
+ break
+ case 'Related':
+ icon = <Repeat2 size={18} className="mr-2" />
+ break
+ case 'Follow-up':
+ icon = <MessageCircleMore size={18} className="mr-2" />
+ break
+ default:
+ icon = <Search size={18} className="mr-2" />
+ }
+
+ return (
+ <>
+ {separator && <Separator className="my-2 bg-primary/10" />}
+ <section
+ className={cn(
+ ` ${size === 'sm' ? 'py-1' : size === 'lg' ? 'py-4' : 'py-2'}`,
+ className
+ )}
+ >
+ {title && (
+ <h2 className="flex items-center text-lg leading-none py-2">
+ {icon}
+ {title}
+ </h2>
+ )}
+ {children}
+ </section>
+ </>
+ )
+}
diff --git a/components/theme-provider.tsx b/components/theme-provider.tsx
new file mode 100644
index 00000000..d4b4bbfd
--- /dev/null
+++ b/components/theme-provider.tsx
@@ -0,0 +1,9 @@
+'use client'
+
+import * as React from 'react'
+import { ThemeProvider as NextThemesProvider } from 'next-themes'
+import { type ThemeProviderProps } from 'next-themes/dist/types'
+
+export function ThemeProvider({ children, ...props }: ThemeProviderProps) {
+ return <NextThemesProvider {...props}>{children}</NextThemesProvider>
+}
diff --git a/components/tool-badge.tsx b/components/tool-badge.tsx
new file mode 100644
index 00000000..f2a22c10
--- /dev/null
+++ b/components/tool-badge.tsx
@@ -0,0 +1,26 @@
+import React from 'react'
+import { Search } from 'lucide-react'
+import { Badge } from './ui/badge'
+
+type ToolBadgeProps = {
+ tool: string
+ children: React.ReactNode
+ className?: string
+}
+
+export const ToolBadge: React.FC<ToolBadgeProps> = ({
+ tool,
+ children,
+ className
+}) => {
+ const icon: Record<string, React.ReactNode> = {
+ search: <Search size={14} />
+ }
+
+ return (
+ <Badge className={className} variant={'secondary'}>
+ {icon[tool]}
+ <span className="ml-1">{children}</span>
+ </Badge>
+ )
+}
diff --git a/components/ui/avatar.tsx b/components/ui/avatar.tsx
new file mode 100644
index 00000000..4ea9b930
--- /dev/null
+++ b/components/ui/avatar.tsx
@@ -0,0 +1,50 @@
+'use client'
+
+import * as React from 'react'
+import * as AvatarPrimitive from '@radix-ui/react-avatar'
+
+import { cn } from '@/lib/utils'
+
+const Avatar = React.forwardRef<
+ React.ElementRef<typeof AvatarPrimitive.Root>,
+ React.ComponentPropsWithoutRef<typeof AvatarPrimitive.Root>
+>(({ className, ...props }, ref) => (
+ <AvatarPrimitive.Root
+ ref={ref}
+ className={cn(
+ 'relative flex h-10 w-10 shrink-0 overflow-hidden rounded-full',
+ className
+ )}
+ {...props}
+ />
+))
+Avatar.displayName = AvatarPrimitive.Root.displayName
+
+const AvatarImage = React.forwardRef<
+ React.ElementRef<typeof AvatarPrimitive.Image>,
+ React.ComponentPropsWithoutRef<typeof AvatarPrimitive.Image>
+>(({ className, ...props }, ref) => (
+ <AvatarPrimitive.Image
+ ref={ref}
+ className={cn('aspect-square h-full w-full', className)}
+ {...props}
+ />
+))
+AvatarImage.displayName = AvatarPrimitive.Image.displayName
+
+const AvatarFallback = React.forwardRef<
+ React.ElementRef<typeof AvatarPrimitive.Fallback>,
+ React.ComponentPropsWithoutRef<typeof AvatarPrimitive.Fallback>
+>(({ className, ...props }, ref) => (
+ <AvatarPrimitive.Fallback
+ ref={ref}
+ className={cn(
+ 'flex h-full w-full items-center justify-center rounded-full bg-muted',
+ className
+ )}
+ {...props}
+ />
+))
+AvatarFallback.displayName = AvatarPrimitive.Fallback.displayName
+
+export { Avatar, AvatarImage, AvatarFallback }
diff --git a/components/ui/badge.tsx b/components/ui/badge.tsx
new file mode 100644
index 00000000..d9a84b39
--- /dev/null
+++ b/components/ui/badge.tsx
@@ -0,0 +1,36 @@
+import * as React from 'react'
+import { cva, type VariantProps } from 'class-variance-authority'
+
+import { cn } from '@/lib/utils'
+
+const badgeVariants = cva(
+ 'inline-flex items-center rounded-full border px-2.5 py-0.5 text-xs font-semibold transition-colors focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2',
+ {
+ variants: {
+ variant: {
+ default:
+ 'border-transparent bg-primary text-primary-foreground hover:bg-primary/80',
+ secondary:
+ 'border-transparent bg-secondary text-secondary-foreground hover:bg-secondary/80',
+ destructive:
+ 'border-transparent bg-destructive text-destructive-foreground hover:bg-destructive/80',
+ outline: 'text-foreground'
+ }
+ },
+ defaultVariants: {
+ variant: 'default'
+ }
+ }
+)
+
+export interface BadgeProps
+ extends React.HTMLAttributes<HTMLDivElement>,
+ VariantProps<typeof badgeVariants> {}
+
+function Badge({ className, variant, ...props }: BadgeProps) {
+ return (
+ <div className={cn(badgeVariants({ variant }), className)} {...props} />
+ )
+}
+
+export { Badge, badgeVariants }
diff --git a/components/ui/button.tsx b/components/ui/button.tsx
new file mode 100644
index 00000000..22d68deb
--- /dev/null
+++ b/components/ui/button.tsx
@@ -0,0 +1,56 @@
+import * as React from 'react'
+import { Slot } from '@radix-ui/react-slot'
+import { cva, type VariantProps } from 'class-variance-authority'
+
+import { cn } from '@/lib/utils'
+
+const buttonVariants = cva(
+ 'inline-flex items-center justify-center whitespace-nowrap rounded-md text-sm font-medium ring-offset-background transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50',
+ {
+ variants: {
+ variant: {
+ default: 'bg-primary text-primary-foreground hover:bg-primary/90',
+ destructive:
+ 'bg-destructive text-destructive-foreground hover:bg-destructive/90',
+ outline:
+ 'border border-input bg-background hover:bg-accent hover:text-accent-foreground',
+ secondary:
+ 'bg-secondary text-secondary-foreground hover:bg-secondary/80',
+ ghost: 'hover:bg-accent hover:text-accent-foreground',
+ link: 'text-primary underline-offset-4 hover:underline'
+ },
+ size: {
+ default: 'h-10 px-4 py-2',
+ sm: 'h-9 rounded-md px-3',
+ lg: 'h-11 rounded-md px-8',
+ icon: 'h-10 w-10'
+ }
+ },
+ defaultVariants: {
+ variant: 'default',
+ size: 'default'
+ }
+ }
+)
+
+export interface ButtonProps
+ extends React.ButtonHTMLAttributes<HTMLButtonElement>,
+ VariantProps<typeof buttonVariants> {
+ asChild?: boolean
+}
+
+const Button = React.forwardRef<HTMLButtonElement, ButtonProps>(
+ ({ className, variant, size, asChild = false, ...props }, ref) => {
+ const Comp = asChild ? Slot : 'button'
+ return (
+ <Comp
+ className={cn(buttonVariants({ variant, size, className }))}
+ ref={ref}
+ {...props}
+ />
+ )
+ }
+)
+Button.displayName = 'Button'
+
+export { Button, buttonVariants }
diff --git a/components/ui/card.tsx b/components/ui/card.tsx
new file mode 100644
index 00000000..4902b398
--- /dev/null
+++ b/components/ui/card.tsx
@@ -0,0 +1,79 @@
+import * as React from 'react'
+
+import { cn } from '@/lib/utils'
+
+const Card = React.forwardRef<
+ HTMLDivElement,
+ React.HTMLAttributes<HTMLDivElement>
+>(({ className, ...props }, ref) => (
+ <div
+ ref={ref}
+ className={cn(
+ 'rounded-lg border bg-card text-card-foreground shadow-sm',
+ className
+ )}
+ {...props}
+ />
+))
+Card.displayName = 'Card'
+
+const CardHeader = React.forwardRef<
+ HTMLDivElement,
+ React.HTMLAttributes<HTMLDivElement>
+>(({ className, ...props }, ref) => (
+ <div
+ ref={ref}
+ className={cn('flex flex-col space-y-1.5 p-6', className)}
+ {...props}
+ />
+))
+CardHeader.displayName = 'CardHeader'
+
+const CardTitle = React.forwardRef<
+ HTMLParagraphElement,
+ React.HTMLAttributes<HTMLHeadingElement>
+>(({ className, ...props }, ref) => (
+ <h3
+ ref={ref}
+ className={cn(
+ 'text-2xl font-semibold leading-none tracking-tight',
+ className
+ )}
+ {...props}
+ />
+))
+CardTitle.displayName = 'CardTitle'
+
+const CardDescription = React.forwardRef<
+ HTMLParagraphElement,
+ React.HTMLAttributes<HTMLParagraphElement>
+>(({ className, ...props }, ref) => (
+ <p
+ ref={ref}
+ className={cn('text-sm text-muted-foreground', className)}
+ {...props}
+ />
+))
+CardDescription.displayName = 'CardDescription'
+
+const CardContent = React.forwardRef<
+ HTMLDivElement,
+ React.HTMLAttributes<HTMLDivElement>
+>(({ className, ...props }, ref) => (
+ <div ref={ref} className={cn('p-6 pt-0', className)} {...props} />
+))
+CardContent.displayName = 'CardContent'
+
+const CardFooter = React.forwardRef<
+ HTMLDivElement,
+ React.HTMLAttributes<HTMLDivElement>
+>(({ className, ...props }, ref) => (
+ <div
+ ref={ref}
+ className={cn('flex items-center p-6 pt-0', className)}
+ {...props}
+ />
+))
+CardFooter.displayName = 'CardFooter'
+
+export { Card, CardHeader, CardFooter, CardTitle, CardDescription, CardContent }
diff --git a/components/ui/carousel.tsx b/components/ui/carousel.tsx
new file mode 100644
index 00000000..52f8fcff
--- /dev/null
+++ b/components/ui/carousel.tsx
@@ -0,0 +1,262 @@
+'use client'
+
+import * as React from 'react'
+import useEmblaCarousel, {
+ type UseEmblaCarouselType
+} from 'embla-carousel-react'
+import { ArrowLeft, ArrowRight } from 'lucide-react'
+
+import { cn } from '@/lib/utils'
+import { Button } from '@/components/ui/button'
+
+type CarouselApi = UseEmblaCarouselType[1]
+type UseCarouselParameters = Parameters<typeof useEmblaCarousel>
+type CarouselOptions = UseCarouselParameters[0]
+type CarouselPlugin = UseCarouselParameters[1]
+
+type CarouselProps = {
+ opts?: CarouselOptions
+ plugins?: CarouselPlugin
+ orientation?: 'horizontal' | 'vertical'
+ setApi?: (api: CarouselApi) => void
+}
+
+type CarouselContextProps = {
+ carouselRef: ReturnType<typeof useEmblaCarousel>[0]
+ api: ReturnType<typeof useEmblaCarousel>[1]
+ scrollPrev: () => void
+ scrollNext: () => void
+ canScrollPrev: boolean
+ canScrollNext: boolean
+} & CarouselProps
+
+const CarouselContext = React.createContext<CarouselContextProps | null>(null)
+
+function useCarousel() {
+ const context = React.useContext(CarouselContext)
+
+ if (!context) {
+ throw new Error('useCarousel must be used within a <Carousel />')
+ }
+
+ return context
+}
+
+const Carousel = React.forwardRef<
+ HTMLDivElement,
+ React.HTMLAttributes<HTMLDivElement> & CarouselProps
+>(
+ (
+ {
+ orientation = 'horizontal',
+ opts,
+ setApi,
+ plugins,
+ className,
+ children,
+ ...props
+ },
+ ref
+ ) => {
+ const [carouselRef, api] = useEmblaCarousel(
+ {
+ ...opts,
+ axis: orientation === 'horizontal' ? 'x' : 'y'
+ },
+ plugins
+ )
+ const [canScrollPrev, setCanScrollPrev] = React.useState(false)
+ const [canScrollNext, setCanScrollNext] = React.useState(false)
+
+ const onSelect = React.useCallback((api: CarouselApi) => {
+ if (!api) {
+ return
+ }
+
+ setCanScrollPrev(api.canScrollPrev())
+ setCanScrollNext(api.canScrollNext())
+ }, [])
+
+ const scrollPrev = React.useCallback(() => {
+ api?.scrollPrev()
+ }, [api])
+
+ const scrollNext = React.useCallback(() => {
+ api?.scrollNext()
+ }, [api])
+
+ const handleKeyDown = React.useCallback(
+ (event: React.KeyboardEvent<HTMLDivElement>) => {
+ if (event.key === 'ArrowLeft') {
+ event.preventDefault()
+ scrollPrev()
+ } else if (event.key === 'ArrowRight') {
+ event.preventDefault()
+ scrollNext()
+ }
+ },
+ [scrollPrev, scrollNext]
+ )
+
+ React.useEffect(() => {
+ if (!api || !setApi) {
+ return
+ }
+
+ setApi(api)
+ }, [api, setApi])
+
+ React.useEffect(() => {
+ if (!api) {
+ return
+ }
+
+ onSelect(api)
+ api.on('reInit', onSelect)
+ api.on('select', onSelect)
+
+ return () => {
+ api?.off('select', onSelect)
+ }
+ }, [api, onSelect])
+
+ return (
+ <CarouselContext.Provider
+ value={{
+ carouselRef,
+ api: api,
+ opts,
+ orientation:
+ orientation || (opts?.axis === 'y' ? 'vertical' : 'horizontal'),
+ scrollPrev,
+ scrollNext,
+ canScrollPrev,
+ canScrollNext
+ }}
+ >
+ <div
+ ref={ref}
+ onKeyDownCapture={handleKeyDown}
+ className={cn('relative', className)}
+ role="region"
+ aria-roledescription="carousel"
+ {...props}
+ >
+ {children}
+ </div>
+ </CarouselContext.Provider>
+ )
+ }
+)
+Carousel.displayName = 'Carousel'
+
+const CarouselContent = React.forwardRef<
+ HTMLDivElement,
+ React.HTMLAttributes<HTMLDivElement>
+>(({ className, ...props }, ref) => {
+ const { carouselRef, orientation } = useCarousel()
+
+ return (
+ <div ref={carouselRef} className="overflow-hidden">
+ <div
+ ref={ref}
+ className={cn(
+ 'flex',
+ orientation === 'horizontal' ? '-ml-4' : '-mt-4 flex-col',
+ className
+ )}
+ {...props}
+ />
+ </div>
+ )
+})
+CarouselContent.displayName = 'CarouselContent'
+
+const CarouselItem = React.forwardRef<
+ HTMLDivElement,
+ React.HTMLAttributes<HTMLDivElement>
+>(({ className, ...props }, ref) => {
+ const { orientation } = useCarousel()
+
+ return (
+ <div
+ ref={ref}
+ role="group"
+ aria-roledescription="slide"
+ className={cn(
+ 'min-w-0 shrink-0 grow-0 basis-full',
+ orientation === 'horizontal' ? 'pl-4' : 'pt-4',
+ className
+ )}
+ {...props}
+ />
+ )
+})
+CarouselItem.displayName = 'CarouselItem'
+
+const CarouselPrevious = React.forwardRef<
+ HTMLButtonElement,
+ React.ComponentProps<typeof Button>
+>(({ className, variant = 'outline', size = 'icon', ...props }, ref) => {
+ const { orientation, scrollPrev, canScrollPrev } = useCarousel()
+
+ return (
+ <Button
+ ref={ref}
+ variant={variant}
+ size={size}
+ className={cn(
+ 'absolute h-8 w-8 rounded-full',
+ orientation === 'horizontal'
+ ? '-left-12 top-1/2 -translate-y-1/2'
+ : '-top-12 left-1/2 -translate-x-1/2 rotate-90',
+ className
+ )}
+ disabled={!canScrollPrev}
+ onClick={scrollPrev}
+ {...props}
+ >
+ <ArrowLeft className="h-4 w-4" />
+ <span className="sr-only">Previous slide</span>
+ </Button>
+ )
+})
+CarouselPrevious.displayName = 'CarouselPrevious'
+
+const CarouselNext = React.forwardRef<
+ HTMLButtonElement,
+ React.ComponentProps<typeof Button>
+>(({ className, variant = 'outline', size = 'icon', ...props }, ref) => {
+ const { orientation, scrollNext, canScrollNext } = useCarousel()
+
+ return (
+ <Button
+ ref={ref}
+ variant={variant}
+ size={size}
+ className={cn(
+ 'absolute h-8 w-8 rounded-full',
+ orientation === 'horizontal'
+ ? '-right-12 top-1/2 -translate-y-1/2'
+ : '-bottom-12 left-1/2 -translate-x-1/2 rotate-90',
+ className
+ )}
+ disabled={!canScrollNext}
+ onClick={scrollNext}
+ {...props}
+ >
+ <ArrowRight className="h-4 w-4" />
+ <span className="sr-only">Next slide</span>
+ </Button>
+ )
+})
+CarouselNext.displayName = 'CarouselNext'
+
+export {
+ type CarouselApi,
+ Carousel,
+ CarouselContent,
+ CarouselItem,
+ CarouselPrevious,
+ CarouselNext
+}
diff --git a/components/ui/checkbox.tsx b/components/ui/checkbox.tsx
new file mode 100644
index 00000000..774ee9ee
--- /dev/null
+++ b/components/ui/checkbox.tsx
@@ -0,0 +1,30 @@
+'use client'
+
+import * as React from 'react'
+import * as CheckboxPrimitive from '@radix-ui/react-checkbox'
+import { Check } from 'lucide-react'
+
+import { cn } from '@/lib/utils'
+
+const Checkbox = React.forwardRef<
+ React.ElementRef<typeof CheckboxPrimitive.Root>,
+ React.ComponentPropsWithoutRef<typeof CheckboxPrimitive.Root>
+>(({ className, ...props }, ref) => (
+ <CheckboxPrimitive.Root
+ ref={ref}
+ className={cn(
+ 'peer h-4 w-4 shrink-0 rounded-sm border border-primary ring-offset-background focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50 data-[state=checked]:bg-primary data-[state=checked]:text-primary-foreground',
+ className
+ )}
+ {...props}
+ >
+ <CheckboxPrimitive.Indicator
+ className={cn('flex items-center justify-center text-current')}
+ >
+ <Check className="h-4 w-4" />
+ </CheckboxPrimitive.Indicator>
+ </CheckboxPrimitive.Root>
+))
+Checkbox.displayName = CheckboxPrimitive.Root.displayName
+
+export { Checkbox }
diff --git a/components/ui/dialog.tsx b/components/ui/dialog.tsx
new file mode 100644
index 00000000..5509e2dd
--- /dev/null
+++ b/components/ui/dialog.tsx
@@ -0,0 +1,122 @@
+'use client'
+
+import * as React from 'react'
+import * as DialogPrimitive from '@radix-ui/react-dialog'
+import { X } from 'lucide-react'
+
+import { cn } from '@/lib/utils'
+
+const Dialog = DialogPrimitive.Root
+
+const DialogTrigger = DialogPrimitive.Trigger
+
+const DialogPortal = DialogPrimitive.Portal
+
+const DialogClose = DialogPrimitive.Close
+
+const DialogOverlay = React.forwardRef<
+ React.ElementRef<typeof DialogPrimitive.Overlay>,
+ React.ComponentPropsWithoutRef<typeof DialogPrimitive.Overlay>
+>(({ className, ...props }, ref) => (
+ <DialogPrimitive.Overlay
+ ref={ref}
+ className={cn(
+ 'fixed inset-0 z-50 bg-black/80 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0',
+ className
+ )}
+ {...props}
+ />
+))
+DialogOverlay.displayName = DialogPrimitive.Overlay.displayName
+
+const DialogContent = React.forwardRef<
+ React.ElementRef<typeof DialogPrimitive.Content>,
+ React.ComponentPropsWithoutRef<typeof DialogPrimitive.Content>
+>(({ className, children, ...props }, ref) => (
+ <DialogPortal>
+ <DialogOverlay />
+ <DialogPrimitive.Content
+ ref={ref}
+ className={cn(
+ 'fixed left-[50%] top-[50%] z-50 grid w-full max-w-lg translate-x-[-50%] translate-y-[-50%] gap-4 border bg-background p-6 shadow-lg duration-200 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[state=closed]:slide-out-to-left-1/2 data-[state=closed]:slide-out-to-top-[48%] data-[state=open]:slide-in-from-left-1/2 data-[state=open]:slide-in-from-top-[48%] sm:rounded-lg',
+ className
+ )}
+ {...props}
+ >
+ {children}
+ <DialogPrimitive.Close className="absolute right-4 top-4 rounded-sm opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:pointer-events-none data-[state=open]:bg-accent data-[state=open]:text-muted-foreground">
+ <X className="h-4 w-4" />
+ <span className="sr-only">Close</span>
+ </DialogPrimitive.Close>
+ </DialogPrimitive.Content>
+ </DialogPortal>
+))
+DialogContent.displayName = DialogPrimitive.Content.displayName
+
+const DialogHeader = ({
+ className,
+ ...props
+}: React.HTMLAttributes<HTMLDivElement>) => (
+ <div
+ className={cn(
+ 'flex flex-col space-y-1.5 text-center sm:text-left',
+ className
+ )}
+ {...props}
+ />
+)
+DialogHeader.displayName = 'DialogHeader'
+
+const DialogFooter = ({
+ className,
+ ...props
+}: React.HTMLAttributes<HTMLDivElement>) => (
+ <div
+ className={cn(
+ 'flex flex-col-reverse sm:flex-row sm:justify-end sm:space-x-2',
+ className
+ )}
+ {...props}
+ />
+)
+DialogFooter.displayName = 'DialogFooter'
+
+const DialogTitle = React.forwardRef<
+ React.ElementRef<typeof DialogPrimitive.Title>,
+ React.ComponentPropsWithoutRef<typeof DialogPrimitive.Title>
+>(({ className, ...props }, ref) => (
+ <DialogPrimitive.Title
+ ref={ref}
+ className={cn(
+ 'text-lg font-semibold leading-none tracking-tight',
+ className
+ )}
+ {...props}
+ />
+))
+DialogTitle.displayName = DialogPrimitive.Title.displayName
+
+const DialogDescription = React.forwardRef<
+ React.ElementRef<typeof DialogPrimitive.Description>,
+ React.ComponentPropsWithoutRef<typeof DialogPrimitive.Description>
+>(({ className, ...props }, ref) => (
+ <DialogPrimitive.Description
+ ref={ref}
+ className={cn('text-sm text-muted-foreground', className)}
+ {...props}
+ />
+))
+DialogDescription.displayName = DialogPrimitive.Description.displayName
+
+export {
+ Dialog,
+ DialogPortal,
+ DialogOverlay,
+ DialogClose,
+ DialogTrigger,
+ DialogContent,
+ DialogHeader,
+ DialogFooter,
+ DialogTitle,
+ DialogDescription
+}
diff --git a/components/ui/dropdown-menu.tsx b/components/ui/dropdown-menu.tsx
new file mode 100644
index 00000000..b0744124
--- /dev/null
+++ b/components/ui/dropdown-menu.tsx
@@ -0,0 +1,200 @@
+'use client'
+
+import * as React from 'react'
+import * as DropdownMenuPrimitive from '@radix-ui/react-dropdown-menu'
+import { Check, ChevronRight, Circle } from 'lucide-react'
+
+import { cn } from '@/lib/utils'
+
+const DropdownMenu = DropdownMenuPrimitive.Root
+
+const DropdownMenuTrigger = DropdownMenuPrimitive.Trigger
+
+const DropdownMenuGroup = DropdownMenuPrimitive.Group
+
+const DropdownMenuPortal = DropdownMenuPrimitive.Portal
+
+const DropdownMenuSub = DropdownMenuPrimitive.Sub
+
+const DropdownMenuRadioGroup = DropdownMenuPrimitive.RadioGroup
+
+const DropdownMenuSubTrigger = React.forwardRef<
+ React.ElementRef<typeof DropdownMenuPrimitive.SubTrigger>,
+ React.ComponentPropsWithoutRef<typeof DropdownMenuPrimitive.SubTrigger> & {
+ inset?: boolean
+ }
+>(({ className, inset, children, ...props }, ref) => (
+ <DropdownMenuPrimitive.SubTrigger
+ ref={ref}
+ className={cn(
+ 'flex cursor-default select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none focus:bg-accent data-[state=open]:bg-accent',
+ inset && 'pl-8',
+ className
+ )}
+ {...props}
+ >
+ {children}
+ <ChevronRight className="ml-auto h-4 w-4" />
+ </DropdownMenuPrimitive.SubTrigger>
+))
+DropdownMenuSubTrigger.displayName =
+ DropdownMenuPrimitive.SubTrigger.displayName
+
+const DropdownMenuSubContent = React.forwardRef<
+ React.ElementRef<typeof DropdownMenuPrimitive.SubContent>,
+ React.ComponentPropsWithoutRef<typeof DropdownMenuPrimitive.SubContent>
+>(({ className, ...props }, ref) => (
+ <DropdownMenuPrimitive.SubContent
+ ref={ref}
+ className={cn(
+ 'z-50 min-w-[8rem] overflow-hidden rounded-md border bg-popover p-1 text-popover-foreground shadow-lg data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2',
+ className
+ )}
+ {...props}
+ />
+))
+DropdownMenuSubContent.displayName =
+ DropdownMenuPrimitive.SubContent.displayName
+
+const DropdownMenuContent = React.forwardRef<
+ React.ElementRef<typeof DropdownMenuPrimitive.Content>,
+ React.ComponentPropsWithoutRef<typeof DropdownMenuPrimitive.Content>
+>(({ className, sideOffset = 4, ...props }, ref) => (
+ <DropdownMenuPrimitive.Portal>
+ <DropdownMenuPrimitive.Content
+ ref={ref}
+ sideOffset={sideOffset}
+ className={cn(
+ 'z-50 min-w-[8rem] overflow-hidden rounded-md border bg-popover p-1 text-popover-foreground shadow-md data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2',
+ className
+ )}
+ {...props}
+ />
+ </DropdownMenuPrimitive.Portal>
+))
+DropdownMenuContent.displayName = DropdownMenuPrimitive.Content.displayName
+
+const DropdownMenuItem = React.forwardRef<
+ React.ElementRef<typeof DropdownMenuPrimitive.Item>,
+ React.ComponentPropsWithoutRef<typeof DropdownMenuPrimitive.Item> & {
+ inset?: boolean
+ }
+>(({ className, inset, ...props }, ref) => (
+ <DropdownMenuPrimitive.Item
+ ref={ref}
+ className={cn(
+ 'relative flex cursor-default select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none transition-colors focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50',
+ inset && 'pl-8',
+ className
+ )}
+ {...props}
+ />
+))
+DropdownMenuItem.displayName = DropdownMenuPrimitive.Item.displayName
+
+const DropdownMenuCheckboxItem = React.forwardRef<
+ React.ElementRef<typeof DropdownMenuPrimitive.CheckboxItem>,
+ React.ComponentPropsWithoutRef<typeof DropdownMenuPrimitive.CheckboxItem>
+>(({ className, children, checked, ...props }, ref) => (
+ <DropdownMenuPrimitive.CheckboxItem
+ ref={ref}
+ className={cn(
+ 'relative flex cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none transition-colors focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50',
+ className
+ )}
+ checked={checked}
+ {...props}
+ >
+ <span className="absolute left-2 flex h-3.5 w-3.5 items-center justify-center">
+ <DropdownMenuPrimitive.ItemIndicator>
+ <Check className="h-4 w-4" />
+ </DropdownMenuPrimitive.ItemIndicator>
+ </span>
+ {children}
+ </DropdownMenuPrimitive.CheckboxItem>
+))
+DropdownMenuCheckboxItem.displayName =
+ DropdownMenuPrimitive.CheckboxItem.displayName
+
+const DropdownMenuRadioItem = React.forwardRef<
+ React.ElementRef<typeof DropdownMenuPrimitive.RadioItem>,
+ React.ComponentPropsWithoutRef<typeof DropdownMenuPrimitive.RadioItem>
+>(({ className, children, ...props }, ref) => (
+ <DropdownMenuPrimitive.RadioItem
+ ref={ref}
+ className={cn(
+ 'relative flex cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none transition-colors focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50',
+ className
+ )}
+ {...props}
+ >
+ <span className="absolute left-2 flex h-3.5 w-3.5 items-center justify-center">
+ <DropdownMenuPrimitive.ItemIndicator>
+ <Circle className="h-2 w-2 fill-current" />
+ </DropdownMenuPrimitive.ItemIndicator>
+ </span>
+ {children}
+ </DropdownMenuPrimitive.RadioItem>
+))
+DropdownMenuRadioItem.displayName = DropdownMenuPrimitive.RadioItem.displayName
+
+const DropdownMenuLabel = React.forwardRef<
+ React.ElementRef<typeof DropdownMenuPrimitive.Label>,
+ React.ComponentPropsWithoutRef<typeof DropdownMenuPrimitive.Label> & {
+ inset?: boolean
+ }
+>(({ className, inset, ...props }, ref) => (
+ <DropdownMenuPrimitive.Label
+ ref={ref}
+ className={cn(
+ 'px-2 py-1.5 text-sm font-semibold',
+ inset && 'pl-8',
+ className
+ )}
+ {...props}
+ />
+))
+DropdownMenuLabel.displayName = DropdownMenuPrimitive.Label.displayName
+
+const DropdownMenuSeparator = React.forwardRef<
+ React.ElementRef<typeof DropdownMenuPrimitive.Separator>,
+ React.ComponentPropsWithoutRef<typeof DropdownMenuPrimitive.Separator>
+>(({ className, ...props }, ref) => (
+ <DropdownMenuPrimitive.Separator
+ ref={ref}
+ className={cn('-mx-1 my-1 h-px bg-muted', className)}
+ {...props}
+ />
+))
+DropdownMenuSeparator.displayName = DropdownMenuPrimitive.Separator.displayName
+
+const DropdownMenuShortcut = ({
+ className,
+ ...props
+}: React.HTMLAttributes<HTMLSpanElement>) => {
+ return (
+ <span
+ className={cn('ml-auto text-xs tracking-widest opacity-60', className)}
+ {...props}
+ />
+ )
+}
+DropdownMenuShortcut.displayName = 'DropdownMenuShortcut'
+
+export {
+ DropdownMenu,
+ DropdownMenuTrigger,
+ DropdownMenuContent,
+ DropdownMenuItem,
+ DropdownMenuCheckboxItem,
+ DropdownMenuRadioItem,
+ DropdownMenuLabel,
+ DropdownMenuSeparator,
+ DropdownMenuShortcut,
+ DropdownMenuGroup,
+ DropdownMenuPortal,
+ DropdownMenuSub,
+ DropdownMenuSubContent,
+ DropdownMenuSubTrigger,
+ DropdownMenuRadioGroup
+}
diff --git a/components/ui/icons.tsx b/components/ui/icons.tsx
new file mode 100644
index 00000000..8a00dc9e
--- /dev/null
+++ b/components/ui/icons.tsx
@@ -0,0 +1,22 @@
+'use client'
+
+import { cn } from '@/lib/utils'
+
+function IconLogo({ className, ...props }: React.ComponentProps<'svg'>) {
+ return (
+ <svg
+ fill="currentColor"
+ viewBox="0 0 256 256"
+ role="img"
+ xmlns="http://www.w3.org/2000/svg"
+ className={cn('h-4 w-4', className)}
+ {...props}
+ >
+ <circle cx="128" cy="128" r="128" fill="black"></circle>
+ <circle cx="102" cy="128" r="18" fill="white"></circle>
+ <circle cx="154" cy="128" r="18" fill="white"></circle>
+ </svg>
+ )
+}
+
+export { IconLogo }
diff --git a/components/ui/input.tsx b/components/ui/input.tsx
new file mode 100644
index 00000000..d52138b9
--- /dev/null
+++ b/components/ui/input.tsx
@@ -0,0 +1,25 @@
+import * as React from 'react'
+
+import { cn } from '@/lib/utils'
+
+export interface InputProps
+ extends React.InputHTMLAttributes<HTMLInputElement> {}
+
+const Input = React.forwardRef<HTMLInputElement, InputProps>(
+ ({ className, type, ...props }, ref) => {
+ return (
+ <input
+ type={type}
+ className={cn(
+ 'flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background file:border-0 file:bg-transparent file:text-sm file:font-medium placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50',
+ className
+ )}
+ ref={ref}
+ {...props}
+ />
+ )
+ }
+)
+Input.displayName = 'Input'
+
+export { Input }
diff --git a/components/ui/label.tsx b/components/ui/label.tsx
new file mode 100644
index 00000000..340513e6
--- /dev/null
+++ b/components/ui/label.tsx
@@ -0,0 +1,26 @@
+'use client'
+
+import * as React from 'react'
+import * as LabelPrimitive from '@radix-ui/react-label'
+import { cva, type VariantProps } from 'class-variance-authority'
+
+import { cn } from '@/lib/utils'
+
+const labelVariants = cva(
+ 'text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70'
+)
+
+const Label = React.forwardRef<
+ React.ElementRef<typeof LabelPrimitive.Root>,
+ React.ComponentPropsWithoutRef<typeof LabelPrimitive.Root> &
+ VariantProps<typeof labelVariants>
+>(({ className, ...props }, ref) => (
+ <LabelPrimitive.Root
+ ref={ref}
+ className={cn(labelVariants(), className)}
+ {...props}
+ />
+))
+Label.displayName = LabelPrimitive.Root.displayName
+
+export { Label }
diff --git a/components/ui/markdown.tsx b/components/ui/markdown.tsx
new file mode 100644
index 00000000..d4491467
--- /dev/null
+++ b/components/ui/markdown.tsx
@@ -0,0 +1,9 @@
+import { FC, memo } from 'react'
+import ReactMarkdown, { Options } from 'react-markdown'
+
+export const MemoizedReactMarkdown: FC<Options> = memo(
+ ReactMarkdown,
+ (prevProps, nextProps) =>
+ prevProps.children === nextProps.children &&
+ prevProps.className === nextProps.className
+)
diff --git a/components/ui/separator.tsx b/components/ui/separator.tsx
new file mode 100644
index 00000000..6c55e0b2
--- /dev/null
+++ b/components/ui/separator.tsx
@@ -0,0 +1,31 @@
+'use client'
+
+import * as React from 'react'
+import * as SeparatorPrimitive from '@radix-ui/react-separator'
+
+import { cn } from '@/lib/utils'
+
+const Separator = React.forwardRef<
+ React.ElementRef<typeof SeparatorPrimitive.Root>,
+ React.ComponentPropsWithoutRef<typeof SeparatorPrimitive.Root>
+>(
+ (
+ { className, orientation = 'horizontal', decorative = true, ...props },
+ ref
+ ) => (
+ <SeparatorPrimitive.Root
+ ref={ref}
+ decorative={decorative}
+ orientation={orientation}
+ className={cn(
+ 'shrink-0 bg-border',
+ orientation === 'horizontal' ? 'h-[1px] w-full' : 'h-full w-[1px]',
+ className
+ )}
+ {...props}
+ />
+ )
+)
+Separator.displayName = SeparatorPrimitive.Root.displayName
+
+export { Separator }
diff --git a/components/ui/skeleton.tsx b/components/ui/skeleton.tsx
new file mode 100644
index 00000000..c23a30d9
--- /dev/null
+++ b/components/ui/skeleton.tsx
@@ -0,0 +1,15 @@
+import { cn } from '@/lib/utils'
+
+function Skeleton({
+ className,
+ ...props
+}: React.HTMLAttributes<HTMLDivElement>) {
+ return (
+ <div
+ className={cn('animate-pulse rounded-md bg-muted', className)}
+ {...props}
+ />
+ )
+}
+
+export { Skeleton }
diff --git a/components/ui/slider.tsx b/components/ui/slider.tsx
new file mode 100644
index 00000000..de1747ce
--- /dev/null
+++ b/components/ui/slider.tsx
@@ -0,0 +1,28 @@
+'use client'
+
+import * as React from 'react'
+import * as SliderPrimitive from '@radix-ui/react-slider'
+
+import { cn } from '@/lib/utils'
+
+const Slider = React.forwardRef<
+ React.ElementRef<typeof SliderPrimitive.Root>,
+ React.ComponentPropsWithoutRef<typeof SliderPrimitive.Root>
+>(({ className, ...props }, ref) => (
+ <SliderPrimitive.Root
+ ref={ref}
+ className={cn(
+ 'relative flex w-full touch-none select-none items-center',
+ className
+ )}
+ {...props}
+ >
+ <SliderPrimitive.Track className="relative h-2 w-full grow overflow-hidden rounded-full bg-secondary">
+ <SliderPrimitive.Range className="absolute h-full bg-primary" />
+ </SliderPrimitive.Track>
+ <SliderPrimitive.Thumb className="block h-5 w-5 rounded-full border-2 border-primary bg-background ring-offset-background transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50" />
+ </SliderPrimitive.Root>
+))
+Slider.displayName = SliderPrimitive.Root.displayName
+
+export { Slider }
diff --git a/components/ui/spinner.tsx b/components/ui/spinner.tsx
new file mode 100644
index 00000000..91c843c8
--- /dev/null
+++ b/components/ui/spinner.tsx
@@ -0,0 +1,25 @@
+// Based on: https://github.com/vercel/ai/blob/main/examples/next-ai-rsc/components/llm-stocks/spinner.tsx
+
+import { Card } from './card'
+import { IconLogo } from './icons'
+
+export const Spinner = () => (
+ <svg
+ fill="none"
+ stroke="currentColor"
+ strokeWidth="1.5"
+ viewBox="0 0 24 24"
+ strokeLinecap="round"
+ strokeLinejoin="round"
+ xmlns="http://www.w3.org/2000/svg"
+ className="h-5 w-5 animate-spin stroke-zinc-400"
+ >
+ <path d="M12 3v3m6.366-.366-2.12 2.12M21 12h-3m.366 6.366-2.12-2.12M12 21v-3m-6.366.366 2.12-2.12M3 12h3m-.366-6.366 2.12 2.12"></path>
+ </svg>
+)
+
+export const LogoSpinner = () => (
+ <div className="p-4 border border-background">
+ <IconLogo className="w-4 h-4 animate-spin" />
+ </div>
+)
diff --git a/components/ui/switch.tsx b/components/ui/switch.tsx
new file mode 100644
index 00000000..22432b9c
--- /dev/null
+++ b/components/ui/switch.tsx
@@ -0,0 +1,29 @@
+'use client'
+
+import * as React from 'react'
+import * as SwitchPrimitives from '@radix-ui/react-switch'
+
+import { cn } from '@/lib/utils'
+
+const Switch = React.forwardRef<
+ React.ElementRef<typeof SwitchPrimitives.Root>,
+ React.ComponentPropsWithoutRef<typeof SwitchPrimitives.Root>
+>(({ className, ...props }, ref) => (
+ <SwitchPrimitives.Root
+ className={cn(
+ 'peer inline-flex h-6 w-11 shrink-0 cursor-pointer items-center rounded-full border-2 border-transparent transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background disabled:cursor-not-allowed disabled:opacity-50 data-[state=checked]:bg-primary data-[state=unchecked]:bg-input',
+ className
+ )}
+ {...props}
+ ref={ref}
+ >
+ <SwitchPrimitives.Thumb
+ className={cn(
+ 'pointer-events-none block h-5 w-5 rounded-full bg-background shadow-lg ring-0 transition-transform data-[state=checked]:translate-x-5 data-[state=unchecked]:translate-x-0'
+ )}
+ />
+ </SwitchPrimitives.Root>
+))
+Switch.displayName = SwitchPrimitives.Root.displayName
+
+export { Switch }
diff --git a/components/ui/textarea.tsx b/components/ui/textarea.tsx
new file mode 100644
index 00000000..cf5e9558
--- /dev/null
+++ b/components/ui/textarea.tsx
@@ -0,0 +1,24 @@
+import * as React from 'react'
+
+import { cn } from '@/lib/utils'
+
+export interface TextareaProps
+ extends React.TextareaHTMLAttributes<HTMLTextAreaElement> {}
+
+const Textarea = React.forwardRef<HTMLTextAreaElement, TextareaProps>(
+ ({ className, ...props }, ref) => {
+ return (
+ <textarea
+ className={cn(
+ 'flex min-h-[80px] w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50',
+ className
+ )}
+ ref={ref}
+ {...props}
+ />
+ )
+ }
+)
+Textarea.displayName = 'Textarea'
+
+export { Textarea }
diff --git a/components/user-message.tsx b/components/user-message.tsx
new file mode 100644
index 00000000..3bc277c4
--- /dev/null
+++ b/components/user-message.tsx
@@ -0,0 +1,18 @@
+import { cn } from '@/lib/utils'
+import React from 'react'
+
+type UserMessageProps = {
+ message: string
+ isFirstMessage?: boolean
+}
+
+export const UserMessage: React.FC<UserMessageProps> = ({
+ message,
+ isFirstMessage
+}) => {
+ return (
+ <div className={cn({ 'pt-4': !isFirstMessage })}>
+ <div className="text-xl">{message}</div>
+ </div>
+ )
+}
diff --git a/lib/utils/index.ts b/lib/utils/index.ts
new file mode 100644
index 00000000..d32b0fe6
--- /dev/null
+++ b/lib/utils/index.ts
@@ -0,0 +1,6 @@
+import { type ClassValue, clsx } from 'clsx'
+import { twMerge } from 'tailwind-merge'
+
+export function cn(...inputs: ClassValue[]) {
+ return twMerge(clsx(inputs))
+}
diff --git a/next.config.mjs b/next.config.mjs
new file mode 100644
index 00000000..4678774e
--- /dev/null
+++ b/next.config.mjs
@@ -0,0 +1,4 @@
+/** @type {import('next').NextConfig} */
+const nextConfig = {};
+
+export default nextConfig;
diff --git a/package.json b/package.json
new file mode 100644
index 00000000..03f6c01e
--- /dev/null
+++ b/package.json
@@ -0,0 +1,48 @@
+{
+ "name": "mophic",
+ "version": "0.1.0",
+ "private": true,
+ "license": "Apache-2.0",
+ "scripts": {
+ "dev": "next dev",
+ "build": "next build",
+ "start": "next start",
+ "lint": "next lint"
+ },
+ "dependencies": {
+ "@radix-ui/react-avatar": "^1.0.4",
+ "@radix-ui/react-checkbox": "^1.0.4",
+ "@radix-ui/react-dialog": "^1.0.5",
+ "@radix-ui/react-dropdown-menu": "^2.0.6",
+ "@radix-ui/react-label": "^2.0.2",
+ "@radix-ui/react-separator": "^1.0.3",
+ "@radix-ui/react-slider": "^1.1.2",
+ "@radix-ui/react-slot": "^1.0.2",
+ "@radix-ui/react-switch": "^1.0.3",
+ "@tailwindcss/typography": "^0.5.12",
+ "ai": "^3.0.14",
+ "class-variance-authority": "^0.7.0",
+ "clsx": "^2.1.0",
+ "embla-carousel-react": "^8.0.0",
+ "exa-js": "^1.0.12",
+ "lucide-react": "^0.363.0",
+ "next": "v14.2.0-canary.60",
+ "next-themes": "^0.3.0",
+ "react": "^18",
+ "react-dom": "^18",
+ "react-icons": "^5.0.1",
+ "react-markdown": "^9.0.1",
+ "tailwind-merge": "^2.2.2",
+ "tailwindcss-animate": "^1.0.7"
+ },
+ "devDependencies": {
+ "typescript": "^5",
+ "@types/node": "^20",
+ "@types/react": "^18",
+ "@types/react-dom": "^18",
+ "postcss": "^8",
+ "tailwindcss": "^3.4.1",
+ "eslint": "^8",
+ "eslint-config-next": "14.2.0-canary.41"
+ }
+}
diff --git a/postcss.config.mjs b/postcss.config.mjs
new file mode 100644
index 00000000..1a69fd2a
--- /dev/null
+++ b/postcss.config.mjs
@@ -0,0 +1,8 @@
+/** @type {import('postcss-load-config').Config} */
+const config = {
+ plugins: {
+ tailwindcss: {},
+ },
+};
+
+export default config;
diff --git a/prettier.config.js b/prettier.config.js
new file mode 100644
index 00000000..9b7f5b7e
--- /dev/null
+++ b/prettier.config.js
@@ -0,0 +1,34 @@
+/** @type {import('prettier').Config} */
+module.exports = {
+ endOfLine: 'lf',
+ semi: false,
+ useTabs: false,
+ singleQuote: true,
+ arrowParens: 'avoid',
+ tabWidth: 2,
+ trailingComma: 'none',
+ importOrder: [
+ '^(react/(.*)$)|^(react$)',
+ '^(next/(.*)$)|^(next$)',
+ '<THIRD_PARTY_MODULES>',
+ '',
+ '^types$',
+ '^@/types/(.*)$',
+ '^@/config/(.*)$',
+ '^@/lib/(.*)$',
+ '^@/hooks/(.*)$',
+ '^@/components/ui/(.*)$',
+ '^@/components/(.*)$',
+ '^@/registry/(.*)$',
+ '^@/styles/(.*)$',
+ '^@/app/(.*)$',
+ '',
+ '^[./]',
+ ],
+ importOrderSeparation: false,
+ importOrderSortSpecifiers: true,
+ importOrderBuiltinModulesToTop: true,
+ importOrderParserPlugins: ['typescript', 'jsx', 'decorators-legacy'],
+ importOrderMergeDuplicateImports: true,
+ importOrderCombineTypeAndValueImports: true,
+};
diff --git a/public/capture-240404.png b/public/capture-240404.png
new file mode 100644
index 00000000..1b63d3ce
Binary files /dev/null and b/public/capture-240404.png differ
diff --git a/tailwind.config.ts b/tailwind.config.ts
new file mode 100644
index 00000000..68c971ee
--- /dev/null
+++ b/tailwind.config.ts
@@ -0,0 +1,84 @@
+import type { Config } from "tailwindcss";
+const { fontFamily } = require("tailwindcss/defaultTheme");
+
+const config = {
+ darkMode: ["class"],
+ content: [
+ "./pages/**/*.{ts,tsx}",
+ "./components/**/*.{ts,tsx}",
+ "./app/**/*.{ts,tsx}",
+ "./src/**/*.{ts,tsx}",
+ ],
+ prefix: "",
+ theme: {
+ container: {
+ center: true,
+ padding: "2rem",
+ screens: {
+ "2xl": "1400px",
+ },
+ },
+ extend: {
+ colors: {
+ border: "hsl(var(--border))",
+ input: "hsl(var(--input))",
+ ring: "hsl(var(--ring))",
+ background: "hsl(var(--background))",
+ foreground: "hsl(var(--foreground))",
+ primary: {
+ DEFAULT: "hsl(var(--primary))",
+ foreground: "hsl(var(--primary-foreground))",
+ },
+ secondary: {
+ DEFAULT: "hsl(var(--secondary))",
+ foreground: "hsl(var(--secondary-foreground))",
+ },
+ destructive: {
+ DEFAULT: "hsl(var(--destructive))",
+ foreground: "hsl(var(--destructive-foreground))",
+ },
+ muted: {
+ DEFAULT: "hsl(var(--muted))",
+ foreground: "hsl(var(--muted-foreground))",
+ },
+ accent: {
+ DEFAULT: "hsl(var(--accent))",
+ foreground: "hsl(var(--accent-foreground))",
+ },
+ popover: {
+ DEFAULT: "hsl(var(--popover))",
+ foreground: "hsl(var(--popover-foreground))",
+ },
+ card: {
+ DEFAULT: "hsl(var(--card))",
+ foreground: "hsl(var(--card-foreground))",
+ },
+ },
+ borderRadius: {
+ lg: "var(--radius)",
+ md: "calc(var(--radius) - 2px)",
+ sm: "calc(var(--radius) - 4px)",
+ },
+ keyframes: {
+ "accordion-down": {
+ from: { height: "0" },
+ to: { height: "var(--radix-accordion-content-height)" },
+ },
+ "accordion-up": {
+ from: { height: "var(--radix-accordion-content-height)" },
+ to: { height: "0" },
+ },
+ },
+ animation: {
+ "accordion-down": "accordion-down 0.2s ease-out",
+ "accordion-up": "accordion-up 0.2s ease-out",
+ },
+ fontFamily: {
+ sans: ["var(--font-sans)", ...fontFamily.sans],
+ },
+ },
+ },
+ plugins: [require("tailwindcss-animate"), require("@tailwindcss/typography")],
+} satisfies Config;
+
+export default config;
diff --git a/tsconfig.json b/tsconfig.json
new file mode 100644
index 00000000..e7ff90fd
--- /dev/null
+++ b/tsconfig.json
@@ -0,0 +1,26 @@
+{
+ "compilerOptions": {
+ "lib": ["dom", "dom.iterable", "esnext"],
+ "allowJs": true,
+ "skipLibCheck": true,
+ "strict": true,
+ "noEmit": true,
+ "esModuleInterop": true,
+ "module": "esnext",
+ "moduleResolution": "bundler",
+ "resolveJsonModule": true,
+ "isolatedModules": true,
+ "jsx": "preserve",
+ "incremental": true,
+ "plugins": [
+ {
+ "name": "next"
+ }
+ ],
+ "paths": {
+ "@/*": ["./*"]
+ }
+ },
+ "include": ["next-env.d.ts", "**/*.ts", "**/*.tsx", ".next/types/**/*.ts"],
+ "exclude": ["node_modules"]
+}