@roadiehq/rag-ai
Version:
71 lines (68 loc) • 2 kB
JavaScript
import { EventSourceParserStream } from 'eventsource-parser/stream';
class RoadieRagAiClient {
discoveryApi;
fetchApi;
configApi;
baseUrl;
identityApi;
constructor(options) {
this.discoveryApi = options.discoveryApi;
this.fetchApi = options.fetchApi;
this.configApi = options.configApi;
this.identityApi = options.identityApi;
}
async getBaseUrl() {
if (!this.baseUrl) {
const endpointPath = this.configApi.getOptionalString("ai.endpointPath");
this.baseUrl = await this.discoveryApi.getBaseUrl(
endpointPath ?? "rag-ai"
);
}
return this.baseUrl;
}
async fetch(path, options = {}) {
const baseUrl = await this.getBaseUrl();
const response = await this.fetchApi.fetch(`${baseUrl}/${path}`, options);
if (!response.ok)
throw new Error(`Failed to retrieved data from path ${path}`);
return response.body;
}
async *ask(question, source) {
const { token } = await this.identityApi.getCredentials();
try {
const stream = await this.fetch(`query/${source}`, {
body: JSON.stringify({
query: question
}),
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${token}`
}
});
if (stream) {
const reader = stream.pipeThrough(new TextDecoderStream()).pipeThrough(new EventSourceParserStream()).getReader();
while (true) {
const { done, value } = await reader.read();
if (done) break;
yield value;
}
} else {
yield {
data: "No response received from the LLM",
event: "message",
type: "event"
};
}
} catch (e) {
console.error(e.message);
yield {
data: `Failed to complete query due to error: ${e.message}`,
event: "error",
type: "event"
};
}
}
}
export { RoadieRagAiClient };
//# sourceMappingURL=client.esm.js.map