[name used in prompts, prompt block listing its tokens]. * * @var array */ const FIELDS = array( 'title' => array( 'meta title', 'meta_title_tokens' ), 'description' => array( 'meta description', 'meta_description_tokens' ), ); /** * The fewest characters each AI token of a field is given. Squeezed * below this, a key feature comes back as a filler word that repeats the * name ("Chunky Knit Turtleneck Sweater | Chunky | ..."), so the token is * left out instead (the same floor TitleGenerator uses). */ const MIN_AI_PART_CHARS = 10; /** * The characters a call's AI parts of one field share: the field's * target range minus what its other parts and separators already take. * * @param array $field SeoMetaStructure title or description. * @param array $known Text of every other part the finished field shows, by token id. * @param string[] $ai_ids Token ids the AI writes in this call. * @param callable $join The field's joiner (SeoMetaAssembly::titleJoiner() or joinDescriptionTokens()). * @return array{targetMin:int,targetMax:int,min:int,max:int,count:int}|null Null when the call writes none of the field or its other parts leave each AI token less than MIN_AI_PART_CHARS. */ public static function budget( array $field, array $known, array $ai_ids, callable $join ): ?array { $count = count( $ai_ids ); if ( 0 === $count ) { return null; } $fixed = self::joinedLength( $field['tokens'], $known + array_fill_keys( $ai_ids, 'x' ), $join ) - $count; list( $target_min, $target_max ) = self::targetRange( $field ); $max = $target_max - $fixed; if ( $max < self::MIN_AI_PART_CHARS * $count ) { return null; } return array( 'targetMin' => $target_min, 'targetMax' => $target_max, 'min' => max( 0, $target_min - $fixed ), 'max' => $max, 'count' => $count, ); } /** * The field's target range, its top capped by the hard limit. * * @param array $field SeoMetaStructure title or description. * @return int[] [min, max]. */ public static function targetRange( array $field ): array { $max = min( (int) $field['targetMax'], (int) $field['hardMax'] ); return array( min( (int) $field['targetMin'], $max ), $max ); } /** * Characters the field shows when joined from $values in token order. * * @param array[] $tokens The field's SeoToken list, in order. * @param array $values Text per token id; a token without one is left out. * @param callable $join The field's joiner. * @return int */ public static function joinedLength( array $tokens, array $values, callable $join ): int { $included = array(); foreach ( $tokens as $token ) { $value = (string) ( $values[ (string) $token['id'] ] ?? '' ); if ( '' !== trim( $value ) ) { $included[] = array( 'value' => $value ); } } return (int) call_user_func( $join, $included )['len']; } /** * How far a length lands outside the field's target range: 0 inside it. * * @param array $field SeoMetaStructure title or description. * @param int $len Characters of the finished field. * @return int */ public static function distance( array $field, int $len ): int { list( $min, $max ) = self::targetRange( $field ); return $len < $min ? $min - $len : max( 0, $len - $max ); } /** * Prompt line giving one field's AI parts their budget. * * @param string $key 'title' | 'description'. * @param array $budget budget()'s result. * @param bool $variants Whether the call asks for alternatives. * @return string */ public static function promptLine( string $key, array $budget, bool $variants = false ): string { list( $name, $block ) = self::FIELDS[ $key ]; $line = 'Length: the finished ' . $name . ' is ' . $budget['targetMin'] . '-' . $budget['targetMax'] . ' characters, separators and its other parts included. ' . 'Your <' . $block . '> values must total ' . self::span( $budget['min'], $budget['max'] ) . ' characters together' . ( $variants ? ' in every alternative' : '' ); if ( $budget['count'] > 1 ) { $line .= ', about ' . self::span( intdiv( $budget['min'], $budget['count'] ), intdiv( $budget['max'], $budget['count'] ) ) . ' per token'; } return $line . '.'; } /** * Retry note for an AI part of a field that missed its target range. * * @param string $key 'title' | 'description'. * @param array $field SeoMetaStructure title or description. * @param int $len Characters of the finished field. * @return string */ public static function missNote( string $key, array $field, int $len ): string { list( $min, $max ) = self::targetRange( $field ); $name = self::FIELDS[ $key ][0]; return $len < $min ? 'the finished ' . $name . ' came out at ' . $len . ' characters, under its ' . $min . '-' . $max . ' target: write this part longer' : 'the finished ' . $name . ' came out at ' . $len . ' characters, over its ' . $min . '-' . $max . ' target: write this part shorter'; } /** * Each field's view, taken before a round resolves its pending tokens. * * @param array $structure Normalized SeoMetaStructure. * @param array $title_state resolveFieldTokens()'s result for the title. * @param array $desc_state resolveFieldTokens()'s result for the description. * @return array Keyed 'title' and 'description'. */ public static function views( array $structure, array $title_state, array $desc_state ): array { return array( 'title' => array( 'field' => $structure['title'], 'state' => $title_state, 'join' => SeoMetaAssembly::titleJoiner( (string) $structure['title']['separator'] ) ), 'description' => array( 'field' => $structure['description'], 'state' => $desc_state, 'join' => array( SeoMetaAssembly::class, 'joinDescriptionTokens' ) ), ); } /** * @param array $views views()'s result. * @return array Pending AI token ids, per field. */ public static function pendingIds( array $views ): array { return array_map( static function ( array $view ): array { return array_map( 'strval', array_keys( $view['state']['pending'] ) ); }, $views ); } /** * The pending AI tokens of each field that get no room: the field's other * parts leave them less than MIN_AI_PART_CHARS each. The last token goes * first, so the ones before it keep a usable share. * * @param array $views views()'s result. * @param string $keyword The value a deferred keyword token will show; '' while unknown. * @return array Token ids to leave out, per field. */ public static function idsWithoutRoom( array $views, string $keyword ): array { $without = array( 'title' => array(), 'description' => array() ); foreach ( $views as $key => $view ) { $ids = array_map( 'strval', array_keys( $view['state']['pending'] ) ); $known = self::knownTexts( $view['state'], $keyword ); while ( ! empty( $ids ) && null === self::budget( $view['field'], $known, $ids, $view['join'] ) ) { $without[ $key ][] = array_pop( $ids ); } } return $without; } /** * Prompt lines giving each field's AI parts in a call their share of * the field's target length; the meta title also shows where its parts * sit, so they add new words instead of repeating the name. * * @param array $views views()'s result. * @param array $call_ids Token ids the call writes, per field. * @param array> $answers Earlier answers the call keeps, per field. * @param string $keyword The value a deferred keyword token will show; '' while unknown. * @param bool $variants Whether the call asks for alternatives. * @return string[] */ public static function promptLines( array $views, array $call_ids, array $answers, string $keyword, bool $variants ): array { $lines = array(); foreach ( $views as $key => $view ) { $ids = $call_ids[ $key ] ?? array(); $known = self::knownTexts( $view['state'], $keyword ) + array_diff_key( $answers[ $key ] ?? array(), array_flip( $ids ) ); $budget = self::budget( $view['field'], $known, $ids, $view['join'] ); if ( 'title' === $key && ! empty( $ids ) ) { $shape = $known; foreach ( $ids as $id ) { $shape[ $id ] = '[' . $id . ']'; } $values = array(); foreach ( $view['field']['tokens'] as $token ) { $value = (string) ( $shape[ (string) $token['id'] ] ?? '' ); if ( '' !== trim( $value ) ) { $values[] = array( 'value' => $value ); } } $lines[] = 'The finished meta title reads: "' . call_user_func( $view['join'], $values )['text'] . '", with each [token id] replaced by your text. Write each one so it adds information the rest of the title does not give: never repeat a word that is already in it.'; } if ( 'description' === $key && ! empty( $ids ) ) { $lines[] = 'The values are joined in order into consecutive sentences: write each one as a complete sentence that starts with a capital letter, and never repeat a phrase that another token already uses.'; } if ( null !== $budget ) { $lines[] = self::promptLine( $key, $budget, $variants ); } } return $lines; } /** * Ask again for every AI part of a field whose first answer leaves the * finished field outside its target length, when those parts can fix * it. A part already asked again for another reason keeps that note, * and a field with a missing part is left out: its length is unknown. * * @param array $views views()'s result. * @param array> $texts Clean first-answer text per token id, per field. * @param string $keyword The value a deferred keyword token will show. * @param array &$retry_ids Ids to ask again, per field, updated in place. * @param array &$notes Retry note per id, updated in place. * @return array The ids asked again for their field's length only, per field. */ public static function queueRetries( array $views, array $texts, string $keyword, array &$retry_ids, array &$notes ): array { $length_only = array( 'title' => array(), 'description' => array() ); foreach ( $views as $key => $view ) { $ids = array_map( 'strval', array_keys( $view['state']['pending'] ) ); if ( empty( $ids ) || count( array_intersect_key( $texts[ $key ], $view['state']['pending'] ) ) < count( $ids ) ) { continue; } $known = self::knownTexts( $view['state'], $keyword ); $len = self::joinedLength( $view['field']['tokens'], $known + $texts[ $key ], $view['join'] ); if ( 0 === self::distance( $view['field'], $len ) || null === self::budget( $view['field'], $known, $ids, $view['join'] ) ) { continue; } foreach ( $ids as $id ) { if ( in_array( $id, $retry_ids[ $key ], true ) ) { continue; } $retry_ids[ $key ][] = $id; $notes[ $id ] = self::missNote( $key, $view['field'], $len ); $length_only[ $key ][] = $id; } } return $length_only; } /** * The length-only retried ids whose first answer stays: the retry did * not bring their field closer to its target length, or did not answer * every one of them cleanly and without a banned phrase. A retry for a * better length never leaves a field worse than the first answer. * * @param array $views views()'s result. * @param array $length_only queueRetries()'s result. * @param array> $before Clean first-answer text per token id, per field. * @param array> $after Clean text per token id once the retry is merged, per field. * @param string $keyword The value a deferred keyword token will show. * @param OutputValidator $validator Banned-phrase matcher. * @param string[] $banned Merged banned phrases. * @return array Ids whose first answer to restore, per field. */ public static function unimprovedRetries( array $views, array $length_only, array $before, array $after, string $keyword, OutputValidator $validator, array $banned ): array { $keep = array( 'title' => array(), 'description' => array() ); foreach ( $length_only as $key => $ids ) { if ( empty( $ids ) ) { continue; } $view = $views[ $key ]; $known = self::knownTexts( $view['state'], $keyword ); $clean = true; foreach ( $ids as $id ) { if ( ! isset( $after[ $key ][ $id ] ) || ! empty( $validator->findBannedPhrases( $after[ $key ][ $id ], $banned ) ) ) { $clean = false; } } $was = self::distance( $view['field'], self::joinedLength( $view['field']['tokens'], $known + $before[ $key ], $view['join'] ) ); $now = self::distance( $view['field'], self::joinedLength( $view['field']['tokens'], $known + $after[ $key ], $view['join'] ) ); if ( ! $clean || $now >= $was ) { $keep[ $key ] = $ids; } } return $keep; } /** * @param array $length_only queueRetries()'s result. * @param array $retry_ids Every id asked again, per field. * @param bool $retry_keyword Whether the retry also asked for the focus keyword. * @return bool Whether the retry asked for nothing but a better length, so its failure leaves a usable answer as it was. */ public static function onlyLengthRetried( array $length_only, array $retry_ids, bool $retry_keyword ): bool { return ! $retry_keyword && count( $length_only['title'] ) === count( $retry_ids['title'] ) && count( $length_only['description'] ) === count( $retry_ids['description'] ); } /** * Text a field shows besides its AI parts: its resolved data, fixed and * keyword values, and a deferred keyword once the AI has answered it. * * @param array $state resolveFieldTokens()'s result. * @param string $keyword The value a deferred keyword token will show; '' while unknown. * @return array */ private static function knownTexts( array $state, string $keyword ): array { $known = array(); foreach ( $state['resolved'] as $id => $entry ) { if ( in_array( $entry['status'], array( 'included', 'fallback' ), true ) ) { $known[ (string) $id ] = (string) $entry['value']; } } foreach ( $state['deferredKeywordIds'] as $id ) { $known[ (string) $id ] = $keyword; } return $known; } /** * @param int $min Lower bound. * @param int $max Upper bound. * @return string "at most 40" when there is no lower bound, else "20-40". */ private static function span( int $min, int $max ): string { return 0 === $min ? 'at most ' . $max : $min . '-' . $max; } }