Using logit bias to alter token probability with the OpenAI API

Learn how to use the logit bias parameter to modify model outputs.

Updated: yesterday

On supported Chat Completions models, use logit_bias to make specific tokens more or less likely to appear in the response.

Set a bias from −100 to 100 for each token ID. Negative values make the token less likely, and positive values make it more likely. The effect depends on the model and the prompt.

Token IDs depend on the model. Use the tokenizer or the Python library tiktoken to check them. A leading space or a change in capitalization can change how a word is split into tokens.

Example 1: Make “time” less likely

Install the openai and tiktoken Python packages and set the OPENAI_API_KEY environment variable. When prompted, enter the ID of a Chat Completions model that supports logit_bias and that tiktoken recognizes.

This example uses the model’s tokenizer to find the IDs for “time” with and without a leading space. It sets the bias for both tokens to −100.

import tiktoken
from openai import OpenAI
client = OpenAI()
model = input("Model ID: ").strip()
encoding = tiktoken.encoding_for_model(model)
def token_id(text):
return str(encoding.encode_single_token(text))
bias = {token_id("time"): -100, token_id(" time"): -100}
completion = client.chat.completions.create(
model=model,
messages=[
{"role": "system", "content": "Finish the user's sentence."},
{"role": "user", "content": "Once upon a"},
],
logit_bias=bias,
)
print(completion.choices[0].message.content)

A bias of −100 strongly discourages those tokens. The word can still appear with different capitalization or as a sequence of other tokens.

If encode_single_token raises a KeyError, the text isn’t a single token for that model. Check how the tokenizer splits it before assigning a bias. Biasing part of a word can affect other words that contain the same token.

Example 2: Give direction with targeted logit bias values

In the first example, change the user’s message to “To make soup, you’ll need a” and replace the bias line with the following line. It discourages “pot” with and without a leading space.

bias = {token_id("pot"): -100, token_id(" pot"): -100}

The response might include the word “saucepan” instead.

Example 3: Increase the odds of a word appearing

In the first example, change the user’s message to “To reheat the soup, use a” and replace the bias line with the following line. It encourages “microwave” with a leading space.

bias = {token_id(" microwave"): 5}

Try a smaller positive value if the model repeats “microwave” too often.

Was this article helpful?