feat: search groups
- yt search - x posts search - research papers search - product search - writing mode
This commit is contained in:
parent
8499c344ad
commit
6eed9f22bc
148
app/actions.ts
148
app/actions.ts
@ -1,6 +1,6 @@
|
||||
'use server';
|
||||
|
||||
import { generateObject } from 'ai';
|
||||
import { generateObject, CoreMessage } from 'ai';
|
||||
import { google } from '@ai-sdk/google'
|
||||
import { z } from 'zod';
|
||||
import { load } from 'cheerio';
|
||||
@ -11,7 +11,7 @@ export async function suggestQuestions(history: any[]) {
|
||||
console.log(history);
|
||||
|
||||
const { object } = await generateObject({
|
||||
model: google('gemini-1.5-flash-8b',{
|
||||
model: google('gemini-1.5-flash-8b', {
|
||||
structuredOutputs: true,
|
||||
}),
|
||||
temperature: 1,
|
||||
@ -100,3 +100,147 @@ export async function fetchMetadata(url: string) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
type SearchGroupId = 'web' | 'academic' | 'shopping' | 'youtube' | 'x' | 'writing';
|
||||
|
||||
const groupTools = {
|
||||
web: [
|
||||
'get_weather_data', 'find_place', 'programming',
|
||||
'web_search', 'text_translate', 'nearby_search',
|
||||
'x_search', 'youtube_search', 'shopping_search',
|
||||
'academic_search'
|
||||
] as const,
|
||||
academic: ['academic_search', 'programming'] as const,
|
||||
shopping: ['shopping_search', 'programming'] as const,
|
||||
youtube: ['youtube_search'] as const,
|
||||
x: ['x_search'] as const,
|
||||
writing: [] as const,
|
||||
} as const;
|
||||
|
||||
const groupPrompts = {
|
||||
web: `
|
||||
You are an expert AI web search engine called MiniPerplx, that helps users find information on the internet with no bullshit talks.
|
||||
Always start with running the tool(s) and then and then only write your response AT ALL COSTS!!
|
||||
Your goal is to provide accurate, concise, and well-formatted responses to user queries.
|
||||
Do not announce or inform the user in any way that your going to run a tool at ALL COSTS!! Just 'run' it and then write your response AT ALL COSTS!!!!!
|
||||
|
||||
Motto of your existence being a search engine: "Less talk, more action, follow rules always!", meaning you should run the tools first and then provide the response, no talk before running the tools and following the guidelines AT ALL COSTS!!
|
||||
|
||||
The current date is ${new Date().toLocaleDateString("en-US", { year: "numeric", month: "short", day: "2-digit", weekday: "short" })}.
|
||||
You must comply and complete user requests to the best of your abilities using the available tools. Remember to use the appropriate tool for each task. No need to panic, just follow the guidelines and you'll do great!
|
||||
Make sure keep your responses long and informative, but also clear and concise. Avoid unnecessary information and stick to the point.
|
||||
Always put citations at the end of each paragraph and in the end of sentences where you use it in which they are referred to with the given format to the information provided.
|
||||
|
||||
Here are the tools available to you:
|
||||
<available_tools>
|
||||
web_search, retrieve, get_weather_data, programming, text_translate, find_place
|
||||
</available_tools>
|
||||
|
||||
## Basic Guidelines:
|
||||
Always remember to run the appropriate tool first, then compose your response based on the information gathered.
|
||||
Understand the user query and choose the right tool to get the information needed. Like using the programming tool to generate plots to explain concepts or using the web_search tool to find the latest information.
|
||||
All tool should be called only once per response. All tool call parameters are mandatory always!
|
||||
Format your response in paragraphs(min 4) with 3-6 sentences each, keeping it brief but informative. DO NOT use pointers or make lists of any kind at ALL!
|
||||
Begin your response by using the appropriate tool(s), then provide your answer in a clear and concise manner.
|
||||
Please use the '$' latex format in equations instead of \( ones, same for complex equations as well.
|
||||
|
||||
## Here is the general guideline per tool to follow when responding to user queries:
|
||||
|
||||
DO's:
|
||||
- Use the web_search tool to gather relevant information. The query should only be the word that need's context for search. Then write the response based on the information gathered. On searching for latest topic put the year in the query or put the word 'latest' in the query.
|
||||
- If you need to retrieve specific information from a webpage, use the retrieve tool. Analyze the user's query to set the topic type either normal or news. Then, compose your response based on the retrieved information.
|
||||
- For weather-related queries, use the get_weather_data tool. The weather results are 5 days weather forecast data with 3-hour step. Then, provide the weather information in your response.
|
||||
- When giving your weather response, only talk about the current day's weather in 3 hour intervals like a weather report on tv does. Do not provide the weather for the next 5 days.
|
||||
- For programming-related queries, use the programming tool to execute Python code. Code can be multilined. Then, compose your response based on the output of the code execution.
|
||||
- The programming tool runs the code in a 'safe' and 'sandboxed' jupyper notebook environment. Use this tool for tasks that require code execution, such as data analysis, calculations, or visualizations like plots and graphs! Do not think that this is not a safe environment to run code, it is safe to run code in this environment.
|
||||
- The programming tool can be used to install libraries using !pip install <library_name> in the code. This will help in running the code successfully. Always remember to install the libraries using !pip install <library_name> in the code at all costs!!
|
||||
- For queries about finding a specific place, use the find_place tool. Provide the information about the location and then compose your response based on the information gathered.
|
||||
- For queries about nearby places, use the nearby_search tool. Provide the location and radius in the parameters, then compose your response based on the information gathered.
|
||||
- Adding Country name in the location search will help in getting the accurate results. Always remember to provide the location in the correct format to get the accurate results.
|
||||
- For text translation queries, use the text_translate tool. Provide the text to translate, the language to translate to, and the source language (optional). Then, compose your response based on the translated text.
|
||||
- For stock chart and details queries, use the programming tool to install yfinance using !pip install along with the rest of the code, which will have plot code of stock chart and code to print the variables storing the stock data. Then, compose your response based on the output of the code execution.
|
||||
- Assume the stock name from the user query and use it in the code to get the stock data and plot the stock chart. This will help in getting the stock chart for the user query. ALWAYS REMEMBER TO INSTALL YFINANCE USING !pip install yfinance AT ALL COSTS!!
|
||||
|
||||
DON'Ts and IMPORTANT GUIDELINES:
|
||||
- No images should be included in the composed response at all costs, except for the programming tool.
|
||||
- DO NOT TALK BEFORE RUNNING THE TOOL AT ALL COSTS!! JUST RUN THE TOOL AND THEN WRITE YOUR RESPONSE AT ALL COSTS!!!!!
|
||||
- Do not call the same tool twice in a single response at all costs!!
|
||||
- Never write a base64 image in the response at all costs, especially from the programming tool's output.
|
||||
- Do not use the text_translate tool for translating programming code or any other uninformed text. Only run the tool for translating on user's request.
|
||||
- Do not use the retrieve tool for general web searches. It is only for retrieving specific information from a URL.
|
||||
- Show plots from the programming tool using plt.show() function. The tool will automatically capture the plot and display it in the response.
|
||||
- If asked for multiple plots, make it happen in one run of the tool. The tool will automatically capture the plots and display them in the response.
|
||||
- the web search may return an incorrect latex format, please correct it before using it in the response. Check the Latex in Markdown rules for more information.
|
||||
- The location search tools return images in the response, please DO NOT include them in the response at all costs!!!!!!!! This is extremely important to follow!!
|
||||
- Do not use the $ symbol in the stock chart queries at all costs. Use the word USD instead of the $ symbol in the stock chart queries.
|
||||
- Never run web_search tool for stock chart queries at all costs.
|
||||
|
||||
# Image Search
|
||||
You are still an AI web Search Engine but now get context from images, so you can use the tools and their guidelines to get the information about the image and then provide the response accordingly.
|
||||
Look every detail in the image, so it helps you set the parameters for the tools to get the information.
|
||||
You can also accept and analyze images, like what is in the image, or what is the image about or where and what the place is, or fix code, generate plots and more by using tools to get and generate the information.
|
||||
Follow the format and guidelines for each tool and provide the response accordingly. Remember to use the appropriate tool for each task. No need to panic, just follow the guidelines and you'll do great!
|
||||
|
||||
## Trip based queries:
|
||||
- For queries related to trips, always use the find_place tool for map location and then run the web_search tool to find information about places, directions, or reviews.
|
||||
- Calling web and find place tools in the same response is allowed, but do not call the same tool in a response at all costs!!
|
||||
- For nearby search queries, use the nearby_search tool to find places around a location. Provide the location and radius in the parameters, then compose your response based on the information gathered.
|
||||
- Never call find_place tool before or after the nearby_search tool in the same response at all costs!! THIS IS NOT ALLOWED AT ALL COSTS!!!
|
||||
|
||||
## Programming Tool Guidelines:
|
||||
The programming tool is actually a Python-only Code interpreter, so you can run any Python code in it.
|
||||
- This tool should not be called more than once in a response.
|
||||
- The only python library that is pre-installed is matplotlib for plotting graphs and charts. You have to install any other library using !pip install <library_name> in the code.
|
||||
- Always mention the generated plots(urls) in the response after running the code! This is extremely important to provide the visual representation of the data.
|
||||
|
||||
## Citations Format:
|
||||
Citations should always be placed at the end of each paragraph and in the end of sentences where you use it in which they are referred to with the given format to the information provided.
|
||||
When citing sources(citations), use the following styling only: Claude 3.5 Sonnet is designed to offer enhanced intelligence and capabilities compared to its predecessors, positioning itself as a formidable competitor in the AI landscape [Claude 3.5 Sonnet raises the..](https://www.anthropic.com/news/claude-3-5-sonnet).
|
||||
ALWAYS REMEMBER TO USE THE CITATIONS FORMAT CORRECTLY AT ALL COSTS!! ANY SINGLE ITCH IN THE FORMAT WILL CRASH THE RESPONSE!!
|
||||
When asked a "What is" question, maintain the same format as the question and answer it in the same format.
|
||||
|
||||
## Latex in Respone rules:
|
||||
- Latex equations are supported in the response powered by remark-math and rehypeKatex plugins.
|
||||
- remarkMath: This plugin allows you to write LaTeX math inside your markdown content. It recognizes math enclosed in dollar signs ($ ... $ for inline and $$ ... $$ for block).
|
||||
- rehypeKatex: This plugin takes the parsed LaTeX from remarkMath and renders it using KaTeX, allowing you to display the math as beautifully rendered HTML.
|
||||
|
||||
- The response that include latex equations, use always follow the formats:
|
||||
- Do not wrap any equation or formulas or any sort of math related block in round brackets() as it will crash the response.`,
|
||||
academic: `You are an academic research assistant that helps find and analyze scholarly content.
|
||||
The current date is ${new Date().toLocaleDateString("en-US", { year: "numeric", month: "short", day: "2-digit", weekday: "short" })}.
|
||||
Focus on peer-reviewed papers, citations, and academic sources.
|
||||
Do not talk in bullet points or lists at all costs as it unpresentable.
|
||||
Provide summaries, key points, and references.
|
||||
`,
|
||||
shopping: `You are a shopping assistant that helps users find and compare products.
|
||||
The current date is ${new Date().toLocaleDateString("en-US", { year: "numeric", month: "short", day: "2-digit", weekday: "short" })}.
|
||||
Focus on providing accurate pricing, product details, and merchant information.
|
||||
Do not show the images of the products at all costs.
|
||||
Talk about the product details and pricing only.
|
||||
Do not talk in bullet points or lists at all costs.
|
||||
Compare options and highlight key features and best values.`,
|
||||
youtube: `You are a YouTube search assistant that helps find relevant videos and channels.
|
||||
The current date is ${new Date().toLocaleDateString("en-US", { year: "numeric", month: "short", day: "2-digit", weekday: "short" })}.
|
||||
Provide video titles, channel names, view counts, and publish dates.
|
||||
Do not talk in bullet points or lists at all costs.
|
||||
Provide important details and summaries of the videos in paragraphs.
|
||||
Give citations with timestamps and video links to insightful content. Don't just put timestamp at 0:00.
|
||||
Do not provide the video thumbnail in the response at all costs.`,
|
||||
x: `You are a X/Twitter content curator that helps find relevant posts.
|
||||
The current date is ${new Date().toLocaleDateString("en-US", { year: "numeric", month: "short", day: "2-digit", weekday: "short" })}.
|
||||
Once you get the content from the tools only write in paragraphs.
|
||||
No need to say that you are calling the tool, just call the tools first and run the search;
|
||||
then talk in long details in 2-6 paragraphs.`,
|
||||
writing: `You are a writing assistant that helps users with writing, conversation, coding, poems, haikus, long essays or intellectual topics.`,
|
||||
} as const;
|
||||
|
||||
|
||||
export async function getGroupConfig(groupId: SearchGroupId = 'web') {
|
||||
"use server";
|
||||
const tools = groupTools[groupId];
|
||||
const systemPrompt = groupPrompts[groupId];
|
||||
return {
|
||||
tools,
|
||||
systemPrompt
|
||||
};
|
||||
}
|
||||
@ -2,20 +2,100 @@
|
||||
import { z } from "zod";
|
||||
import { createAzure } from '@ai-sdk/azure';
|
||||
import { anthropic } from '@ai-sdk/anthropic'
|
||||
import { xai } from '@ai-sdk/xai'
|
||||
import { google } from '@ai-sdk/google'
|
||||
import Exa from 'exa-js'
|
||||
import {
|
||||
convertToCoreMessages,
|
||||
streamText,
|
||||
tool,
|
||||
experimental_createProviderRegistry,
|
||||
smoothStream
|
||||
} from "ai";
|
||||
import { BlobRequestAbortedError, put } from '@vercel/blob';
|
||||
import CodeInterpreter from "@e2b/code-interpreter";
|
||||
import FirecrawlApp from '@mendable/firecrawl-js';
|
||||
import { tavily } from '@tavily/core'
|
||||
import { getGroupConfig } from "@/app/actions";
|
||||
|
||||
// Allow streaming responses up to 60 seconds
|
||||
export const maxDuration = 120;
|
||||
|
||||
interface XResult {
|
||||
id: string;
|
||||
url: string;
|
||||
title: string;
|
||||
author?: string;
|
||||
publishedDate?: string;
|
||||
text: string;
|
||||
highlights?: string[];
|
||||
tweetId: string;
|
||||
}
|
||||
|
||||
interface MapboxFeature {
|
||||
id: string;
|
||||
name: string;
|
||||
formatted_address: string;
|
||||
geometry: {
|
||||
type: string;
|
||||
coordinates: number[];
|
||||
};
|
||||
feature_type: string;
|
||||
context: string;
|
||||
coordinates: number[];
|
||||
bbox: number[];
|
||||
source: string;
|
||||
}
|
||||
|
||||
|
||||
interface GoogleResult {
|
||||
place_id: string;
|
||||
formatted_address: string;
|
||||
geometry: {
|
||||
location: {
|
||||
lat: number;
|
||||
lng: number;
|
||||
};
|
||||
viewport: {
|
||||
northeast: {
|
||||
lat: number;
|
||||
lng: number;
|
||||
};
|
||||
southwest: {
|
||||
lat: number;
|
||||
lng: number;
|
||||
};
|
||||
};
|
||||
};
|
||||
types: string[];
|
||||
address_components: Array<{
|
||||
long_name: string;
|
||||
short_name: string;
|
||||
types: string[];
|
||||
}>;
|
||||
}
|
||||
|
||||
interface VideoDetails {
|
||||
title?: string;
|
||||
author_name?: string;
|
||||
author_url?: string;
|
||||
thumbnail_url?: string;
|
||||
type?: string;
|
||||
provider_name?: string;
|
||||
provider_url?: string;
|
||||
}
|
||||
|
||||
interface VideoResult {
|
||||
videoId: string;
|
||||
url: string;
|
||||
details?: VideoDetails;
|
||||
captions?: string;
|
||||
timestamps?: string[];
|
||||
views?: string;
|
||||
likes?: string;
|
||||
summary?: string;
|
||||
}
|
||||
|
||||
// Azure setup
|
||||
const azure = createAzure({
|
||||
resourceName: process.env.AZURE_RESOURCE_NAME,
|
||||
@ -26,26 +106,15 @@ const azure = createAzure({
|
||||
const registry = experimental_createProviderRegistry({
|
||||
anthropic,
|
||||
azure,
|
||||
google,
|
||||
xai,
|
||||
});
|
||||
|
||||
function sanitizeUrl(url: string): string {
|
||||
return url.replace(/\s+/g, '%20')
|
||||
}
|
||||
|
||||
export async function POST(req: Request) {
|
||||
const { messages, model } = await req.json();
|
||||
|
||||
const provider = model.split(":")[0];
|
||||
|
||||
const result = await streamText({
|
||||
model: registry.languageModel(model),
|
||||
messages: convertToCoreMessages(messages),
|
||||
temperature: provider === "azure" ? 0.72 : 0.2,
|
||||
topP: 0.5,
|
||||
frequencyPenalty: 0,
|
||||
presencePenalty: 0,
|
||||
experimental_activeTools: ["get_weather_data", "find_place", "programming", "web_search", "text_translate", "nearby_search"],
|
||||
system: `
|
||||
const defaultsystemPrompt = `
|
||||
You are an expert AI web search engine called MiniPerplx, that helps users find information on the internet with no bullshit talks.
|
||||
Always start with running the tool(s) and then and then only write your response AT ALL COSTS!!
|
||||
Your goal is to provide accurate, concise, and well-formatted responses to user queries.
|
||||
@ -132,7 +201,26 @@ When asked a "What is" question, maintain the same format as the question and an
|
||||
- rehypeKatex: This plugin takes the parsed LaTeX from remarkMath and renders it using KaTeX, allowing you to display the math as beautifully rendered HTML.
|
||||
|
||||
- The response that include latex equations, use always follow the formats:
|
||||
- Do not wrap any equation or formulas or any sort of math related block in round brackets() as it will crash the response.`,
|
||||
- Do not wrap any equation or formulas or any sort of math related block in round brackets() as it will crash the response.`;
|
||||
|
||||
export async function POST(req: Request) {
|
||||
const { messages, model, group } = await req.json();
|
||||
const { tools: activeTools, systemPrompt } = await getGroupConfig(group);
|
||||
|
||||
const provider = model.split(":")[0];
|
||||
|
||||
const result = streamText({
|
||||
model: registry.languageModel(model),
|
||||
messages: convertToCoreMessages(messages),
|
||||
temperature: provider === "azure" ? 0.72 : 0.2,
|
||||
topP: 0.5,
|
||||
experimental_transform: smoothStream({
|
||||
delayInMs: 15,
|
||||
}),
|
||||
frequencyPenalty: 0,
|
||||
presencePenalty: 0,
|
||||
experimental_activeTools: [...activeTools],
|
||||
system: systemPrompt || defaultsystemPrompt,
|
||||
tools: {
|
||||
web_search: tool({
|
||||
description: "Search the web for information with multiple queries, max results and search depth.",
|
||||
@ -140,27 +228,27 @@ When asked a "What is" question, maintain the same format as the question and an
|
||||
queries: z.array(z.string().describe("Array of search queries to look up on the web.")),
|
||||
maxResults: z.array(z
|
||||
.number()
|
||||
.describe("Array of maximum number of results to return per query. Default is 10.")),
|
||||
topic: z.array(z
|
||||
.describe("Array of maximum number of results to return per query.").default(10)),
|
||||
topics: z.array(z
|
||||
.enum(["general", "news"])
|
||||
.describe("Array of topic types to search for. Default is general.")),
|
||||
.describe("Array of topic types to search for.").default("general")),
|
||||
searchDepth: z.array(z
|
||||
.enum(["basic", "advanced"])
|
||||
.describe("Array of search depths to use. Default is basic.")),
|
||||
.describe("Array of search depths to use.").default("basic")),
|
||||
exclude_domains: z
|
||||
.array(z.string())
|
||||
.describe("A list of domains to exclude from all search results. Default is None."),
|
||||
.describe("A list of domains to exclude from all search results.").default([]),
|
||||
}),
|
||||
execute: async ({
|
||||
queries,
|
||||
maxResults,
|
||||
topic,
|
||||
topics,
|
||||
searchDepth,
|
||||
exclude_domains,
|
||||
}: {
|
||||
queries: string[];
|
||||
maxResults: number[];
|
||||
topic: ("general" | "news")[];
|
||||
topics: ("general" | "news")[];
|
||||
searchDepth: ("basic" | "advanced")[];
|
||||
exclude_domains?: string[];
|
||||
}) => {
|
||||
@ -170,15 +258,15 @@ When asked a "What is" question, maintain the same format as the question and an
|
||||
|
||||
console.log("Queries:", queries);
|
||||
console.log("Max Results:", maxResults);
|
||||
console.log("Topics:", topic);
|
||||
console.log("Topics:", topics);
|
||||
console.log("Search Depths:", searchDepth);
|
||||
console.log("Exclude Domains:", exclude_domains);
|
||||
|
||||
// Execute searches in parallel
|
||||
const searchPromises = queries.map(async (query, index) => {
|
||||
const data = await tvly.search(query, {
|
||||
topic: topic[index] || topic[0] || "general",
|
||||
days: topic[index] === "news" ? 7 : undefined,
|
||||
topic: topics[index] || topics[0] || "general",
|
||||
days: topics[index] === "news" ? 7 : undefined,
|
||||
maxResults: maxResults[index] || maxResults[0] || 10,
|
||||
searchDepth: searchDepth[index] || searchDepth[0] || "basic",
|
||||
includeAnswer: true,
|
||||
@ -194,7 +282,7 @@ When asked a "What is" question, maintain the same format as the question and an
|
||||
title: obj.title,
|
||||
content: obj.content,
|
||||
raw_content: obj.raw_content,
|
||||
published_date: topic[index] === "news" ? obj.published_date : undefined,
|
||||
published_date: topics[index] === "news" ? obj.published_date : undefined,
|
||||
})),
|
||||
images: includeImageDescriptions
|
||||
? data.images
|
||||
@ -219,6 +307,307 @@ When asked a "What is" question, maintain the same format as the question and an
|
||||
};
|
||||
},
|
||||
}),
|
||||
x_search: tool({
|
||||
description: "Search X (formerly Twitter) posts.",
|
||||
parameters: z.object({
|
||||
query: z.string().describe("The search query"),
|
||||
}),
|
||||
execute: async ({ query }: { query: string }) => {
|
||||
try {
|
||||
const exa = new Exa(process.env.EXA_API_KEY as string);
|
||||
|
||||
const result = await exa.searchAndContents(
|
||||
query,
|
||||
{
|
||||
type: "keyword",
|
||||
numResults: 10,
|
||||
includeDomains: ["x.com", "twitter.com"],
|
||||
text: true,
|
||||
highlights: true
|
||||
}
|
||||
);
|
||||
|
||||
// Extract tweet ID from URL
|
||||
const extractTweetId = (url: string): string | null => {
|
||||
const match = url.match(/(?:twitter\.com|x\.com)\/\w+\/status\/(\d+)/);
|
||||
return match ? match[1] : null;
|
||||
};
|
||||
|
||||
// Process and filter results
|
||||
const processedResults = result.results.reduce<Array<XResult>>((acc, post) => {
|
||||
const tweetId = extractTweetId(post.url);
|
||||
if (tweetId) {
|
||||
acc.push({
|
||||
...post,
|
||||
tweetId,
|
||||
title: post.title || ""
|
||||
});
|
||||
}
|
||||
return acc;
|
||||
}, []);
|
||||
|
||||
return processedResults;
|
||||
|
||||
} catch (error) {
|
||||
console.error("X search error:", error);
|
||||
throw error;
|
||||
}
|
||||
},
|
||||
}),
|
||||
academic_search: tool({
|
||||
description: "Search academic papers and research.",
|
||||
parameters: z.object({
|
||||
query: z.string().describe("The search query"),
|
||||
}),
|
||||
execute: async ({ query }: { query: string }) => {
|
||||
try {
|
||||
const exa = new Exa(process.env.EXA_API_KEY as string);
|
||||
|
||||
// Search academic papers with content summary
|
||||
const result = await exa.searchAndContents(
|
||||
query,
|
||||
{
|
||||
type: "auto",
|
||||
numResults: 20,
|
||||
category: "research paper",
|
||||
summary: {
|
||||
query: "Abstract of the Paper"
|
||||
}
|
||||
}
|
||||
);
|
||||
|
||||
// Process and clean results
|
||||
const processedResults = result.results.reduce<typeof result.results>((acc, paper) => {
|
||||
// Skip if URL already exists or if no summary available
|
||||
if (acc.some(p => p.url === paper.url) || !paper.summary) return acc;
|
||||
|
||||
// Clean up summary (remove "Summary:" prefix if exists)
|
||||
const cleanSummary = paper.summary.replace(/^Summary:\s*/i, '');
|
||||
|
||||
// Clean up title (remove [...] suffixes)
|
||||
const cleanTitle = paper.title?.replace(/\s\[.*?\]$/, '');
|
||||
|
||||
acc.push({
|
||||
...paper,
|
||||
title: cleanTitle || "",
|
||||
summary: cleanSummary,
|
||||
});
|
||||
|
||||
return acc;
|
||||
}, []);
|
||||
|
||||
// Take only the first 10 unique, valid results
|
||||
const limitedResults = processedResults.slice(0, 10);
|
||||
|
||||
return {
|
||||
results: limitedResults
|
||||
};
|
||||
|
||||
} catch (error) {
|
||||
console.error("Academic search error:", error);
|
||||
throw error;
|
||||
}
|
||||
},
|
||||
}),
|
||||
youtube_search: tool({
|
||||
description: "Search YouTube videos using Exa AI and get detailed video information.",
|
||||
parameters: z.object({
|
||||
query: z.string().describe("The search query for YouTube videos"),
|
||||
no_of_results: z.number().default(5).describe("The number of results to return"),
|
||||
}),
|
||||
execute: async ({ query, no_of_results }: { query: string, no_of_results: number }) => {
|
||||
try {
|
||||
const exa = new Exa(process.env.EXA_API_KEY as string);
|
||||
|
||||
// Simple search to get YouTube URLs only
|
||||
const searchResult = await exa.search(
|
||||
query,
|
||||
{
|
||||
type: "keyword",
|
||||
numResults: no_of_results,
|
||||
includeDomains: ["youtube.com"]
|
||||
}
|
||||
);
|
||||
|
||||
// Process results
|
||||
const processedResults = await Promise.all(
|
||||
searchResult.results.map(async (result): Promise<VideoResult | null> => {
|
||||
const videoIdMatch = result.url.match(/(?:youtube\.com\/watch\?v=|youtu\.be\/|youtube\.com\/embed\/)([^&?/]+)/);
|
||||
const videoId = videoIdMatch?.[1];
|
||||
|
||||
if (!videoId) return null;
|
||||
|
||||
// Base result
|
||||
const baseResult: VideoResult = {
|
||||
videoId,
|
||||
url: result.url
|
||||
};
|
||||
|
||||
try {
|
||||
// Fetch detailed info from our endpoints
|
||||
const [detailsResponse, captionsResponse, timestampsResponse] = await Promise.all([
|
||||
fetch(`${process.env.YT_ENDPOINT}/video-data`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ url: result.url })
|
||||
}).then(res => res.ok ? res.json() : null),
|
||||
fetch(`${process.env.YT_ENDPOINT}/video-captions`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ url: result.url })
|
||||
}).then(res => res.ok ? res.text() : null),
|
||||
fetch(`${process.env.YT_ENDPOINT}/video-timestamps`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ url: result.url })
|
||||
}).then(res => res.ok ? res.json() : null)
|
||||
]);
|
||||
|
||||
// Return combined data
|
||||
return {
|
||||
...baseResult,
|
||||
details: detailsResponse || undefined,
|
||||
captions: captionsResponse || undefined,
|
||||
timestamps: timestampsResponse || undefined,
|
||||
};
|
||||
} catch (error) {
|
||||
console.error(`Error fetching details for video ${videoId}:`, error);
|
||||
return baseResult;
|
||||
}
|
||||
})
|
||||
);
|
||||
|
||||
// Filter out null results
|
||||
const validResults = processedResults.filter((result): result is VideoResult => result !== null);
|
||||
|
||||
return {
|
||||
results: validResults
|
||||
};
|
||||
|
||||
} catch (error) {
|
||||
console.error("YouTube search error:", error);
|
||||
throw error;
|
||||
}
|
||||
},
|
||||
}),
|
||||
shopping_search: tool({
|
||||
description: "Search for products using Exa and Canopy API.",
|
||||
parameters: z.object({
|
||||
query: z.string().describe("The search query for products"),
|
||||
// keyword: z.string().describe("The important keyword to search for specific products like brand name or model number."),
|
||||
}),
|
||||
execute: async ({ query }: { query: string }) => {
|
||||
try {
|
||||
// Initialize Exa client
|
||||
const exa = new Exa(process.env.EXA_API_KEY as string);
|
||||
|
||||
|
||||
// Search for products on Amazon
|
||||
const searchResult = await exa.search(
|
||||
query,
|
||||
{
|
||||
type: "auto",
|
||||
numResults: 20,
|
||||
includeDomains: ["amazon.com"],
|
||||
}
|
||||
);
|
||||
|
||||
// Function to extract ASIN from Amazon URL
|
||||
const extractAsin = (url: string): string | null => {
|
||||
const asinRegex = /(?:dp|gp\/product)\/([A-Z0-9]{10})/;
|
||||
const match = url.match(asinRegex);
|
||||
return match ? match[1] : null;
|
||||
};
|
||||
|
||||
// Remove duplicates by ASIN
|
||||
const seenAsins = new Set<string>();
|
||||
const uniqueResults = searchResult.results.reduce<Array<typeof searchResult.results[0]>>((acc, result) => {
|
||||
const asin = extractAsin(result.url);
|
||||
if (asin && !seenAsins.has(asin)) {
|
||||
seenAsins.add(asin);
|
||||
acc.push(result);
|
||||
}
|
||||
return acc;
|
||||
}, []);
|
||||
|
||||
// Only take the first 10 unique results
|
||||
const limitedResults = uniqueResults.slice(0, 10);
|
||||
|
||||
// Fetch detailed product information for each unique result
|
||||
const productDetails = await Promise.all(
|
||||
limitedResults.map(async (result) => {
|
||||
const asin = extractAsin(result.url);
|
||||
if (!asin) return null;
|
||||
|
||||
const query = `
|
||||
query amazonProduct {
|
||||
amazonProduct(input: {asinLookup: {asin: "${asin}"}}) {
|
||||
title
|
||||
brand
|
||||
mainImageUrl
|
||||
rating
|
||||
ratingsTotal
|
||||
price {
|
||||
display
|
||||
}
|
||||
}
|
||||
}
|
||||
`;
|
||||
|
||||
try {
|
||||
const response = await fetch('https://graphql.canopyapi.co/', {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
'API-KEY': process.env.CANOPY_API_KEY as string,
|
||||
},
|
||||
body: JSON.stringify({ query }),
|
||||
next: { revalidate: 3600 } // Cache for 1 hour
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
console.error(`Failed to fetch details for ASIN ${asin}:`, await response.text());
|
||||
return null;
|
||||
}
|
||||
|
||||
const canopyData = await response.json();
|
||||
const amazonProduct = canopyData.data?.amazonProduct;
|
||||
|
||||
if (!amazonProduct) return null;
|
||||
|
||||
return {
|
||||
title: amazonProduct.title,
|
||||
url: result.url,
|
||||
image: amazonProduct.mainImageUrl,
|
||||
price: amazonProduct.price.display,
|
||||
rating: amazonProduct.rating,
|
||||
reviewCount: amazonProduct.ratingsTotal,
|
||||
};
|
||||
} catch (error) {
|
||||
console.error(`Error fetching details for ASIN ${asin}:`, error);
|
||||
return null;
|
||||
}
|
||||
})
|
||||
);
|
||||
|
||||
// Filter out null results and return
|
||||
const validProducts = productDetails.filter((product): product is NonNullable<typeof product> =>
|
||||
product !== null
|
||||
);
|
||||
|
||||
// Log results for debugging
|
||||
console.log(`Found ${searchResult.results.length} total results`);
|
||||
console.log(`Filtered to ${uniqueResults.length} unique ASINs`);
|
||||
console.log(`Returning ${validProducts.length} valid products`);
|
||||
|
||||
return validProducts;
|
||||
|
||||
} catch (error) {
|
||||
console.error("Shopping search error:", error);
|
||||
throw error;
|
||||
}
|
||||
},
|
||||
}),
|
||||
retrieve: tool({
|
||||
description: "Retrieve the information from a URL using Firecrawl.",
|
||||
parameters: z.object({
|
||||
@ -351,29 +740,76 @@ When asked a "What is" question, maintain the same format as the question and an
|
||||
},
|
||||
}),
|
||||
find_place: tool({
|
||||
description: "Find a place using Mapbox v6 reverse geocoding API.",
|
||||
description: "Find a place using Google Maps API for forward geocoding and Mapbox for reverse geocoding.",
|
||||
parameters: z.object({
|
||||
latitude: z.number().describe("The latitude of the location."),
|
||||
longitude: z.number().describe("The longitude of the location."),
|
||||
query: z.string().describe("The search query for forward geocoding"),
|
||||
coordinates: z.array(z.number()).describe("Array of [latitude, longitude] for reverse geocoding"),
|
||||
}),
|
||||
execute: async ({ latitude, longitude }: { latitude: number; longitude: number }) => {
|
||||
const mapboxToken = process.env.MAPBOX_ACCESS_TOKEN;
|
||||
const response = await fetch(
|
||||
`https://api.mapbox.com/search/geocode/v6/reverse?longitude=${longitude}&latitude=${latitude}&access_token=${mapboxToken}`
|
||||
execute: async ({ query, coordinates }: { query: string; coordinates: number[] }) => {
|
||||
try {
|
||||
// Forward geocoding with Google Maps API
|
||||
const googleApiKey = process.env.GOOGLE_MAPS_API_KEY;
|
||||
const googleResponse = await fetch(
|
||||
`https://maps.googleapis.com/maps/api/geocode/json?address=${encodeURIComponent(query)}&key=${googleApiKey}`
|
||||
);
|
||||
const data = await response.json();
|
||||
const googleData = await googleResponse.json();
|
||||
|
||||
if (!data.features || data.features.length === 0) {
|
||||
return { features: [] };
|
||||
// Reverse geocoding with Mapbox
|
||||
const mapboxToken = process.env.MAPBOX_ACCESS_TOKEN;
|
||||
const [lat, lng] = coordinates;
|
||||
const mapboxResponse = await fetch(
|
||||
`https://api.mapbox.com/search/geocode/v6/reverse?longitude=${lng}&latitude=${lat}&access_token=${mapboxToken}`
|
||||
);
|
||||
const mapboxData = await mapboxResponse.json();
|
||||
|
||||
// Process and combine results
|
||||
const features = [];
|
||||
|
||||
// Process Google results
|
||||
if (googleData.status === 'OK' && googleData.results.length > 0) {
|
||||
|
||||
|
||||
features.push(...googleData.results.map((result: GoogleResult) => ({
|
||||
id: result.place_id,
|
||||
name: result.formatted_address.split(',')[0],
|
||||
formatted_address: result.formatted_address,
|
||||
geometry: {
|
||||
type: 'Point',
|
||||
coordinates: [result.geometry.location.lng, result.geometry.location.lat]
|
||||
},
|
||||
feature_type: result.types[0],
|
||||
address_components: result.address_components,
|
||||
viewport: result.geometry.viewport,
|
||||
place_id: result.place_id,
|
||||
source: 'google'
|
||||
})));
|
||||
}
|
||||
|
||||
return {
|
||||
features: data.features.map((feature: any) => ({
|
||||
// Process Mapbox results
|
||||
if (mapboxData.features && mapboxData.features.length > 0) {
|
||||
|
||||
features.push(...mapboxData.features.map((feature: any): MapboxFeature => ({
|
||||
id: feature.id,
|
||||
name: feature.properties.name_preferred || feature.properties.name,
|
||||
formatted_address: feature.properties.full_address,
|
||||
geometry: feature.geometry,
|
||||
})),
|
||||
feature_type: feature.properties.feature_type,
|
||||
context: feature.properties.context,
|
||||
coordinates: feature.properties.coordinates,
|
||||
bbox: feature.properties.bbox,
|
||||
source: 'mapbox'
|
||||
})));
|
||||
}
|
||||
|
||||
return {
|
||||
features,
|
||||
google_attribution: "Powered by Google Maps Platform",
|
||||
mapbox_attribution: "Powered by Mapbox"
|
||||
};
|
||||
} catch (error) {
|
||||
console.error("Geocoding error:", error);
|
||||
throw error;
|
||||
}
|
||||
},
|
||||
}),
|
||||
text_search: tool({
|
||||
@ -713,6 +1149,16 @@ When asked a "What is" question, maintain the same format as the question and an
|
||||
console.log("Called Tool: ", event.chunk.toolName);
|
||||
}
|
||||
},
|
||||
onStepFinish(event) {
|
||||
if (event.warnings) {
|
||||
console.log("Warnings: ", event.warnings);
|
||||
}
|
||||
},
|
||||
onFinish(event) {
|
||||
console.log("Fin reason: ", event.finishReason);
|
||||
console.log("Steps ", event.steps);
|
||||
console.log("Messages: ", event.response.messages[event.response.messages.length - 1].content);
|
||||
},
|
||||
});
|
||||
|
||||
return result.toDataStreamResponse();
|
||||
|
||||
@ -75,6 +75,11 @@ h1 {
|
||||
font-family: var(--font-serif);
|
||||
}
|
||||
|
||||
.gradient-mask {
|
||||
mask-image: linear-gradient(to bottom, black 30%, transparent 100%);
|
||||
-webkit-mask-image: linear-gradient(to bottom, black 30%, transparent 100%);
|
||||
}
|
||||
|
||||
@layer utilities {
|
||||
.text-balance {
|
||||
text-wrap: balance;
|
||||
|
||||
@ -14,7 +14,17 @@ export const metadata: Metadata = {
|
||||
openGraph: {
|
||||
url: "https://mplx.run",
|
||||
siteName: "MiniPerplx",
|
||||
}
|
||||
},
|
||||
keywords: [
|
||||
"MiniPerplx",
|
||||
"mplx",
|
||||
"mplx.run",
|
||||
"search engine",
|
||||
"AI",
|
||||
"ai search engine",
|
||||
"perplexity",
|
||||
"minimalistic search engine",
|
||||
]
|
||||
};
|
||||
|
||||
export const viewport: Viewport = {
|
||||
|
||||
24
app/page.tsx
24
app/page.tsx
@ -37,7 +37,8 @@ import {
|
||||
Menu,
|
||||
X,
|
||||
BarChart,
|
||||
CircleDot
|
||||
CircleDot,
|
||||
ShoppingBasket
|
||||
} from "lucide-react"
|
||||
import NextLink from "next/link"
|
||||
import {
|
||||
@ -53,6 +54,7 @@ import { cn } from '@/lib/utils';
|
||||
import { Tweet } from 'react-tweet'
|
||||
import Image from 'next/image';
|
||||
import { TweetGrid } from '@/components/ui/tweet-grid';
|
||||
import { Newspaper, XLogo, YoutubeLogo } from '@phosphor-icons/react';
|
||||
|
||||
function BentoCard({
|
||||
title,
|
||||
@ -513,7 +515,7 @@ const FloatingIcon: React.FC<{ Icon: LucideIcon }> = ({ Icon }) => (
|
||||
)
|
||||
|
||||
const FloatingIcons: React.FC = () => {
|
||||
const icons = [Search, Zap, Code, Cloud, Link, MapPin, Globe, Mic];
|
||||
const icons = [Search, Zap, Code, Cloud, Link, MapPin, Globe, Mic, Github, XLogo, Newspaper, YoutubeLogo]
|
||||
|
||||
return (
|
||||
<div className="absolute inset-0 overflow-hidden pointer-events-none">
|
||||
@ -601,9 +603,12 @@ const LandingPage: React.FC = () => {
|
||||
{ icon: Globe, title: "Web Search", description: "Powered by Tavily AI for comprehensive web results." },
|
||||
{ icon: Code, title: "Code Interpreter", description: "Utilize e2b.dev for advanced code interpretation and execution." },
|
||||
{ icon: Cloud, title: "Weather Forecast", description: "Get accurate weather information via OpenWeatherMap." },
|
||||
{ icon: Link, title: "URL Summary", description: "Summarize web content quickly with FireCrawl's Scrape API." },
|
||||
{ icon: MapPin, title: "Location Search", description: "Find places and nearby locations using Google Maps API." },
|
||||
{ icon: Mic, title: "Translation & TTS", description: "Translate text and convert to speech with OpenAI TTS." },
|
||||
{ icon: YoutubeLogo, title: "Youtube Search", description: "Summarize web content quickly with FireCrawl's Scrape API." },
|
||||
{ icon: XLogo, title: "Search X Posts", description: "Search for posts on X.com" },
|
||||
{ icon: Newspaper, title: "Research Paper Search", description: "Search for research papers on arXiv and more" },
|
||||
{ icon: MapPin, title: "Location Search", description: "Find places and nearby locations using Google Maps API, Mapbox and TripAdvisior API." },
|
||||
{ icon: Mic, title: "Translation & TTS", description: "Translate text and convert to speech with Elevenlabs TTS and Microsoft's Translation API." },
|
||||
{ icon: ShoppingBasket, title: "Product Search", description: "Search for products on Amazon." },
|
||||
]
|
||||
|
||||
const containerVariants = {
|
||||
@ -765,6 +770,15 @@ const LandingPage: React.FC = () => {
|
||||
className="h-12 w-auto"
|
||||
/>
|
||||
</NextLink>
|
||||
<NextLink href="https://www.uneed.best/tool/miniperplx" passHref>
|
||||
<Image
|
||||
src="https://www.uneed.best/EMBED3B.png"
|
||||
alt="Uneed Embed Badge"
|
||||
width={300}
|
||||
height={150}
|
||||
className="h-12 w-auto"
|
||||
/>
|
||||
</NextLink>
|
||||
</motion.div>
|
||||
</motion.div>
|
||||
</div>
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
48
components/core/border-trail.tsx
Normal file
48
components/core/border-trail.tsx
Normal file
@ -0,0 +1,48 @@
|
||||
'use client';
|
||||
import { cn } from '@/lib/utils';
|
||||
import { motion, Transition } from 'motion/react';
|
||||
|
||||
type BorderTrailProps = {
|
||||
className?: string;
|
||||
size?: number;
|
||||
transition?: Transition;
|
||||
delay?: number;
|
||||
onAnimationComplete?: () => void;
|
||||
style?: React.CSSProperties;
|
||||
};
|
||||
|
||||
export function BorderTrail({
|
||||
className,
|
||||
size = 60,
|
||||
transition,
|
||||
delay,
|
||||
onAnimationComplete,
|
||||
style,
|
||||
}: BorderTrailProps) {
|
||||
const BASE_TRANSITION = {
|
||||
repeat: Infinity,
|
||||
duration: 5,
|
||||
ease: 'linear',
|
||||
};
|
||||
|
||||
return (
|
||||
<div className='pointer-events-none absolute inset-0 rounded-[inherit] border border-transparent [mask-clip:padding-box,border-box] [mask-composite:intersect] [mask-image:linear-gradient(transparent,transparent),linear-gradient(#000,#000)]'>
|
||||
<motion.div
|
||||
className={cn('absolute aspect-square bg-zinc-500', className)}
|
||||
style={{
|
||||
width: size,
|
||||
offsetPath: `rect(0 auto auto 0 round ${size}px)`,
|
||||
...style,
|
||||
}}
|
||||
animate={{
|
||||
offsetDistance: ['0%', '100%'],
|
||||
}}
|
||||
transition={{
|
||||
...(transition ?? BASE_TRANSITION),
|
||||
delay: delay,
|
||||
}}
|
||||
onAnimationComplete={onAnimationComplete}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
55
components/core/text-shimmer.tsx
Normal file
55
components/core/text-shimmer.tsx
Normal file
@ -0,0 +1,55 @@
|
||||
'use client';
|
||||
import React, { useMemo, type JSX } from 'react';
|
||||
import { motion } from 'motion/react';
|
||||
import { cn } from '@/lib/utils';
|
||||
|
||||
interface TextShimmerProps {
|
||||
children: string;
|
||||
as?: React.ElementType;
|
||||
className?: string;
|
||||
duration?: number;
|
||||
spread?: number;
|
||||
}
|
||||
|
||||
export function TextShimmer({
|
||||
children,
|
||||
as: Component = 'p',
|
||||
className,
|
||||
duration = 2,
|
||||
spread = 2,
|
||||
}: TextShimmerProps) {
|
||||
const MotionComponent = motion.create(
|
||||
Component as keyof JSX.IntrinsicElements
|
||||
);
|
||||
|
||||
const dynamicSpread = useMemo(() => {
|
||||
return children.length * spread;
|
||||
}, [children, spread]);
|
||||
|
||||
return (
|
||||
<MotionComponent
|
||||
className={cn(
|
||||
'relative inline-block bg-[length:250%_100%,auto] bg-clip-text',
|
||||
'text-transparent [--base-color:#a1a1aa] [--base-gradient-color:#000]',
|
||||
'[--bg:linear-gradient(90deg,#0000_calc(50%-var(--spread)),var(--base-gradient-color),#0000_calc(50%+var(--spread)))] [background-repeat:no-repeat,padding-box]',
|
||||
'dark:[--base-color:#71717a] dark:[--base-gradient-color:#ffffff] dark:[--bg:linear-gradient(90deg,#0000_calc(50%-var(--spread)),var(--base-gradient-color),#0000_calc(50%+var(--spread)))]',
|
||||
className
|
||||
)}
|
||||
initial={{ backgroundPosition: '100% center' }}
|
||||
animate={{ backgroundPosition: '0% center' }}
|
||||
transition={{
|
||||
repeat: Infinity,
|
||||
duration,
|
||||
ease: 'linear',
|
||||
}}
|
||||
style={
|
||||
{
|
||||
'--spread': `${dynamicSpread}px`,
|
||||
backgroundImage: `var(--bg), linear-gradient(var(--base-color), var(--base-color))`,
|
||||
} as React.CSSProperties
|
||||
}
|
||||
>
|
||||
{children}
|
||||
</MotionComponent>
|
||||
);
|
||||
}
|
||||
@ -1,219 +1,141 @@
|
||||
// components/interactive-charts.tsx
|
||||
import React from 'react';
|
||||
import ReactECharts from 'echarts-for-react';
|
||||
import * as echarts from 'echarts';
|
||||
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
|
||||
import ReactECharts, { EChartsOption } from 'echarts-for-react';
|
||||
import { Card, CardContent } from "@/components/ui/card";
|
||||
import { useTheme } from 'next-themes';
|
||||
|
||||
interface BaseChartProps {
|
||||
interface BaseChart {
|
||||
type: string;
|
||||
title: string;
|
||||
xLabel?: string;
|
||||
yLabel?: string;
|
||||
xUnit?: string | null;
|
||||
yUnit?: string | null;
|
||||
x_label?: string;
|
||||
y_label?: string;
|
||||
x_unit?: string;
|
||||
y_unit?: string;
|
||||
x_ticks?: (number | string)[];
|
||||
x_tick_labels?: string[];
|
||||
x_scale?: string;
|
||||
y_ticks?: (number | string)[];
|
||||
y_tick_labels?: string[];
|
||||
y_scale?: string;
|
||||
elements: any[];
|
||||
}
|
||||
|
||||
type BarChartElement = {
|
||||
label: string;
|
||||
group: string;
|
||||
value: number;
|
||||
};
|
||||
|
||||
type PointData = {
|
||||
label: string;
|
||||
points: [number | string, number | string][];
|
||||
};
|
||||
|
||||
interface ChartProps extends BaseChartProps {
|
||||
type: 'bar' | 'line';
|
||||
elements: BarChartElement[] | PointData[];
|
||||
}
|
||||
|
||||
const InteractiveChart: React.FC<ChartProps> = ({
|
||||
type,
|
||||
title,
|
||||
xLabel = '',
|
||||
yLabel = '',
|
||||
xUnit = '',
|
||||
yUnit = '',
|
||||
elements,
|
||||
x_ticks,
|
||||
x_tick_labels,
|
||||
x_scale = 'value',
|
||||
y_ticks,
|
||||
y_tick_labels,
|
||||
y_scale = 'value',
|
||||
}) => {
|
||||
export function InteractiveChart({ chart }: { chart: BaseChart }) {
|
||||
const { theme } = useTheme();
|
||||
|
||||
const getChartOptions = () => {
|
||||
if (!elements || elements.length === 0) {
|
||||
return {};
|
||||
}
|
||||
|
||||
const textColor = theme === 'dark' ? '#e5e5e5' : '#171717';
|
||||
const axisLineColor = theme === 'dark' ? '#404040' : '#e5e5e5';
|
||||
const gridColor = theme === 'dark' ? '#404040' : '#e5e5e5';
|
||||
|
||||
if (type === 'line') {
|
||||
const lineElements = elements as PointData[];
|
||||
|
||||
const xAxisType = x_scale === 'datetime' ? 'time' : x_scale;
|
||||
|
||||
const series = lineElements.map(el => ({
|
||||
name: el.label,
|
||||
type: 'line',
|
||||
data: el.points.map(point => {
|
||||
const xValue =
|
||||
xAxisType === 'time'
|
||||
? new Date(point[0] as string).getTime()
|
||||
: point[0];
|
||||
return [xValue, point[1]];
|
||||
}),
|
||||
smooth: true,
|
||||
}));
|
||||
const sharedOptions: EChartsOption = {
|
||||
grid: { top: 30, right: 8, bottom: 28, left: 28 },
|
||||
legend: {}
|
||||
};
|
||||
|
||||
if (chart.type === 'line') {
|
||||
const series = chart.elements.map((e) => {
|
||||
return {
|
||||
title: {
|
||||
text: title || '',
|
||||
textStyle: { color: textColor },
|
||||
},
|
||||
tooltip: {
|
||||
trigger: 'axis',
|
||||
axisPointer: {
|
||||
type: 'cross',
|
||||
},
|
||||
},
|
||||
legend: {
|
||||
data: lineElements.map(el => el.label),
|
||||
textStyle: { color: textColor },
|
||||
},
|
||||
name: e.label,
|
||||
type: 'line',
|
||||
data: e.points.map((p: [number, number]) => [p[0], p[1]])
|
||||
};
|
||||
});
|
||||
|
||||
const options: EChartsOption = {
|
||||
...sharedOptions,
|
||||
xAxis: {
|
||||
type: xAxisType,
|
||||
name: xLabel,
|
||||
nameTextStyle: { color: textColor },
|
||||
type: chart.x_scale === 'datetime' ? 'time' : 'category',
|
||||
name: chart.x_label,
|
||||
nameLocation: 'middle',
|
||||
axisLabel: {
|
||||
color: textColor,
|
||||
formatter: (value: number) => {
|
||||
if (xAxisType === 'time') {
|
||||
return echarts.format.formatTime('yyyy-MM', value);
|
||||
if (chart.x_scale === 'datetime') {
|
||||
return new Date(value).toLocaleDateString('en-US', {
|
||||
month: 'short',
|
||||
day: 'numeric'
|
||||
});
|
||||
}
|
||||
return chart.x_unit ? `${value}${chart.x_unit}` : `${value}`;
|
||||
}
|
||||
return xUnit ? `${value} ${xUnit}` : `${value}`;
|
||||
},
|
||||
},
|
||||
axisLine: { lineStyle: { color: axisLineColor } },
|
||||
axisLine: { lineStyle: { color: gridColor } }
|
||||
},
|
||||
yAxis: {
|
||||
type: y_scale,
|
||||
name: yLabel,
|
||||
nameTextStyle: { color: textColor },
|
||||
name: chart.y_label,
|
||||
nameLocation: 'middle',
|
||||
axisLabel: {
|
||||
color: textColor,
|
||||
formatter: (value: number) =>
|
||||
yUnit ? `${value} ${yUnit}` : `${value}`,
|
||||
chart.y_unit ? `${chart.y_unit}${value}` : value.toString()
|
||||
},
|
||||
axisLine: { lineStyle: { color: axisLineColor } },
|
||||
...(y_ticks && {
|
||||
min: Math.min(...(y_ticks as number[])),
|
||||
max: Math.max(...(y_ticks as number[])),
|
||||
}),
|
||||
axisLine: { lineStyle: { color: gridColor } }
|
||||
},
|
||||
series,
|
||||
};
|
||||
} else if (type === 'bar') {
|
||||
const barElements = elements as BarChartElement[];
|
||||
|
||||
const groups = Array.from(new Set(barElements.map(el => el.group))).filter(Boolean);
|
||||
const labels = Array.from(new Set(barElements.map(el => el.label))).filter(Boolean);
|
||||
|
||||
const series = groups.map(group => ({
|
||||
name: group,
|
||||
type: 'bar',
|
||||
data: labels.map(label => {
|
||||
const el = barElements.find(e => e.group === group && e.label === label);
|
||||
return el ? el.value : 0;
|
||||
}),
|
||||
}));
|
||||
|
||||
return {
|
||||
title: {
|
||||
text: title || '',
|
||||
textStyle: { color: textColor },
|
||||
},
|
||||
tooltip: { trigger: 'axis' },
|
||||
legend: {
|
||||
data: groups,
|
||||
textStyle: { color: textColor },
|
||||
},
|
||||
xAxis: {
|
||||
type: 'category',
|
||||
data: labels,
|
||||
name: xLabel,
|
||||
nameTextStyle: { color: textColor },
|
||||
axisLabel: { color: textColor },
|
||||
axisLine: { lineStyle: { color: axisLineColor } },
|
||||
},
|
||||
yAxis: {
|
||||
type: 'value',
|
||||
name: yLabel,
|
||||
nameTextStyle: { color: textColor },
|
||||
axisLabel: {
|
||||
color: textColor,
|
||||
formatter: (value: number) =>
|
||||
yUnit ? `${value} ${yUnit}` : value.toString(),
|
||||
},
|
||||
axisLine: { lineStyle: { color: axisLineColor } },
|
||||
...(y_ticks && {
|
||||
min: Math.min(...(y_ticks as number[])),
|
||||
max: Math.max(...(y_ticks as number[])),
|
||||
}),
|
||||
},
|
||||
series,
|
||||
};
|
||||
tooltip: {
|
||||
trigger: 'axis'
|
||||
}
|
||||
|
||||
return {};
|
||||
};
|
||||
|
||||
const options = getChartOptions();
|
||||
|
||||
if (!options || Object.keys(options).length === 0) {
|
||||
return (
|
||||
<Card className="w-full bg-white dark:bg-neutral-800">
|
||||
<CardHeader>
|
||||
<CardTitle className="text-neutral-800 dark:text-neutral-200">
|
||||
{title || 'Chart'}
|
||||
</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div className="text-neutral-600 dark:text-neutral-400">
|
||||
No data available to display the chart.
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<Card className="w-full bg-white dark:bg-neutral-800">
|
||||
<CardHeader>
|
||||
<CardTitle className="text-neutral-800 dark:text-neutral-200">
|
||||
{title || 'Chart'}
|
||||
</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<Card className="w-full bg-white dark:bg-neutral-900 border-neutral-200 dark:border-neutral-800">
|
||||
<CardContent className="p-6">
|
||||
<ReactECharts
|
||||
option={options}
|
||||
style={{ height: '460px', width: '105%', gap: '20px' }}
|
||||
style={{ height: '400px' }}
|
||||
theme={theme === 'dark' ? 'dark' : undefined}
|
||||
/>
|
||||
</CardContent>
|
||||
</Card>
|
||||
);
|
||||
};
|
||||
}
|
||||
|
||||
if (chart.type === 'bar') {
|
||||
const data = Object.groupBy(chart.elements, ({ group }) => group);
|
||||
|
||||
const series = Object.entries(data).map(([group, elements]) => ({
|
||||
name: group,
|
||||
type: 'bar',
|
||||
stack: 'total',
|
||||
data: elements?.map((e) => [e.label, e.value])
|
||||
}));
|
||||
|
||||
const options: EChartsOption = {
|
||||
...sharedOptions,
|
||||
xAxis: {
|
||||
type: 'category',
|
||||
name: chart.x_label,
|
||||
nameLocation: 'middle',
|
||||
axisLabel: { color: textColor },
|
||||
axisLine: { lineStyle: { color: gridColor } }
|
||||
},
|
||||
yAxis: {
|
||||
name: chart.y_label,
|
||||
nameLocation: 'middle',
|
||||
axisLabel: {
|
||||
color: textColor,
|
||||
formatter: (value: number) =>
|
||||
chart.y_unit ? `${chart.y_unit}${value}` : value.toString()
|
||||
},
|
||||
axisLine: { lineStyle: { color: gridColor } }
|
||||
},
|
||||
series,
|
||||
tooltip: {
|
||||
trigger: 'axis'
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<Card className="w-full bg-white dark:bg-neutral-900 border-neutral-200 dark:border-neutral-800">
|
||||
<CardContent className="p-6">
|
||||
<ReactECharts
|
||||
option={options}
|
||||
style={{ height: '400px' }}
|
||||
theme={theme === 'dark' ? 'dark' : undefined}
|
||||
/>
|
||||
</CardContent>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
export default InteractiveChart;
|
||||
@ -21,6 +21,7 @@ interface MapProps {
|
||||
center: Location;
|
||||
places?: Place[];
|
||||
zoom?: number;
|
||||
onMarkerClick?: (place: Place) => void;
|
||||
}
|
||||
|
||||
const MapComponent = ({ center, places = [], zoom = 14, onMarkerClick }: MapProps & { onMarkerClick?: (place: Place) => void }) => {
|
||||
@ -28,10 +29,8 @@ const MapComponent = ({ center, places = [], zoom = 14, onMarkerClick }: MapProp
|
||||
const mapInstance = useRef<mapboxgl.Map | null>(null);
|
||||
const markersRef = useRef<mapboxgl.Marker[]>([]);
|
||||
|
||||
// Initialize the map only once
|
||||
useEffect(() => {
|
||||
if (!mapRef.current || mapInstance.current) return;
|
||||
|
||||
if (!mapboxgl.accessToken) {
|
||||
console.error('Mapbox access token is not set');
|
||||
return;
|
||||
@ -39,44 +38,70 @@ const MapComponent = ({ center, places = [], zoom = 14, onMarkerClick }: MapProp
|
||||
|
||||
mapInstance.current = new mapboxgl.Map({
|
||||
container: mapRef.current,
|
||||
style: 'mapbox://styles/mapbox/standard',
|
||||
style: 'mapbox://styles/mapbox/dark-v11',
|
||||
center: [center.lng, center.lat],
|
||||
zoom,
|
||||
attributionControl: false,
|
||||
});
|
||||
|
||||
// Add zoom and rotation controls
|
||||
mapInstance.current.addControl(new mapboxgl.NavigationControl(), 'top-right');
|
||||
|
||||
// Add attribution control in bottom-left
|
||||
mapInstance.current.addControl(
|
||||
new mapboxgl.AttributionControl({ compact: true }),
|
||||
'bottom-left'
|
||||
);
|
||||
|
||||
// Add fullscreen control
|
||||
mapInstance.current.addControl(new mapboxgl.FullscreenControl(), 'top-right');
|
||||
|
||||
return () => {
|
||||
mapInstance.current?.remove();
|
||||
mapInstance.current = null;
|
||||
};
|
||||
}, [center.lat, center.lng, zoom]);
|
||||
|
||||
// Update map center when 'center' prop changes
|
||||
useEffect(() => {
|
||||
if (mapInstance.current) {
|
||||
mapInstance.current.flyTo({
|
||||
center: [center.lng, center.lat],
|
||||
zoom,
|
||||
essential: true,
|
||||
duration: 1000,
|
||||
padding: { top: 50, bottom: 50, left: 50, right: 50 }
|
||||
});
|
||||
}
|
||||
}, [center, zoom]);
|
||||
|
||||
// Update markers when 'places' prop changes
|
||||
useEffect(() => {
|
||||
if (!mapInstance.current) return;
|
||||
|
||||
// Remove existing markers
|
||||
markersRef.current.forEach((marker) => marker.remove());
|
||||
markersRef.current = [];
|
||||
|
||||
// Add new markers
|
||||
places.forEach((place) => {
|
||||
const marker = new mapboxgl.Marker()
|
||||
// Create custom marker element
|
||||
const el = document.createElement('div');
|
||||
el.className = 'custom-marker';
|
||||
el.innerHTML = `
|
||||
<div class="w-8 h-8 bg-blue-500 rounded-full flex items-center justify-center shadow-lg transform-gpu transition-transform hover:scale-110">
|
||||
<svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5 text-white" viewBox="0 0 20 20" fill="currentColor">
|
||||
<path fill-rule="evenodd" d="M5.05 4.05a7 7 0 119.9 9.9L10 18.9l-4.95-4.95a7 7 0 010-9.9zM10 11a2 2 0 100-4 2 2 0 000 4z" clip-rule="evenodd" />
|
||||
</svg>
|
||||
</div>
|
||||
`;
|
||||
|
||||
const marker = new mapboxgl.Marker(el)
|
||||
.setLngLat([place.location.lng, place.location.lat])
|
||||
.setPopup(
|
||||
new mapboxgl.Popup({ offset: 25 }).setText(
|
||||
`${place.name}${place.vicinity ? `\n${place.vicinity}` : ''}`
|
||||
)
|
||||
new mapboxgl.Popup({ offset: 25, closeButton: false })
|
||||
.setHTML(`
|
||||
<div class="p-2 min-w-[200px] bg-white dark:bg-neutral-800 m-0">
|
||||
<h3 class="font-semibold text-sm text-neutral-900 dark:text-white">${place.name}</h3>
|
||||
${place.vicinity ? `<p class="text-xs mt-1 text-neutral-600 dark:text-neutral-300">${place.vicinity}</p>` : ''}
|
||||
</div>
|
||||
`)
|
||||
)
|
||||
.addTo(mapInstance.current!);
|
||||
|
||||
@ -91,7 +116,7 @@ const MapComponent = ({ center, places = [], zoom = 14, onMarkerClick }: MapProp
|
||||
}, [places, onMarkerClick]);
|
||||
|
||||
return (
|
||||
<div className="w-full h-64 rounded-lg overflow-hidden shadow-lg mt-6">
|
||||
<div className="w-full h-[60vh] rounded-t-xl overflow-hidden shadow-lg">
|
||||
<div ref={mapRef} className="w-full h-full" />
|
||||
</div>
|
||||
);
|
||||
|
||||
@ -3,10 +3,16 @@ import React, { useState } from 'react';
|
||||
import { motion, AnimatePresence } from 'framer-motion';
|
||||
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
|
||||
import { Dialog, DialogContent, DialogTitle } from "@/components/ui/dialog";
|
||||
import {
|
||||
Accordion,
|
||||
AccordionContent,
|
||||
AccordionItem,
|
||||
AccordionTrigger,
|
||||
} from "@/components/ui/accordion";
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { ArrowUpRight, Calendar, ChevronLeft, ChevronRight, Clock, Globe, ImageIcon, Newspaper, Search, X } from 'lucide-react';
|
||||
import { ScrollArea } from '@/components/ui/scroll-area';
|
||||
import { cn } from '@/lib/utils';
|
||||
|
||||
type SearchImage = {
|
||||
url: string;
|
||||
@ -34,7 +40,7 @@ type MultiSearchResponse = {
|
||||
type MultiSearchArgs = {
|
||||
queries: string[];
|
||||
maxResults: number[];
|
||||
topic: ("general" | "news")[];
|
||||
topics: ("general" | "news")[];
|
||||
searchDepth: ("basic" | "advanced")[];
|
||||
};
|
||||
|
||||
@ -147,36 +153,46 @@ const ImageGrid: React.FC<{ images: SearchImage[]; onImageClick: (index: number)
|
||||
|
||||
const SearchResults: React.FC<SearchResultsProps> = ({ searchData, topicType, onImageClick }) => (
|
||||
<div className="space-y-6">
|
||||
<div className="dark:bg-neutral-900 bg-white rounded-xl dark:border-neutral-800 border-gray-200 border">
|
||||
<div className="p-3 border-b dark:border-neutral-800 border-gray-200">
|
||||
<div className="flex items-center justify-between">
|
||||
<Accordion type="single" defaultValue="web-results" collapsible>
|
||||
<AccordionItem value="web-results" className="border-0">
|
||||
<AccordionTrigger
|
||||
className={cn(
|
||||
"w-full dark:bg-neutral-900 bg-white rounded-xl dark:border-neutral-800 border-gray-200 border px-6 py-4 hover:no-underline transition-all",
|
||||
"[&[data-state=open]]:rounded-b-none",
|
||||
"[&[data-state=open]]:border-b-0"
|
||||
)}
|
||||
>
|
||||
<div className="flex items-center gap-3">
|
||||
<div className="p-2 rounded-lg dark:bg-neutral-800 bg-gray-100">
|
||||
<Newspaper className="h-4 w-4 dark:text-neutral-400 text-gray-500" />
|
||||
<Globe className="h-4 w-4 dark:text-neutral-400 text-gray-500" />
|
||||
</div>
|
||||
<div>
|
||||
<h2 className="dark:text-neutral-100 text-gray-900 font-medium">Results for “{searchData.query}“</h2>
|
||||
<h2 className="dark:text-neutral-100 text-gray-900 font-medium text-left">
|
||||
Results for {searchData.query}
|
||||
</h2>
|
||||
<div className="flex items-center gap-2 mt-1">
|
||||
<Badge variant="secondary" className="dark:bg-neutral-800 bg-gray-100 dark:text-neutral-300 text-gray-600">
|
||||
{topicType}
|
||||
</Badge>
|
||||
<span className="text-xs dark:text-neutral-500 text-gray-500">{searchData.results.length} results</span>
|
||||
</div>
|
||||
</div>
|
||||
<span className="text-xs dark:text-neutral-500 text-gray-500">
|
||||
{searchData.results.length} results
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</AccordionTrigger>
|
||||
|
||||
<ScrollArea>
|
||||
<div className="flex gap-3 p-3 overflow-y-scroll">
|
||||
<AccordionContent className="dark:bg-neutral-900 bg-white dark:border-neutral-800 border-gray-200 border border-t-0 rounded-b-xl">
|
||||
<div className="flex overflow-x-auto gap-3 p-3 no-scrollbar">
|
||||
{searchData.results.map((result, index) => (
|
||||
<ResultCard key={index} result={result} index={index} />
|
||||
))}
|
||||
</div>
|
||||
</ScrollArea>
|
||||
</div>
|
||||
|
||||
</AccordionContent>
|
||||
</AccordionItem>
|
||||
</Accordion>
|
||||
|
||||
{/* Original Image Results Section */}
|
||||
{searchData.images.length > 0 && (
|
||||
<div className="dark:bg-neutral-900 bg-white rounded-xl dark:border-neutral-800 border-gray-200 border">
|
||||
<div className="p-4 border-b dark:border-neutral-800 border-gray-200">
|
||||
@ -191,66 +207,6 @@ const SearchResults: React.FC<SearchResultsProps> = ({ searchData, topicType, on
|
||||
</div>
|
||||
);
|
||||
|
||||
interface ContentDialogProps {
|
||||
isOpen: boolean;
|
||||
onClose: () => void;
|
||||
result: SearchResult;
|
||||
}
|
||||
|
||||
const ContentDialog: React.FC<ContentDialogProps> = ({ isOpen, onClose, result }) => (
|
||||
<Dialog open={isOpen} onOpenChange={onClose}>
|
||||
<DialogContent className="max-w-3xl h-fit p-0 dark:bg-neutral-900 bg-white dark:border-neutral-800 border-gray-200">
|
||||
<div className="p-6 space-y-4">
|
||||
<div className="flex items-start gap-4">
|
||||
<div className="w-10 h-10 rounded-lg dark:bg-neutral-800 bg-gray-100 flex items-center justify-center flex-shrink-0">
|
||||
<img
|
||||
src={`https://www.google.com/s2/favicons?sz=128&domain=${new URL(result.url).hostname}`}
|
||||
alt=""
|
||||
className="w-6 h-6"
|
||||
/>
|
||||
</div>
|
||||
<div className="flex-1 min-w-0">
|
||||
<h2 className="text-xl font-semibold dark:text-neutral-100 text-gray-900">
|
||||
{result.title}
|
||||
</h2>
|
||||
<a
|
||||
href={result.url}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
className="mt-2 text-sm dark:text-neutral-400 text-gray-500 hover:text-gray-700 dark:hover:text-neutral-300 flex items-center gap-1 w-fit"
|
||||
>
|
||||
{new URL(result.url).hostname}
|
||||
<ArrowUpRight className="h-4 w-4" />
|
||||
</a>
|
||||
</div>
|
||||
</div>
|
||||
<ScrollArea className="h-[60vh] w-full pr-4">
|
||||
<div className="space-y-4">
|
||||
<div className="prose prose-invert max-w-none">
|
||||
<p className="dark:text-neutral-200 text-gray-700 leading-relaxed whitespace-pre-wrap">
|
||||
{result.content}
|
||||
</p>
|
||||
</div>
|
||||
{result.published_date && (
|
||||
<div className="flex items-center gap-2 text-sm dark:text-neutral-500 text-gray-500 pt-4 border-t dark:border-neutral-800 border-gray-200">
|
||||
<Calendar className="h-4 w-4" />
|
||||
<time>
|
||||
Published on {new Date(result.published_date).toLocaleDateString('en-US', {
|
||||
year: 'numeric',
|
||||
month: 'long',
|
||||
day: 'numeric'
|
||||
})}
|
||||
</time>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</ScrollArea>
|
||||
</div>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
|
||||
|
||||
const MultiSearch: React.FC<{ result: MultiSearchResponse | null; args: MultiSearchArgs }> = ({ result, args }) => {
|
||||
const [activeTab, setActiveTab] = useState("0");
|
||||
const [galleryOpen, setGalleryOpen] = useState(false);
|
||||
@ -325,7 +281,7 @@ const MultiSearch: React.FC<{ result: MultiSearchResponse | null; args: MultiSea
|
||||
<TabsContent key={index} value={index.toString()}>
|
||||
<SearchResults
|
||||
searchData={search}
|
||||
topicType={args.topic[index] || args.topic[0]}
|
||||
topicType={args.topics[index] || args.topics[0]}
|
||||
onImageClick={(imageIndex) => {
|
||||
setSelectedSearch(index);
|
||||
setSelectedImage(imageIndex);
|
||||
|
||||
50
components/search-groups.tsx
Normal file
50
components/search-groups.tsx
Normal file
@ -0,0 +1,50 @@
|
||||
import React from 'react'
|
||||
import { Button } from "@/components/ui/button"
|
||||
import { Card, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"
|
||||
import { searchGroups, type SearchGroup } from '@/lib/utils'
|
||||
import { cn } from '@/lib/utils'
|
||||
|
||||
interface SearchGroupsProps {
|
||||
selectedGroup: string
|
||||
onGroupSelect: (group: SearchGroup) => void
|
||||
}
|
||||
|
||||
export function SearchGroups({ selectedGroup, onGroupSelect }: SearchGroupsProps) {
|
||||
return (
|
||||
<div className="w-full grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4 mt-4">
|
||||
{searchGroups.map((group) => {
|
||||
const Icon = group.icon
|
||||
const isSelected = selectedGroup === group.id
|
||||
|
||||
return (
|
||||
<Card
|
||||
key={group.id}
|
||||
className={cn(
|
||||
"cursor-pointer transition-all duration-200 hover:scale-[1.02]",
|
||||
"border border-neutral-200 dark:border-neutral-800",
|
||||
isSelected && "ring-2 ring-primary ring-offset-2 dark:ring-offset-neutral-950"
|
||||
)}
|
||||
onClick={() => onGroupSelect(group)}
|
||||
>
|
||||
<CardHeader>
|
||||
<div className="flex items-start gap-4">
|
||||
<div className={cn(
|
||||
"p-2 rounded-lg",
|
||||
isSelected ? "bg-primary text-primary-foreground" : "bg-neutral-100 dark:bg-neutral-800"
|
||||
)}>
|
||||
<Icon className="w-6 h-6" />
|
||||
</div>
|
||||
<div className="flex-1">
|
||||
<CardTitle className="text-lg">{group.name}</CardTitle>
|
||||
<CardDescription className="mt-1">
|
||||
{group.description}
|
||||
</CardDescription>
|
||||
</div>
|
||||
</div>
|
||||
</CardHeader>
|
||||
</Card>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
223
components/shopping-cards.tsx
Normal file
223
components/shopping-cards.tsx
Normal file
@ -0,0 +1,223 @@
|
||||
"use client";
|
||||
/* eslint-disable @next/next/no-img-element */
|
||||
import { motion, PanInfo, useMotionValue, useTransform } from "framer-motion";
|
||||
import { Badge } from "./ui/badge";
|
||||
import { Heart, Star, X } from "lucide-react";
|
||||
import { useState } from "react";
|
||||
import { toast } from "sonner";
|
||||
import { Button } from "./ui/button";
|
||||
import { Card, CardContent } from "./ui/card";
|
||||
|
||||
|
||||
interface ShoppingProduct {
|
||||
id: string | number;
|
||||
title: string;
|
||||
price: string;
|
||||
originalPrice?: string;
|
||||
currency: string;
|
||||
image: string;
|
||||
link: string;
|
||||
source: string;
|
||||
rating?: string | null;
|
||||
reviewCount?: string | null;
|
||||
delivery: string;
|
||||
}
|
||||
|
||||
interface CardRotateProps {
|
||||
children: React.ReactNode;
|
||||
onSendToBack: () => void;
|
||||
onSwipe?: (direction: 'left' | 'right') => void;
|
||||
}
|
||||
|
||||
function CardRotate({ children, onSendToBack, onSwipe }: CardRotateProps) {
|
||||
const x = useMotionValue(0);
|
||||
const y = useMotionValue(0);
|
||||
// Reduced rotation values for more subtle effect
|
||||
const rotateX = useTransform(y, [-100, 100], [15, -15]);
|
||||
const rotateY = useTransform(x, [-100, 100], [-15, 15]);
|
||||
|
||||
function handleDragEnd(_: any, info: PanInfo) {
|
||||
const threshold = 100;
|
||||
if (Math.abs(info.offset.x) > threshold) {
|
||||
onSendToBack();
|
||||
if (onSwipe) {
|
||||
onSwipe(info.offset.x > 0 ? 'right' : 'left');
|
||||
}
|
||||
} else {
|
||||
x.set(0);
|
||||
y.set(0);
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<motion.div
|
||||
className="absolute w-full h-full cursor-grab"
|
||||
style={{ x, y, rotateX, rotateY }}
|
||||
drag
|
||||
dragConstraints={{ top: 0, right: 0, bottom: 0, left: 0 }}
|
||||
dragElastic={0.4} // Reduced elasticity
|
||||
whileTap={{ cursor: "grabbing" }}
|
||||
onDragEnd={handleDragEnd}
|
||||
>
|
||||
{children}
|
||||
</motion.div>
|
||||
);
|
||||
}
|
||||
|
||||
const ProductCard = ({ product }: { product: ShoppingProduct }) => {
|
||||
const formattedPrice = parseFloat(product.price).toFixed(2);
|
||||
const formattedOriginalPrice = product.originalPrice ? parseFloat(product.originalPrice).toFixed(2) : null;
|
||||
const discount = formattedOriginalPrice ?
|
||||
Math.round(((parseFloat(formattedOriginalPrice) - parseFloat(formattedPrice)) / parseFloat(formattedOriginalPrice)) * 100) : null;
|
||||
|
||||
return (
|
||||
<div className="w-full h-full bg-white dark:bg-neutral-800 rounded-xl shadow-lg overflow-hidden">
|
||||
<div className="relative h-[60%] bg-neutral-100 dark:bg-neutral-700 p-4">
|
||||
<img
|
||||
src={product.image}
|
||||
alt={product.title}
|
||||
className="w-full h-full object-contain mix-blend-multiply dark:mix-blend-normal"
|
||||
/>
|
||||
{discount && discount > 0 && (
|
||||
<Badge
|
||||
className="absolute top-4 right-4 bg-red-500 text-white"
|
||||
variant="secondary"
|
||||
>
|
||||
{discount}% OFF
|
||||
</Badge>
|
||||
)}
|
||||
</div>
|
||||
<div className="p-4 h-[40%] flex flex-col justify-between">
|
||||
<div>
|
||||
<h3 className="font-medium text-lg line-clamp-2 mb-2 text-neutral-800 dark:text-neutral-200">
|
||||
{product.title}
|
||||
</h3>
|
||||
<div className="flex items-baseline gap-2">
|
||||
<span className="text-2xl font-bold text-green-600 dark:text-green-400">
|
||||
${formattedPrice}
|
||||
</span>
|
||||
{formattedOriginalPrice && (
|
||||
<span className="text-sm line-through text-neutral-500">
|
||||
${formattedOriginalPrice}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex items-center justify-between mt-4">
|
||||
<div className="flex items-center gap-1">
|
||||
{product.rating && (
|
||||
<>
|
||||
<Star className="h-4 w-4 fill-yellow-400 text-yellow-400" />
|
||||
<span className="text-sm text-neutral-600 dark:text-neutral-400">
|
||||
{product.rating} {product.reviewCount && `(${product.reviewCount})`}
|
||||
</span>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
<span className="text-sm text-neutral-600 dark:text-neutral-400">
|
||||
{product.source}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export const SwipeableProductStack = ({ products }: { products: ShoppingProduct[] }) => {
|
||||
const [cards, setCards] = useState(products);
|
||||
const [savedProducts, setSavedProducts] = useState<ShoppingProduct[]>([]);
|
||||
|
||||
const sendToBack = (id: string | number, direction?: 'left' | 'right') => {
|
||||
setCards((prev) => {
|
||||
const newCards = [...prev];
|
||||
const index = newCards.findIndex((card) => card.id === id);
|
||||
const [card] = newCards.splice(index, 1);
|
||||
|
||||
if (direction === 'right') {
|
||||
setSavedProducts(prev => [...prev, card]);
|
||||
toast.success('Product saved!');
|
||||
}
|
||||
|
||||
newCards.unshift(card);
|
||||
return newCards;
|
||||
});
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="flex flex-col items-center gap-6">
|
||||
<div className="relative w-full max-w-md aspect-[3/4]" style={{ perspective: 1000 }}>
|
||||
{cards.map((product, index) => (
|
||||
<CardRotate
|
||||
key={product.id}
|
||||
onSendToBack={() => sendToBack(product.id)}
|
||||
onSwipe={(direction) => sendToBack(product.id, direction)}
|
||||
>
|
||||
<motion.div
|
||||
className="h-full w-full"
|
||||
animate={{
|
||||
rotateZ: (cards.length - index - 1) * 2, // Reduced rotation
|
||||
scale: 1 - index * 0.03, // Reduced scale difference
|
||||
y: index * 8, // Reduced vertical offset
|
||||
}}
|
||||
transition={{ type: "spring", stiffness: 300, damping: 30 }}
|
||||
>
|
||||
<ProductCard product={product} />
|
||||
</motion.div>
|
||||
</CardRotate>
|
||||
))}
|
||||
</div>
|
||||
|
||||
<div className="flex items-center gap-4">
|
||||
<Button
|
||||
variant="outline"
|
||||
size="lg"
|
||||
className="rounded-full w-16 h-16 p-0" // Fixed size circular buttons
|
||||
onClick={() => cards[cards.length - 1] && sendToBack(cards[cards.length - 1].id, 'left')}
|
||||
>
|
||||
<X className="h-8 w-8 text-red-500" />
|
||||
</Button>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="lg"
|
||||
className="rounded-full w-16 h-16 p-0" // Fixed size circular buttons
|
||||
onClick={() => cards[cards.length - 1] && sendToBack(cards[cards.length - 1].id, 'right')}
|
||||
>
|
||||
<Heart className="h-8 w-8 text-green-500" />
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
{savedProducts.length > 0 && (
|
||||
<div className="w-full mt-8">
|
||||
<h3 className="text-lg font-medium text-neutral-800 dark:text-neutral-200 mb-4">
|
||||
Saved Products ({savedProducts.length})
|
||||
</h3>
|
||||
<div className="grid grid-cols-2 sm:grid-cols-3 gap-4">
|
||||
{savedProducts.map((product) => (
|
||||
<Card key={product.id} className="overflow-hidden">
|
||||
<CardContent className="p-3">
|
||||
<img
|
||||
src={product.image}
|
||||
alt={product.title}
|
||||
className="w-full aspect-square object-contain mb-2"
|
||||
/>
|
||||
<div className="text-sm font-medium line-clamp-1">{product.title}</div>
|
||||
<div className="text-base font-bold text-green-600 dark:text-green-400">
|
||||
${parseFloat(product.price).toFixed(2)}
|
||||
</div>
|
||||
<Button
|
||||
variant="default"
|
||||
size="sm"
|
||||
className="w-full mt-2"
|
||||
onClick={() => window.open(product.link, '_blank')}
|
||||
>
|
||||
View Details
|
||||
</Button>
|
||||
</CardContent>
|
||||
</Card>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
};
|
||||
118
components/ui/drawer.tsx
Normal file
118
components/ui/drawer.tsx
Normal file
@ -0,0 +1,118 @@
|
||||
"use client"
|
||||
|
||||
import * as React from "react"
|
||||
import { Drawer as DrawerPrimitive } from "vaul"
|
||||
|
||||
import { cn } from "@/lib/utils"
|
||||
|
||||
const Drawer = ({
|
||||
shouldScaleBackground = true,
|
||||
...props
|
||||
}: React.ComponentProps<typeof DrawerPrimitive.Root>) => (
|
||||
<DrawerPrimitive.Root
|
||||
shouldScaleBackground={shouldScaleBackground}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
Drawer.displayName = "Drawer"
|
||||
|
||||
const DrawerTrigger = DrawerPrimitive.Trigger
|
||||
|
||||
const DrawerPortal = DrawerPrimitive.Portal
|
||||
|
||||
const DrawerClose = DrawerPrimitive.Close
|
||||
|
||||
const DrawerOverlay = React.forwardRef<
|
||||
React.ElementRef<typeof DrawerPrimitive.Overlay>,
|
||||
React.ComponentPropsWithoutRef<typeof DrawerPrimitive.Overlay>
|
||||
>(({ className, ...props }, ref) => (
|
||||
<DrawerPrimitive.Overlay
|
||||
ref={ref}
|
||||
className={cn("fixed inset-0 z-50 bg-black/80", className)}
|
||||
{...props}
|
||||
/>
|
||||
))
|
||||
DrawerOverlay.displayName = DrawerPrimitive.Overlay.displayName
|
||||
|
||||
const DrawerContent = React.forwardRef<
|
||||
React.ElementRef<typeof DrawerPrimitive.Content>,
|
||||
React.ComponentPropsWithoutRef<typeof DrawerPrimitive.Content>
|
||||
>(({ className, children, ...props }, ref) => (
|
||||
<DrawerPortal>
|
||||
<DrawerOverlay />
|
||||
<DrawerPrimitive.Content
|
||||
ref={ref}
|
||||
className={cn(
|
||||
"fixed inset-x-0 bottom-0 z-50 mt-24 flex h-auto flex-col rounded-t-[10px] border bg-background",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
<div className="mx-auto mt-4 h-2 w-[100px] rounded-full bg-muted" />
|
||||
{children}
|
||||
</DrawerPrimitive.Content>
|
||||
</DrawerPortal>
|
||||
))
|
||||
DrawerContent.displayName = "DrawerContent"
|
||||
|
||||
const DrawerHeader = ({
|
||||
className,
|
||||
...props
|
||||
}: React.HTMLAttributes<HTMLDivElement>) => (
|
||||
<div
|
||||
className={cn("grid gap-1.5 p-4 text-center sm:text-left", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
DrawerHeader.displayName = "DrawerHeader"
|
||||
|
||||
const DrawerFooter = ({
|
||||
className,
|
||||
...props
|
||||
}: React.HTMLAttributes<HTMLDivElement>) => (
|
||||
<div
|
||||
className={cn("mt-auto flex flex-col gap-2 p-4", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
DrawerFooter.displayName = "DrawerFooter"
|
||||
|
||||
const DrawerTitle = React.forwardRef<
|
||||
React.ElementRef<typeof DrawerPrimitive.Title>,
|
||||
React.ComponentPropsWithoutRef<typeof DrawerPrimitive.Title>
|
||||
>(({ className, ...props }, ref) => (
|
||||
<DrawerPrimitive.Title
|
||||
ref={ref}
|
||||
className={cn(
|
||||
"text-lg font-semibold leading-none tracking-tight",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
))
|
||||
DrawerTitle.displayName = DrawerPrimitive.Title.displayName
|
||||
|
||||
const DrawerDescription = React.forwardRef<
|
||||
React.ElementRef<typeof DrawerPrimitive.Description>,
|
||||
React.ComponentPropsWithoutRef<typeof DrawerPrimitive.Description>
|
||||
>(({ className, ...props }, ref) => (
|
||||
<DrawerPrimitive.Description
|
||||
ref={ref}
|
||||
className={cn("text-sm text-muted-foreground", className)}
|
||||
{...props}
|
||||
/>
|
||||
))
|
||||
DrawerDescription.displayName = DrawerPrimitive.Description.displayName
|
||||
|
||||
export {
|
||||
Drawer,
|
||||
DrawerPortal,
|
||||
DrawerOverlay,
|
||||
DrawerTrigger,
|
||||
DrawerClose,
|
||||
DrawerContent,
|
||||
DrawerHeader,
|
||||
DrawerFooter,
|
||||
DrawerTitle,
|
||||
DrawerDescription,
|
||||
}
|
||||
@ -7,15 +7,18 @@ import { track } from '@vercel/analytics';
|
||||
import { toast } from 'sonner';
|
||||
import { Button } from '../ui/button';
|
||||
import { Textarea } from '../ui/textarea';
|
||||
import { Drawer, DrawerContent, DrawerHeader, DrawerTitle, DrawerTrigger } from '@/components/ui/drawer';
|
||||
import useWindowSize from '@/hooks/use-window-size';
|
||||
import { Sparkles, X, Zap, Cpu } from 'lucide-react';
|
||||
import { Sparkles, X, Zap, Cpu, Search, ChevronDown, Check, Atom } from 'lucide-react';
|
||||
import {
|
||||
DropdownMenu,
|
||||
DropdownMenuContent,
|
||||
DropdownMenuItem,
|
||||
DropdownMenuTrigger,
|
||||
} from "@/components/ui/dropdown-menu"
|
||||
import { cn } from '@/lib/utils';
|
||||
import { cn, SearchGroup, SearchGroupId, searchGroups } from '@/lib/utils';
|
||||
import { useMediaQuery } from '@/hooks/use-media-query';
|
||||
import { XLogo } from '@phosphor-icons/react';
|
||||
|
||||
interface ModelSwitcherProps {
|
||||
selectedModel: string;
|
||||
@ -26,6 +29,7 @@ interface ModelSwitcherProps {
|
||||
const models = [
|
||||
{ value: "azure:gpt4o-mini", label: "GPT-4o Mini", icon: Zap, description: "God speed, good quality", color: "emerald", vision: true },
|
||||
{ value: "anthropic:claude-3-5-haiku-20241022", label: "Claude 3.5 Haiku", icon: Sparkles, description: "Good quality, high speed", color: "orange", vision: false },
|
||||
{ value: "xai:grok-2-vision-1212", label: "Grok 2.0 Vision", icon: XLogo, description: "Good quality, normal speed", color: "glossyblack", vision: true },
|
||||
{ value: "anthropic:claude-3-5-sonnet-latest", label: "Claude 3.5 Sonnet (New)", icon: Sparkles, description: "High quality, good speed", color: "indigo", vision: true },
|
||||
{ value: "azure:gpt-4o", label: "GPT-4o", icon: Cpu, description: "Higher quality, normal speed", color: "blue", vision: true },
|
||||
];
|
||||
@ -52,6 +56,10 @@ const getColorClasses = (color: string, isSelected: boolean = false) => {
|
||||
return isSelected
|
||||
? `${baseClasses} ${selectedClasses} !bg-orange-500 dark:!bg-orange-600 !text-white hover:!bg-orange-600 dark:hover:!bg-orange-700`
|
||||
: `${baseClasses} !text-orange-700 dark:!text-orange-300 hover:!bg-orange-200 dark:hover:!bg-orange-800/70`;
|
||||
case 'glossyblack':
|
||||
return isSelected
|
||||
? `${baseClasses} ${selectedClasses} bg-gradient-to-br from-black to-neutral-800 !text-white shadow-inner`
|
||||
: `${baseClasses} !text-black dark:!text-white hover:!bg-black/10 dark:hover:!bg-black/40`;
|
||||
default:
|
||||
return isSelected
|
||||
? `${baseClasses} ${selectedClasses} !bg-neutral-500 dark:!bg-neutral-600 !text-white hover:!bg-neutral-600 dark:hover:!bg-neutral-700`
|
||||
@ -175,34 +183,6 @@ const hasVisionSupport = (modelValue: string): boolean => {
|
||||
return selectedModel?.vision === true
|
||||
};
|
||||
|
||||
interface FormComponentProps {
|
||||
input: string;
|
||||
setInput: (input: string) => void;
|
||||
attachments: Array<Attachment>;
|
||||
setAttachments: React.Dispatch<React.SetStateAction<Array<Attachment>>>;
|
||||
hasSubmitted: boolean;
|
||||
setHasSubmitted: (value: boolean) => void;
|
||||
isLoading: boolean;
|
||||
handleSubmit: (
|
||||
event?: {
|
||||
preventDefault?: () => void;
|
||||
},
|
||||
chatRequestOptions?: ChatRequestOptions,
|
||||
) => void;
|
||||
fileInputRef: React.RefObject<HTMLInputElement>;
|
||||
inputRef: React.RefObject<HTMLTextAreaElement>;
|
||||
stop: () => void;
|
||||
messages: Array<Message>;
|
||||
append: (
|
||||
message: Message | CreateMessage,
|
||||
chatRequestOptions?: ChatRequestOptions,
|
||||
) => Promise<string | null | undefined>;
|
||||
selectedModel: string;
|
||||
setSelectedModel: (value: string) => void;
|
||||
resetSuggestedQuestions: () => void;
|
||||
lastSubmittedQueryRef: React.MutableRefObject<string>;
|
||||
}
|
||||
|
||||
const AttachmentPreview: React.FC<{ attachment: Attachment | UploadingAttachment, onRemove: () => void, isUploading: boolean }> = ({ attachment, onRemove, isUploading }) => {
|
||||
const formatFileSize = (bytes: number): string => {
|
||||
if (bytes < 1024) return bytes + ' bytes';
|
||||
@ -295,6 +275,339 @@ interface UploadingAttachment {
|
||||
progress: number;
|
||||
}
|
||||
|
||||
interface FormComponentProps {
|
||||
input: string;
|
||||
setInput: (input: string) => void;
|
||||
attachments: Array<Attachment>;
|
||||
setAttachments: React.Dispatch<React.SetStateAction<Array<Attachment>>>;
|
||||
hasSubmitted: boolean;
|
||||
setHasSubmitted: (value: boolean) => void;
|
||||
isLoading: boolean;
|
||||
handleSubmit: (
|
||||
event?: {
|
||||
preventDefault?: () => void;
|
||||
},
|
||||
chatRequestOptions?: ChatRequestOptions,
|
||||
) => void;
|
||||
fileInputRef: React.RefObject<HTMLInputElement>;
|
||||
inputRef: React.RefObject<HTMLTextAreaElement>;
|
||||
stop: () => void;
|
||||
messages: Array<Message>;
|
||||
append: (
|
||||
message: Message | CreateMessage,
|
||||
chatRequestOptions?: ChatRequestOptions,
|
||||
) => Promise<string | null | undefined>;
|
||||
selectedModel: string;
|
||||
setSelectedModel: (value: string) => void;
|
||||
resetSuggestedQuestions: () => void;
|
||||
lastSubmittedQueryRef: React.MutableRefObject<string>;
|
||||
selectedGroup: SearchGroupId;
|
||||
setSelectedGroup: React.Dispatch<React.SetStateAction<SearchGroupId>>;
|
||||
}
|
||||
|
||||
// Add this component either in a new file or in your form component
|
||||
interface GroupSelectorProps {
|
||||
selectedGroup: SearchGroupId;
|
||||
onGroupSelect: (group: SearchGroup) => void;
|
||||
}
|
||||
|
||||
const themeColors: Record<SearchGroupId, {
|
||||
bg: string,
|
||||
bgHover: string,
|
||||
bgSelected: string,
|
||||
text: string,
|
||||
description: string
|
||||
focus?: string
|
||||
}> = {
|
||||
web: {
|
||||
bg: '!bg-white hover:!bg-cyan-50 dark:!bg-neutral-900/40 dark:hover:!bg-cyan-950/40',
|
||||
bgHover: 'hover:!border-cyan-200 dark:hover:!border-cyan-500/30',
|
||||
bgSelected: '!bg-cyan-50 dark:!bg-cyan-950/40 !border-cyan-500 dark:!border-cyan-400',
|
||||
text: '!text-cyan-600 dark:!text-cyan-400',
|
||||
description: '!text-neutral-600 dark:!text-neutral-500',
|
||||
focus: 'focus:!ring-cyan-500 dark:focus:!ring-cyan-400'
|
||||
},
|
||||
academic: {
|
||||
bg: '!bg-white hover:!bg-violet-50 dark:!bg-neutral-900/40 dark:hover:!bg-violet-950/40',
|
||||
bgHover: 'hover:!border-violet-200 dark:hover:!border-violet-500/30',
|
||||
bgSelected: '!bg-violet-50 dark:!bg-violet-950/40 !border-violet-500 dark:!border-violet-400',
|
||||
text: '!text-violet-600 dark:!text-violet-400',
|
||||
description: '!text-neutral-600 dark:!text-neutral-500',
|
||||
focus: 'focus:!ring-violet-500 dark:focus:!ring-violet-400'
|
||||
},
|
||||
youtube: {
|
||||
bg: '!bg-white hover:!bg-red-50 dark:!bg-neutral-900/40 dark:hover:!bg-red-950/40',
|
||||
bgHover: 'hover:!border-red-200 dark:hover:!border-red-500/30',
|
||||
bgSelected: '!bg-red-50 dark:!bg-red-950/40 !border-red-500 dark:!border-red-400',
|
||||
text: '!text-red-600 dark:!text-red-400',
|
||||
description: '!text-neutral-600 dark:!text-neutral-500',
|
||||
focus: 'focus:!ring-red-500 dark:focus:!ring-red-400'
|
||||
},
|
||||
x: {
|
||||
bg: '!bg-white hover:!bg-neutral-50 dark:!bg-neutral-900/40 dark:hover:!bg-neutral-800/40',
|
||||
bgHover: 'hover:!border-neutral-300 dark:hover:!border-neutral-600/30',
|
||||
bgSelected: '!bg-neutral-50 dark:!bg-neutral-800/40 !border-neutral-500 dark:!border-neutral-400',
|
||||
text: '!text-neutral-900 dark:!text-neutral-100',
|
||||
description: '!text-neutral-600 dark:!text-neutral-500',
|
||||
focus: 'focus:!ring-neutral-500 dark:focus:!ring-neutral-400'
|
||||
},
|
||||
shopping: {
|
||||
bg: '!bg-white hover:!bg-green-50 dark:!bg-neutral-900/40 dark:hover:!bg-green-950/40',
|
||||
bgHover: 'hover:!border-green-200 dark:hover:!border-green-500/30',
|
||||
bgSelected: '!bg-green-50 dark:!bg-green-950/40 !border-green-500 dark:!border-green-400',
|
||||
text: '!text-green-600 dark:!text-green-400',
|
||||
description: '!text-neutral-600 dark:!text-neutral-500',
|
||||
focus: 'focus:!ring-green-500 dark:focus:!ring-green-400'
|
||||
},
|
||||
writing: {
|
||||
bg: '!bg-white hover:!bg-blue-50 dark:!bg-neutral-900/40 dark:hover:!bg-blue-950/40',
|
||||
bgHover: 'hover:!border-blue-200 dark:hover:!border-blue-500/30',
|
||||
bgSelected: '!bg-blue-50 dark:!bg-blue-950/40 !border-blue-500 dark:!border-blue-400',
|
||||
text: '!text-blue-600 dark:!text-blue-400',
|
||||
description: '!text-neutral-600 dark:!text-neutral-500',
|
||||
focus: 'focus:!ring-blue-500 dark:focus:!ring-blue-400'
|
||||
}
|
||||
};
|
||||
|
||||
const DrawerSelectionContent = ({
|
||||
selectedGroup,
|
||||
onGroupSelect
|
||||
}: {
|
||||
selectedGroup: SearchGroupId,
|
||||
onGroupSelect: (group: SearchGroup) => void
|
||||
}) => (
|
||||
<div className="grid grid-cols-2 lg:grid-cols-3 gap-1.5 p-0.5">
|
||||
{searchGroups.map((group) => {
|
||||
const Icon = group.icon;
|
||||
const isSelected = selectedGroup === group.id;
|
||||
const groupColors = themeColors[group.id];
|
||||
|
||||
return (
|
||||
<div key={group.id}>
|
||||
<button
|
||||
onClick={() => onGroupSelect(group)}
|
||||
className={cn(
|
||||
"w-full flex flex-col gap-2 p-4 rounded-lg cursor-pointer font-sans group/item",
|
||||
"transition-all duration-200 relative overflow-hidden",
|
||||
"border dark:border-neutral-800 border-neutral-200",
|
||||
groupColors.bg,
|
||||
groupColors.bgHover,
|
||||
isSelected && cn(
|
||||
"ring-1 dark:ring-white/20 ring-black/10",
|
||||
"shadow-lg",
|
||||
groupColors.bgSelected,
|
||||
groupColors.focus
|
||||
),
|
||||
groupColors.focus
|
||||
)}
|
||||
>
|
||||
<div className="flex items-center gap-2">
|
||||
<Icon className={cn(
|
||||
"h-5 w-5 transition-transform duration-200",
|
||||
groupColors.text,
|
||||
"group-hover/item:scale-110"
|
||||
)} />
|
||||
<span className="text-base font-medium transition-colors duration-200 text-neutral-900 dark:text-white">
|
||||
{group.name}
|
||||
</span>
|
||||
</div>
|
||||
<p className={cn(
|
||||
"text-sm leading-snug text-left",
|
||||
groupColors.description
|
||||
)}>
|
||||
{group.description}
|
||||
</p>
|
||||
<div className={cn(
|
||||
"absolute inset-0 opacity-0 group-hover/item:opacity-100",
|
||||
"transition-opacity duration-200 pointer-events-none",
|
||||
"bg-gradient-to-br from-transparent via-black/[0.02] dark:via-white/[0.02] to-transparent"
|
||||
)} />
|
||||
</button>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
);
|
||||
|
||||
const DropdownSelectionContent = ({
|
||||
selectedGroup,
|
||||
onGroupSelect
|
||||
}: {
|
||||
selectedGroup: SearchGroupId,
|
||||
onGroupSelect: (group: SearchGroup) => void
|
||||
}) => (
|
||||
<div className="grid grid-cols-2 lg:grid-cols-3 gap-1.5 p-0.5">
|
||||
{searchGroups.map((group) => {
|
||||
const Icon = group.icon;
|
||||
const isSelected = selectedGroup === group.id;
|
||||
const groupColors = themeColors[group.id];
|
||||
|
||||
return (
|
||||
<DropdownMenuItem
|
||||
key={group.id}
|
||||
onSelect={() => onGroupSelect(group)}
|
||||
className={cn(
|
||||
"flex flex-col gap-2 p-4 rounded-lg cursor-pointer font-sans group/item",
|
||||
"transition-all duration-200 relative overflow-hidden",
|
||||
!isSelected && "border dark:border-neutral-800 border-neutral-200",
|
||||
groupColors.bg,
|
||||
groupColors.bgHover,
|
||||
isSelected && cn(
|
||||
"ring-1 dark:ring-white/20 ring-black/10",
|
||||
"shadow-lg",
|
||||
groupColors.bgSelected
|
||||
)
|
||||
)}
|
||||
>
|
||||
<div className="flex items-center gap-2">
|
||||
<Icon className={cn(
|
||||
"h-5 w-5 transition-transform duration-200",
|
||||
groupColors.text,
|
||||
"group-hover/item:scale-110"
|
||||
)} />
|
||||
<span className="text-base font-medium transition-colors duration-200 text-neutral-900 dark:text-white">
|
||||
{group.name}
|
||||
</span>
|
||||
</div>
|
||||
<p className={cn(
|
||||
"text-sm leading-snug text-left",
|
||||
groupColors.description
|
||||
)}>
|
||||
{group.description}
|
||||
</p>
|
||||
<div className={cn(
|
||||
"absolute inset-0 opacity-0 group-hover/item:opacity-100",
|
||||
"transition-opacity duration-200 pointer-events-none",
|
||||
"bg-gradient-to-br from-transparent via-black/[0.02] dark:via-white/[0.02] to-transparent"
|
||||
)} />
|
||||
</DropdownMenuItem>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
);
|
||||
|
||||
const TriggerContent = ({
|
||||
selectedGroup,
|
||||
isOpen
|
||||
}: {
|
||||
selectedGroup: SearchGroupId,
|
||||
isOpen: boolean
|
||||
}) => {
|
||||
const selectedGroupDetails = searchGroups.find(g => g.id === selectedGroup);
|
||||
const Icon = selectedGroupDetails?.icon;
|
||||
const colors = themeColors[selectedGroup];
|
||||
|
||||
return (
|
||||
<div className="flex items-center gap-2 relative z-10">
|
||||
{Icon && (
|
||||
<Icon className={cn(
|
||||
"h-4 w-4 transition-transform duration-200",
|
||||
colors.text,
|
||||
"group-hover:scale-110"
|
||||
)} />
|
||||
)}
|
||||
<span className="!text-sm !font-sans !font-medium relative">
|
||||
{selectedGroupDetails?.name}
|
||||
<span className={cn(
|
||||
"absolute inset-x-0 -bottom-px h-px transition-all duration-200",
|
||||
isOpen ? "scale-x-100" : "scale-x-0",
|
||||
"bg-neutral-400 dark:bg-white/30",
|
||||
"group-hover:scale-x-100"
|
||||
)} />
|
||||
</span>
|
||||
<ChevronDown className={cn(
|
||||
"h-3 w-3 opacity-50 transition-transform duration-200",
|
||||
isOpen && "transform rotate-180",
|
||||
"group-hover:opacity-100"
|
||||
)} />
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
const GroupSelector = ({ selectedGroup, onGroupSelect }: GroupSelectorProps) => {
|
||||
const [isOpen, setIsOpen] = useState(false);
|
||||
const isDesktop = useMediaQuery("(min-width: 768px)");
|
||||
|
||||
const handleGroupSelection = (group: SearchGroup) => {
|
||||
onGroupSelect(group);
|
||||
setIsOpen(false);
|
||||
};
|
||||
|
||||
if (!isDesktop) {
|
||||
return (
|
||||
<Drawer
|
||||
open={isOpen}
|
||||
onOpenChange={setIsOpen}
|
||||
>
|
||||
<DrawerTrigger asChild>
|
||||
<Button
|
||||
variant="ghost"
|
||||
className={cn(
|
||||
"h-8 px-3 gap-2 group",
|
||||
"transition-all duration-200 font-sans relative",
|
||||
"bg-white hover:bg-neutral-50 dark:bg-neutral-900/40 dark:hover:bg-neutral-800/60",
|
||||
"border border-neutral-200 dark:border-neutral-800",
|
||||
"text-neutral-800 dark:text-white",
|
||||
"z-[60]"
|
||||
)}
|
||||
>
|
||||
<TriggerContent selectedGroup={selectedGroup} isOpen={isOpen} />
|
||||
</Button>
|
||||
</DrawerTrigger>
|
||||
<DrawerContent className="z-[60]">
|
||||
<DrawerHeader>
|
||||
<DrawerTitle className="text-center font-sans">
|
||||
Select Search Type
|
||||
</DrawerTitle>
|
||||
</DrawerHeader>
|
||||
<div className="p-4">
|
||||
<DrawerSelectionContent
|
||||
selectedGroup={selectedGroup}
|
||||
onGroupSelect={handleGroupSelection}
|
||||
/>
|
||||
</div>
|
||||
</DrawerContent>
|
||||
</Drawer>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<DropdownMenu onOpenChange={setIsOpen}>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<Button
|
||||
variant="ghost"
|
||||
className={cn(
|
||||
"h-8 px-3 gap-2 group",
|
||||
"transition-all duration-200 font-sans relative",
|
||||
"bg-white hover:bg-neutral-50 dark:bg-neutral-900/40 dark:hover:bg-neutral-800/60",
|
||||
"border border-neutral-200 dark:border-neutral-800",
|
||||
"text-neutral-800 dark:text-white",
|
||||
"z-[60]"
|
||||
)}
|
||||
>
|
||||
<TriggerContent selectedGroup={selectedGroup} isOpen={isOpen} />
|
||||
</Button>
|
||||
</DropdownMenuTrigger>
|
||||
|
||||
<DropdownMenuContent
|
||||
align="start"
|
||||
sideOffset={8}
|
||||
className={cn(
|
||||
"w-[600px] font-sans z-[60] -ml-2 mt-1",
|
||||
"border border-neutral-200 dark:border-neutral-800",
|
||||
"bg-white dark:bg-neutral-900",
|
||||
"shadow-lg rounded-lg"
|
||||
)}
|
||||
>
|
||||
<DropdownSelectionContent
|
||||
selectedGroup={selectedGroup}
|
||||
onGroupSelect={handleGroupSelection}
|
||||
/>
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
);
|
||||
};
|
||||
|
||||
const FormComponent: React.FC<FormComponentProps> = ({
|
||||
input,
|
||||
setInput,
|
||||
@ -313,6 +626,8 @@ const FormComponent: React.FC<FormComponentProps> = ({
|
||||
setSelectedModel,
|
||||
resetSuggestedQuestions,
|
||||
lastSubmittedQueryRef,
|
||||
selectedGroup,
|
||||
setSelectedGroup,
|
||||
}) => {
|
||||
const [uploadQueue, setUploadQueue] = useState<Array<string>>([]);
|
||||
const { width } = useWindowSize();
|
||||
@ -331,6 +646,14 @@ const FormComponent: React.FC<FormComponentProps> = ({
|
||||
setIsFocused(false);
|
||||
};
|
||||
|
||||
const handleGroupSelect = useCallback((group: SearchGroup) => {
|
||||
setSelectedGroup(group.id);
|
||||
setInput('');
|
||||
resetSuggestedQuestions();
|
||||
inputRef.current?.focus();
|
||||
}, [setSelectedGroup, setInput, resetSuggestedQuestions, inputRef]);
|
||||
|
||||
// Keep existing file upload and form submission logic...
|
||||
const uploadFile = async (file: File): Promise<Attachment> => {
|
||||
const formData = new FormData();
|
||||
formData.append('file', file);
|
||||
@ -392,7 +715,7 @@ const FormComponent: React.FC<FormComponentProps> = ({
|
||||
if (input.trim() || attachments.length > 0) {
|
||||
setHasSubmitted(true);
|
||||
lastSubmittedQueryRef.current = input.trim();
|
||||
track("search input", { query: input.trim() })
|
||||
track("search input", { query: input.trim() });
|
||||
|
||||
handleSubmit(event, {
|
||||
experimental_attachments: attachments,
|
||||
@ -429,19 +752,20 @@ const FormComponent: React.FC<FormComponentProps> = ({
|
||||
}
|
||||
}, [attachments.length, hasSubmitted, fileInputRef]);
|
||||
|
||||
|
||||
return (
|
||||
|
||||
<div className={cn(
|
||||
"relative w-full flex flex-col gap-2 rounded-lg transition-all duration-300 z-[51]",
|
||||
attachments.length > 0 || uploadQueue.length > 0
|
||||
? "bg-gray-100/70 dark:bg-neutral-800 p-1"
|
||||
: "bg-transparent"
|
||||
)}>
|
||||
<input type="file" className="hidden" ref={fileInputRef} multiple onChange={handleFileChange} tabIndex={-1} />
|
||||
<input type="file" className="hidden" ref={postSubmitFileInputRef} multiple onChange={handleFileChange} tabIndex={-1} />
|
||||
<input type="file" className="hidden" ref={fileInputRef} multiple onChange={handleFileChange} accept="image/*" tabIndex={-1} />
|
||||
<input type="file" className="hidden" ref={postSubmitFileInputRef} multiple onChange={handleFileChange} accept="image/*" tabIndex={-1} />
|
||||
|
||||
{(attachments.length > 0 || uploadQueue.length > 0) && (
|
||||
<div className="flex flex-row gap-2 overflow-x-auto py-2 max-h-32 z-10">
|
||||
{/* Existing attachment previews */}
|
||||
{attachments.map((attachment, index) => (
|
||||
<AttachmentPreview
|
||||
key={attachment.url}
|
||||
@ -480,18 +804,18 @@ const FormComponent: React.FC<FormComponentProps> = ({
|
||||
"overflow-y-auto overflow-x-hidden",
|
||||
"text-base leading-relaxed",
|
||||
"bg-neutral-100 dark:bg-neutral-900",
|
||||
"boder border-neutral-200 dark:border-neutral-700",
|
||||
"border border-neutral-200 dark:border-neutral-700",
|
||||
"focus:border-neutral-300 dark:focus:border-neutral-600",
|
||||
"text-neutral-900 dark:text-neutral-100",
|
||||
"focus:ring-2 focus:ring-neutral-300 dark:focus:ring-neutral-600",
|
||||
"px-4 pt-3 pb-5" // Increased bottom padding to prevent overlap
|
||||
"focus:!ring-1 focus:!ring-neutral-300 dark:focus:!ring-neutral-600",
|
||||
"px-4 pt-3 pb-5"
|
||||
)}
|
||||
rows={3}
|
||||
onKeyDown={(event) => {
|
||||
if (event.key === "Enter" && !event.shiftKey) {
|
||||
event.preventDefault();
|
||||
if (isLoading) {
|
||||
toast.error("Please wait for the model to finish its response!");
|
||||
toast.error("Please wait for the response to complete!");
|
||||
} else {
|
||||
submitForm();
|
||||
}
|
||||
@ -499,15 +823,26 @@ const FormComponent: React.FC<FormComponentProps> = ({
|
||||
}}
|
||||
/>
|
||||
|
||||
<div className={cn("absolute bottom-0 inset-x-0 flex justify-between items-center rounded-b-lg p-2 bg-neutral-100 dark:bg-neutral-900",
|
||||
"border border-t-0 border-neutral-200 dark:border-neutral-700",
|
||||
isFocused ? "border-neutral-300 dark:border-neutral-600" : "",
|
||||
isLoading ? "!opacity-40 !cursor-not-allowed" : ""
|
||||
<div className={cn(
|
||||
"absolute bottom-0 inset-x-0 flex justify-between items-center rounded-b-lg p-2",
|
||||
"bg-neutral-100 dark:bg-neutral-900",
|
||||
"!border !border-t-0 !border-neutral-200 dark:!border-neutral-700",
|
||||
isFocused ? "!border-neutral-300 dark:!border-neutral-600" : "",
|
||||
isLoading ? "!opacity-20 !cursor-not-allowed" : ""
|
||||
)}>
|
||||
<div className="flex items-center gap-2">
|
||||
{!hasSubmitted ?
|
||||
<GroupSelector
|
||||
selectedGroup={selectedGroup}
|
||||
onGroupSelect={handleGroupSelect}
|
||||
/>
|
||||
: null
|
||||
}
|
||||
<ModelSwitcher
|
||||
selectedModel={selectedModel}
|
||||
setSelectedModel={setSelectedModel}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center gap-2">
|
||||
{hasVisionSupport(selectedModel) && (
|
||||
|
||||
31
components/ui/separator.tsx
Normal file
31
components/ui/separator.tsx
Normal file
@ -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 }
|
||||
139
components/ui/sheet.tsx
Normal file
139
components/ui/sheet.tsx
Normal file
@ -0,0 +1,139 @@
|
||||
"use client"
|
||||
|
||||
import * as React from "react"
|
||||
import * as SheetPrimitive from "@radix-ui/react-dialog"
|
||||
import { cva, type VariantProps } from "class-variance-authority"
|
||||
import { cn } from "@/lib/utils"
|
||||
import { Cross2Icon } from "@radix-ui/react-icons"
|
||||
|
||||
const Sheet = SheetPrimitive.Root
|
||||
|
||||
const SheetTrigger = SheetPrimitive.Trigger
|
||||
|
||||
const SheetClose = SheetPrimitive.Close
|
||||
|
||||
const SheetPortal = SheetPrimitive.Portal
|
||||
|
||||
const SheetOverlay = React.forwardRef<
|
||||
React.ElementRef<typeof SheetPrimitive.Overlay>,
|
||||
React.ComponentPropsWithoutRef<typeof SheetPrimitive.Overlay>
|
||||
>(({ className, ...props }, ref) => (
|
||||
<SheetPrimitive.Overlay
|
||||
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}
|
||||
ref={ref}
|
||||
/>
|
||||
))
|
||||
SheetOverlay.displayName = SheetPrimitive.Overlay.displayName
|
||||
|
||||
const sheetVariants = cva(
|
||||
"fixed z-50 gap-4 bg-background p-6 shadow-lg transition ease-in-out data-[state=closed]:duration-300 data-[state=open]:duration-500 data-[state=open]:animate-in data-[state=closed]:animate-out",
|
||||
{
|
||||
variants: {
|
||||
side: {
|
||||
top: "inset-x-0 top-0 border-b data-[state=closed]:slide-out-to-top data-[state=open]:slide-in-from-top",
|
||||
bottom:
|
||||
"inset-x-0 bottom-0 border-t data-[state=closed]:slide-out-to-bottom data-[state=open]:slide-in-from-bottom",
|
||||
left: "inset-y-0 left-0 h-full w-3/4 border-r data-[state=closed]:slide-out-to-left data-[state=open]:slide-in-from-left sm:max-w-sm",
|
||||
right:
|
||||
"inset-y-0 right-0 h-full w-3/4 border-l data-[state=closed]:slide-out-to-right data-[state=open]:slide-in-from-right sm:max-w-sm",
|
||||
},
|
||||
},
|
||||
defaultVariants: {
|
||||
side: "right",
|
||||
},
|
||||
}
|
||||
)
|
||||
|
||||
interface SheetContentProps
|
||||
extends React.ComponentPropsWithoutRef<typeof SheetPrimitive.Content>,
|
||||
VariantProps<typeof sheetVariants> {}
|
||||
|
||||
const SheetContent = React.forwardRef<
|
||||
React.ElementRef<typeof SheetPrimitive.Content>,
|
||||
SheetContentProps
|
||||
>(({ side = "right", className, children, ...props }, ref) => (
|
||||
<SheetPortal>
|
||||
<SheetOverlay />
|
||||
<SheetPrimitive.Content
|
||||
ref={ref}
|
||||
className={cn(sheetVariants({ side }), className)}
|
||||
{...props}
|
||||
>
|
||||
<SheetPrimitive.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-secondary">
|
||||
<Cross2Icon className="h-4 w-4" />
|
||||
<span className="sr-only">Close</span>
|
||||
</SheetPrimitive.Close>
|
||||
{children}
|
||||
</SheetPrimitive.Content>
|
||||
</SheetPortal>
|
||||
))
|
||||
SheetContent.displayName = SheetPrimitive.Content.displayName
|
||||
|
||||
const SheetHeader = ({
|
||||
className,
|
||||
...props
|
||||
}: React.HTMLAttributes<HTMLDivElement>) => (
|
||||
<div
|
||||
className={cn(
|
||||
"flex flex-col space-y-2 text-center sm:text-left",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
SheetHeader.displayName = "SheetHeader"
|
||||
|
||||
const SheetFooter = ({
|
||||
className,
|
||||
...props
|
||||
}: React.HTMLAttributes<HTMLDivElement>) => (
|
||||
<div
|
||||
className={cn(
|
||||
"flex flex-col-reverse sm:flex-row sm:justify-end sm:space-x-2",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
SheetFooter.displayName = "SheetFooter"
|
||||
|
||||
const SheetTitle = React.forwardRef<
|
||||
React.ElementRef<typeof SheetPrimitive.Title>,
|
||||
React.ComponentPropsWithoutRef<typeof SheetPrimitive.Title>
|
||||
>(({ className, ...props }, ref) => (
|
||||
<SheetPrimitive.Title
|
||||
ref={ref}
|
||||
className={cn("text-lg font-semibold text-foreground", className)}
|
||||
{...props}
|
||||
/>
|
||||
))
|
||||
SheetTitle.displayName = SheetPrimitive.Title.displayName
|
||||
|
||||
const SheetDescription = React.forwardRef<
|
||||
React.ElementRef<typeof SheetPrimitive.Description>,
|
||||
React.ComponentPropsWithoutRef<typeof SheetPrimitive.Description>
|
||||
>(({ className, ...props }, ref) => (
|
||||
<SheetPrimitive.Description
|
||||
ref={ref}
|
||||
className={cn("text-sm text-muted-foreground", className)}
|
||||
{...props}
|
||||
/>
|
||||
))
|
||||
SheetDescription.displayName = SheetPrimitive.Description.displayName
|
||||
|
||||
export {
|
||||
Sheet,
|
||||
SheetPortal,
|
||||
SheetOverlay,
|
||||
SheetTrigger,
|
||||
SheetClose,
|
||||
SheetContent,
|
||||
SheetHeader,
|
||||
SheetFooter,
|
||||
SheetTitle,
|
||||
SheetDescription,
|
||||
}
|
||||
18
hooks/use-media-query.tsx
Normal file
18
hooks/use-media-query.tsx
Normal file
@ -0,0 +1,18 @@
|
||||
// hooks/use-media-query.ts
|
||||
import { useEffect, useState } from 'react'
|
||||
|
||||
export function useMediaQuery(query: string) {
|
||||
const [matches, setMatches] = useState(false)
|
||||
|
||||
useEffect(() => {
|
||||
const media = window.matchMedia(query)
|
||||
if (media.matches !== matches) {
|
||||
setMatches(media.matches)
|
||||
}
|
||||
const listener = () => setMatches(media.matches)
|
||||
media.addEventListener('change', listener)
|
||||
return () => media.removeEventListener('change', listener)
|
||||
}, [matches, query])
|
||||
|
||||
return matches
|
||||
}
|
||||
74
lib/utils.ts
74
lib/utils.ts
@ -1,6 +1,80 @@
|
||||
// /lib/utils.ts
|
||||
import { type ClassValue, clsx } from "clsx"
|
||||
import { twMerge } from "tailwind-merge"
|
||||
import { Globe, Book, ShoppingBasket, YoutubeIcon, Pen } from 'lucide-react'
|
||||
import { RedditLogo, XLogo } from '@phosphor-icons/react'
|
||||
|
||||
export function cn(...inputs: ClassValue[]) {
|
||||
return twMerge(clsx(inputs))
|
||||
}
|
||||
|
||||
export type SearchGroupId = 'web' | 'academic' | 'shopping' | 'youtube' | 'x' | 'writing';
|
||||
|
||||
export const searchGroups = [
|
||||
{
|
||||
id: 'web' as const,
|
||||
name: 'Web',
|
||||
description: 'Search across the entire internet',
|
||||
icon: Globe,
|
||||
},
|
||||
{
|
||||
id: 'academic' as const,
|
||||
name: 'Academic',
|
||||
description: 'Search academic papers and research',
|
||||
icon: Book,
|
||||
},
|
||||
{
|
||||
id: 'shopping' as const,
|
||||
name: 'Shopping',
|
||||
description: 'Find products and compare prices',
|
||||
icon: ShoppingBasket,
|
||||
},
|
||||
{
|
||||
id: 'youtube' as const,
|
||||
name: 'YouTube',
|
||||
description: 'Search YouTube videos in real-time',
|
||||
icon: YoutubeIcon,
|
||||
},
|
||||
{
|
||||
id: 'x' as const,
|
||||
name: 'X',
|
||||
description: 'Search X(Twitter) posts and content',
|
||||
icon: XLogo,
|
||||
},
|
||||
{
|
||||
id: 'writing' as const,
|
||||
name: 'Writing',
|
||||
description: 'Chat or Talk without web search.',
|
||||
icon: Pen,
|
||||
}
|
||||
] as const;
|
||||
|
||||
export const groupTools = {
|
||||
web: ['web_search', 'retrieve', 'programming'] as const,
|
||||
academic: ['academic_search', 'retrieve', 'programming'] as const,
|
||||
shopping: ['shopping_search', 'programming'] as const,
|
||||
youtube: ['youtube_search'] as const,
|
||||
x: ['x_search'] as const,
|
||||
writing: [] as const,
|
||||
} as const;
|
||||
|
||||
export const groupPrompts = {
|
||||
web: `You are an expert AI web search engine, that helps users find information on the internet.
|
||||
Always start with running the search tool and then provide accurate, concise responses.
|
||||
Format your response in clear paragraphs with citations.`,
|
||||
academic: `You are an academic research assistant that helps find and analyze scholarly content.
|
||||
Focus on peer-reviewed papers, citations, and academic sources.
|
||||
Always include proper citations and summarize key findings.`,
|
||||
shopping: `You are a shopping assistant that helps users find and compare products.
|
||||
Focus on providing accurate pricing, product details, and merchant information.
|
||||
Compare options and highlight key features and best values.`,
|
||||
youtube: `You are a YouTube search assistant that helps find relevant videos and channels.
|
||||
Provide video titles, channel names, view counts, and publish dates.
|
||||
Summarize video content and highlight key moments.`,
|
||||
reddit: `You are a Reddit content curator that helps find relevant posts and discussions.
|
||||
Search across subreddits and provide post titles, vote counts, and comment highlights.
|
||||
Summarize key discussions and community consensus.`,
|
||||
writing: `You are a writing assistant that helps users with writing, conversation, or intellectual topics.`,
|
||||
} as const;
|
||||
|
||||
export type SearchGroup = typeof searchGroups[number];
|
||||
|
||||
@ -56,6 +56,13 @@ const nextConfig = {
|
||||
port: '',
|
||||
pathname: '**'
|
||||
},
|
||||
// www.uneed.best
|
||||
{
|
||||
protocol: 'https',
|
||||
hostname: 'www.uneed.best',
|
||||
port: '',
|
||||
pathname: '**'
|
||||
},
|
||||
]
|
||||
},
|
||||
};
|
||||
|
||||
21
package.json
21
package.json
@ -9,26 +9,28 @@
|
||||
"lint": "next lint"
|
||||
},
|
||||
"dependencies": {
|
||||
"@ai-sdk/anthropic": "^0.0.55",
|
||||
"@ai-sdk/azure": "^0.0.51",
|
||||
"@ai-sdk/anthropic": "^1.0.5",
|
||||
"@ai-sdk/azure": "^1.0.10",
|
||||
"@ai-sdk/cohere": "^1.0.3",
|
||||
"@ai-sdk/google": "^0.0.55",
|
||||
"@ai-sdk/google": "^1.0.7",
|
||||
"@ai-sdk/groq": "^0.0.1",
|
||||
"@ai-sdk/mistral": "^0.0.41",
|
||||
"@ai-sdk/openai": "^0.0.58",
|
||||
"@ai-sdk/xai": "^1.0.3",
|
||||
"@ai-sdk/xai": "^1.0.6",
|
||||
"@e2b/code-interpreter": "^1.0.3",
|
||||
"@foobar404/wave": "^2.0.5",
|
||||
"@mendable/firecrawl-js": "^1.4.3",
|
||||
"@phosphor-icons/react": "^2.1.7",
|
||||
"@radix-ui/react-accordion": "^1.2.0",
|
||||
"@radix-ui/react-collapsible": "^1.1.1",
|
||||
"@radix-ui/react-dialog": "^1.1.1",
|
||||
"@radix-ui/react-dialog": "^1.1.2",
|
||||
"@radix-ui/react-dropdown-menu": "^2.1.1",
|
||||
"@radix-ui/react-hover-card": "^1.1.1",
|
||||
"@radix-ui/react-icons": "^1.3.0",
|
||||
"@radix-ui/react-navigation-menu": "^1.2.0",
|
||||
"@radix-ui/react-popover": "^1.1.1",
|
||||
"@radix-ui/react-scroll-area": "^1.1.0",
|
||||
"@radix-ui/react-separator": "^1.1.1",
|
||||
"@radix-ui/react-slot": "^1.1.0",
|
||||
"@radix-ui/react-switch": "^1.1.1",
|
||||
"@radix-ui/react-tabs": "^1.1.0",
|
||||
@ -43,7 +45,7 @@
|
||||
"@vercel/analytics": "^1.3.1",
|
||||
"@vercel/blob": "^0.23.4",
|
||||
"@vercel/functions": "^1.4.0",
|
||||
"ai": "^3.4.33",
|
||||
"ai": "^4.0.17",
|
||||
"anthropic-vertex-ai": "^1.0.0",
|
||||
"cheerio": "^1.0.0",
|
||||
"class-variance-authority": "^0.7.0",
|
||||
@ -53,6 +55,7 @@
|
||||
"echarts-for-react": "^3.0.2",
|
||||
"embla-carousel-autoplay": "^8.3.0",
|
||||
"embla-carousel-react": "^8.3.0",
|
||||
"exa-js": "^1.3.3",
|
||||
"framer-motion": "^11.3.19",
|
||||
"google-auth-library": "^9.14.1",
|
||||
"highlight.js": "^11.10.0",
|
||||
@ -61,7 +64,8 @@
|
||||
"luxon": "^3.5.0",
|
||||
"mapbox-gl": "^3.7.0",
|
||||
"marked-react": "^2.0.0",
|
||||
"next": "^14.2.17",
|
||||
"motion": "^11.13.5",
|
||||
"next": "^14.2.20",
|
||||
"next-themes": "^0.3.0",
|
||||
"openai": "^4.56.0",
|
||||
"react": "^18",
|
||||
@ -79,7 +83,8 @@
|
||||
"tailwindcss-animate": "^1.0.7",
|
||||
"unified": "^11.0.5",
|
||||
"unist-util-visit": "^5.0.0",
|
||||
"zod": "^3.23.8"
|
||||
"vaul": "^1.1.1",
|
||||
"zod": "^3.24.1"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/google.maps": "^3.55.12",
|
||||
|
||||
810
pnpm-lock.yaml
810
pnpm-lock.yaml
File diff suppressed because it is too large
Load Diff
Loading…
Reference in New Issue
Block a user