开发环境与生产环境的配置档案
特定环境的配置、功能开关和分阶段部署。
开发环境与生产环境的配置档案 是 CoddyKit 上的免费 AI Agents 课时。 这是第 4 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 AI Agents 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 AI Agents 课程共包含 4 节课。
配置方案为何重要
生产代理和开发代理应有不同的行为:不同的日志记录级别、不同的模型层级(成本与质量)、不同的数据库、不同的速率限制。配置方案可以让这一切自动完成——只需一个环境变量,就能一次性切换所有设置。
使用 ENV 变量检测环境
标准做法是读取 ENV(或 ENVIRONMENT)变量,用它标识当前的部署环境。然后,代码会根据该值选择适当的配置方案。
import os
# Read the environment identifier
ENV = os.getenv('ENV', 'development').lower()
if ENV not in ('development', 'staging', 'production'):
raise ValueError(
f'Invalid ENV value: "{ENV}". '
f'Must be: development, staging, or production'
)
print(f'Running in {ENV} mode')
# Usage:
# ENV=development python agent.py -> dev settings
# ENV=staging python agent.py -> staging settings
# ENV=production python agent.py -> prod settings
# python agent.py -> defaults to development为各环境定义配置类
定义一个基础配置类,并为每个环境定义子类。每个子类都覆盖本环境中有所不同的值。与使用包含大量条件判断的字典相比,这种方式更易读,也更安全地支持类型检查。
import os
class BaseConfig:
OPENAI_API_KEY: str = os.environ.get('OPENAI_API_KEY', '')
MAX_STEPS: int = 20
LOG_LEVEL: str = 'INFO'
CACHE_ENABLED: bool = True
CACHE_TTL_SECONDS: int = 3600
class DevelopmentConfig(BaseConfig):
MODEL: str = 'gpt-4o-mini' # cheaper in dev
LOG_LEVEL: str = 'DEBUG' # verbose logging in dev
CACHE_ENABLED: bool = False # fresh results in dev
MAX_STEPS: int = 10 # shorter loops in dev
class StagingConfig(BaseConfig):
MODEL: str = 'gpt-4o-mini'
LOG_LEVEL: str = 'INFO'
MAX_STEPS: int = 20
class ProductionConfig(BaseConfig):
MODEL: str = 'gpt-4o' # best quality in prod
LOG_LEVEL: str = 'WARNING' # less noise in prod
MAX_STEPS: int = 30 # more steps allowed in prod
if __name__ == '__main__':
for cls in (DevelopmentConfig, StagingConfig, ProductionConfig):
c = cls()
print(f'{cls.__name__}: model={c.MODEL} log_level={c.LOG_LEVEL} max_steps={c.MAX_STEPS} cache={c.CACHE_ENABLED}')
配置工厂:选择正确的方案
配置工厂函数会读取 ENV 变量,并返回适当的配置类。这个函数是唯一需要了解环境切换逻辑的地方。
import os
def get_config():
env = os.getenv('ENV', 'development').lower()
configs = {
'development': DevelopmentConfig,
'staging': StagingConfig,
'production': ProductionConfig
}
config_class = configs.get(env)
if not config_class:
raise ValueError(f'Unknown environment: {env}')
return config_class()
# Usage throughout your agent:
config = get_config()
print(f'Model: {config.MODEL}')
print(f'Max steps: {config.MAX_STEPS}')
print(f'Log level: {config.LOG_LEVEL}')
# All code uses config.MODEL, config.LOG_LEVEL etc.
# Switching environments requires only changing ENV variable使用 Pydantic Settings 进行类型化配置
pydantic-settings 提供了一种强大且类型安全的配置定义方式。它会自动读取环境变量、验证类型,并可从 .env 文件加载配置。请使用 pip install pydantic-settings 进行安装。
# pip install pydantic-settings
from pydantic_settings import BaseSettings
from pydantic import Field
from typing import Literal
class AgentSettings(BaseSettings):
# Required fields — raise error if not set
openai_api_key: str
search_api_key: str
# Optional with defaults
env: Literal['development', 'staging', 'production'] = 'development'
model: str = 'gpt-4o-mini'
max_steps: int = Field(default=20, ge=1, le=100) # validated range
log_level: str = 'INFO'
cache_enabled: bool = True
cache_ttl_seconds: int = Field(default=3600, ge=60)
class Config:
env_file = '.env'
case_sensitive = False # OPENAI_API_KEY -> openai_api_key
# settings = AgentSettings() # raises ValidationError if required vars missing使用 Pydantic Settings 配置特定环境的覆盖值
将 Pydantic Settings 与计算属性结合起来,应用特定环境的默认值,同时仍允许通过环境变量覆盖这些默认值。
from pydantic_settings import BaseSettings
from pydantic import model_validator
import os
class AgentSettings(BaseSettings):
openai_api_key: str
env: str = 'development'
model: str = ''
log_level: str = ''
max_steps: int = 0
@model_validator(mode='after')
def apply_env_defaults(self) -> 'AgentSettings':
env_defaults = {
'development': {'model': 'gpt-4o-mini', 'log_level': 'DEBUG', 'max_steps': 10},
'staging': {'model': 'gpt-4o-mini', 'log_level': 'INFO', 'max_steps': 20},
'production': {'model': 'gpt-4o', 'log_level': 'WARNING', 'max_steps': 30}
}
defaults = env_defaults.get(self.env, env_defaults['development'])
if not self.model: self.model = defaults['model']
if not self.log_level: self.log_level = defaults['log_level']
if not self.max_steps: self.max_steps = defaults['max_steps']
return self
class Config:
env_file = '.env'为各环境设置功能开关
使用配置方案按环境启用或停用功能。例如,仅在开发环境中启用调试界面,仅在生产环境中使用真实支付,并在预发布环境中指向沙箱服务。
import os
class AgentFeatureFlags:
env = os.getenv('ENV', 'development')
# Enable memory persistence (requires DB)
MEMORY_ENABLED: bool = env in ('staging', 'production')
# Use real payment processing
REAL_PAYMENTS: bool = env == 'production'
# Enable verbose step-by-step output
VERBOSE_STEPS: bool = env == 'development'
# Use cheap model for unit test runs
FORCE_MINI_MODEL: bool = os.getenv('CI') == 'true'
flags = AgentFeatureFlags()
print(f'Memory: {flags.MEMORY_ENABLED}')
print(f'Verbose: {flags.VERBOSE_STEPS}')
print(f'Payments: {flags.REAL_PAYMENTS}')在启动时验证配置
在启动时验证所有配置并打印摘要,以便操作人员在代理开始处理任务之前确认其配置正确。这样可以避免生产环境中的静默配置错误。
import os
import sys
def validate_and_print_config(config) -> None:
print(f'=== Agent Configuration ===')
print(f'Environment : {config.env}')
print(f'Model : {config.model}')
print(f'Max steps : {config.max_steps}')
print(f'Log level : {config.log_level}')
print(f'Cache : {"enabled" if config.cache_enabled else "disabled"}')
print(f'OpenAI key : ...{config.openai_api_key[-4:]}')
print('===========================')
# Critical validations
if config.env == 'production' and config.log_level == 'DEBUG':
print('WARNING: DEBUG logging in production exposes sensitive data!')
if not config.openai_api_key:
print('FATAL: OPENAI_API_KEY not set')
sys.exit(1)
print('Configuration validated.')
if __name__ == '__main__':
from types import SimpleNamespace
demo_config = SimpleNamespace(
env='development', model='gpt-4o-mini', max_steps=10,
log_level='DEBUG', cache_enabled=False, openai_api_key='sk-demo-1234'
)
validate_and_print_config(demo_config)
按环境覆盖配置值
在 CI/CD 流水线中,无需更改整个配置方案即可覆盖特定的配置值。将单独的变量与 ENV 变量一同传入,为特定部署自定义设置。
# Staging deployment with custom model override:
# ENV=staging AGENT_MODEL=gpt-4o python agent.py
# Production with reduced max_steps for cost control:
# ENV=production AGENT_MAX_STEPS=15 python agent.py
# CI test run — use production profile but with cheap model:
# ENV=production AGENT_MODEL=gpt-4o-mini CI=true python agent.py
# The config class reads ENV first for the profile,
# then individual overrides take precedence:
import os
env = os.getenv('ENV', 'development')
config = get_config() # loads base profile for env
# Individual overrides applied on top:
if os.getenv('AGENT_MODEL'):
config.MODEL = os.getenv('AGENT_MODEL')
if os.getenv('AGENT_MAX_STEPS'):
config.MAX_STEPS = int(os.getenv('AGENT_MAX_STEPS'))
print(f'Final model: {config.MODEL}')为团队成员记录配置方案
清晰地记录配置方案——可以写在代码注释、README 中,或两者兼有。新开发人员需要了解各环境之间有哪些变化,才能放心地完成部署。
# config_profiles.py — Configuration per environment
#
# | Setting | development | staging | production |
# |----------------|----------------|----------------|-------------|
# | MODEL | gpt-4o-mini | gpt-4o-mini | gpt-4o |
# | MAX_STEPS | 10 | 20 | 30 |
# | LOG_LEVEL | DEBUG | INFO | WARNING |
# | CACHE_ENABLED | False | True | True |
# | MEMORY_DB | SQLite (local) | PostgreSQL | PostgreSQL |
#
# To switch environments:
# ENV=staging python agent.py
#
# To override a single setting:
# ENV=production AGENT_MAX_STEPS=15 python agent.py
print('Config profile table documents all per-environment differences')测试中的配置:强制使用测试方案
测试始终应使用特定的测试配置,绝不能使用生产环境设置。创建一个测试配置 fixture,应用适当的设置,并防止任何意外的生产 API 调用。
import os
import pytest
@pytest.fixture(autouse=True)
def test_environment(monkeypatch):
'Force test configuration for all tests'
monkeypatch.setenv('ENV', 'test')
monkeypatch.setenv('AGENT_MODEL', 'gpt-4o-mini')
monkeypatch.setenv('AGENT_MAX_STEPS', '5') # short loops in tests
monkeypatch.setenv('LOG_LEVEL', 'DEBUG')
monkeypatch.setenv('CACHE_ENABLED', 'false')
# Use a fake API key — tests should mock all LLM calls
monkeypatch.setenv('OPENAI_API_KEY', 'test-key-not-real')
# This fixture runs before every test automatically
# Tests cannot accidentally use production settings知识检查:配置方案
测试您对特定环境配置方案的理解。
回顾:开发与生产环境的配置方案
现在,您已经掌握了适用于不同环境中代理的完整配置管理策略:
- 使用
ENV变量标识部署环境 - 为每个环境定义配置类,并设置适当的默认值
- 使用配置工厂自动选择正确的方案
- 使用
pydantic-settings定义类型安全且经过验证的配置 - 使用功能开关按环境启用或停用功能
- 在启动时验证并打印配置,以便操作人员确认设置
- 在 pytest fixture 中强制使用测试配置,防止调用生产服务
良好的配置管理能让同一代码库安全地部署到开发、预发布和生产环境。
用 AI 导师学习 AI Agents — 免费
在浏览器中编写并运行真实代码,获得全天候 AI 导师的即时帮助,并在网页或应用中继续学习。
- 课程
- 60
- 课程
- 239
常见问题解答
「开发环境与生产环境的配置档案」课时是免费的吗?
是的 — 「开发环境与生产环境的配置档案」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 AI Agents 课程的其余内容,请升级到 CoddyKit PRO。 AI Agents 课程共包含 4 节课。
「开发环境与生产环境的配置档案」这节课中我会学到什么?
特定环境的配置、功能开关和分阶段部署。 你通过在浏览器中直接运行的动手代码来练习 AI Agents,全天候 AI 导师会在你学习这节课的过程中回答你的问题。
学习 AI Agents 需要有经验吗?
无需任何先前经验。CoddyKit 上的 AI Agents 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 4 节课,共 4 节。
「开发环境与生产环境的配置档案」课时需要多长时间?
大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。
我能在这节 AI Agents 课中编写并运行代码吗?
能。每节 AI Agents 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。
此课程中的所有课时
- 代理的环境变量
- .env 文件与 python-dotenv
- 密钥轮换与安全性
- 开发环境与生产环境的配置档案