π¨ The ultimate agentic social media scheduling tool π€
TypeScript nextjsopen-sourceopen-source-social-media-scheduling-toolosspostiz-cloudpostiz-hostedredisscheduling-toolsocial-media-scheduling-tooltypescript
fix: translate AI generation provider errors into clean responses
Gilad Resisi1785cf916d92
diff --git a/libraries/nestjs-libraries/src/agent/agent.graph.service.ts b/libraries/nestjs-libraries/src/agent/agent.graph.service.tsindex 567708cc9..ada9684da 100644--- a/libraries/nestjs-libraries/src/agent/agent.graph.service.ts+++ b/libraries/nestjs-libraries/src/agent/agent.graph.service.ts@@ -15,6 +15,7 @@ import { z } from 'zod';import { MediaService } from '@gitroom/nestjs-libraries/database/prisma/media/media.service';import { UploadFactory } from '@gitroom/nestjs-libraries/upload/upload.factory';import { GeneratorDto } from '@gitroom/nestjs-libraries/dtos/generator/generator.dto';+import { generationError } from '@gitroom/nestjs-libraries/openai/generation.error';const tools = !process.env.TAVILY_API_KEY? []@@ -318,19 +319,23 @@ export class AgentGraphService {return {};}- const newContent = await Promise.all(- (state.content || []).map(async (p) => {- const image = await dalle.invoke(p.prompt!);- return {- ...p,- image,- };- })- );+ try {+ const newContent = await Promise.all(+ (state.content || []).map(async (p) => {+ const image = await dalle.invoke(p.prompt!);+ return {+ ...p,+ image,+ };+ })+ );- return {- content: newContent,- };+ return {+ content: newContent,+ };+ } catch (err) {+ throw generationError(err);+ }}async uploadPictures(state: WorkflowChannelsState) {diff --git a/libraries/nestjs-libraries/src/database/prisma/media/media.service.ts b/libraries/nestjs-libraries/src/database/prisma/media/media.service.tsindex 2b9f39cfb..1d1164a91 100644--- a/libraries/nestjs-libraries/src/database/prisma/media/media.service.ts+++ b/libraries/nestjs-libraries/src/database/prisma/media/media.service.ts@@ -1,6 +1,7 @@import { HttpException, Injectable } from '@nestjs/common';import { MediaRepository } from '@gitroom/nestjs-libraries/database/prisma/media/media.repository';import { OpenaiService } from '@gitroom/nestjs-libraries/openai/openai.service';+import { generationError } from '@gitroom/nestjs-libraries/openai/generation.error';import { SubscriptionService } from '@gitroom/nestjs-libraries/database/prisma/subscriptions/subscription.service';import { Organization } from '@prisma/client';import { SaveMediaInformationDto } from '@gitroom/nestjs-libraries/dtos/media/save.media.information.dto';@@ -37,19 +38,23 @@ export class MediaService {org: Organization,generatePromptFirst?: boolean) {- const generating = await this._subscriptionService.useCredit(- org,- 'ai_images',- async () => {- if (generatePromptFirst) {- prompt = await this._openAi.generatePromptForPicture(prompt);- console.log('Prompt:', prompt);+ try {+ const generating = await this._subscriptionService.useCredit(+ org,+ 'ai_images',+ async () => {+ if (generatePromptFirst) {+ prompt = await this._openAi.generatePromptForPicture(prompt);+ console.log('Prompt:', prompt);+ }+ return this._openAi.generateImage(prompt);}- return this._openAi.generateImage(prompt);- }- );+ );- return generating;+ return generating;+ } catch (err) {+ throw generationError(err);+ }}saveFile(org: string, fileName: string, filePath: string, originalName?: string) {@@ -82,44 +87,51 @@ export class MediaService {}async generateVideo(org: Organization, body: VideoDto) {- const totalCredits = await this._subscriptionService.checkCredits(- org,- 'ai_videos'- );-- if (totalCredits.credits <= 0) {- throw new SubscriptionException({- action: AuthorizationActions.Create,- section: Sections.VIDEOS_PER_MONTH,- });- }+ try {+ const totalCredits = await this._subscriptionService.checkCredits(+ org,+ 'ai_videos'+ );- const video = this._videoManager.getVideoByName(body.type);- if (!video) {- throw new Error(`Video type ${body.type} not found`);- }+ if (totalCredits.credits <= 0) {+ throw new SubscriptionException({+ action: AuthorizationActions.Create,+ section: Sections.VIDEOS_PER_MONTH,+ });+ }- if (!video.trial && org.isTrailing) {- throw new HttpException('This video is not available in trial mode', 406);- }+ const video = this._videoManager.getVideoByName(body.type);+ if (!video) {+ throw new Error(`Video type ${body.type} not found`);+ }- console.log(body.customParams);- await video.instance.processAndValidate(body.customParams);- console.log('no err');-- return await this._subscriptionService.useCredit(- org,- 'ai_videos',- async () => {- const loadedData = await video.instance.process(- body.output,- body.customParams+ if (!video.trial && org.isTrailing) {+ throw new HttpException(+ 'This video is not available in trial mode',+ 406);-- const file = await this.storage.uploadSimple(loadedData);- return this.saveFile(org.id, file.split('/').pop(), file);}- );++ console.log(body.customParams);+ await video.instance.processAndValidate(body.customParams);+ console.log('no err');++ return await this._subscriptionService.useCredit(+ org,+ 'ai_videos',+ async () => {+ const loadedData = await video.instance.process(+ body.output,+ body.customParams+ );++ const file = await this.storage.uploadSimple(loadedData);+ return this.saveFile(org.id, file.split('/').pop(), file);+ }+ );+ } catch (err) {+ throw generationError(err);+ }}async videoFunction(identifier: string, functionName: string, body: any) {diff --git a/libraries/nestjs-libraries/src/openai/generation.error.ts b/libraries/nestjs-libraries/src/openai/generation.error.tsnew file mode 100644index 000000000..90f710865--- /dev/null+++ b/libraries/nestjs-libraries/src/openai/generation.error.ts@@ -0,0 +1,42 @@+import { HttpException } from '@nestjs/common';++// e.g. "400 Your request was rejected by the safety system, safety_violations=[sexual]"+const SAFETY_VIOLATIONS_REGEX = /safety_violations=\[([^\]]*)\]/i;++// Match genuine content-safety rejections by message, NOT by a bare 400 status:+// a 400 can just as easily be an invalid-parameter error, which must not be+// reported to the user as a safety violation.+const SAFETY_MESSAGE_REGEX =+ /safety system|safety_violations|content[ _]policy|rejected as a result of our safety|moderation/i;++/**+ * Normalizes errors thrown by AI generation providers (OpenAI image/chat,+ * LangChain DALL-E, Fal, Veo3, HeyGen, ElevenLabs, ...) into a clean+ * HttpException so a provider rejection (most notably an OpenAI safety+ * violation) returns a proper response instead of crashing the backend.+ *+ * When the provider reports a content-safety rejection, the flagged+ * category/categories are surfaced back to the user.+ */+export function generationError(err: any): HttpException {+ // Preserve errors we already raised intentionally (e.g. SubscriptionException).+ if (err instanceof HttpException) {+ return err;+ }++ const message: string =+ err?.error?.message || err?.message || String(err || '');++ if (SAFETY_MESSAGE_REGEX.test(message)) {+ const categories = message.match(SAFETY_VIOLATIONS_REGEX)?.[1]?.trim();+ const detail = categories ? ` Flagged categories: ${categories}.` : '';+ return new HttpException(+ `Your request was rejected by the AI safety system.${detail} Please adjust your prompt and try again.`,+ 422+ );+ }++ // Not a recognized safety rejection (e.g. an invalid-parameter 400) β return+ // a generic message rather than mislabeling it as a content-safety issue.+ return new HttpException('AI generation failed, please try again later.', 500);+}