Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 6 additions & 12 deletions backend/src/libs/packages/api/base-http-api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import {
HTTPHeader,
} from '#libs/packages/http/http.js';
import { HTTPError } from '#libs/packages/http/http.js';
import { type ServerErrorResponse, type ValueOf } from '#libs/types/types.js';
import { type ValueOf } from '#libs/types/types.js';

import { type HTTPApi, type HTTPApiOptions } from './libs/types/types.js';

Expand Down Expand Up @@ -83,17 +83,11 @@ class BaseHttpApi implements HTTPApi {
return response;
}

private async handleError(response: Response): Promise<never> {
let parsedException: ServerErrorResponse;

try {
parsedException = (await response.json()) as ServerErrorResponse;
} catch {
parsedException = {
errorType: ServerErrorType.COMMON,
message: response.statusText,
};
}
private handleError(response: Response): Promise<never> {
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

we also need to catch and rethrow error in service, because we need to override status code, for example if open ai respond with 401, we don't want to respond with 401 because user will be signed out

const parsedException = {
errorType: ServerErrorType.COMMON,
message: response.statusText,
};

throw new HTTPError({
status: response.status as ValueOf<typeof HTTPCode>,
Expand Down
102 changes: 63 additions & 39 deletions backend/src/libs/packages/open-ai/open-ai.package.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
import { ContentType } from '#libs/enums/enums.js';
import { ChatError } from '#libs/exceptions/exceptions.js';
import { type ValueOf } from '#libs/types/types.js';

import { BaseHttpApi } from '../api/api.js';
import { type BaseHttp } from '../http/http.js';
import { type BaseHttp, HTTPCode, HTTPError } from '../http/http.js';
import { IMAGE_SIZE } from './libs/constants/constants.js';
import {
OpenAiApiPath,
Expand Down Expand Up @@ -48,55 +49,78 @@ class OpenAi extends BaseHttpApi {
public async getMessageResponse(
messages: OpenAiMessageGenerateRequestDto[],
): Promise<string | null> {
const data = await this.load<OpenAiMessageGenerateResponseDto>(
this.getFullEndpoint(
OpenAiApiPath.CHAT,
OpenAiChatApiPath.COMPLETIONS,
{},
),
{
method: 'POST',
payload: JSON.stringify({
model: this.model,
messages,
}),
token: this.apiKey,
contentType: ContentType.JSON,
},
);
try {
const data = await this.load<OpenAiMessageGenerateResponseDto>(
this.getFullEndpoint(
OpenAiApiPath.CHAT,
OpenAiChatApiPath.COMPLETIONS,
{},
),
{
method: 'POST',
payload: JSON.stringify({
model: this.model,
messages,
}),
token: this.apiKey,
contentType: ContentType.JSON,
},
);

const [response] = data.choices;
const [response] = data.choices;

return response?.message.content ?? null;
return response?.message.content ?? null;
} catch (error: unknown) {
this.throwError(error);
}
}

public async generateImages({
prompt,
number = this.defaultImageGenerateConfig.number,
size = this.defaultImageGenerateConfig.size,
}: OpenAiImageGenerateRequestDto): Promise<string | null> {
const data = await this.load<OpenAiImageGenerateResponseDto>(
this.getFullEndpoint(
OpenAiApiPath.IMAGES,
OpenAiImagesApiPath.GENERATIONS,
{},
),
{
method: 'POST',
payload: JSON.stringify({
prompt,
n: number,
size,
response_format: this.defaultImageGenerateConfig.responseFormat,
}),
token: this.apiKey,
contentType: ContentType.JSON,
},
);
try {
const data = await this.load<OpenAiImageGenerateResponseDto>(
this.getFullEndpoint(
OpenAiApiPath.IMAGES,
OpenAiImagesApiPath.GENERATIONS,
{},
),
{
method: 'POST',
payload: JSON.stringify({
prompt,
n: number,
size,
response_format: this.defaultImageGenerateConfig.responseFormat,
}),
token: this.apiKey,
contentType: ContentType.JSON,
},
);

const [response] = data.data;
const [response] = data.data;

return response?.b64_json ?? null;
return response?.b64_json ?? null;
} catch (error: unknown) {
this.throwError(error);
}
}

private throwError(error: unknown): never {
if (error instanceof HTTPError) {
if (error.status === HTTPCode.UNAUTHORIZED) {
throw new ChatError({
message: error.message,
status: HTTPCode.BAD_REQUEST,
});
}

throw new ChatError({ message: error.message, status: error.status });
}

throw new ChatError({});
}
}

Expand Down