🎬 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
fix: resolve AI text and slideshow duration issues
darkzOGxe26792ae00dc
diff --git a/test.js b/test.jsindex f21f3b7..d526934 100644--- a/test.js+++ b/test.js@@ -46,6 +46,7 @@ class SystemTest {{ name: 'Placeholder Scheduling Guard', test: () => this.testPlaceholderSchedulingGuard() },{ name: 'FFmpeg Resolution', test: () => this.testFFmpegResolution() },{ name: 'Gemini Media Provider Selection', test: () => this.testGeminiMediaProvider() },+ { name: 'Slideshow Duration Selection', test: () => this.testSlideshowDurationSelection() },{ name: 'Slideshow Renderer', test: () => this.testSlideshowRenderer() },{ name: 'Evergreen Template Topics', test: () => this.testEvergreenTopics() },{ name: 'Walkthrough Module', test: () => this.testWalkthroughModule() },@@ -2427,6 +2428,47 @@ class SystemTest {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');+ // Some reasoning models reject any explicit non-default temperature. The+ // request should be retried once without that optional parameter while+ // preserving the modern token parameter and all other request details.+ const temperatureCalls = [];+ service.client.chat.completions.create = async (params) => {+ temperatureCalls.push(params);+ if (temperatureCalls.length === 1) {+ const err = new Error("Unsupported value: 'temperature' does not support 0.2 with this model. Only the default (1) value is supported.");+ err.status = 400;+ throw err;+ }+ return { choices: [{ message: { content: 'temperature-ok' } }] };+ };+ const temperatureResult = await service.generateText('temperature prompt', { maxTokens: 321, temperature: 0.2 });+ if (temperatureResult !== 'temperature-ok') throw new Error('Temperature fallback did not return content');+ if (temperatureCalls.length !== 2) throw new Error('Expected exactly one retry without temperature');+ if (temperatureCalls[0].temperature !== 0.2 || temperatureCalls[0].max_completion_tokens !== 321) {+ throw new Error('Initial request did not preserve the requested sampling and token parameters');+ }+ if ('temperature' in temperatureCalls[1] || temperatureCalls[1].max_completion_tokens !== 321) {+ throw new Error('Temperature retry must omit only temperature and preserve max_completion_tokens');+ }++ // Do not hide unrelated 400s merely because their message mentions temperature.+ let invalidTemperatureAttempts = 0;+ service.client.chat.completions.create = async () => {+ invalidTemperatureAttempts++;+ const err = new Error('temperature must be between 0 and 2');+ err.status = 400;+ throw err;+ };+ let invalidTemperatureRejected = false;+ try {+ await service.generateText('invalid temperature prompt', { temperature: 3 });+ } catch (error) {+ invalidTemperatureRejected = /between 0 and 2/i.test(error.message);+ }+ if (!invalidTemperatureRejected || invalidTemperatureAttempts !== 1) {+ throw new Error('Unrelated temperature validation errors must surface without retry');+ }+// 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: '' } }] });@@ -2634,7 +2676,7 @@ class SystemTest {async testSlideshowRenderer() {const { AIVideoGenerator } = require('./utils/ai-video-generator');- const { checkFFmpeg } = require('./utils/ffmpeg');+ const { checkFFmpeg, getMediaDuration } = require('./utils/ffmpeg');const fs = require('fs').promises;const os = require('os');@@ -2697,6 +2739,10 @@ class SystemTest {if (!stats.size) {throw new Error('Rendered slideshow video is empty');}+ const renderedDuration = await getMediaDuration(videoPath);+ if (renderedDuration < 5.8 || renderedDuration > 6.2) {+ throw new Error(`Crossfades changed the requested 6s slideshow duration to ${renderedDuration}s`);+ }// Missing narration must fail closed unless the operator explicitly confirmed silence.const finalPath = path.join(dir, 'final.mp4');@@ -2727,6 +2773,38 @@ class SystemTest {this.logger.info('Slideshow renderer test completed successfully');}+ async testSlideshowDurationSelection() {+ const { AIVideoGenerator } = require('./utils/ai-video-generator');+ const script = {+ hook: { text: 'Hi.' },+ introduction: { greeting: '', topicIntro: '' },+ mainContent: { sections: [] },+ conclusion: { finalThought: '' }+ };++ let probedPath = null;+ const measuredGenerator = new AIVideoGenerator({}, {+ getMediaDuration: async audioPath => {+ probedPath = audioPath;+ return 40;+ }+ });+ const measuredDuration = await measuredGenerator.resolveSlideshowDuration(script, 'narration.mp3');+ if (probedPath !== 'narration.mp3' || measuredDuration !== 40.5) {+ throw new Error(`Slideshow duration must use real narration length plus margin; got ${measuredDuration}`);+ }++ const fallbackGenerator = new AIVideoGenerator({}, {+ getMediaDuration: async () => { throw new Error('probe unavailable'); }+ });+ const fallbackDuration = await fallbackGenerator.resolveSlideshowDuration(script, 'narration.mp3');+ if (fallbackDuration !== 30) {+ throw new Error(`Unavailable narration probe must use the 30s script estimate; got ${fallbackDuration}`);+ }++ this.logger.info('Slideshow duration selection test completed successfully');+ }+async testEvergreenTopics() {const { ContentStrategyAgent } = require('./agents/content-strategy-agent');const agent = new ContentStrategyAgent(null, {});diff --git a/utils/ai-text-service.js b/utils/ai-text-service.jsindex 0c2d99d..a123df5 100644--- a/utils/ai-text-service.js+++ b/utils/ai-text-service.js@@ -132,30 +132,50 @@ class AITextService {temperature,};- 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,- });+ const tokenParams = [+ { max_completion_tokens: maxTokens },+ { max_tokens: maxTokens },+ ];++ let lastError = null;+ for (let index = 0; index < tokenParams.length; index++) {+ const request = { ...params, ...tokenParams[index] };+ try {+ const response = await this.client.chat.completions.create(request);return this._extractContent(response);+ } catch (error) {+ lastError = error;+ const message = error?.message || '';+ const unsupportedTemperature =+ error?.status === 400 &&+ /temperature/i.test(message) &&+ /(unsupported value|does not support|only the default)/i.test(message);++ if (unsupportedTemperature) {+ const { temperature: _temperature, ...withoutTemperature } = request;+ try {+ const response = await this.client.chat.completions.create(withoutTemperature);+ return this._extractContent(response);+ } catch (retryError) {+ lastError = retryError;+ }+ }++ // Older models and some providers reject max_completion_tokens with a+ // 400; retry with the legacy max_tokens spelling. This also applies if+ // the temperature-compatible retry exposed the token incompatibility.+ if (+ index === 0 &&+ lastError?.status === 400 &&+ /max(_completion)?_tokens/i.test(lastError.message || '')+ ) {+ continue;+ }+ throw lastError;}- throw error;}++ throw lastError;}_extractContent(response) {diff --git a/utils/ai-video-generator.js b/utils/ai-video-generator.jsindex ccd30a0..a33e5db 100644--- a/utils/ai-video-generator.js+++ b/utils/ai-video-generator.js@@ -5,7 +5,7 @@ const path = require('path');const axios = require('axios');const sharp = require('sharp');const { Logger } = require('./logger');-const { runFFmpeg, checkFFmpeg, ffmpegInstallHint } = require('./ffmpeg');+const { runFFmpeg, getMediaDuration, checkFFmpeg, ffmpegInstallHint } = require('./ffmpeg');const { MediaGenerationService } = require('./media-generation-service');class AIVideoGenerator {@@ -13,6 +13,7 @@ class AIVideoGenerator {this.logger = new Logger('AIVideoGenerator');const resolvedCredentials = credentials?.credentials || credentials || {};this.db = options.db || null;+ this.getMediaDuration = options.getMediaDuration || getMediaDuration;this.lastVideoResult = null;this.lastNarrationResult = null;@@ -508,7 +509,7 @@ class AIVideoGenerator {}const videoPath = outputPath.replace('.mp4', '_visual.mp4');- const duration = this.calculateScriptDuration(script);+ const duration = await this.resolveSlideshowDuration(script, audioPath);await this.renderSlidesToVideo(stills, duration, videoPath);// Add audio@@ -521,13 +522,23 @@ class AIVideoGenerator {}}+ async resolveSlideshowDuration(script, audioPath) {+ try {+ return (await this.getMediaDuration(audioPath)) + 0.5;+ } catch (error) {+ this.logger.warn(`Could not read narration duration, falling back to word-count estimate: ${error.message}`);+ return this.calculateScriptDuration(script);+ }+ }+async renderSlidesToVideo(stills, totalDuration, videoPath) {if (stills.length === 0) {throw new Error('No slides to render');}const fade = 0.5;- const perSlide = Math.max(2, totalDuration / stills.length);+ const overlapDuration = fade * Math.max(0, stills.length - 1);+ const perSlide = Math.max(2, (totalDuration + overlapDuration) / stills.length);const args = ['-y'];for (const still of stills) {