-
Notifications
You must be signed in to change notification settings - Fork 28
feat(search): serve hybrid retrieval to MCP style search #46
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,63 @@ | ||
| import { NextRequest, NextResponse } from "next/server"; | ||
|
|
||
| import { searchStyleSlugs } from "@/lib/retrieval/style-search-service"; | ||
| import { | ||
| checkRateLimit, | ||
| createRateLimitHeaders, | ||
| getRequestClientKey, | ||
| } from "@/lib/security/rate-limit"; | ||
|
|
||
| const MAX_QUERY_LENGTH = 200; | ||
|
|
||
| // Rankings change only with a deployment; identical queries can be shared. | ||
| const SEARCH_CACHE_CONTROL = | ||
| "public, max-age=300, s-maxage=3600, stale-while-revalidate=86400"; | ||
|
|
||
| /** | ||
| * Hybrid style search: BM25 + vector + RRF over the curated catalog. | ||
| * | ||
| * Returns ranked slugs only. Callers already hold the catalog (from | ||
| * `/api/styles`) and join on slug, so this stays small and cacheable. `mode` | ||
| * says whether the vector path answered or the keyword path served alone. | ||
| */ | ||
| export async function GET(request: NextRequest) { | ||
| const rateLimit = checkRateLimit({ | ||
| namespace: "style-search", | ||
| key: getRequestClientKey(request), | ||
| limit: 60, | ||
| windowMs: 60 * 1000, | ||
| }); | ||
| if (!rateLimit.allowed) { | ||
| return NextResponse.json( | ||
| { error: "Too many requests. Try again later." }, | ||
| { status: 429, headers: createRateLimitHeaders(rateLimit) }, | ||
| ); | ||
| } | ||
|
|
||
| const query = (request.nextUrl.searchParams.get("q") ?? "").trim(); | ||
| if (!query) { | ||
| return NextResponse.json({ error: "Missing query parameter q." }, { status: 400 }); | ||
| } | ||
| if (query.length > MAX_QUERY_LENGTH) { | ||
| return NextResponse.json( | ||
| { error: `Query must be at most ${MAX_QUERY_LENGTH} characters.` }, | ||
| { status: 400 }, | ||
| ); | ||
| } | ||
|
|
||
| try { | ||
| const result = await searchStyleSlugs(query); | ||
| return NextResponse.json( | ||
| { query, total: result.results.length, ...result }, | ||
| // A degraded answer is cached briefly so the vector path gets retried soon. | ||
| { | ||
| headers: { | ||
| "Cache-Control": result.mode === "hybrid" ? SEARCH_CACHE_CONTROL : "public, max-age=60", | ||
| }, | ||
| }, | ||
| ); | ||
| } catch (error) { | ||
| console.error("[api/search] failed:", error); | ||
| return NextResponse.json({ error: "Search is temporarily unavailable." }, { status: 503 }); | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,134 @@ | ||
| /** | ||
| * @module retrieval/style-search-service | ||
| * | ||
| * The production entry point for hybrid style search (BM25 + vector + RRF). | ||
| * | ||
| * `hybrid-search.ts` is the algorithm; this module is the wiring a server | ||
| * process needs around it: one corpus index per process, the vector index read | ||
| * from disk, and the embedding provider built from the environment. | ||
| * | ||
| * Every missing piece degrades rather than fails. No `DASHSCOPE_API_KEY`, no | ||
| * `.data/style-vectors.json`, an index built for another model, or a slow | ||
| * embedding call all fall back to the keyword path, and the response says | ||
| * which one answered. That keeps search available on a host that has not been | ||
| * given the key yet. | ||
| */ | ||
|
|
||
| import { chunkStyles } from "@/lib/retrieval/chunk-styles"; | ||
| import { | ||
| DEFAULT_EMBEDDING_DIMENSIONS, | ||
| DEFAULT_EMBEDDING_MODEL, | ||
| createDashScopeEmbeddingProvider, | ||
| type EmbeddingProvider, | ||
| } from "@/lib/retrieval/embedding"; | ||
| import { | ||
| createHybridSearcher, | ||
| type DegradeReason, | ||
| type HybridSearcher, | ||
| } from "@/lib/retrieval/hybrid-search"; | ||
| import { JsonFileVectorStore, type VectorStore } from "@/lib/retrieval/vector-store"; | ||
| import { styles } from "@/lib/styles/registry"; | ||
|
|
||
| /** A query answered from the network should not wait on a slow embedding. */ | ||
| const QUERY_EMBEDDING_TIMEOUT_MS = 1_500; | ||
| const QUERY_CACHE_LIMIT = 500; | ||
|
|
||
| export type StyleSearchMode = "hybrid" | "keyword"; | ||
|
|
||
| export interface StyleSearchResult { | ||
| mode: StyleSearchMode; | ||
| /** Set when the vector path was unavailable for this query. */ | ||
| degradeReason?: DegradeReason; | ||
| results: Array<{ slug: string; score: number }>; | ||
| } | ||
|
|
||
| interface ServiceState { | ||
| searcher: HybridSearcher; | ||
| /** Why the vector path is off for every query, when it is. */ | ||
| staticDegrade?: DegradeReason; | ||
| } | ||
|
|
||
| let statePromise: Promise<ServiceState> | null = null; | ||
| const queryCache = new Map<string, StyleSearchResult>(); | ||
|
|
||
| function createProvider(): EmbeddingProvider | null { | ||
| try { | ||
| return createDashScopeEmbeddingProvider({ timeoutMs: QUERY_EMBEDDING_TIMEOUT_MS, maxAttempts: 1 }); | ||
| } catch { | ||
| return null; | ||
| } | ||
| } | ||
|
|
||
| async function openVectorStore(): Promise<VectorStore | null> { | ||
| try { | ||
| const store = await JsonFileVectorStore.open({ | ||
| dimensions: DEFAULT_EMBEDDING_DIMENSIONS, | ||
| model: DEFAULT_EMBEDDING_MODEL, | ||
| }); | ||
| return store.size() > 0 ? store : null; | ||
| } catch { | ||
| // A stale index (other model or dimensions) is unusable, not fatal. | ||
| return null; | ||
| } | ||
| } | ||
|
|
||
| async function buildState(): Promise<ServiceState> { | ||
| const provider = createProvider(); | ||
| const vectorStore = await openVectorStore(); | ||
| const searcher = createHybridSearcher({ | ||
| chunks: chunkStyles(styles), | ||
| embeddingProvider: vectorStore ? provider : null, | ||
| vectorStore, | ||
| topK: styles.length, | ||
| vectorTimeoutMs: QUERY_EMBEDDING_TIMEOUT_MS, | ||
| }); | ||
| const staticDegrade: DegradeReason | undefined = !provider ? "no-provider" : !vectorStore ? "no-store" : undefined; | ||
| return { searcher, staticDegrade }; | ||
| } | ||
|
|
||
| function getState(): Promise<ServiceState> { | ||
| if (!statePromise) { | ||
| statePromise = buildState().catch((error: unknown) => { | ||
| statePromise = null; | ||
| throw error; | ||
| }); | ||
| } | ||
| return statePromise; | ||
| } | ||
|
|
||
| export async function searchStyleSlugs(query: string): Promise<StyleSearchResult> { | ||
| const key = query.trim().toLowerCase(); | ||
| const cached = queryCache.get(key); | ||
| if (cached) return cached; | ||
|
|
||
| const { searcher, staticDegrade } = await getState(); | ||
| let degradeReason: DegradeReason | undefined = staticDegrade; | ||
| const hits = await searcher.search(key, { | ||
| onDegrade: (info) => { | ||
| degradeReason ??= info.reason; | ||
| }, | ||
| }); | ||
|
|
||
| const result: StyleSearchResult = { | ||
| mode: degradeReason ? "keyword" : "hybrid", | ||
| ...(degradeReason ? { degradeReason } : {}), | ||
| results: hits.map((hit) => ({ slug: hit.slug, score: hit.score })), | ||
| }; | ||
|
|
||
| // Only full-quality answers are cached, so a transient embedding failure | ||
| // does not pin a keyword-only ranking for that query. | ||
| if (result.mode === "hybrid" || staticDegrade) { | ||
| if (queryCache.size >= QUERY_CACHE_LIMIT) { | ||
| const oldest = queryCache.keys().next().value; | ||
| if (oldest !== undefined) queryCache.delete(oldest); | ||
| } | ||
| queryCache.set(key, result); | ||
| } | ||
| return result; | ||
| } | ||
|
|
||
| /** Exposed for tests. */ | ||
| export function resetStyleSearchService(): void { | ||
| statePromise = null; | ||
| queryCache.clear(); | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🩺 Stability & Availability | 🟡 Minor | ⚡ Quick win
🔎 Supported by static analysis
🏁 Script executed:
Repository: AnxForever/stylekit
Length of output: 15736
🏁 Script executed:
Repository: AnxForever/stylekit
Length of output: 31009
🏁 Script executed:
Repository: AnxForever/stylekit
Length of output: 9257
Ship the vector index with production deployments.
openVectorStorereads.data/style-vectors.jsonrelative to the process working directory. The documented ECS deployment syncs the checkout and.nextdirectory, but.data/is gitignored. The build script does not runbuild-style-index, and CI does not generate or upload the index. Unless the release process separately creates and copies.data/style-vectors.jsonto/www/stylekit/.data/, the read returns an empty store,staticDegradebecomes"no-store", and queries use keyword mode.Add an explicit release step to generate the index and copy it with the deployment artifact. The index must use
DEFAULT_EMBEDDING_MODELandDEFAULT_EMBEDDING_DIMENSIONS.The output-file-tracing concern does not apply to the documented ECS deployment, which runs
next startfrom the synchronized application directory.🤖 Prompt for AI Agents