Start learning free

LESSON 113 OF 129 · AI ENGINEERING: PRODUCTION

Settings per Environment in Python

Practice

The same code runs in two places: on your computer while you build it, and on the server where customers use it. A few settings should differ: which model answers, how long an answer may be, how long to wait for it. Read them from environment variables, and changing a setting means changing one value on the server, not the code.

A value with a default: os.environ.get works like a dictionary's get: the name first, then the value to use when the variable isn't set. An environment variable is always text, so a number has to be converted.

import os

shop_name = os.environ.get("SHOP_NAME", "Corner Shop")
port = int(os.environ.get("PORT", "5000"))

In this lesson load_settings() returns a dictionary with four settings. APP_ENV names the environment, and dev is the default. The main model is the rule and dev gets the cheap one, unless AI_MODEL names a model: then that one wins. AI_MAX_TOKENS (default 300) and AI_TIMEOUT (default 10) become numbers.

Your program is started the way the server starts it, with APP_ENV=production and AI_MAX_TOKENS=150. Then the check calls load_settings() in four environments, the first with nothing set. The program must print:

env: production
model: claude-sonnet-5-5
max_tokens: 150
timeout: 10.0
Welcome to the Corner Shop, where every mug, lamp and teapot is picked with care.
The model was asked for: claude-sonnet-5-5 with max_tokens 150
The client waits at most: 10.0 seconds
The check calls load_settings() in four environments:
Nothing set (your computer):
  {'env': 'dev', 'model': 'claude-haiku-5-5', 'max_tokens': 300, 'timeout': 10.0}
…

Your task: fill load_settings so it reads the four settings from the environment with their defaults, print the settings the program picked, then create the client and call the model with values that come only from settings.


Assignment
Follow the Coding Tutorial to build load_settings, print the settings in use and call the model with them.


Hint
The order of the lines in load_settings matters: AI_MODEL is read after the dev check, so the model you name yourself wins. Both the variable and its default are text: wrap the whole os.environ.get(...) in int() or float().


STEP 1 OF 12
    Ctrl + Enter to check

    Ai Env Settings in Python

    Keep going with Python1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free