1
+ import { config } from "./config.js" ;
2
+
1
3
export interface SearchResult {
2
4
id : string ;
3
5
title ?: string ;
@@ -11,26 +13,36 @@ export interface SearchResult {
11
13
semanticRelevancyScore ?: number ;
12
14
}
13
15
16
+ const RESULTS_TO_RETURN = 10 ;
17
+
14
18
export class SemanticSearch {
15
19
private readonly apiUrl : string ;
16
20
17
- constructor ( ) {
18
- // Allow overriding the API URL for testing via environment variable
19
- this . apiUrl =
20
- process . env . HF_SEARCH_API_URL ||
21
- "https://huggingface.co/api/spaces/semantic-search" ;
21
+ constructor ( apiUrl ?: string ) {
22
+ this . apiUrl = apiUrl || "https://huggingface.co/api/spaces/semantic-search" ;
22
23
}
23
24
24
- async search ( query : string , limit : number = 10 ) : Promise < SearchResult [ ] > {
25
+ async search (
26
+ query : string ,
27
+ limit : number = RESULTS_TO_RETURN
28
+ ) : Promise < SearchResult [ ] > {
25
29
try {
26
30
if ( ! query ) {
27
31
return [ ] ;
28
32
}
29
33
30
- const encodedQuery = encodeURIComponent ( query ) ;
31
- const url = `${ this . apiUrl } ?q=${ encodedQuery } &sdk=gradio` ;
34
+ const url =
35
+ `${ this . apiUrl } ?` + new URLSearchParams ( { q : query , sdk : "gradio" } ) ;
36
+
37
+ const headers : HeadersInit = {
38
+ "Content-Type" : "application/json" ,
39
+ } ;
40
+
41
+ if ( config . hfToken ) {
42
+ headers [ "Authorization" ] = `Bearer ${ config . hfToken } ` ;
43
+ }
32
44
33
- const response = await fetch ( url ) ;
45
+ const response = await fetch ( url , headers ) ;
34
46
35
47
if ( ! response . ok ) {
36
48
throw new Error (
@@ -67,7 +79,11 @@ export class SemanticSearch {
67
79
const author = result . authorData ?. fullname || result . author || "Unknown" ;
68
80
const id = result . id || "" ;
69
81
70
- markdown += `| ${ escapeMarkdown ( title ) } | ${ escapeMarkdown ( description ) } | ${ escapeMarkdown ( author ) } | \`${ escapeMarkdown ( id ) } \` |\n` ;
82
+ markdown +=
83
+ `| [${ escapeMarkdown ( title ) } ](https://huggingface.co/api/spaces/${ id } ) ` +
84
+ `| ${ escapeMarkdown ( description ) } ` +
85
+ `| ${ escapeMarkdown ( author ) } ` +
86
+ `| \`${ escapeMarkdown ( id ) } \` |\n` ;
71
87
}
72
88
73
89
markdown +=
0 commit comments