07. Dictionaries for AI Config
Why Dictionaries for AI
AI systems require configuration: model names, hyperparameters, API endpoints. Dictionaries map cleanly to JSON, the format of most AI APIs.
Creating Dictionaries
config = {
"model": "gpt-4",
"temperature": 0.7,
"max_tokens": 500,
"stop_sequences": ["###", "END"]
}
Accessing Values
model = config["model"] # Raises KeyError if missing
model = config.get("model") # Returns None if missing
model = config.get("model", "gpt-3.5") # Default value if missing
Modifying Dictionaries
config["temperature"] = 0.9 # Update existing
config["api_key"] = "sk-..." # Add new key
del config["stop_sequences"] # Delete key
Iterating Over Dictionaries
# Keys only
for key in config:
print(key)
# Keys and values
for key, value in config.items():
print(f"{key}: {value}")
# Values only
for value in config.values():
print(value)
Nested Dictionaries
request = {
"model": "gpt-4",
"parameters": {
"temperature": 0.7,
"top_p": 0.9,
"frequency_penalty": 0.0
},
"messages": [
{"role": "system", "content": "You are helpful."},
{"role": "user", "content": "Hello."}
]
}
# Access nested values
temp = request["parameters"]["temperature"]
first_message = request["messages"][0]["content"]
Local verification checkpoint
Run the smallest example from this chapter in a local workspace and record the package version, runtime, data path, and observed output. If the result depends on model size, vector count, CPU/GPU backend, or available memory, note that constraint beside the exercise so the lesson remains reproducible.
Local verification checkpoint
Run the smallest example from this chapter in a local workspace and record the package version, runtime, data path, and observed output. If the result depends on model size, vector count, CPU/GPU backend, or available memory, note that constraint beside the exercise so the lesson remains reproducible.
Create a configuration dictionary for calling an AI model. Include model name, temperature, max_tokens, and a list of stop sequences. Access each value individually and print them.