Text Generation and Model Parameters

Learn common Chat Completions generation parameters and understand model output, finish reasons, and token usage.

🎯 Introduction

In the previous article, we called a model through AIHubMix using the OpenAI SDK and received an answer. In practice, we also need to control the style and length of that answer, check whether generation completed, and track token usage.

Continuing with product descriptions, this article adds common parameters to the existing code and explains messages, max_completion_tokens, temperature, and response fields through sample output. You will learn to adjust generation for your application and decide whether a result is ready to use.


🛠 Generate a Product Description

Continue with the ai-sdk-course project from the previous article, using Node.js 24.x and openai@7.62.0. The .env file in the project root already contains your AIHubMix key, endpoint, and model ID. No additional configuration or dependencies are needed.

Create 02.generate.mjs in the project root:

import OpenAI from "openai";

const client = new OpenAI({
    apiKey: process.env.AI_API_KEY,
    baseURL: process.env.AI_BASE_URL
});

const response = await client.chat.completions.create({
    model: process.env.AI_MODEL,
    messages: [
        {
            role: "system",
            content: "You are an e-commerce copywriter. Answer in concise, objective Chinese."
        },
        {
            role: "user",
            content: "Write a product description of no more than 60 Chinese characters for a 500 ml insulated bottle."
        }
    ],
    max_completion_tokens: 200
});

const choice = response.choices[0];

console.log("Generated text:", choice.message.content);
console.log("Response ID:", response.id);
console.log("Finish reason:", choice.finish_reason);
console.log("Token usage:", response.usage);

Run this from the project root:

node --env-file=.env 02.generate.mjs

If you need the local HTTP proxy configured in the previous article, run:

HTTPS_PROXY=http://127.0.0.1:7890 NODE_USE_ENV_PROXY=1 node --env-file=.env 02.generate.mjs

Your terminal might display:

Generated text: A 500 ml capacity for commuting and everyday hydration. Refer to the product specifications for materials and heat retention.
Response ID: chatcmpl-example-id
Finish reason: stop
Token usage: { prompt_tokens: 48, completion_tokens: 35, total_tokens: 83 }

This example illustrates the response structure; it is not an actual API test record. Your reply, response ID, and token usage will differ. Compared with the previous article, this request adds a system message and an output token limit, and reads the response ID and finish reason.


🧱 Control How the Model Generates Text

messages: Separate Response Instructions from the Task

This request sends two messages:

  • system: Sets general response instructions, such as writing concise, objective Chinese as an e-commerce copywriter.
  • user: Specifies the current task, such as describing a 500 ml insulated bottle in no more than 60 Chinese characters.

This separates response instructions from the specific task. To describe a wireless mouse or keyboard later, keep the system instructions and change only the user content.

This article still covers text generation in a single request. The next article explains how to include messages from earlier turns.

max_completion_tokens: Set an Output Limit

max_completion_tokens: 200 limits the output token budget for this generation. It does not mean 200 Chinese characters, nor does it require the model to generate exactly 200 tokens.

There are two distinct limits here:

LimitPurpose
"No more than 60 Chinese characters" in the promptCommunicates the desired description length, which the model attempts to follow
max_completion_tokens: 200Sets a budget of at most 200 output tokens for generation

For example, the model may finish normally after writing just 40 Chinese characters; it will not keep adding text to reach 200 tokens. Conversely, a limit that is too low may stop generation before the description is finished.

If your application strictly requires at most 60 Chinese characters, validate the final text length in your program. Neither a prompt instruction nor a token limit replaces strict application validation.

temperature: Adjust Variation in Wording

Product copy sometimes needs consistent wording and sometimes benefits from creativity. For models that support temperature, this parameter adjusts sampling randomness during generation.

For example, replace the output limit section of the original request with:

    max_completion_tokens: 200,
    temperature: 0.3

Then use the same prompt: "Write a slogan for a 500 ml insulated bottle." Different settings may produce tendencies like these:

