Skip to content

Commit cbf6815

Browse files
authored
fix(docs): cap search query length and time out the embedding call (#8601)
* fix(docs): cap search query length and time out the embedding call * fix(docs): truncate long search queries instead of dropping them * fix(docs): truncate search queries on a code point boundary
1 parent 0bf9219 commit cbf6815

2 files changed

Lines changed: 12 additions & 2 deletions

File tree

‎apps/docs/app/api/search/route.ts‎

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import { createLogger } from '@sim/logger'
2+
import { truncateAtCodePoint } from '@sim/utils/string'
23
import { sql } from 'drizzle-orm'
34
import { type NextRequest, NextResponse } from 'next/server'
45
import { db, docsEmbeddings } from '@/lib/db'
@@ -11,6 +12,8 @@ export const revalidate = 0
1112

1213
const DEFAULT_SEARCH_LIMIT = 10
1314
const MAX_SEARCH_LIMIT = 20
15+
/** Bounds the paid embedding call per request; real searches are a few words. */
16+
const MAX_QUERY_LENGTH = 256
1417

1518
/** PostgreSQL text-search configuration for the docs' English content. */
1619
const TS_CONFIG = 'english'
@@ -28,7 +31,11 @@ function getSearchLimit(value: unknown): number {
2831
function getSearchParams(request: NextRequest) {
2932
const searchParams = request.nextUrl.searchParams
3033
return {
31-
query: searchParams.get('query') || searchParams.get('q') || '',
34+
query: truncateAtCodePoint(
35+
searchParams.get('query') || searchParams.get('q') || '',
36+
MAX_QUERY_LENGTH,
37+
''
38+
),
3239
limit: getSearchLimit(searchParams.get('limit')),
3340
}
3441
}
@@ -38,7 +45,7 @@ export async function GET(request: NextRequest) {
3845
try {
3946
const { query, limit } = getSearchParams(request)
4047

41-
if (!query || query.trim().length === 0) {
48+
if (query.trim().length === 0) {
4249
return NextResponse.json([])
4350
}
4451

‎apps/docs/lib/embeddings.ts‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1+
const EMBEDDING_TIMEOUT_MS = 10_000
2+
13
/**
24
* Generate embeddings for search queries using OpenAI API
35
*/
@@ -19,6 +21,7 @@ export async function generateSearchEmbedding(query: string): Promise<number[]>
1921
model: 'text-embedding-3-small',
2022
encoding_format: 'float',
2123
}),
24+
signal: AbortSignal.timeout(EMBEDDING_TIMEOUT_MS),
2225
})
2326

2427
if (!response.ok) {

0 commit comments

Comments
 (0)