The API says the input plus requested output exceeds the model’s context window.
Why this happens
The input tokens, instructions, conversation history, and maximum output must fit together. Exceeding the context limit generates a bad request error.
Answer 1: Count tokens and trim input deliberately
from openai import OpenAI
import tiktoken
client = OpenAI()
enc = tiktoken.get_encoding("o200k_base")
tokens = enc.encode(long_text)
max_input_tokens = 128000 - 4096
if len(tokens) > max_input_tokens:
long_text = enc.decode(tokens[:max_input_tokens])
