Add KI-Suche via OpenRouter GPT-4o-mini

- /api/ai-search: sends user description to GPT-4o-mini, returns 2-4
  structured query/region pairs as JSON
- AiSearchModal: textarea, generates previews, user selects queries to run
- KI-Suche button in hero section of /suche page

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
Timo Uttenweiler
2026-04-08 14:00:54 +02:00
parent a39a98b6dc
commit 0f5d18dac7
3 changed files with 377 additions and 6 deletions

View File

@@ -0,0 +1,90 @@
import { NextRequest, NextResponse } from "next/server";
const SYSTEM_PROMPT = `Du bist ein Experte für B2B-Lead-Generierung im deutschsprachigen Raum.
Deine Aufgabe: Wandle die Beschreibung des Nutzers in 24 konkrete Google-Suchanfragen um, die lokale Unternehmen und Dienstleister finden.
Regeln:
- Jede Query besteht aus einem kurzen Suchbegriff (Branche/Tätigkeit) und einer Region (Bundesland, Stadt oder Gebiet)
- Suchbegriffe sind konkret, auf Deutsch, wie ein Mensch bei Google suchen würde
- Keine Firmennamen, keine Websites, keine Social-Media-Begriffe
- Wenn der Nutzer keine Region nennt, verteile auf sinnvolle deutsche Regionen (z.B. Bayern, NRW, Baden-Württemberg)
- Wenn der Nutzer eine spezifische Region nennt, halte dich daran — teile ggf. in Städte auf für mehr Abdeckung
- count immer 50 außer der Nutzer nennt explizit eine Zahl (dann zwischen 25 und 100)
- Maximal 4 Queries zurückgeben
- Keine Erklärungen, nur JSON
Antworte ausschließlich mit einem JSON-Array, kein Markdown, kein Text drumherum:
[
{ "query": "Dachdecker", "region": "Bayern", "count": 50 },
{ "query": "Dachdecker", "region": "NRW", "count": 50 }
]`;
export async function POST(req: NextRequest) {
try {
const { description } = await req.json() as { description: string };
if (!description?.trim()) {
return NextResponse.json({ error: "Beschreibung fehlt" }, { status: 400 });
}
const apiKey = process.env.OPENROUTER_API_KEY;
if (!apiKey) {
return NextResponse.json({ error: "OpenRouter API Key nicht konfiguriert" }, { status: 500 });
}
const res = await fetch("https://openrouter.ai/api/v1/chat/completions", {
method: "POST",
headers: {
"Authorization": `Bearer ${apiKey}`,
"Content-Type": "application/json",
"HTTP-Referer": "https://onvyaleads.app",
"X-Title": "OnyvaLeads",
},
body: JSON.stringify({
model: "openai/gpt-4o-mini",
temperature: 0.4,
max_tokens: 512,
messages: [
{ role: "system", content: SYSTEM_PROMPT },
{ role: "user", content: description.trim() },
],
}),
});
if (!res.ok) {
const err = await res.text();
console.error("[ai-search] OpenRouter error:", err);
return NextResponse.json({ error: "KI-Anfrage fehlgeschlagen" }, { status: 500 });
}
const data = await res.json() as {
choices: Array<{ message: { content: string } }>;
};
const raw = data.choices[0]?.message?.content?.trim() ?? "";
let queries: Array<{ query: string; region: string; count: number }>;
try {
queries = JSON.parse(raw);
} catch {
const match = raw.match(/\[[\s\S]*\]/);
if (!match) throw new Error("Kein JSON in Antwort");
queries = JSON.parse(match[0]);
}
queries = queries
.filter(q => typeof q.query === "string" && q.query.trim())
.slice(0, 4)
.map(q => ({
query: q.query.trim(),
region: (q.region ?? "").trim(),
count: Math.min(Math.max(Number(q.count) || 50, 25), 100),
}));
return NextResponse.json({ queries });
} catch (err) {
console.error("[ai-search] error:", err);
return NextResponse.json({ error: "Fehler bei der KI-Anfrage" }, { status: 500 });
}
}

View File

