pythonnlpopenai-apitext-generation

How to Generate Text with Specific Length Using AI API


I am attempting to generate text outputs that are exactly a certain number of characters or words long using AI API (OpenAI GPT, Claude, Gemini...), but I'm facing difficulties. Here's what I've tried so far:

Setting Max Tokens: I've used the max_tokens parameter hoping to limit the output length, but then text is truncated.

Explicit Prompt Requests: I've tried including explicit instructions in the prompt about the desired length. However, this approach has not produced the precise output lengths I need (ex: gives 600 words instead of 800).

I am looking for suggestions on how to configure the API calls or promtp to achieve exact output lengths. Is there a way to better utilize OpenAI/Claude’s parameters, or is there a method to post-process the text to fit the required length?

I need this because I inject the text in slides. Any alternative solution?


Solution

  • This won't work. LLMs are bad at counting. There are a lot of humorous examples over internet.