Compare commits
6 Commits
feat/front
...
feat/llm-e
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
a273f29e07 | ||
|
|
2f4239a83b | ||
|
|
e13b1ea2d5 | ||
|
|
637f1540cf | ||
|
|
71ef567d0d | ||
|
|
3a448a5063 |
@@ -1,216 +0,0 @@
|
||||
"use client"
|
||||
|
||||
import { useState } from "react"
|
||||
import { Input } from "@/components/ui/input"
|
||||
import { Button } from "@/components/ui/button"
|
||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"
|
||||
import { Badge } from "@/components/ui/badge"
|
||||
import { Avatar, AvatarFallback } from "@/components/ui/avatar"
|
||||
import { Search, Eye, BarChart3, Filter, X, Loader2 } from "lucide-react"
|
||||
import Link from "next/link"
|
||||
|
||||
const allComparisons = [
|
||||
{
|
||||
id: "1",
|
||||
title: "React vs Vue vs Svelte",
|
||||
description: "Frontend framework comparison for modern web development",
|
||||
items: ["React", "Vue", "Svelte"],
|
||||
tags: ["Tech", "JavaScript"],
|
||||
author: "Alex Johnson",
|
||||
overallScore: 8.5,
|
||||
views: 1247,
|
||||
},
|
||||
{
|
||||
id: "2",
|
||||
title: "GPT-4 vs Claude vs Gemini",
|
||||
description: "Comparing top AI language models for reasoning tasks",
|
||||
items: ["GPT-4", "Claude 3", "Gemini Pro"],
|
||||
tags: ["AI", "Products"],
|
||||
author: "Sarah Chen",
|
||||
overallScore: 8.8,
|
||||
views: 3891,
|
||||
},
|
||||
{
|
||||
id: "3",
|
||||
title: "Notion vs Obsidian vs Roam",
|
||||
description: "Knowledge management tools for productivity",
|
||||
items: ["Notion", "Obsidian", "Roam Research"],
|
||||
tags: ["Productivity", "Tools"],
|
||||
author: "Mike Peters",
|
||||
overallScore: 7.5,
|
||||
views: 892,
|
||||
},
|
||||
{
|
||||
id: "4",
|
||||
title: "AWS vs GCP vs Azure",
|
||||
description: "Cloud platform comparison for enterprise infrastructure",
|
||||
items: ["AWS", "Google Cloud", "Microsoft Azure"],
|
||||
tags: ["Tech", "Cloud"],
|
||||
author: "Emma Wilson",
|
||||
overallScore: 9.0,
|
||||
views: 2156,
|
||||
},
|
||||
{
|
||||
id: "5",
|
||||
title: "iPhone 15 Pro vs Samsung S24 Ultra",
|
||||
description: "Flagship smartphone comparison with camera and performance benchmarks",
|
||||
items: ["iPhone 15 Pro", "Samsung S24 Ultra"],
|
||||
tags: ["Products", "Mobile"],
|
||||
author: "James Lee",
|
||||
overallScore: 8.2,
|
||||
views: 3421,
|
||||
},
|
||||
{
|
||||
id: "6",
|
||||
title: "Python vs Rust vs Go",
|
||||
description: "Systems programming languages compared for performance and productivity",
|
||||
items: ["Python", "Rust", "Go"],
|
||||
tags: ["Tech", "Programming"],
|
||||
author: "Anna Kim",
|
||||
overallScore: 8.4,
|
||||
views: 1873,
|
||||
},
|
||||
]
|
||||
|
||||
const categories = ["All", "Tech", "Products", "AI", "Cloud", "Productivity"]
|
||||
|
||||
export default function ExplorePage() {
|
||||
const [searchQuery, setSearchQuery] = useState("")
|
||||
const [selectedCategory, setSelectedCategory] = useState("All")
|
||||
const [loading, setLoading] = useState(false)
|
||||
|
||||
const filteredComparisons = allComparisons.filter((comparison) => {
|
||||
const matchesSearch =
|
||||
searchQuery === "" ||
|
||||
comparison.title.toLowerCase().includes(searchQuery.toLowerCase()) ||
|
||||
comparison.items.some((item) =>
|
||||
item.toLowerCase().includes(searchQuery.toLowerCase())
|
||||
)
|
||||
const matchesCategory =
|
||||
selectedCategory === "All" ||
|
||||
comparison.tags.some((tag) => tag.toLowerCase() === selectedCategory.toLowerCase())
|
||||
return matchesSearch && matchesCategory
|
||||
})
|
||||
|
||||
return (
|
||||
<div className="max-w-6xl mx-auto p-4 sm:p-6 space-y-6">
|
||||
<div className="space-y-4">
|
||||
<h1 className="text-2xl font-bold">Explore Comparisons</h1>
|
||||
|
||||
<div className="flex flex-col sm:flex-row gap-4">
|
||||
<div className="relative flex-1">
|
||||
<Search className="absolute left-3 top-1/2 -translate-y-1/2 size-4 text-muted-foreground" />
|
||||
<Input
|
||||
type="search"
|
||||
placeholder="Search comparisons..."
|
||||
value={searchQuery}
|
||||
onChange={(e) => setSearchQuery(e.target.value)}
|
||||
className="pl-9"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex flex-wrap gap-2">
|
||||
{categories.map((category) => (
|
||||
<Button
|
||||
key={category}
|
||||
variant={selectedCategory === category ? "default" : "outline"}
|
||||
size="sm"
|
||||
onClick={() => setSelectedCategory(category)}
|
||||
className="rounded-full"
|
||||
>
|
||||
{category}
|
||||
</Button>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{loading ? (
|
||||
<div className="flex items-center justify-center py-12">
|
||||
<Loader2 className="size-8 animate-spin text-primary" />
|
||||
</div>
|
||||
) : filteredComparisons.length > 0 ? (
|
||||
<div className="grid gap-6 sm:grid-cols-2 lg:grid-cols-3">
|
||||
{filteredComparisons.map((comparison) => (
|
||||
<Link key={comparison.id} href={`/compare/${comparison.id}`}>
|
||||
<Card className="h-full transition-all hover:border-primary hover:shadow-md">
|
||||
<CardHeader className="pb-3">
|
||||
<div className="flex items-start justify-between gap-2">
|
||||
<CardTitle className="text-base line-clamp-1 flex-1">
|
||||
{comparison.title}
|
||||
</CardTitle>
|
||||
</div>
|
||||
<CardDescription className="text-sm line-clamp-2">
|
||||
{comparison.description}
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-3">
|
||||
<div className="flex flex-wrap gap-1.5">
|
||||
{comparison.tags.map((tag) => (
|
||||
<Badge key={tag} variant="secondary" className="text-xs">
|
||||
{tag}
|
||||
</Badge>
|
||||
))}
|
||||
</div>
|
||||
|
||||
<div className="flex items-center gap-2 text-sm text-muted-foreground">
|
||||
<Avatar className="size-6">
|
||||
<AvatarFallback className="text-[10px]">
|
||||
{comparison.author.split(" ").map((n) => n[0]).join("")}
|
||||
</AvatarFallback>
|
||||
</Avatar>
|
||||
<span className="text-xs">{comparison.author}</span>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center justify-between pt-2 border-t">
|
||||
<span className="text-sm text-muted-foreground">
|
||||
{comparison.items.join(" vs ")}
|
||||
</span>
|
||||
<div className="flex items-center gap-3 text-sm">
|
||||
<span className="flex items-center gap-1 text-muted-foreground">
|
||||
<Eye className="size-3.5" />
|
||||
{comparison.views.toLocaleString()}
|
||||
</span>
|
||||
<span className="font-semibold text-foreground bg-primary/10 px-2 py-0.5 rounded">
|
||||
{comparison.overallScore}/10
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</Link>
|
||||
))}
|
||||
</div>
|
||||
) : (
|
||||
<Card className="p-8 text-center">
|
||||
<div className="flex flex-col items-center gap-4">
|
||||
<div className="size-12 rounded-full bg-muted flex items-center justify-center">
|
||||
<Search className="size-6 text-muted-foreground" />
|
||||
</div>
|
||||
<div>
|
||||
<p className="font-medium">No comparisons found</p>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
Try adjusting your search or filters
|
||||
</p>
|
||||
</div>
|
||||
<Button
|
||||
variant="outline"
|
||||
onClick={() => {
|
||||
setSearchQuery("")
|
||||
setSelectedCategory("All")
|
||||
}}
|
||||
>
|
||||
Clear Filters
|
||||
</Button>
|
||||
</div>
|
||||
</Card>
|
||||
)}
|
||||
|
||||
<div className="flex justify-center">
|
||||
<Button variant="outline" className="gap-2">
|
||||
Load More
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -1,174 +1,50 @@
|
||||
"use client"
|
||||
|
||||
import Link from "next/link"
|
||||
import { usePathname } from "next/navigation"
|
||||
import { Sparkles, Home, BarChart3, Compass, User, Menu, X, Search } from "lucide-react"
|
||||
import { useState } from "react"
|
||||
import { Button } from "@/components/ui/button"
|
||||
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar"
|
||||
import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuLabel, DropdownMenuSeparator, DropdownMenuTrigger } from "@/components/ui/dropdown-menu"
|
||||
import { Input } from "@/components/ui/input"
|
||||
import { cn } from "@/lib/utils"
|
||||
|
||||
const navItems = [
|
||||
{ href: "/", label: "Home", icon: Home },
|
||||
{ href: "/compare", label: "Compare", icon: BarChart3 },
|
||||
{ href: "/explore", label: "Explore", icon: Compass },
|
||||
{ href: "/profile", label: "Profile", icon: User },
|
||||
]
|
||||
|
||||
function NavSidebar({ className }: { className?: string }) {
|
||||
const pathname = usePathname()
|
||||
|
||||
return (
|
||||
<nav className={cn("flex flex-col gap-1", className)}>
|
||||
{navItems.map((item) => {
|
||||
const isActive = pathname === item.href || (item.href !== "/" && pathname.startsWith(item.href))
|
||||
return (
|
||||
<Link key={item.href} href={item.href}>
|
||||
<Button
|
||||
variant={isActive ? "secondary" : "ghost"}
|
||||
className={cn(
|
||||
"w-full justify-start gap-2",
|
||||
isActive && "bg-muted text-primary font-medium"
|
||||
)}
|
||||
>
|
||||
<item.icon className="size-4" />
|
||||
{item.label}
|
||||
</Button>
|
||||
</Link>
|
||||
)
|
||||
})}
|
||||
</nav>
|
||||
)
|
||||
}
|
||||
|
||||
function MobileNav() {
|
||||
const pathname = usePathname()
|
||||
|
||||
return (
|
||||
<nav className="fixed bottom-0 left-0 right-0 z-50 border-t bg-background/95 backdrop-blur supports-[backdrop-filter]:bg-background/60 md:hidden">
|
||||
<div className="flex items-center justify-around h-14">
|
||||
{navItems.map((item) => {
|
||||
const isActive = pathname === item.href || (item.href !== "/" && pathname.startsWith(item.href))
|
||||
return (
|
||||
<Link key={item.href} href={item.href} className="flex flex-col items-center gap-1 py-2 px-3">
|
||||
<item.icon className={cn("size-5", isActive ? "text-primary" : "text-muted-foreground")} />
|
||||
<span className={cn("text-xs", isActive ? "text-primary font-medium" : "text-muted-foreground")}>
|
||||
{item.label}
|
||||
</span>
|
||||
</Link>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
</nav>
|
||||
)
|
||||
}
|
||||
import { Sparkles } from "lucide-react"
|
||||
|
||||
export default function MainLayout({
|
||||
children,
|
||||
}: {
|
||||
children: React.ReactNode
|
||||
}) {
|
||||
const [mobileMenuOpen, setMobileMenuOpen] = useState(false)
|
||||
const [searchQuery, setSearchQuery] = useState("")
|
||||
|
||||
return (
|
||||
<div className="min-h-screen flex flex-col">
|
||||
<header className="sticky top-0 z-50 w-full border-b bg-background/95 backdrop-blur supports-[backdrop-filter]:bg-background/60">
|
||||
<div className="container flex h-14 items-center px-4 mx-auto gap-4">
|
||||
<Link href="/" className="flex items-center gap-2 font-semibold shrink-0">
|
||||
<div className="container flex h-14 items-center px-4 mx-auto">
|
||||
<Link href="/" className="flex items-center gap-2 font-semibold mr-8">
|
||||
<Sparkles className="size-5 text-primary" />
|
||||
<span className="text-lg hidden sm:inline">ComparAIson</span>
|
||||
<span className="text-lg">ComparAIson</span>
|
||||
</Link>
|
||||
|
||||
<div className="flex-1 max-w-md mx-auto hidden md:block">
|
||||
<div className="flex-1 max-w-md">
|
||||
<div className="relative">
|
||||
<Search className="absolute left-3 top-1/2 -translate-y-1/2 size-4 text-muted-foreground" />
|
||||
<Input
|
||||
<input
|
||||
type="search"
|
||||
placeholder="Search comparisons..."
|
||||
value={searchQuery}
|
||||
onChange={(e) => setSearchQuery(e.target.value)}
|
||||
className="pl-9 h-9"
|
||||
className="w-full h-8 rounded-lg border border-input bg-muted/50 px-3 text-sm ring-offset-background placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center gap-2 ml-auto">
|
||||
<Link href="/compare" className="hidden sm:block">
|
||||
<Button size="sm" className="gap-2">
|
||||
<Sparkles className="size-3.5" />
|
||||
<div className="flex items-center gap-3 ml-auto">
|
||||
<Link href="/compare">
|
||||
<button className="h-8 px-3 rounded-lg text-sm font-medium bg-primary text-primary-foreground hover:bg-primary/80 transition-colors">
|
||||
New Comparison
|
||||
</Button>
|
||||
</button>
|
||||
</Link>
|
||||
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger className="rounded-full">
|
||||
<Avatar className="size-8">
|
||||
<AvatarImage src="/placeholder-avatar.png" />
|
||||
<AvatarFallback className="bg-primary/10 text-primary font-medium">U</AvatarFallback>
|
||||
</Avatar>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="end" className="w-48">
|
||||
<DropdownMenuLabel>My Account</DropdownMenuLabel>
|
||||
<DropdownMenuSeparator />
|
||||
<DropdownMenuItem>
|
||||
<Link href="/profile" className="w-full">Profile</Link>
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuItem>
|
||||
<Link href="/compare" className="w-full">New Comparison</Link>
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuSeparator />
|
||||
<DropdownMenuItem>
|
||||
<Link href="/sign-in" className="w-full">Sign Out</Link>
|
||||
</DropdownMenuItem>
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
className="md:hidden"
|
||||
onClick={() => setMobileMenuOpen(!mobileMenuOpen)}
|
||||
>
|
||||
{mobileMenuOpen ? <X className="size-5" /> : <Menu className="size-5" />}
|
||||
</Button>
|
||||
<div className="size-8 rounded-full bg-muted flex items-center justify-center text-xs font-medium text-muted-foreground">
|
||||
U
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{mobileMenuOpen && (
|
||||
<div className="border-t md:hidden bg-background p-4">
|
||||
<div className="relative mb-4">
|
||||
<Search className="absolute left-3 top-1/2 -translate-y-1/2 size-4 text-muted-foreground" />
|
||||
<Input
|
||||
type="search"
|
||||
placeholder="Search comparisons..."
|
||||
value={searchQuery}
|
||||
onChange={(e) => setSearchQuery(e.target.value)}
|
||||
className="pl-9"
|
||||
/>
|
||||
</div>
|
||||
<NavSidebar />
|
||||
</div>
|
||||
)}
|
||||
</header>
|
||||
|
||||
<div className="flex flex-1">
|
||||
<aside className="hidden md:block w-52 border-r bg-muted/20 p-4 shrink-0">
|
||||
<NavSidebar />
|
||||
</aside>
|
||||
<main className="flex-1">{children}</main>
|
||||
|
||||
<main className="flex-1 pb-16 md:pb-0">{children}</main>
|
||||
</div>
|
||||
|
||||
<MobileNav />
|
||||
|
||||
<footer className="border-t py-4 hidden md:block">
|
||||
<footer className="border-t py-4">
|
||||
<div className="container mx-auto px-4 text-center text-xs text-muted-foreground">
|
||||
ComparAIson — AI-powered deep research comparisons
|
||||
</div>
|
||||
</footer>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,157 +0,0 @@
|
||||
"use client"
|
||||
|
||||
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar"
|
||||
import { Button } from "@/components/ui/button"
|
||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"
|
||||
import { Badge } from "@/components/ui/badge"
|
||||
import { BarChart3, Eye, Calendar, Plus, ArrowRight } from "lucide-react"
|
||||
import Link from "next/link"
|
||||
|
||||
const mockUser = {
|
||||
name: "Alex Johnson",
|
||||
email: "alex@example.com",
|
||||
avatar: "/placeholder-avatar.png",
|
||||
}
|
||||
|
||||
const mockComparisons = [
|
||||
{
|
||||
id: "1",
|
||||
title: "React vs Vue vs Svelte",
|
||||
items: ["React", "Vue", "Svelte"],
|
||||
tags: ["Tech", "JavaScript"],
|
||||
overallScore: 8.5,
|
||||
views: 1247,
|
||||
createdAt: "2024-01-15",
|
||||
},
|
||||
{
|
||||
id: "2",
|
||||
title: "GPT-4 vs Claude vs Gemini",
|
||||
items: ["GPT-4", "Claude 3", "Gemini Pro"],
|
||||
tags: ["AI", "Products"],
|
||||
overallScore: 8.8,
|
||||
views: 3891,
|
||||
createdAt: "2024-01-10",
|
||||
},
|
||||
{
|
||||
id: "3",
|
||||
title: "Notion vs Obsidian vs Roam",
|
||||
items: ["Notion", "Obsidian", "Roam Research"],
|
||||
tags: ["Productivity"],
|
||||
overallScore: 7.5,
|
||||
views: 892,
|
||||
createdAt: "2024-01-05",
|
||||
},
|
||||
]
|
||||
|
||||
const stats = [
|
||||
{ label: "Total Comparisons", value: 12, icon: BarChart3 },
|
||||
{ label: "Total Views", value: "8.2K", icon: Eye },
|
||||
]
|
||||
|
||||
export default function ProfilePage() {
|
||||
return (
|
||||
<div className="max-w-4xl mx-auto p-4 sm:p-6 space-y-8">
|
||||
<div className="flex items-center gap-6">
|
||||
<Avatar className="size-20">
|
||||
<AvatarImage src={mockUser.avatar} />
|
||||
<AvatarFallback className="text-2xl bg-primary/10 text-primary font-semibold">
|
||||
{mockUser.name.split(" ").map((n) => n[0]).join("")}
|
||||
</AvatarFallback>
|
||||
</Avatar>
|
||||
<div className="space-y-1.5">
|
||||
<h1 className="text-2xl font-bold">{mockUser.name}</h1>
|
||||
<p className="text-muted-foreground">{mockUser.email}</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="grid gap-4 sm:grid-cols-2">
|
||||
{stats.map((stat) => (
|
||||
<Card key={stat.label}>
|
||||
<CardContent className="flex items-center gap-4 p-4">
|
||||
<div className="size-10 rounded-lg bg-primary/10 flex items-center justify-center">
|
||||
<stat.icon className="size-5 text-primary" />
|
||||
</div>
|
||||
<div>
|
||||
<p className="text-2xl font-bold">{stat.value}</p>
|
||||
<p className="text-sm text-muted-foreground">{stat.label}</p>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
))}
|
||||
</div>
|
||||
|
||||
<div className="space-y-4">
|
||||
<div className="flex items-center justify-between">
|
||||
<h2 className="text-xl font-semibold">My Comparisons</h2>
|
||||
<Link href="/compare">
|
||||
<Button size="sm" className="gap-2">
|
||||
<Plus className="size-4" />
|
||||
New Comparison
|
||||
</Button>
|
||||
</Link>
|
||||
</div>
|
||||
|
||||
{mockComparisons.length > 0 ? (
|
||||
<div className="grid gap-4 sm:grid-cols-2">
|
||||
{mockComparisons.map((comparison) => (
|
||||
<Link key={comparison.id} href={`/compare/${comparison.id}`}>
|
||||
<Card className="h-full transition-all hover:border-primary hover:shadow-md">
|
||||
<CardHeader className="pb-3">
|
||||
<CardTitle className="text-base line-clamp-1">{comparison.title}</CardTitle>
|
||||
<CardDescription className="flex items-center gap-2 text-xs">
|
||||
<Calendar className="size-3.5" />
|
||||
{comparison.createdAt}
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-3">
|
||||
<div className="flex flex-wrap gap-1.5">
|
||||
{comparison.tags.map((tag) => (
|
||||
<Badge key={tag} variant="secondary" className="text-xs">
|
||||
{tag}
|
||||
</Badge>
|
||||
))}
|
||||
</div>
|
||||
<div className="flex items-center justify-between">
|
||||
<span className="text-sm text-muted-foreground">
|
||||
{comparison.items.join(" vs ")}
|
||||
</span>
|
||||
<div className="flex items-center gap-3 text-sm text-muted-foreground">
|
||||
<span className="flex items-center gap-1">
|
||||
<Eye className="size-3.5" />
|
||||
{comparison.views.toLocaleString()}
|
||||
</span>
|
||||
<span className="font-semibold text-foreground">
|
||||
{comparison.overallScore}/10
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</Link>
|
||||
))}
|
||||
</div>
|
||||
) : (
|
||||
<Card className="p-8 text-center">
|
||||
<div className="flex flex-col items-center gap-4">
|
||||
<div className="size-12 rounded-full bg-muted flex items-center justify-center">
|
||||
<BarChart3 className="size-6 text-muted-foreground" />
|
||||
</div>
|
||||
<div>
|
||||
<p className="font-medium">No comparisons yet</p>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
Create your first comparison to get started
|
||||
</p>
|
||||
</div>
|
||||
<Link href="/compare">
|
||||
<Button className="gap-2">
|
||||
<Plus className="size-4" />
|
||||
Create Comparison
|
||||
</Button>
|
||||
</Link>
|
||||
</div>
|
||||
</Card>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -18,6 +18,10 @@ function slugify(text: string): string {
|
||||
.slice(0, 200);
|
||||
}
|
||||
|
||||
// TODO: Implement rate limiting per IP/user
|
||||
// Example: Use Upstash Ratelimit or a simple in-memory counter
|
||||
// const ratelimit = new Ratelimit({ redis, limiter: slidingWindow(5, "1m") })
|
||||
|
||||
export async function POST(request: Request) {
|
||||
const body: { query?: string; items?: string[]; dimensions?: string[] } =
|
||||
await request.json();
|
||||
@@ -25,7 +29,21 @@ export async function POST(request: Request) {
|
||||
|
||||
if (!items || items.length < 2) {
|
||||
return Response.json(
|
||||
{ error: "At least 2 items are required" },
|
||||
{ error: "At least 2 items are required for comparison" },
|
||||
{ status: 400 }
|
||||
);
|
||||
}
|
||||
|
||||
if (items.length > 10) {
|
||||
return Response.json(
|
||||
{ error: "Maximum 10 items allowed per comparison" },
|
||||
{ status: 400 }
|
||||
);
|
||||
}
|
||||
|
||||
if (items.some((item) => item.trim().length === 0)) {
|
||||
return Response.json(
|
||||
{ error: "Item names cannot be empty" },
|
||||
{ status: 400 }
|
||||
);
|
||||
}
|
||||
@@ -70,6 +88,20 @@ export async function POST(request: Request) {
|
||||
);
|
||||
}
|
||||
|
||||
if (progress.stage === "searching") {
|
||||
controller.enqueue(
|
||||
encoder.encode(
|
||||
serializeSSE("progress", {
|
||||
status: "researching",
|
||||
message: `Searching the web for ${progress.item}... (${progress.results} results found)`,
|
||||
itemsCompleted,
|
||||
totalItems: items.length,
|
||||
currentStep: `Searching ${progress.item}`,
|
||||
})
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
if (progress.stage === "researching") {
|
||||
itemsCompleted++;
|
||||
controller.enqueue(
|
||||
@@ -102,7 +134,17 @@ export async function POST(request: Request) {
|
||||
if (progress.stage === "complete") {
|
||||
const result = progress.result;
|
||||
|
||||
const comparisonData: Omit<ComparisonData, "id" | "userId" | "slug" | "tags" | "isPublic" | "viewCount" | "createdAt" | "updatedAt"> = {
|
||||
const comparisonData: Omit<
|
||||
ComparisonData,
|
||||
| "id"
|
||||
| "userId"
|
||||
| "slug"
|
||||
| "tags"
|
||||
| "isPublic"
|
||||
| "viewCount"
|
||||
| "createdAt"
|
||||
| "updatedAt"
|
||||
> = {
|
||||
title,
|
||||
query: query || "",
|
||||
status: "completed",
|
||||
@@ -177,7 +219,7 @@ export async function POST(request: Request) {
|
||||
encoder.encode(
|
||||
serializeSSE("progress", {
|
||||
status: "failed",
|
||||
message: progress.error,
|
||||
message: `Comparison failed: ${progress.error}`,
|
||||
itemsCompleted,
|
||||
totalItems: items.length,
|
||||
currentStep: "Failed",
|
||||
@@ -192,11 +234,16 @@ export async function POST(request: Request) {
|
||||
.set({ status: "failed", updatedAt: new Date() })
|
||||
.where(eq(comparisons.id, id));
|
||||
|
||||
const message =
|
||||
error instanceof Error
|
||||
? error.message
|
||||
: "An unexpected error occurred during research";
|
||||
|
||||
controller.enqueue(
|
||||
encoder.encode(
|
||||
serializeSSE("progress", {
|
||||
status: "failed",
|
||||
message: error instanceof Error ? error.message : "Unknown error",
|
||||
message: `Comparison failed: ${message}`,
|
||||
itemsCompleted,
|
||||
totalItems: items.length,
|
||||
currentStep: "Failed",
|
||||
|
||||
237
src/app/page.tsx
237
src/app/page.tsx
@@ -1,186 +1,65 @@
|
||||
import Link from "next/link"
|
||||
import { Sparkles, BarChart3, Search, Share2, ArrowRight, CheckCircle2 } from "lucide-react"
|
||||
import { Button } from "@/components/ui/button"
|
||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"
|
||||
import Image from "next/image";
|
||||
|
||||
const exampleComparisons = [
|
||||
{
|
||||
title: "React vs Vue vs Svelte",
|
||||
description: "Frontend framework comparison for modern web development",
|
||||
tags: ["Tech", "JavaScript"],
|
||||
items: ["React", "Vue", "Svelte"],
|
||||
scores: [8.5, 7.8, 8.2],
|
||||
},
|
||||
{
|
||||
title: "GPT-4 vs Claude vs Gemini",
|
||||
description: "Comparing top AI language models for reasoning tasks",
|
||||
tags: ["AI", "Products"],
|
||||
items: ["GPT-4", "Claude 3", "Gemini Pro"],
|
||||
scores: [8.8, 9.0, 8.4],
|
||||
},
|
||||
{
|
||||
title: "Notion vs Obsidian vs Roam",
|
||||
description: "Knowledge management tools for productivity",
|
||||
tags: ["Products", "Productivity"],
|
||||
items: ["Notion", "Obsidian", "Roam Research"],
|
||||
scores: [7.5, 8.3, 7.2],
|
||||
},
|
||||
{
|
||||
title: "AWS vs GCP vs Azure",
|
||||
description: "Cloud platform comparison for enterprise infrastructure",
|
||||
tags: ["Tech", "Cloud"],
|
||||
items: ["AWS", "Google Cloud", "Microsoft Azure"],
|
||||
scores: [9.0, 8.2, 8.5],
|
||||
},
|
||||
]
|
||||
|
||||
const features = [
|
||||
{
|
||||
icon: BarChart3,
|
||||
title: "Rich Visualizations",
|
||||
description: "Interactive radar charts, bar graphs, and comparison tables to understand your results at a glance.",
|
||||
},
|
||||
{
|
||||
icon: Search,
|
||||
title: "Deep Research",
|
||||
description: "AI-powered research that gathers comprehensive data from multiple sources for each item.",
|
||||
},
|
||||
{
|
||||
icon: Share2,
|
||||
title: "Save & Share",
|
||||
description: "Keep your comparisons private or share them with the world. Build a library of research.",
|
||||
},
|
||||
]
|
||||
|
||||
export default function HomePage() {
|
||||
export default function Home() {
|
||||
return (
|
||||
<div className="flex flex-col min-h-screen">
|
||||
<section className="flex-1 flex flex-col items-center justify-center py-20 px-4 bg-gradient-to-b from-background to-muted/30">
|
||||
<div className="max-w-3xl mx-auto text-center space-y-8">
|
||||
<div className="inline-flex items-center gap-2 px-4 py-2 rounded-full bg-primary/10 text-primary text-sm font-medium mb-4">
|
||||
<Sparkles className="size-4" />
|
||||
AI-Powered Research
|
||||
</div>
|
||||
|
||||
<h1 className="text-4xl sm:text-5xl lg:text-6xl font-bold tracking-tight leading-tight">
|
||||
Compare Anything with{" "}
|
||||
<span className="text-primary">AI-Powered</span> Deep Research
|
||||
<div className="flex flex-col flex-1 items-center justify-center bg-zinc-50 font-sans dark:bg-black">
|
||||
<main className="flex flex-1 w-full max-w-3xl flex-col items-center justify-between py-32 px-16 bg-white dark:bg-black sm:items-start">
|
||||
<Image
|
||||
className="dark:invert"
|
||||
src="/next.svg"
|
||||
alt="Next.js logo"
|
||||
width={100}
|
||||
height={20}
|
||||
priority
|
||||
/>
|
||||
<div className="flex flex-col items-center gap-6 text-center sm:items-start sm:text-left">
|
||||
<h1 className="max-w-xs text-3xl font-semibold leading-10 tracking-tight text-black dark:text-zinc-50">
|
||||
To get started, edit the page.tsx file.
|
||||
</h1>
|
||||
|
||||
<p className="text-lg sm:text-xl text-muted-foreground max-w-2xl mx-auto">
|
||||
Stop spending hours researching. Let AI do the work for you with comprehensive,
|
||||
multi-dimensional comparisons on anything you can think of.
|
||||
<p className="max-w-md text-lg leading-8 text-zinc-600 dark:text-zinc-400">
|
||||
Looking for a starting point or more instructions? Head over to{" "}
|
||||
<a
|
||||
href="https://vercel.com/templates?framework=next.js&utm_source=create-next-app&utm_medium=appdir-template-tw&utm_campaign=create-next-app"
|
||||
className="font-medium text-zinc-950 dark:text-zinc-50"
|
||||
>
|
||||
Templates
|
||||
</a>{" "}
|
||||
or the{" "}
|
||||
<a
|
||||
href="https://nextjs.org/learn?utm_source=create-next-app&utm_medium=appdir-template-tw&utm_campaign=create-next-app"
|
||||
className="font-medium text-zinc-950 dark:text-zinc-50"
|
||||
>
|
||||
Learning
|
||||
</a>{" "}
|
||||
center.
|
||||
</p>
|
||||
|
||||
<div className="flex flex-col sm:flex-row gap-4 justify-center pt-4">
|
||||
<Link href="/compare">
|
||||
<Button size="lg" className="gap-2 text-lg px-8">
|
||||
<Sparkles className="size-5" />
|
||||
Start Comparing
|
||||
<ArrowRight className="size-4" />
|
||||
</Button>
|
||||
</Link>
|
||||
<Link href="/explore">
|
||||
<Button size="lg" variant="outline" className="text-lg px-8">
|
||||
Explore Examples
|
||||
</Button>
|
||||
</Link>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section className="py-16 px-4 bg-muted/20">
|
||||
<div className="max-w-5xl mx-auto">
|
||||
<h2 className="text-2xl font-bold text-center mb-10">Example Comparisons</h2>
|
||||
|
||||
<div className="grid gap-6 sm:grid-cols-2 lg:grid-cols-4">
|
||||
{exampleComparisons.map((example) => (
|
||||
<Link key={example.title} href="/compare" className="group">
|
||||
<Card className="h-full transition-all group-hover:border-primary group-hover:shadow-md">
|
||||
<CardHeader className="pb-3">
|
||||
<div className="flex items-center gap-2 mb-2">
|
||||
<span className="text-lg font-bold">{example.title}</span>
|
||||
</div>
|
||||
<CardDescription className="text-sm line-clamp-2">
|
||||
{example.description}
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-3">
|
||||
<div className="flex flex-wrap gap-1.5">
|
||||
{example.tags.map((tag) => (
|
||||
<span
|
||||
key={tag}
|
||||
className="px-2 py-0.5 rounded-full bg-muted text-xs font-medium"
|
||||
>
|
||||
{tag}
|
||||
</span>
|
||||
))}
|
||||
</div>
|
||||
<div className="flex items-center justify-between text-sm">
|
||||
<span className="text-muted-foreground">
|
||||
{example.items.slice(0, 2).join(" vs ")}
|
||||
{example.items.length > 2 && ` vs ${example.items.length - 2}+`}
|
||||
</span>
|
||||
</div>
|
||||
<div className="flex items-center gap-1">
|
||||
{example.scores.slice(0, 3).map((score, i) => (
|
||||
<div
|
||||
key={i}
|
||||
className="h-1 flex-1 rounded-full bg-primary/30"
|
||||
style={{ width: `${score * 10}%` }}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</Link>
|
||||
))}
|
||||
</div>
|
||||
<div className="flex flex-col gap-4 text-base font-medium sm:flex-row">
|
||||
<a
|
||||
className="flex h-12 w-full items-center justify-center gap-2 rounded-full bg-foreground px-5 text-background transition-colors hover:bg-[#383838] dark:hover:bg-[#ccc] md:w-[158px]"
|
||||
href="https://vercel.com/new?utm_source=create-next-app&utm_medium=appdir-template-tw&utm_campaign=create-next-app"
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
>
|
||||
<Image
|
||||
className="dark:invert"
|
||||
src="/vercel.svg"
|
||||
alt="Vercel logomark"
|
||||
width={16}
|
||||
height={16}
|
||||
/>
|
||||
Deploy Now
|
||||
</a>
|
||||
<a
|
||||
className="flex h-12 w-full items-center justify-center rounded-full border border-solid border-black/[.08] px-5 transition-colors hover:border-transparent hover:bg-black/[.04] dark:border-white/[.145] dark:hover:bg-[#1a1a1a] md:w-[158px]"
|
||||
href="https://nextjs.org/docs?utm_source=create-next-app&utm_medium=appdir-template-tw&utm_campaign=create-next-app"
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
>
|
||||
Documentation
|
||||
</a>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section className="py-20 px-4">
|
||||
<div className="max-w-4xl mx-auto">
|
||||
<h2 className="text-2xl font-bold text-center mb-12">Why ComparAIson?</h2>
|
||||
|
||||
<div className="grid gap-8 sm:grid-cols-3">
|
||||
{features.map((feature) => (
|
||||
<div key={feature.title} className="flex flex-col items-center text-center space-y-3">
|
||||
<div className="size-12 rounded-xl bg-primary/10 flex items-center justify-center">
|
||||
<feature.icon className="size-6 text-primary" />
|
||||
</div>
|
||||
<h3 className="font-semibold text-lg">{feature.title}</h3>
|
||||
<p className="text-muted-foreground text-sm">{feature.description}</p>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section className="py-16 px-4 bg-primary text-primary-foreground">
|
||||
<div className="max-w-2xl mx-auto text-center space-y-6">
|
||||
<h2 className="text-2xl sm:text-3xl font-bold">Ready to compare?</h2>
|
||||
<p className="text-primary-foreground/80">
|
||||
Start your first comparison in seconds. It's free to get started.
|
||||
</p>
|
||||
<Link href="/compare">
|
||||
<Button size="lg" variant="secondary" className="gap-2 text-lg px-8">
|
||||
<Sparkles className="size-5" />
|
||||
Start Comparing
|
||||
</Button>
|
||||
</Link>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<footer className="border-t py-8 px-4">
|
||||
<div className="max-w-4xl mx-auto flex flex-col sm:flex-row items-center justify-between gap-4 text-sm text-muted-foreground">
|
||||
<div className="flex items-center gap-2">
|
||||
<Sparkles className="size-4 text-primary" />
|
||||
<span className="font-semibold">ComparAIson</span>
|
||||
</div>
|
||||
<p>AI-powered deep research comparisons</p>
|
||||
</div>
|
||||
</footer>
|
||||
</main>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
@@ -3,7 +3,9 @@ import type {
|
||||
ComparisonResult,
|
||||
ResearchProgress,
|
||||
} from "./types";
|
||||
import { generateComparison } from "./providers/openai";
|
||||
import { searchItem, type SearchResult } from "./providers/tavily";
|
||||
import { generateComparisonWithResearch } from "./providers/openai";
|
||||
import { getActiveProvider } from "./providers";
|
||||
|
||||
export type {
|
||||
ComparisonRequest,
|
||||
@@ -24,21 +26,44 @@ export async function* runResearch(
|
||||
return;
|
||||
}
|
||||
|
||||
for (let i = 0; i < request.items.length; i++) {
|
||||
yield {
|
||||
stage: "researching",
|
||||
item: request.items[i],
|
||||
progress: Math.round(((i + 0.5) / request.items.length) * 80),
|
||||
};
|
||||
const provider = getActiveProvider();
|
||||
const searchResults: Record<string, SearchResult[]> = {};
|
||||
|
||||
if (provider.hasSearch) {
|
||||
for (let i = 0; i < request.items.length; i++) {
|
||||
const item = request.items[i];
|
||||
const results = await searchItem(item, request.query);
|
||||
searchResults[item] = results;
|
||||
|
||||
yield {
|
||||
stage: "searching",
|
||||
item,
|
||||
results: results.length,
|
||||
};
|
||||
|
||||
yield {
|
||||
stage: "researching",
|
||||
item,
|
||||
progress: Math.round(((i + 1) / request.items.length) * 50),
|
||||
};
|
||||
}
|
||||
} else {
|
||||
for (let i = 0; i < request.items.length; i++) {
|
||||
yield {
|
||||
stage: "researching",
|
||||
item: request.items[i],
|
||||
progress: Math.round(((i + 0.5) / request.items.length) * 80),
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
yield {
|
||||
stage: "synthesizing",
|
||||
message: "Synthesizing research into structured comparison...",
|
||||
message: `Synthesizing research into structured comparison using ${provider.name}...`,
|
||||
};
|
||||
|
||||
try {
|
||||
const result = await generateComparison(request);
|
||||
const result = await provider.synthesize(request, searchResults);
|
||||
yield { stage: "complete", result };
|
||||
} catch (error) {
|
||||
yield {
|
||||
|
||||
63
src/lib/llm/providers/index.ts
Normal file
63
src/lib/llm/providers/index.ts
Normal file
@@ -0,0 +1,63 @@
|
||||
import type { ComparisonRequest, ComparisonResult } from "../types";
|
||||
import type { SearchResult } from "./tavily";
|
||||
import { generateComparisonWithResearch, generateComparison } from "./openai";
|
||||
import { synthesizeResearch } from "./perplexity";
|
||||
|
||||
export interface Provider {
|
||||
name: string;
|
||||
hasSearch: boolean;
|
||||
synthesize: (
|
||||
request: ComparisonRequest,
|
||||
searchResults: Record<string, SearchResult[]>
|
||||
) => Promise<ComparisonResult>;
|
||||
}
|
||||
|
||||
export function getActiveProvider(): Provider {
|
||||
const hasTavily = !!process.env.TAVILY_API_KEY;
|
||||
const hasPerplexity = !!process.env.PERPLEXITY_API_KEY;
|
||||
const hasOpenAI = !!process.env.OPENAI_API_KEY;
|
||||
|
||||
if (hasTavily && hasPerplexity) {
|
||||
console.log("[llm] Using provider: Tavily search + Perplexity synthesis");
|
||||
return {
|
||||
name: "Tavily + Perplexity",
|
||||
hasSearch: true,
|
||||
synthesize: synthesizeResearch,
|
||||
};
|
||||
}
|
||||
|
||||
if (hasTavily && hasOpenAI) {
|
||||
console.log("[llm] Using provider: Tavily search + OpenAI synthesis");
|
||||
return {
|
||||
name: "Tavily + OpenAI",
|
||||
hasSearch: true,
|
||||
synthesize: generateComparisonWithResearch,
|
||||
};
|
||||
}
|
||||
|
||||
if (hasOpenAI) {
|
||||
console.log("[llm] Using provider: OpenAI only (no web search)");
|
||||
return {
|
||||
name: "OpenAI",
|
||||
hasSearch: false,
|
||||
synthesize: async (request) => generateComparison(request),
|
||||
};
|
||||
}
|
||||
|
||||
console.warn(
|
||||
"[llm] No API keys configured. Research will fail at synthesis."
|
||||
);
|
||||
return {
|
||||
name: "None",
|
||||
hasSearch: false,
|
||||
synthesize: async () => {
|
||||
throw new Error(
|
||||
"No LLM provider configured. Set OPENAI_API_KEY, TAVILY_API_KEY, or PERPLEXITY_API_KEY."
|
||||
);
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
export { searchItem, type SearchResult } from "./tavily";
|
||||
export { generateComparison, generateComparisonWithResearch } from "./openai";
|
||||
export { synthesizeResearch } from "./perplexity";
|
||||
@@ -5,6 +5,7 @@ import type {
|
||||
DimensionResult,
|
||||
ItemResearch,
|
||||
} from "../types";
|
||||
import type { SearchResult } from "./tavily";
|
||||
|
||||
const client = new OpenAI({
|
||||
apiKey: process.env.OPENAI_API_KEY,
|
||||
@@ -140,3 +141,75 @@ Provide a comprehensive comparison with scores, pros/cons, and a recommendation.
|
||||
`Failed to generate comparison after ${MAX_RETRIES} attempts: ${lastError?.message}`
|
||||
);
|
||||
}
|
||||
|
||||
export async function generateComparisonWithResearch(
|
||||
request: ComparisonRequest,
|
||||
searchResults: Record<string, SearchResult[]>
|
||||
): Promise<ComparisonResult> {
|
||||
const allResults = Object.values(searchResults).flat();
|
||||
if (allResults.length === 0) {
|
||||
return generateComparison(request);
|
||||
}
|
||||
|
||||
let researchContext = "Web research data:\n\n";
|
||||
for (const [itemName, results] of Object.entries(searchResults)) {
|
||||
if (results.length === 0) continue;
|
||||
researchContext += `=== ${itemName} ===\n`;
|
||||
for (const r of results) {
|
||||
researchContext += `- ${r.title}: ${r.content}\n Source: ${r.url}\n`;
|
||||
}
|
||||
researchContext += "\n";
|
||||
}
|
||||
|
||||
const userPrompt = `Compare the following items: ${request.items.join(", ")}
|
||||
${request.query ? `Focus: ${request.query}` : ""}
|
||||
${request.dimensions?.length ? `Specific dimensions to include: ${request.dimensions.join(", ")}` : ""}
|
||||
|
||||
${researchContext}
|
||||
|
||||
Use the web research data above to provide factual, data-driven insights. Reference specific data points in your analysis. Provide a comprehensive comparison with scores, pros/cons, and a recommendation.`;
|
||||
|
||||
let lastError: Error | null = null;
|
||||
|
||||
for (let attempt = 1; attempt <= MAX_RETRIES; attempt++) {
|
||||
try {
|
||||
const response = await client.chat.completions.create({
|
||||
model: "gpt-4o-mini",
|
||||
messages: [
|
||||
{ role: "system", content: SYSTEM_PROMPT },
|
||||
{
|
||||
role: "system",
|
||||
content:
|
||||
"You have access to real web search results. Use them to ground your comparison in factual data. Cite specific findings from the research when scoring and analyzing items.",
|
||||
},
|
||||
{ role: "user", content: userPrompt },
|
||||
],
|
||||
response_format: { type: "json_object" },
|
||||
temperature: 0.3,
|
||||
});
|
||||
|
||||
const content = response.choices[0]?.message?.content;
|
||||
if (!content) {
|
||||
throw new Error("Empty response from OpenAI");
|
||||
}
|
||||
|
||||
const parsed: unknown = JSON.parse(content);
|
||||
|
||||
if (!validateComparisonResult(parsed)) {
|
||||
throw new Error("Invalid comparison result structure from OpenAI");
|
||||
}
|
||||
|
||||
return parsed;
|
||||
} catch (error) {
|
||||
lastError = error instanceof Error ? error : new Error(String(error));
|
||||
|
||||
if (attempt < MAX_RETRIES) {
|
||||
await sleep(RETRY_DELAY_MS * attempt);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
throw new Error(
|
||||
`Failed to generate comparison with research after ${MAX_RETRIES} attempts: ${lastError?.message}`
|
||||
);
|
||||
}
|
||||
|
||||
117
src/lib/llm/providers/perplexity.ts
Normal file
117
src/lib/llm/providers/perplexity.ts
Normal file
@@ -0,0 +1,117 @@
|
||||
import type { ComparisonRequest, ComparisonResult } from "../types";
|
||||
import type { SearchResult } from "./tavily";
|
||||
import { generateComparisonWithResearch } from "./openai";
|
||||
|
||||
const PERPLEXITY_API_URL = "https://api.perplexity.ai/chat/completions";
|
||||
|
||||
const SYSTEM_PROMPT = `You are a research synthesis engine. Given web search results for multiple items, produce a structured JSON comparison.
|
||||
|
||||
You MUST respond with valid JSON matching this exact structure:
|
||||
{
|
||||
"items": [
|
||||
{
|
||||
"name": "item name",
|
||||
"description": "brief overview",
|
||||
"overallScore": 7.5,
|
||||
"dimensions": {
|
||||
"Dimension Name": {
|
||||
"score": 8,
|
||||
"summary": "brief assessment",
|
||||
"details": "detailed analysis",
|
||||
"pros": ["pro 1"],
|
||||
"cons": ["con 1"]
|
||||
}
|
||||
},
|
||||
"pros": ["overall pro 1"],
|
||||
"cons": ["overall con 1"],
|
||||
"sources": [{ "title": "source", "url": "https://...", "snippet": "excerpt" }]
|
||||
}
|
||||
],
|
||||
"dimensions": ["Dimension 1", "Dimension 2"],
|
||||
"summary": "comparison summary",
|
||||
"recommendation": "clear recommendation"
|
||||
}`;
|
||||
|
||||
export async function synthesizeResearch(
|
||||
request: ComparisonRequest,
|
||||
searchResults: Record<string, SearchResult[]>
|
||||
): Promise<ComparisonResult> {
|
||||
const apiKey = process.env.PERPLEXITY_API_KEY;
|
||||
if (!apiKey) {
|
||||
return generateComparisonWithResearch(request, searchResults);
|
||||
}
|
||||
|
||||
const allResults = Object.values(searchResults).flat();
|
||||
if (allResults.length === 0) {
|
||||
return generateComparisonWithResearch(request, searchResults);
|
||||
}
|
||||
|
||||
let researchContext = "Search results for each item:\n\n";
|
||||
for (const [itemName, results] of Object.entries(searchResults)) {
|
||||
if (results.length === 0) continue;
|
||||
researchContext += `=== ${itemName} ===\n`;
|
||||
for (const r of results) {
|
||||
researchContext += `- ${r.title}: ${r.content}\n Source: ${r.url}\n`;
|
||||
}
|
||||
researchContext += "\n";
|
||||
}
|
||||
|
||||
const userPrompt = `Compare: ${request.items.join(", ")}
|
||||
${request.query ? `Focus: ${request.query}` : ""}
|
||||
${request.dimensions?.length ? `Dimensions: ${request.dimensions.join(", ")}` : ""}
|
||||
|
||||
${researchContext}`;
|
||||
|
||||
try {
|
||||
const response = await fetch(PERPLEXITY_API_URL, {
|
||||
method: "POST",
|
||||
headers: {
|
||||
Authorization: `Bearer ${apiKey}`,
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
body: JSON.stringify({
|
||||
model: "sonar",
|
||||
messages: [
|
||||
{ role: "system", content: SYSTEM_PROMPT },
|
||||
{ role: "user", content: userPrompt },
|
||||
],
|
||||
temperature: 0.3,
|
||||
}),
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
console.error(
|
||||
`Perplexity API error: ${response.status} ${response.statusText}`
|
||||
);
|
||||
return generateComparisonWithResearch(request, searchResults);
|
||||
}
|
||||
|
||||
const data = await response.json();
|
||||
const content = data.choices?.[0]?.message?.content;
|
||||
|
||||
if (!content) {
|
||||
console.error("Empty response from Perplexity");
|
||||
return generateComparisonWithResearch(request, searchResults);
|
||||
}
|
||||
|
||||
const parsed: unknown = JSON.parse(content);
|
||||
|
||||
if (
|
||||
!parsed ||
|
||||
typeof parsed !== "object" ||
|
||||
!Array.isArray((parsed as Record<string, unknown>).items) ||
|
||||
!Array.isArray((parsed as Record<string, unknown>).dimensions)
|
||||
) {
|
||||
console.error("Invalid structure from Perplexity, falling back to OpenAI");
|
||||
return generateComparisonWithResearch(request, searchResults);
|
||||
}
|
||||
|
||||
return parsed as ComparisonResult;
|
||||
} catch (error) {
|
||||
console.error(
|
||||
"Perplexity synthesis failed, falling back to OpenAI:",
|
||||
error instanceof Error ? error.message : error
|
||||
);
|
||||
return generateComparisonWithResearch(request, searchResults);
|
||||
}
|
||||
}
|
||||
69
src/lib/llm/providers/tavily.ts
Normal file
69
src/lib/llm/providers/tavily.ts
Normal file
@@ -0,0 +1,69 @@
|
||||
export interface SearchResult {
|
||||
title: string;
|
||||
url: string;
|
||||
content: string;
|
||||
score: number;
|
||||
}
|
||||
|
||||
const TAVILY_API_URL = "https://api.tavily.com/search";
|
||||
|
||||
export async function searchItem(
|
||||
itemName: string,
|
||||
context: string
|
||||
): Promise<SearchResult[]> {
|
||||
const apiKey = process.env.TAVILY_API_KEY;
|
||||
if (!apiKey) {
|
||||
return [];
|
||||
}
|
||||
|
||||
try {
|
||||
const query = `${itemName} ${context}`.trim();
|
||||
|
||||
const response = await fetch(TAVILY_API_URL, {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
body: JSON.stringify({
|
||||
api_key: apiKey,
|
||||
query,
|
||||
max_results: 5,
|
||||
include_answer: false,
|
||||
search_depth: "advanced",
|
||||
}),
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
console.error(
|
||||
`Tavily API error: ${response.status} ${response.statusText}`
|
||||
);
|
||||
return [];
|
||||
}
|
||||
|
||||
const data = await response.json();
|
||||
|
||||
if (!data.results || !Array.isArray(data.results)) {
|
||||
return [];
|
||||
}
|
||||
|
||||
return data.results.map(
|
||||
(result: {
|
||||
title?: string;
|
||||
url?: string;
|
||||
content?: string;
|
||||
score?: number;
|
||||
}) => ({
|
||||
title: result.title ?? "",
|
||||
url: result.url ?? "",
|
||||
content: result.content ?? "",
|
||||
score: result.score ?? 0,
|
||||
})
|
||||
);
|
||||
} catch (error) {
|
||||
console.error(
|
||||
`Tavily search failed for "${itemName}":`,
|
||||
error instanceof Error ? error.message : error
|
||||
);
|
||||
return [];
|
||||
}
|
||||
}
|
||||
@@ -31,6 +31,7 @@ export interface ComparisonResult {
|
||||
|
||||
export type ResearchProgress =
|
||||
| { stage: "parsing"; message: string }
|
||||
| { stage: "searching"; item: string; results: number }
|
||||
| { stage: "researching"; item: string; progress: number }
|
||||
| { stage: "synthesizing"; message: string }
|
||||
| { stage: "complete"; result: ComparisonResult }
|
||||
|
||||
Reference in New Issue
Block a user