@@ -5,6 +5,7 @@ import Link from "next/link";
import { toast } from "sonner"; import { toast } from "sonner";
import { SearchCard } from "@/components/search/SearchCard"; import { SearchCard } from "@/components/search/SearchCard";
import { LoadingCard, type LeadResult } from "@/components/search/LoadingCard"; import { LoadingCard, type LeadResult } from "@/components/search/LoadingCard";
import { AiSearchModal } from "@/components/search/AiSearchModal";
export default function SuchePage() { export default function SuchePage() {
const [query, setQuery] = useState(""); const [query, setQuery] = useState("");
@@ -18,6 +19,7 @@ export default function SuchePage() {
const [deleting, setDeleting] = useState(false); const [deleting, setDeleting] = useState(false);
const [onlyNew, setOnlyNew] = useState(false); const [onlyNew, setOnlyNew] = useState(false);
const [saveOnlyNew, setSaveOnlyNew] = useState(false); const [saveOnlyNew, setSaveOnlyNew] = useState(false);
const [aiOpen, setAiOpen] = useState(false);
function handleChange(field: "query" | "region" | "count", value: string | number) { function handleChange(field: "query" | "region" | "count", value: string | number) {
if (field === "query") setQuery(value as string); if (field === "query") setQuery(value as string);
@@ -130,12 +132,33 @@ export default function SuchePage() {
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><circle cx="11" cy="11" r="8"/><path d="m21 21-4.35-4.35"/></svg> <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><circle cx="11" cy="11" r="8"/><path d="m21 21-4.35-4.35"/></svg>
<span>Lead-Suche</span> <span>Lead-Suche</span>
</div> </div>
<h1 style={{ fontSize: 22, fontWeight: 500, color: "#ffffff", margin: 0, marginBottom: 6 }}> <div className="flex items-start justify-between">
Leads finden <div>
</h1> <h1 style={{ fontSize: 22, fontWeight: 500, color: "#ffffff", margin: 0, marginBottom: 6 }}>
<p style={{ fontSize: 13, color: "#9ca3af", margin: 0 }}> Leads finden
Suchbegriff eingeben wir finden passende Unternehmen mit Kontaktdaten. </h1>
</p> <p style={{ fontSize: 13, color: "#9ca3af", margin: 0 }}>
Suchbegriff eingeben wir finden passende Unternehmen mit Kontaktdaten.
</p>
</div>
<button
onClick={() => setAiOpen(true)}
disabled={loading}
style={{
display: "flex", alignItems: "center", gap: 7,
padding: "8px 14px", borderRadius: 8,
border: "1px solid rgba(139,92,246,0.35)",
background: "rgba(139,92,246,0.1)", color: "#a78bfa",
fontSize: 13, fontWeight: 500,
cursor: loading ? "not-allowed" : "pointer",
opacity: loading ? 0.5 : 1, whiteSpace: "nowrap",
}}
onMouseEnter={e => { if (!loading) { e.currentTarget.style.background = "rgba(139,92,246,0.18)"; e.currentTarget.style.borderColor = "rgba(139,92,246,0.6)"; }}}
onMouseLeave={e => { e.currentTarget.style.background = "rgba(139,92,246,0.1)"; e.currentTarget.style.borderColor = "rgba(139,92,246,0.35)"; }}
>
KI-Suche
</button>
</div>
</div> </div>
</div> </div>
@@ -162,6 +185,41 @@ export default function SuchePage() {
/> />
)} )}
{/* AI Modal */}
{aiOpen && (
<AiSearchModal
onStart={(queries) => {
setAiOpen(false);
if (!queries.length) return;
// Fill first query into the search fields and submit
const first = queries[0];
setQuery(first.query);
setRegion(first.region);
setCount(first.count);
setLoading(true);
setJobId(null);
setLeads([]);
setSearchDone(false);
setSelected(new Set());
fetch("/api/search", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ query: first.query, region: first.region, count: first.count }),
})
.then(r => r.json())
.then((d: { jobId?: string; error?: string }) => {
if (d.jobId) setJobId(d.jobId);
else throw new Error(d.error);
})
.catch(err => {
toast.error(err instanceof Error ? err.message : "Fehler");
setLoading(false);
});
}}
onClose={() => setAiOpen(false)}
/>
)}
{/* Results */} {/* Results */}
{searchDone && leads.length > 0 && (() => { {searchDone && leads.length > 0 && (() => {
const newCount = leads.filter(l => l.isNew).length; const newCount = leads.filter(l => l.isNew).length;

View File

@@ -0,0 +1,223 @@
"use client";
import { useState } from "react";
interface Query {
query: string;
region: string;
count: number;
}
interface AiSearchModalProps {
onStart: (queries: Query[]) => void;
onClose: () => void;
}
export function AiSearchModal({ onStart, onClose }: AiSearchModalProps) {
const [description, setDescription] = useState("");
const [loading, setLoading] = useState(false);
const [queries, setQueries] = useState<Query[]>([]);
const [selected, setSelected] = useState<Set<number>>(new Set());
const [error, setError] = useState("");
async function generate() {
if (!description.trim() || loading) return;
setLoading(true);
setError("");
setQueries([]);
try {
const res = await fetch("/api/ai-search", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ description }),
});
const data = await res.json() as { queries?: Query[]; error?: string };
if (!res.ok || !data.queries) throw new Error(data.error || "Fehler");
setQueries(data.queries);
setSelected(new Set(data.queries.map((_, i) => i)));
} catch (e) {
setError(e instanceof Error ? e.message : "Unbekannter Fehler");
} finally {
setLoading(false);
}
}
function toggle(i: number) {
setSelected(prev => {
const n = new Set(prev);
if (n.has(i)) n.delete(i); else n.add(i);
return n;
});
}
function handleStart() {
const chosen = queries.filter((_, i) => selected.has(i));
if (!chosen.length) return;
onStart(chosen);
}
return (
<div
style={{
position: "fixed", inset: 0, zIndex: 50,
display: "flex", alignItems: "center", justifyContent: "center",
background: "rgba(0,0,0,0.6)",
}}
onClick={onClose}
>
<div
style={{
background: "#111118", border: "1px solid #1e1e2e", borderRadius: 14,
padding: 28, width: "100%", maxWidth: 520,
display: "flex", flexDirection: "column", gap: 16,
}}
onClick={e => e.stopPropagation()}
>
{/* Header */}
<div style={{ display: "flex", alignItems: "flex-start", justifyContent: "space-between" }}>
<div>
<div style={{ display: "flex", alignItems: "center", gap: 8, marginBottom: 4 }}>
<span style={{ fontSize: 18 }}></span>
<h2 style={{ margin: 0, fontSize: 16, fontWeight: 500, color: "#fff" }}>
KI-gestützte Suche
</h2>
</div>
<p style={{ margin: 0, fontSize: 12, color: "#6b7280" }}>
Beschreibe deine Zielgruppe die KI generiert passende Suchanfragen.
</p>
</div>
<button onClick={onClose} style={{ background: "none", border: "none", color: "#6b7280", cursor: "pointer", padding: 4 }}>
<svg width="16" height="16" viewBox="0 0 16 16" fill="currentColor">
<path d="M4.646 4.646a.5.5 0 0 1 .708 0L8 7.293l2.646-2.647a.5.5 0 0 1 .708.708L8.707 8l2.647 2.646a.5.5 0 0 1-.708.708L8 8.707l-2.646 2.647a.5.5 0 0 1-.708-.708L7.293 8 4.646 5.354a.5.5 0 0 1 0-.708z"/>
</svg>
</button>
</div>
{/* Textarea */}
<div>
<textarea
value={description}
onChange={e => setDescription(e.target.value)}
onKeyDown={e => { if (e.key === "Enter" && e.ctrlKey) generate(); }}
placeholder="z.B. Ich suche kleine Dachdecker und Solarinstallateure in Bayern, am liebsten mit Inhaber direkt erreichbar."
rows={4}
style={{
width: "100%", background: "#0d0d18", border: "1px solid #1e1e2e",
borderRadius: 8, padding: "10px 12px", fontSize: 13, color: "#fff",
outline: "none", resize: "vertical", fontFamily: "inherit",
lineHeight: 1.6, boxSizing: "border-box",
}}
onFocus={e => { e.currentTarget.style.borderColor = "#3b82f6"; }}
onBlur={e => { e.currentTarget.style.borderColor = "#1e1e2e"; }}
/>
<p style={{ margin: "4px 0 0", fontSize: 11, color: "#4b5563" }}>
Tipp: Branche, Region, Firmengröße und gewünschten Entscheidungsträger erwähnen · Strg+Enter zum Generieren
</p>
</div>
{/* Generate button */}
{queries.length === 0 && (
<button
onClick={generate}
disabled={!description.trim() || loading}
style={{
width: "100%", padding: "11px 16px", borderRadius: 8, border: "none",
background: !description.trim() || loading ? "#1e1e2e" : "linear-gradient(135deg, #3b82f6, #8b5cf6)",
color: !description.trim() || loading ? "#4b5563" : "#fff",
fontSize: 14, fontWeight: 500, cursor: !description.trim() || loading ? "not-allowed" : "pointer",
display: "flex", alignItems: "center", justifyContent: "center", gap: 8,
}}
>
{loading ? (
<>
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" style={{ animation: "spin 1s linear infinite" }}>
<path d="M21 12a9 9 0 1 1-6.219-8.56"/>
</svg>
Suchanfragen werden generiert
</>
) : (
<> Suchanfragen generieren</>
)}
</button>
)}
{/* Error */}
{error && (
<p style={{ margin: 0, fontSize: 12, color: "#ef4444", background: "rgba(239,68,68,0.08)", padding: "8px 12px", borderRadius: 6, borderLeft: "3px solid #ef4444" }}>
{error}
</p>
)}
{/* Generated queries */}
{queries.length > 0 && (
<div style={{ display: "flex", flexDirection: "column", gap: 8 }}>
<p style={{ margin: 0, fontSize: 11, color: "#6b7280", textTransform: "uppercase", letterSpacing: "0.05em" }}>
Generierte Suchanfragen wähle aus was starten soll
</p>
{queries.map((q, i) => (
<button
key={i}
onClick={() => toggle(i)}
style={{
display: "flex", alignItems: "center", justifyContent: "space-between",
padding: "10px 14px", borderRadius: 8, cursor: "pointer", textAlign: "left",
border: selected.has(i) ? "1px solid rgba(59,130,246,0.5)" : "1px solid #1e1e2e",
background: selected.has(i) ? "rgba(59,130,246,0.08)" : "#0d0d18",
transition: "all 0.15s",
}}
>
<div>
<span style={{ fontSize: 13, color: "#fff", fontWeight: 500 }}>{q.query}</span>
{q.region && (
<span style={{ fontSize: 12, color: "#6b7280", marginLeft: 8 }}>📍 {q.region}</span>
)}
</div>
<div style={{ display: "flex", alignItems: "center", gap: 8 }}>
<span style={{ fontSize: 11, color: "#4b5563" }}>{q.count} Leads</span>
<div style={{
width: 16, height: 16, borderRadius: 4,
border: selected.has(i) ? "none" : "1px solid #2e2e3e",
background: selected.has(i) ? "#3b82f6" : "transparent",
display: "flex", alignItems: "center", justifyContent: "center", flexShrink: 0,
}}>
{selected.has(i) && (
<svg width="10" height="10" viewBox="0 0 10 10" fill="none">
<path d="M2 5l2.5 2.5L8 3" stroke="white" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round"/>
</svg>
)}
</div>
</div>
</button>
))}
<div style={{ display: "flex", gap: 8, marginTop: 4 }}>
<button
onClick={() => { setQueries([]); setSelected(new Set()); }}
style={{
flex: 1, padding: "10px", borderRadius: 8, border: "1px solid #1e1e2e",
background: "#0d0d18", color: "#6b7280", fontSize: 13, cursor: "pointer",
}}
>
Neu generieren
</button>
<button
onClick={handleStart}
disabled={selected.size === 0}
style={{
flex: 2, padding: "10px", borderRadius: 8, border: "none",
background: selected.size > 0 ? "linear-gradient(135deg, #3b82f6, #8b5cf6)" : "#1e1e2e",
color: selected.size > 0 ? "#fff" : "#4b5563",
fontSize: 13, fontWeight: 500, cursor: selected.size > 0 ? "pointer" : "not-allowed",
}}
>
{selected.size} {selected.size === 1 ? "Suche" : "Suchen"} starten
</button>
</div>
</div>
)}
<style>{`@keyframes spin { to { transform: rotate(360deg) } }`}</style>
</div>
</div>
);
}