🎬 Open-source, self-hosted AI agent that runs a YouTube channel end to end: researches topics, writes scripts, generates narration, visuals and video, optimizes SEO, and publishes after your approval, then learns from analytics. Works with Gemini, OpenAI, OpenRouter, DeepSeek and more.
JavaScript ai-agentsautomationcontent-automationcontent-creationcontent-strategygoogle-geminijavascriptnodejsopenaiself-hostedseo-optimizationsocial-media-automationthumbnail-generatorvideo-generationyoutube-apiyoutube-automationyoutube-botyoutube-channelyoutube-shortsyoutube-uploader
v2.4.2: Fix OpenAI max_tokens 400, empty AI responses, and silent video generation errors
darkzOGxe5dda920bc59
diff --git a/package-lock.json b/package-lock.jsonindex d1d9b1b..e1847a7 100644--- a/package-lock.json+++ b/package-lock.json@@ -1,6 +1,6 @@{"name": "youtube-automation-agent",- "version": "2.4.1",+ "version": "2.4.2","lockfileVersion": 3,"requires": true,"packages": {diff --git a/package.json b/package.jsonindex bb5f54b..3207a81 100644--- a/package.json+++ b/package.json@@ -1,6 +1,6 @@{"name": "youtube-automation-agent",- "version": "2.4.1",+ "version": "2.4.2","description": "Fully automated YouTube channel management system with specialized AI agents","main": "index.js","scripts": {diff --git a/test.js b/test.jsindex bf81706..b6a3ae9 100644--- a/test.js+++ b/test.js@@ -21,6 +21,7 @@ class SystemTest {{ name: 'API Validation and Security', test: () => this.testAPIValidationAndSecurity() },{ name: 'Publishing Safety', test: () => this.testPublishingSafety() },{ name: 'Multi-Provider Credential Validation', test: () => this.testCredentialValidation() },+ { name: 'AI Text Service Token Compatibility', test: () => this.testAITextServiceTokenParams() },{ name: 'Placeholder Scheduling Guard', test: () => this.testPlaceholderSchedulingGuard() },{ name: 'FFmpeg Resolution', test: () => this.testFFmpegResolution() },{ name: 'Gemini Media Provider Selection', test: () => this.testGeminiMediaProvider() },@@ -328,6 +329,69 @@ class SystemTest {this.logger.info('Credential validation test completed successfully');}+ async testAITextServiceTokenParams() {+ const { AITextService } = require('./utils/ai-text-service');++ const savedEnv = process.env.OPENAI_API_KEY;+ delete process.env.OPENAI_API_KEY;+ try {+ const service = new AITextService({+ aiProvider: { provider: 'openai', apiKey: 'test-key', model: 'gpt-5.5' }+ });++ // Newer OpenAI models (gpt-5.x) reject max_tokens — the request must use+ // max_completion_tokens, never the legacy spelling.+ const calls = [];+ service.client.chat.completions.create = async (params) => {+ calls.push(params);+ return { choices: [{ message: { content: '{"ok":true}' } }] };+ };++ const result = await service.generateText('test prompt', { maxTokens: 512 });+ if (result !== '{"ok":true}') throw new Error('generateText did not return the model content');+ if (calls[0].max_completion_tokens !== 512) {+ throw new Error('Modern models must receive max_completion_tokens, not max_tokens');+ }+ if (calls[0].max_tokens !== undefined) {+ throw new Error('Legacy max_tokens must not be sent to modern models');+ }++ // Legacy models reject max_completion_tokens with a 400 — the service must+ // retry the identical request using max_tokens.+ let attempt = 0;+ service.client.chat.completions.create = async (_params) => {+ attempt++;+ if (attempt === 1) {+ const err = new Error("Unsupported parameter: 'max_completion_tokens' is not supported with this model.");+ err.status = 400;+ throw err;+ }+ return { choices: [{ message: { content: 'legacy-ok' } }] };+ };+ const legacyResult = await service.generateText('legacy prompt');+ if (legacyResult !== 'legacy-ok') throw new Error('Legacy fallback did not return content');+ if (attempt !== 2) throw new Error('Expected exactly one retry with max_tokens');++ // An empty model body must surface as a descriptive error, not the cryptic+ // "Unexpected end of JSON input" the agents used to log.+ service.client.chat.completions.create = async () => ({ choices: [{ message: { content: '' } }] });+ let emptyRejected = false;+ try {+ await service.generateText('empty prompt');+ } catch (error) {+ emptyRejected = /empty response/i.test(error.message);+ }+ if (!emptyRejected) {+ throw new Error('Empty response was not rejected with a descriptive error');+ }+ } finally {+ if (savedEnv === undefined) delete process.env.OPENAI_API_KEY;+ else process.env.OPENAI_API_KEY = savedEnv;+ }++ this.logger.info('AI text service token parameter test completed successfully');+ }+async testPlaceholderSchedulingGuard() {const { PublishingSchedulingAgent } = require('./agents/publishing-scheduling-agent');const agent = new PublishingSchedulingAgent({diff --git a/utils/ai-text-service.js b/utils/ai-text-service.jsindex 89a061a..8c639d5 100644--- a/utils/ai-text-service.js+++ b/utils/ai-text-service.js@@ -104,21 +104,68 @@ class AITextService {contents: prompt,config: { maxOutputTokens: maxTokens, temperature },});- return response.text;+ const text = response && response.text;+ if (typeof text !== 'string' || !text.trim()) {+ throw new Error(+ `${this.providerName} returned an empty response. Check the API key and model quota — free-tier Gemini keys are rate-limited and can return empty output.`+ );+ }+ return text;}if (!this.client) {throw new Error('No AI text provider configured');}- const response = await this.client.chat.completions.create({+ const params = {model,messages: [{ role: 'user', content: prompt }],- max_tokens: maxTokens,temperature,- });+ };- return response.choices[0].message.content;+ try {+ // Newer OpenAI models (gpt-5.x and later) reject the legacy max_tokens+ // parameter with a 400 error and require max_completion_tokens instead.+ const response = await this.client.chat.completions.create({+ ...params,+ max_completion_tokens: maxTokens,+ });+ return this._extractContent(response);+ } catch (error) {+ // Older models and some providers reject max_completion_tokens with a 400;+ // retry the same request using the legacy max_tokens spelling.+ if (+ error &&+ error.status === 400 &&+ /max(_completion)?_tokens/i.test(error.message || '')+ ) {+ const response = await this.client.chat.completions.create({+ ...params,+ max_tokens: maxTokens,+ });+ return this._extractContent(response);+ }+ throw error;+ }+ }++ _extractContent(response) {+ const content =+ response &&+ response.choices &&+ response.choices[0] &&+ response.choices[0].message+ ? response.choices[0].message.content+ : null;++ if (typeof content !== 'string' || !content.trim()) {+ // A null/empty body used to surface as cryptic "Unexpected end of JSON input"+ // in the agents' JSON parsers. Report the real cause instead.+ throw new Error(+ `${this.providerName} returned an empty response. Check the API key and model quota.`+ );+ }+ return content;}isAvailable() {diff --git a/utils/ai-video-generator.js b/utils/ai-video-generator.jsindex 802c811..25ee080 100644--- a/utils/ai-video-generator.js+++ b/utils/ai-video-generator.js@@ -279,7 +279,11 @@ class AIVideoGenerator {// Fallback to simple slideshow with Playwrightreturn await this.generateSlideshowVideo(script, visualAssets, audioPath, outputPath);} catch (error) {- this.logger.error('Video generation failed:', error);+ // The Logger's console line only shows the message string, so put the real+ // reason inline. Previously the stack alone went to the file transport and+ // the console printed "Video generation failed:" with no detail.+ const reason = error && error.message ? error.message : String(error);+ this.logger.error(`Video generation failed: ${reason}`, error);return await this.simulateVideoGeneration(script, visualAssets, audioPath, outputPath);}}