ParameterExample copy
temperature: 0.3 (lower)A portable 500 ml insulated bottle for everyday hydration.
temperature: 1 (higher)Take warmth with you and savor every sip.

These are manually written illustrations, not results from two real model calls. The parameter does not guarantee these particular outputs.

At a lower temperature, the model generally favors higher-probability continuations, producing less variation. Higher values generally produce more varied wording. Try lower values for information extraction or tasks with fixed formats and higher values for creative copy, then evaluate the actual results.

Reducing randomness does not ensure factual accuracy. If product materials or heat-retention times are missing, lowering temperature cannot guarantee the model will avoid inventing them. Supply this information from reliable product data.

Support for temperature varies by model, and some models do not support it. When switching models through AIHubMix, check the parameters supported by the platform and model. Omit unsupported parameters.

🧱 Understand the Model Response

Along with the answer text, Chat Completions returns data that helps you assess generation:

FieldPurpose
response.idIdentifies this response to help locate the request
response.choices[0].message.contentReads the text of the first candidate result
response.choices[0].finish_reasonIndicates why generation stopped
response.usageProvides token statistics for this call, when returned by the platform

choices is a list of candidate results. This example does not request multiple candidates, so it reads choices[0].

finish_reason: Why Check the Finish Reason?

These two illustrative outputs show the difference between normal completion and truncation:

Finish reasonGenerated text (illustrative)
stopThis 500 ml insulated bottle is suitable for commuting, office use, and everyday hydration.
lengthThis 500 ml insulated bottle is suitable for commuting, office use, and...

The second response contains text, but it may be unfinished. You cannot simply save it as a complete product description.

Common finish_reason values include:

ValueMeaning
stopThe model finished generation normally
lengthThe generation length limit was reached; output may be incomplete
content_filterContent was filtered; the answer may not have been returned in full

For example, after obtaining choice, add this check:

if (choice.finish_reason === "length") {
    console.warn("Output reached the token limit; the product description may be incomplete");
}

When you see length, consider raising the output limit or asking for a shorter response. stop means only that generation ended normally; it does not guarantee factual accuracy or compliance with the 60-character requirement.

usage: How Many Input and Output Tokens Were Used?

The example's response.usage contains three main fields:

FieldMeaning
prompt_tokensTokens used by the input messages
completion_tokensTokens used by model generation
total_tokensTotal tokens counted for this request

For example, the sample output uses 48 input tokens and 35 output tokens, totaling 83. These numbers are illustrative; the server measures actual usage. Fields returned by different models on AIHubMix may also differ.

Token usage helps estimate costs, but is not itself a monetary amount. Calculate actual costs using AIHubMix's rates for the selected model.


❓ Knowledge Check

Q1: If the prompt already says "no more than 60 Chinese characters", do I still need an output token limit?

They serve different purposes. The character limit describes the desired copy, while the token limit controls the generation budget. Validate the generated text in code if the character limit must be enforced strictly.

Q2: Does lowering temperature guarantee accurate product information?

No. It adjusts sampling randomness rather than verifying facts. Product capacity, materials, and heat-retention times must come from reliable product data; parameter adjustments cannot guarantee their accuracy.


🧪 Exercise

Using 02.generate.mjs, complete these two exercises:

  1. Change the product to a wireless mouse. Keep max_completion_tokens: 200 and run several times with temperature: 0.3 and temperature: 1, comparing the wording. A small sample may show little difference, which is normal. Skip this step if your model does not support temperature.
  2. Keep the product description task and temporarily lower max_completion_tokens, for example to 20. Check whether finish_reason becomes length. If it does not, request a somewhat longer description and test again. Restore the limit to 200 afterward.

Success criteria: Explain the roles of system and user, distinguish character limits from token limits, recognize potentially truncated output, and locate input and output token counts in usage.


🎉 You can now generate text, adjust generation parameters to suit your needs, and check whether the result is complete. Next, you will use messages for multi-turn conversations.