Intermediate level · Module 1: Python for AI Agent Development · Lesson 2 of 3
Configuration, Secrets and Costs
Learners keep API keys out of code, configure budgets and limits, and estimate the token cost of agent runs before using paid services.
In this lesson you will
- Store secrets and settings safely
- Estimate and limit token usage and cost
Key concepts
environment variables.env and .gitignoretoken budgetrate limitscost estimate
The lesson
API keys are passwords. Read them from environment variables (os.environ['MODEL_API_KEY']) or a local .env file that is listed in .gitignore, and never commit them to Git or paste them into notebooks that are shared.
Agents can make many model calls per task. Estimate cost before running: number of calls × (input tokens + output tokens) × the provider's price per token. Set a token budget per task and per day, and stop when it is reached.
Providers limit how many requests or tokens you can send per minute. When the limit is reached they return an error (often HTTP 429); the code must wait and retry rather than fail or loop.
Step by step
- Move all settings and keys to environment variables and add .env to .gitignore.
- Log token counts for each call (from the provider's response or an estimate).
- Estimate the cost of 100 project questions.
- Add a per-task token budget that stops the agent.
Practice activity
Write a cost estimate and implement a token budget for the project.
Expected result: No secrets in code, logged token usage and a budget that stops runaway tasks.
Check your understanding
-
Where should API keys be stored?
Show answer
In environment variables or an ignored .env file, never in code or Git.
-
How do you estimate the cost of a task?
Show answer
Number of calls × tokens per call × price per token.
Further learning
Taught live by an instructor — online or in person. Free course lessons are for self-study and do not lead to a certificate — see registration options.