Skip to content

Commit c615762

Browse files
refactoring private class variabeles
1 parent cb3bddd commit c615762

File tree

4 files changed

+50
-48
lines changed

4 files changed

+50
-48
lines changed

component/src/services/huggingFace/huggingFaceQuestionAnswerIO.ts

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -8,20 +8,20 @@ import {DeepChat} from '../../deepChat';
88
export class HuggingFaceQuestionAnswerIO extends HuggingFaceIO {
99
override permittedErrorPrefixes = ['Authorization header', 'Error in'];
1010

11-
private readonly context: string;
11+
private readonly _context: string;
1212

1313
constructor(deepChat: DeepChat) {
1414
const config = deepChat.directConnection?.huggingFace?.questionAnswer as NonNullable<HuggingFace['questionAnswer']>;
1515
const apiKey = deepChat.directConnection?.huggingFace;
1616
super(deepChat, 'Ask a question', 'bert-large-uncased-whole-word-masking-finetuned-squad', config, apiKey);
17-
this.context = config.context;
17+
this._context = config.context;
1818
}
1919

2020
override preprocessBody(_: HuggingFaceQuestionAnswerConfig, messages: MessageContentI[]) {
2121
const mostRecentMessageText = messages[messages.length - 1].text;
2222
if (!mostRecentMessageText) return;
2323
return {
24-
inputs: {question: mostRecentMessageText, context: this.context, options: {wait_for_model: true}},
24+
inputs: {question: mostRecentMessageText, context: this._context, options: {wait_for_model: true}},
2525
} as unknown as {inputs: string};
2626
}
2727

component/src/services/openAI/assistant/openAIAssistantIOI.ts

Lines changed: 34 additions & 32 deletions
Original file line numberDiff line numberDiff line change
@@ -50,6 +50,8 @@ export type URLSegments = {
5050
getFilesPostfix: string;
5151
};
5252

53+
// WORK - need to refactor to be in Responses API
54+
// https://platform.openai.com/docs/guides/responses-vs-chat-completions
5355
export class OpenAIAssistantIOI extends DirectServiceIO {
5456
override insertKeyPlaceholderText = 'OpenAI API Key';
5557
override keyHelpUrl = 'https://platform.openai.com/account/api-keys';
@@ -59,30 +61,30 @@ export class OpenAIAssistantIOI extends DirectServiceIO {
5961
functionHandler?: AssistantFunctionHandler;
6062
filesToolType: OpenAIAssistant['files_tool_type'];
6163
readonly shouldFetchHistory: boolean = false;
62-
private messages?: Messages;
64+
private _messages?: Messages;
6365
private run_id?: string;
64-
private searchedForThreadId = false;
65-
private readonly config: OpenAIAssistant = {};
66-
private readonly newAssistantDetails: OpenAINewAssistant = {model: 'gpt-4'};
67-
private waitingForStreamResponse = false;
68-
private readonly isSSEStream: boolean = false;
66+
private _searchedForThreadId = false;
67+
private readonly _config: OpenAIAssistant = {};
68+
private readonly _newAssistantDetails: OpenAINewAssistant = {model: 'gpt-4'};
69+
private _waitingForStreamResponse = false;
70+
private readonly _isSSEStream: boolean = false;
6971
private readonly urlSegments: URLSegments;
70-
private messageStream: MessageStream | undefined;
72+
private _messageStream: MessageStream | undefined;
7173

7274
// prettier-ignore
7375
constructor(deepChat: DeepChat, config: OpenAI['assistant'], urlSegments: URLSegments,
7476
keyVerificationDetails: KeyVerificationDetails, buildHeadersFunc: BuildHeadersFunc, apiKey?: APIKey) {
7577
super(deepChat, keyVerificationDetails, buildHeadersFunc, apiKey);
7678
this.urlSegments = urlSegments;
7779
if (typeof config === 'object') {
78-
this.config = config; // stored that assistant_id could be added
79-
const {new_assistant, thread_id, load_thread_history} = this.config;
80-
Object.assign(this.newAssistantDetails, new_assistant);
80+
this._config = config; // stored that assistant_id could be added
81+
const {new_assistant, thread_id, load_thread_history} = this._config;
82+
Object.assign(this._newAssistantDetails, new_assistant);
8183
if (thread_id) this.sessionId = thread_id;
8284
if (load_thread_history) this.shouldFetchHistory = true;
8385
}
8486
this.maxMessages = 1; // messages are stored in OpenAI threads and can't create new thread with 'assistant' messages
85-
this.isSSEStream = Boolean(this.stream && (typeof this.stream !== 'object' || !this.stream.simulation));
87+
this._isSSEStream = Boolean(this.stream && (typeof this.stream !== 'object' || !this.stream.simulation));
8688
}
8789

8890
public async fetchHistoryFunc() {
@@ -176,7 +178,7 @@ export class OpenAIAssistantIOI extends DirectServiceIO {
176178
}
177179

178180
private callService(messages: Messages, pMessages: MessageContentI[], uploadedFiles?: UploadedFile[]) {
179-
this.messages = messages;
181+
this._messages = messages;
180182
if (this.sessionId) {
181183
// https://platform.openai.com/docs/api-reference/messages/createMessage
182184
this.url = `${this.urlSegments.threadsPrefix}/${this.sessionId}/messages${this.urlSegments.createMessagePostfix}`;
@@ -186,7 +188,7 @@ export class OpenAIAssistantIOI extends DirectServiceIO {
186188
// https://platform.openai.com/docs/api-reference/runs/createThreadAndRun
187189
this.url = `${this.urlSegments.threadsPrefix}/runs${this.urlSegments.threadsPosfix}`;
188190
const body = this.createNewThreadMessages(this.rawBody, pMessages, uploadedFiles);
189-
if (this.isSSEStream) {
191+
if (this._isSSEStream) {
190192
this.createStreamRun(body);
191193
} else {
192194
HTTPRequest.request(this, body, messages);
@@ -195,11 +197,11 @@ export class OpenAIAssistantIOI extends DirectServiceIO {
195197
}
196198

197199
override async callServiceAPI(messages: Messages, pMessages: MessageContentI[], files?: File[]) {
198-
this.waitingForStreamResponse = false;
200+
this._waitingForStreamResponse = false;
199201
if (!this.connectSettings) throw new Error('Request settings have not been set up');
200-
this.rawBody.assistant_id ??= this.config.assistant_id || (await this.createNewAssistant());
202+
this.rawBody.assistant_id ??= this._config.assistant_id || (await this.createNewAssistant());
201203
// here instead of constructor as messages may be loaded later
202-
if (!this.searchedForThreadId) this.searchPreviousMessagesForThreadId(messages.messageToElements);
204+
if (!this._searchedForThreadId) this.searchPreviousMessagesForThreadId(messages.messageToElements);
203205
const uploadedFiles = files
204206
? await OpenAIAssistantUtils.storeFiles(this, messages, files, this.urlSegments.storeFiles)
205207
: undefined;
@@ -210,9 +212,9 @@ export class OpenAIAssistantIOI extends DirectServiceIO {
210212
private async createNewAssistant() {
211213
try {
212214
this.url = this.urlSegments.newAssistantUrl;
213-
const result = await OpenAIUtils.directFetch(this, JSON.parse(JSON.stringify(this.newAssistantDetails)), 'POST');
214-
this.config.assistant_id = (result as OpenAINewAssistantResult).id;
215-
return this.config.assistant_id;
215+
const result = await OpenAIUtils.directFetch(this, JSON.parse(JSON.stringify(this._newAssistantDetails)), 'POST');
216+
this._config.assistant_id = (result as OpenAINewAssistantResult).id;
217+
return this._config.assistant_id;
216218
} catch (e) {
217219
console.error(e);
218220
console.error('Failed to create a new assistant'); // letting later calls throw and handle error
@@ -223,13 +225,13 @@ export class OpenAIAssistantIOI extends DirectServiceIO {
223225
private searchPreviousMessagesForThreadId(messageToElements: MessageToElements) {
224226
const messageWithSession = messageToElements.find(([msgToEls]) => msgToEls._sessionId);
225227
if (messageWithSession) this.sessionId = messageWithSession[0]._sessionId;
226-
this.searchedForThreadId = true;
228+
this._searchedForThreadId = true;
227229
}
228230

229231
// prettier-ignore
230232
override async extractResultData(result: OpenAIAssistantInitReqResult):
231233
Promise<ResponseI | {makingAnotherRequest: true}> {
232-
if (this.waitingForStreamResponse || (this.isSSEStream && this.sessionId)) {
234+
if (this._waitingForStreamResponse || (this._isSSEStream && this.sessionId)) {
233235
return await this.handleStream(result);
234236
}
235237
if (result.error) {
@@ -242,7 +244,7 @@ export class OpenAIAssistantIOI extends DirectServiceIO {
242244
// https://platform.openai.com/docs/api-reference/runs/getRun
243245
const url = `${this.urlSegments.threadsPrefix}/${this.sessionId}/runs/${this.run_id}${this.urlSegments.threadsPosfix}`;
244246
const requestInit = {method: 'GET', headers: this.connectSettings?.headers};
245-
HTTPRequest.executePollRequest(this, url, requestInit, this.messages as Messages); // poll for run status
247+
HTTPRequest.executePollRequest(this, url, requestInit, this._messages as Messages); // poll for run status
246248
return {makingAnotherRequest: true};
247249
}
248250

@@ -257,8 +259,8 @@ export class OpenAIAssistantIOI extends DirectServiceIO {
257259
this.run_id = result.id;
258260
// updates the user sent message with the session id (the message event sent did not have this id)
259261
// user can clear the messages when they make a request, hence checking if messages length > 0
260-
if (this.messages && this.messages.messageToElements.length > 0) {
261-
this.messages.messageToElements[this.messages.messageToElements.length - 1][0]._sessionId = this.sessionId;
262+
if (this._messages && this._messages.messageToElements.length > 0) {
263+
this._messages.messageToElements[this._messages.messageToElements.length - 1][0]._sessionId = this.sessionId;
262264
}
263265
}
264266
}
@@ -276,7 +278,7 @@ export class OpenAIAssistantIOI extends DirectServiceIO {
276278
async extractPollResultData(result: OpenAIRunResult): PollResult {
277279
const {status, required_action} = result;
278280
if (status === 'queued' || status === 'in_progress') return {timeoutMS: OpenAIAssistantIOI.POLLING_TIMEOUT_MS};
279-
if (status === 'completed' && this.messages) {
281+
if (status === 'completed' && this._messages) {
280282
const threadMessages = await this.getThreadMessages(result.thread_id);
281283
const {text, files} = threadMessages.shift() as ResponseI;
282284
setTimeout(() => {
@@ -317,7 +319,7 @@ export class OpenAIAssistantIOI extends DirectServiceIO {
317319
const prefix = `${this.urlSegments.threadsPrefix}/${this.sessionId}`;
318320
const postfix = `/runs/${this.run_id}/submit_tool_outputs${this.urlSegments.threadsPosfix}`;
319321
this.url = `${prefix}${postfix}`;
320-
if (this.isSSEStream) {
322+
if (this._isSSEStream) {
321323
await this.createStreamRun({tool_outputs});
322324
} else {
323325
await OpenAIUtils.directFetch(this, {tool_outputs}, 'POST');
@@ -331,10 +333,10 @@ export class OpenAIAssistantIOI extends DirectServiceIO {
331333
this.run_id = result.id;
332334
return await this.handleTools(toolCalls);
333335
}
334-
if (this.waitingForStreamResponse) {
336+
if (this._waitingForStreamResponse) {
335337
return this.parseStreamResult(result);
336338
}
337-
if (this.isSSEStream && this.sessionId) {
339+
if (this._isSSEStream && this.sessionId) {
338340
// https://platform.openai.com/docs/api-reference/runs/createRun
339341
this.url = `${this.urlSegments.threadsPrefix}/${this.sessionId}/runs${this.urlSegments.threadsPosfix}`;
340342
const newBody = JSON.parse(JSON.stringify(this.rawBody));
@@ -345,14 +347,14 @@ export class OpenAIAssistantIOI extends DirectServiceIO {
345347

346348
// prettier-ignore
347349
private async parseStreamResult(result: OpenAIAssistantInitReqResult) {
348-
if (result.content && result.content.length > 0 && this.messages) {
350+
if (result.content && result.content.length > 0 && this._messages) {
349351
// if file is included and there is an annotation/link in text, process at the end
350352
const textContent = result.content.find((content) => content.text);
351353
if (textContent?.text?.annotations && textContent.text.annotations.length > 0) {
352354
const textFileFirst = result.content.find((content) => !!content.text) || result.content[0];
353355
const downloadCb = OpenAIAssistantUtils.getFilesAndText.bind(this,
354356
this, {role: 'assistant', content: result.content}, this.urlSegments, textFileFirst);
355-
this.messageStream?.endStreamAfterFileDownloaded(this.messages, downloadCb);
357+
this._messageStream?.endStreamAfterFileDownloaded(this._messages, downloadCb);
356358
return {text: ''};
357359
}
358360
}
@@ -377,7 +379,7 @@ export class OpenAIAssistantIOI extends DirectServiceIO {
377379
// eslint-disable-next-line @typescript-eslint/no-explicit-any
378380
private async createStreamRun(body: any) {
379381
body.stream = true;
380-
this.waitingForStreamResponse = true;
381-
this.messageStream = (await Stream.request(this, body, this.messages as Messages, true, true)) as MessageStream;
382+
this._waitingForStreamResponse = true;
383+
this._messageStream = (await Stream.request(this, body, this._messages as Messages, true, true)) as MessageStream;
382384
}
383385
}

component/src/services/utils/directServiceIO.ts

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -12,16 +12,16 @@ export class DirectServiceIO extends BaseServiceIO {
1212
insertKeyPlaceholderText = 'API Key';
1313
keyHelpUrl = '';
1414
sessionId?: string;
15-
private readonly keyVerificationDetails: KeyVerificationDetails;
16-
private readonly buildHeadersFunc: BuildHeadersFunc;
15+
private readonly _keyVerificationDetails: KeyVerificationDetails;
16+
private readonly _buildHeadersFunc: BuildHeadersFunc;
1717

1818
// prettier-ignore
1919
constructor(deepChat: DeepChat, keyVerificationDetails: KeyVerificationDetails,
2020
buildHeadersFunc: BuildHeadersFunc, apiKey?: APIKey, existingFileTypes?: ServiceFileTypes) {
2121
super(deepChat, existingFileTypes);
2222
Object.assign(this.rawBody, deepChat.connect?.additionalBodyProps);
23-
this.keyVerificationDetails = keyVerificationDetails;
24-
this.buildHeadersFunc = buildHeadersFunc;
23+
this._keyVerificationDetails = keyVerificationDetails;
24+
this._buildHeadersFunc = buildHeadersFunc;
2525
if (apiKey) this.setApiKeyProperties(apiKey);
2626
this.connectSettings = this.buildConnectSettings(this.key || '', deepChat.connect);
2727
}
@@ -34,7 +34,7 @@ export class DirectServiceIO extends BaseServiceIO {
3434
private buildConnectSettings(key: string, connectSettings?: Connect) {
3535
const connectSettingsObj = connectSettings ?? {};
3636
connectSettingsObj.headers ??= {};
37-
Object.assign(connectSettingsObj.headers, this.buildHeadersFunc(key));
37+
Object.assign(connectSettingsObj.headers, this._buildHeadersFunc(key));
3838
return connectSettingsObj;
3939
}
4040

@@ -46,8 +46,8 @@ export class DirectServiceIO extends BaseServiceIO {
4646

4747
// prettier-ignore
4848
override verifyKey(key: string, keyVerificationHandlers: KeyVerificationHandlers) {
49-
const {url, method, handleVerificationResult, createHeaders, body} = this.keyVerificationDetails;
50-
const headers = createHeaders?.(key) || this.buildHeadersFunc(key);
49+
const {url, method, handleVerificationResult, createHeaders, body} = this._keyVerificationDetails;
50+
const headers = createHeaders?.(key) || this._buildHeadersFunc(key);
5151
HTTPRequest.verifyKey(key, url, headers, method,
5252
this.keyAuthenticated.bind(this, keyVerificationHandlers.onSuccess), keyVerificationHandlers.onFail,
5353
keyVerificationHandlers.onLoad, handleVerificationResult, body);

component/src/views/chat/input/buttons/microphone/speechToText/silenceSubmit.ts

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -5,22 +5,22 @@ import {SpeechToText} from './speechToText';
55

66
export class SilenceSubmit {
77
private _silenceTimeout?: number;
8-
private readonly silenceMS: number = 2000;
9-
private readonly stop: boolean = true;
8+
private readonly _silenceMS: number = 2000;
9+
private readonly _stop: boolean = true;
1010

1111
constructor(submitAfterSilence: SubmitAfterSilence, stopAfterSubmit?: boolean) {
12-
if (typeof stopAfterSubmit === 'boolean' && stopAfterSubmit === false) this.stop = false;
13-
if (typeof submitAfterSilence === 'number') this.silenceMS = submitAfterSilence;
12+
if (typeof stopAfterSubmit === 'boolean' && stopAfterSubmit === false) this._stop = false;
13+
if (typeof submitAfterSilence === 'number') this._silenceMS = submitAfterSilence;
1414
}
1515

1616
private setSilenceTimeout(textInput: TextInputEl, buttonClick: () => void) {
1717
this._silenceTimeout = setTimeout(() => {
1818
textInput.submit?.();
1919
SpeechToElement.stop();
20-
if (!this.stop) {
20+
if (!this._stop) {
2121
setTimeout(buttonClick, SpeechToText.MICROPHONE_RESET_TIMEOUT_MS);
2222
}
23-
}, this.silenceMS);
23+
}, this._silenceMS);
2424
}
2525

2626
public clearSilenceTimeout() {

0 commit comments

Comments
 (0)