Sub topic 7
Adding a system prompt and temperature control
This chapter assumes you can run a gr.ChatInterface app, know the (message, history) function contract, and have seen the messages-style history format and the streaming generator pattern. You also need an OpenAI-compatible API key in the OPENAI_API_KEY environment variable.
By the end you will be able to pass extra controls from the UI into your chat function, explain how Gradio orders those arguments, and avoid the common mistakes that come with them.
Why extra inputs exist
A plain chat function receives two things: the new message and the history. Real applications need more settings. Two of the most common are:
- System prompt: a message with the role
systemthat sets the assistant's behavior, tone, or constraints. The model reads it before the conversation. - Temperature: a number that controls how random the model's word choices are. Low values (near 0) give more predictable output. Higher values give more varied output. The usual range is 0 to 2 for OpenAI models, and many apps limit the slider to 0 to 1.
You could hard-code both in the function. Then every change means editing code and restarting. The additional_inputs parameter of gr.ChatInterface lets users change them in the browser.
How additional_inputs works
additional_inputs takes a list of Gradio components. Gradio shows them in a collapsible "Additional Inputs" accordion below the chat box. When the user sends a message, Gradio reads the current value of each component and calls your function like this:
fn(message, history, *additional_input_values)The order matters. The values arrive positionally, in the same order as the list. If your list is [system_textbox, temperature_slider], your function signature must be (message, history, system_prompt, temperature). Names do not matter, but position does.
The complete example
This is the full app. It builds an OpenAI-style message list, passes the temperature to the API, and streams the answer.
import gradio as gr
from openai import OpenAI
client = OpenAI() # reads OPENAI_API_KEY from the environment
def respond(message, history, system_prompt, temperature):
messages = [{"role": "system", "content": system_prompt}]
messages += [{"role": h["role"], "content": h["content"]} for h in history]
messages.append({"role": "user", "content": message})
stream = client.chat.completions.create(
model="gpt-4o-mini",
messages=messages,
temperature=temperature,
stream=True,
)
reply = ""
for chunk in stream:
delta = chunk.choices[0].delta.content or ""
reply += delta
yield reply
demo = gr.ChatInterface(
fn=respond,
type="messages",
additional_inputs=[
gr.Textbox("You are a helpful assistant.", label="System prompt"),
gr.Slider(0, 1, value=0.7, label="Temperature"),
],
)
if __name__ == "__main__":
demo.launch()Walk through the pieces that matter for this chapter.
- The system message goes first. The list starts with the system prompt, then the prior turns, then the new user message. Most chat APIs expect this order.
- The history is copied, not passed through. With
type="messages", each history item is a dictionary withroleandcontent. The list comprehension keeps only those two keys. This matters because Gradio can attach extra keys, such asmetadataoroptions, and some APIs reject unknown fields. - The system prompt is not stored in history. Gradio's history contains only the visible conversation. You prepend the system prompt on every call, so the user's latest edit takes effect on the next message.
yieldsends the full text so far. Each yield replaces the displayed reply, so you accumulatereplyand yield the whole string, not only the new fragment.
Choosing components for the inputs
The component you pick controls what values your function receives.
| Setting | Component | Value your function gets |
|---|---|---|
| System prompt | `gr.Textbox(lines=3)` | `str` |
| Temperature | `gr.Slider(0, 1, step=0.1)` | `float` or `int` |
| Model name | `gr.Dropdown(choices=[...])` | `str` |
| Max tokens | `gr.Number(precision=0)` | `int` |
| Enable tools | `gr.Checkbox()` | `bool` |
Two details to watch. A gr.Slider can return an integer when the value lands on a whole number, so do not assume a float. Also, the first positional argument of gr.Textbox is its initial value, which is why gr.Textbox("You are a helpful assistant.", label="System prompt") pre-fills the box.
For a long system prompt, a one-line textbox is hard to edit. Use lines and max_lines:
import gradio as gr
system_box = gr.Textbox(
value="You are a helpful assistant. Answer in short paragraphs.",
label="System prompt",
lines=4,
max_lines=10,
)Controlling how the accordion appears
By default the extra inputs sit in a closed accordion. You can change its label and whether it starts open with additional_inputs_accordion:
import gradio as gr
def respond(message, history, system_prompt, temperature):
return f"[T={temperature}] {system_prompt} | {message}"
demo = gr.ChatInterface(
fn=respond,
type="messages",
additional_inputs=[
gr.Textbox("You are a helpful assistant.", label="System prompt"),
gr.Slider(0, 1, value=0.7, label="Temperature"),
],
additional_inputs_accordion=gr.Accordion(label="Model settings", open=True),
)
if __name__ == "__main__":
demo.launch()This version has no model call. It echoes the settings, which makes it a quick way to confirm that the order and values of your inputs are what you expect before you spend API credits.
What temperature does
The model produces a probability for every possible next token. Temperature rescales those probabilities before one is chosen.
- At 0, the model almost always picks the most likely token. Repeated runs give nearly the same answer. This suits extraction, classification, and code.
- Around 0.7, there is moderate variety. This is a common default for conversation.
- Near the top of the range, less likely tokens are picked more often. Output becomes more creative and also more likely to drift or contradict itself.
Temperature 0 is not a guarantee of identical output. Hosted models can still vary slightly between calls. Do not build logic that depends on exact repeatability.
Some models do not accept a custom temperature. Certain reasoning models, for example, only allow the default value and return an error if you set another. If you switch models, check the provider's documentation for the supported parameters.
Common errors
Argument count mismatch. If your function has four parameters but you supply one additional input, Gradio calls it with three arguments and Python raises a TypeError about a missing argument. Count the list entries and the parameters. The function takes two plus the number of additional inputs.
Swapped order. If the list is [slider, textbox] but the function expects (message, history, system_prompt, temperature), the system prompt becomes a number and the temperature becomes text. The API call then fails or behaves oddly. Because Python does not complain about names, this error only shows up at runtime.
Sending the system prompt twice. If you add the system prompt to the list on every call and also store it in your own state, it appears twice. Build the list fresh each time from the textbox value.
Leaking extra history keys. Passing history straight to the API can include keys the API does not accept. Copy only role and content, as the example does.
Empty system prompt. If the user clears the textbox, you send a system message with empty content. Some APIs reject it. Guard against this:
def build_messages(system_prompt, history, message):
messages = []
if system_prompt and system_prompt.strip():
messages.append({"role": "system", "content": system_prompt.strip()})
messages += [{"role": h["role"], "content": h["content"]} for h in history]
messages.append({"role": "user", "content": message})
return messages
if __name__ == "__main__":
print(build_messages("", [], "Hi"))
print(build_messages("Be brief.", [{"role": "user", "content": "Hi"}], "Again"))Move this helper into your app and call it from respond. It is also easy to test on its own, without running the UI.
Edge cases to know about
- Changing the system prompt mid-conversation. The new prompt applies to the next reply only. Earlier assistant turns were produced under the old prompt, and the model still sees them. The behavior may feel inconsistent. If you need a clean slate, clear the chat.
- Settings are per request, not per session store. Gradio sends the current widget values with each message. You do not need
gr.Statefor them. - Sharing a deployed app. Anyone who can open the app can edit the system prompt. If the prompt contains instructions you do not want users to alter, keep it in server code instead of exposing it as an input.
- Sliders limit input, but your function should still validate. A client calling the API through
gradio_clientcan send any value. Clamp the temperature to the range your model accepts before using it.
Exercises
Exercise
A ChatInterface has additionalinputs=[gr.Dropdown(["gpt-4o-mini", "gpt-4o"], value="gpt-4o-mini"), gr.Textbox(), gr.Slider(0, 1)]. Write the function signature that receives the model name, system prompt, and temperature, and explain what happens if you write (message, history, temperature, model, systemprompt) instead.
Show answer
The signature is def respond(message, history, model, systemprompt, temperature). Gradio passes additional input values by position, in list order, after message and history. With the swapped signature, temperature would receive the model name string, model would receive the system prompt text, and systemprompt would receive the slider number. Python raises no error at call time for this, so the failure appears later, for example when the API rejects a string temperature.
Exercise
Your app crashes with "TypeError: respond() missing 1 required positional argument" after you add a second extra input to the function signature but not to the interface. What is wrong and how do you fix it?
Show answer
The function expects message, history, and two extra values, but additionalinputs lists only one component, so Gradio supplies only three arguments. Add a second component to additionalinputs, in the right position, or remove the unused parameter from the function.
Exercise
Why does the example copy history items into new dictionaries with only role and content instead of passing history directly to the API?
Show answer
Gradio history items can contain extra keys, such as metadata, that the model API may not accept. Copying only role and content produces a clean message list and avoids request errors.