knowledge-ask
Version:
A frontend nuxt library to call the knowledge-hub API.
93 lines (84 loc) • 3.1 kB
text/typescript
import { VectorDocument, SimilaritySearchRequest } from "./types";
import { ref, computed } from "vue";
import { useFetch } from "nuxt3/app";
import { defineStore } from "pinia";
import {
AsyncDataExecuteOptions,
AsyncDataRequestStatus,
} from "nuxt3/dist/app/composables/asyncData";
export const useSimilaritySearch = defineStore("similarity-search", () => {
const maxItems = ref<number>(5);
const query = ref<string>("");
const knowledgeHubURL = ref<string>("");
const data = ref<Array<VectorDocument> | null>(null);
const pending = ref<boolean>(false);
const error = ref<any | null>(null);
const refresh = ref<
((opts?: AsyncDataExecuteOptions) => Promise<void>) | undefined
>(undefined);
const status = ref<AsyncDataRequestStatus>();
// Action to execute the fetch
const similaritySearch = async (
requestData: SimilaritySearchRequest = {
maxItems: maxItems.value,
query: query.value,
knowledgeHubURL: knowledgeHubURL.value,
}
) => {
maxItems.value = requestData.maxItems;
query.value = requestData.query;
knowledgeHubURL.value = requestData.knowledgeHubURL;
const {
data: _data,
pending: _pending,
error: _error,
refresh: _refresh,
status: _status,
} = await useFetch<Array<VectorDocument>, any>(
`${knowledgeHubURL}/vector_documents/similarity_search`,
{
method: "POST",
body: { content: query },
onRequest({ request, options }) {
options.headers = options.headers || {};
options.headers["Content-Type"] = "application/json";
// TODO: Add authorization, we can set it like this:
// options.headers.authorization = 'Bearer ' + YOUR_TOKEN_HERE;
},
onRequestError({ request, options, error }) {
console.error("Request error:", error);
},
onResponse({ request, response, options }) {
// Process the response data
// if we want to do something with the data, like storing or caching it:
// localStorage.setItem('vectorDocuments', JSON.stringify(response._data));
},
onResponseError({ request, response, options }) {
// Handle the response errors
console.error("Response error:", response);
},
}
);
data.value = _data.value;
pending.value = _pending.value;
error.value = _error.value;
refresh.value = _refresh;
status.value = _status.value;
return {
data,
pending,
error,
refresh,
status,
};
};
return {
maxItems,
query,
knowledgeHubURL,
data,
pending,
error,
similaritySearch,
};
});