forked from TabbyML/tabby
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat: implement /v1beta/search interface (TabbyML#516)
* feat: implement /v1beta/search interface * update * update * improve debugger
- Loading branch information
Showing
11 changed files
with
232 additions
and
31 deletions.
There are no files selected for viewing
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Oops, something went wrong.
This file contains 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 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,20 @@ | ||
use tantivy::{ | ||
tokenizer::{RegexTokenizer, RemoveLongFilter, TextAnalyzer}, | ||
Index, | ||
}; | ||
|
||
pub trait IndexExt { | ||
fn register_tokenizer(&self); | ||
} | ||
|
||
pub static CODE_TOKENIZER: &str = "code"; | ||
|
||
impl IndexExt for Index { | ||
fn register_tokenizer(&self) { | ||
let code_tokenizer = TextAnalyzer::builder(RegexTokenizer::new(r"(?:\w+)").unwrap()) | ||
.filter(RemoveLongFilter::limit(128)) | ||
.build(); | ||
|
||
self.tokenizers().register(CODE_TOKENIZER, code_tokenizer); | ||
} | ||
} |
This file contains 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 |
---|---|---|
@@ -1,5 +1,6 @@ | ||
pub mod config; | ||
pub mod events; | ||
pub mod index; | ||
pub mod path; | ||
pub mod usage; | ||
|
||
|
This file contains 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 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 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 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 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,144 @@ | ||
use std::sync::Arc; | ||
|
||
use anyhow::Result; | ||
use axum::{ | ||
extract::{Query, State}, | ||
Json, | ||
}; | ||
use hyper::StatusCode; | ||
use serde::{Deserialize, Serialize}; | ||
use tabby_common::{index::IndexExt, path}; | ||
use tantivy::{ | ||
collector::{Count, TopDocs}, | ||
query::QueryParser, | ||
schema::{Field, FieldType, NamedFieldDocument, Schema}, | ||
DocAddress, Document, Index, IndexReader, Score, | ||
}; | ||
use tracing::instrument; | ||
use utoipa::IntoParams; | ||
|
||
#[derive(Deserialize, IntoParams)] | ||
pub struct SearchQuery { | ||
#[param(default = "get")] | ||
q: String, | ||
|
||
#[param(default = 20)] | ||
limit: Option<usize>, | ||
|
||
#[param(default = 0)] | ||
offset: Option<usize>, | ||
} | ||
|
||
#[derive(Serialize)] | ||
pub struct SearchResponse { | ||
q: String, | ||
num_hits: usize, | ||
hits: Vec<Hit>, | ||
} | ||
|
||
#[derive(Serialize)] | ||
pub struct Hit { | ||
score: Score, | ||
doc: NamedFieldDocument, | ||
id: u32, | ||
} | ||
|
||
#[utoipa::path( | ||
get, | ||
params(SearchQuery), | ||
path = "/v1beta/search", | ||
operation_id = "search", | ||
tag = "v1beta", | ||
responses( | ||
(status = 200, description = "Success" , content_type = "application/json"), | ||
(status = 405, description = "When code search is not enabled, the endpoint will returns 405 Method Not Allowed"), | ||
) | ||
)] | ||
#[instrument(skip(state, query))] | ||
pub async fn search( | ||
State(state): State<Arc<IndexServer>>, | ||
query: Query<SearchQuery>, | ||
) -> Result<Json<SearchResponse>, StatusCode> { | ||
let Ok(serp) = state.search( | ||
&query.q, | ||
query.limit.unwrap_or(20), | ||
query.offset.unwrap_or(0), | ||
) else { | ||
return Err(StatusCode::INTERNAL_SERVER_ERROR); | ||
}; | ||
|
||
Ok(Json(serp)) | ||
} | ||
|
||
pub struct IndexServer { | ||
reader: IndexReader, | ||
query_parser: QueryParser, | ||
schema: Schema, | ||
} | ||
|
||
impl IndexServer { | ||
pub fn new() -> Self { | ||
Self::load().expect("Failed to load code state") | ||
} | ||
|
||
fn load() -> Result<Self> { | ||
let index = Index::open_in_dir(path::index_dir())?; | ||
index.register_tokenizer(); | ||
|
||
let schema = index.schema(); | ||
let default_fields: Vec<Field> = schema | ||
.fields() | ||
.filter(|&(_, field_entry)| match field_entry.field_type() { | ||
FieldType::Str(ref text_field_options) => { | ||
text_field_options.get_indexing_options().is_some() | ||
} | ||
_ => false, | ||
}) | ||
.map(|(field, _)| field) | ||
.collect(); | ||
let query_parser = | ||
QueryParser::new(schema.clone(), default_fields, index.tokenizers().clone()); | ||
let reader = index.reader()?; | ||
Ok(Self { | ||
reader, | ||
query_parser, | ||
schema, | ||
}) | ||
} | ||
|
||
fn search(&self, q: &str, limit: usize, offset: usize) -> tantivy::Result<SearchResponse> { | ||
let query = self | ||
.query_parser | ||
.parse_query(q) | ||
.expect("Parsing the query failed"); | ||
let searcher = self.reader.searcher(); | ||
let (top_docs, num_hits) = { | ||
searcher.search( | ||
&query, | ||
&(TopDocs::with_limit(limit).and_offset(offset), Count), | ||
)? | ||
}; | ||
let hits: Vec<Hit> = { | ||
top_docs | ||
.iter() | ||
.map(|(score, doc_address)| { | ||
let doc = searcher.doc(*doc_address).unwrap(); | ||
self.create_hit(*score, doc, *doc_address) | ||
}) | ||
.collect() | ||
}; | ||
Ok(SearchResponse { | ||
q: q.to_owned(), | ||
num_hits, | ||
hits, | ||
}) | ||
} | ||
|
||
fn create_hit(&self, score: Score, doc: Document, doc_address: DocAddress) -> Hit { | ||
Hit { | ||
score, | ||
doc: self.schema.to_named_doc(&doc), | ||
id: doc_address.doc_id, | ||
} | ||
} | ||
} |
This file contains 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,38 @@ | ||
import re | ||
import requests | ||
import streamlit as st | ||
from typing import NamedTuple | ||
|
||
class Doc(NamedTuple): | ||
name: str | ||
body: str | ||
score: float | ||
filepath: str | ||
|
||
@staticmethod | ||
def from_json(json: dict): | ||
doc = json["doc"] | ||
return Doc( | ||
name=doc["name"][0], | ||
body=doc["body"][0], | ||
score=json["score"], | ||
filepath=doc["filepath"][0], | ||
) | ||
|
||
# force wide mode | ||
st.set_page_config(layout="wide") | ||
|
||
language = st.text_input("Language", "rust") | ||
query = st.text_area("Query", "get") | ||
tokens = re.findall(r"\w+", query) | ||
tokens = [x for x in tokens if x != "AND" and x != "OR" and x != "NOT"] | ||
|
||
query = "(" + " ".join(tokens) + ")" + " " + "AND language:" + language | ||
|
||
if query: | ||
r = requests.get("http://localhost:8080/v1beta/search", params=dict(q=query)) | ||
hits = r.json()["hits"] | ||
for x in hits: | ||
doc = Doc.from_json(x) | ||
st.write(doc.name + "@" + doc.filepath + " : " + str(doc.score)) | ||
st.code(doc.body) |
This file contains 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