---
name: ai-content-length-conditioning
category: software-development
tags: [ai, prompt-engineering, content-processing, telegram-bot, conditional-prompts]
description: Modify AI processing pipeline to conditionally expand short content or only fix grammar on long content based on character length threshold.
---

# AI Content Length Conditioning

Conditionally adjust AI processing behavior based on content length. Short texts get expanded to a target length; long texts only get grammar/spelling fixes.

## When to use

- An AI bot processes user-submitted content (posts, messages, articles)
- You want short submissions (~200 chars) expanded to a readable length (~600 chars)
- You want long submissions preserved with only grammar/spelling fixes
- The AI model supports detailed system prompts with conditional instructions

## Approach

### 1. Check length in code

Add a length check before the AI prompt is constructed. **Use raw text length** (before AI processing) since AI always adds some formatting overhead:

```typescript
const SHORT_TEXT_THRESHOLD = 500;  // chars — below this = expand
const TARGET_LENGTH = 600;          // chars — target expanded length

const isShortText = rawText.length < SHORT_TEXT_THRESHOLD;
```

### 2. Build conditional instruction

```typescript
const sizeInstruction = isShortText
  ? `Текст короткий — РАСКРОЙ ТЕМУ, добавь деталей, примеров, развей мысль. Доведи объём до ${TARGET_LENGTH} символов, но сохрани стиль и голос автора. Не выдумывай того, чего нет в оригинале.`
  : `Текст уже подробный — только ИСПРАВЬ ОРФОГРАФИЮ И ПУНКТУАЦИЮ. Не меняй содержание, не добавляй, не расширяй. Сохрани оригинальный объём.`;
```

### 3. Inject into prompt

Concatenate the size instruction into the system prompt **before** the main task description:

```typescript
const prompt = `Ты — редактор.\n\n${sizeInstruction}\n\nОсновная задача:\n1. ...`;
```

### 4. Handle ALL processing paths

Apply the same pattern to **every** AI function that processes content. If you have `processPostWithAI` and `processCrewPostWithAI`, both need the size instruction. Missing one will create inconsistency — crew ads won't get conditioned.

## Key design decisions

| Parameter | Suggested value | Rationale |
|-----------|----------------|-----------|
| Threshold | 500 chars | Leaves room for AI to add ~100 more chars to reach 600 target |
| Target | 600 chars | Long enough for readable content, not excessive |
| Short instruction | Focus on expansion | "раскрой тему, добавь деталей, развей мысль" |
| Long instruction | Focus on preservation | "только орфографию и пунктуацию, не меняй содержание" |
| Guard clause | "Не выдумывай того, чего нет" | Prevents AI hallucination when expanding |

## Pitfalls

- **AI may still expand long texts** — some models are verbose by default. The "только исправь" instruction helps but doesn't guarantee preservation. Monitor output sizes.
- **500-char threshold means raw text** — consider the input length before AI processing, since AI will always add some formatting overhead (titles, spacing).
- **Multilingual content** — 500 Cyrillic chars carry more information than 500 Latin chars. Adjust threshold per language if needed.
- **Build failures in monorepo** — if root build fails due to unrelated packages, build only the affected package:
  ```bash
  # Find package name
  cat artifacts/api-server/package.json | grep '"name"'
  # Build single package
  pnpm --filter=@workspace/api-server run build
  ```
- **Verify backup before editing** — always backup the original file before modifying production AI prompts.
