八周带你手搓AI应用-Day6-第一周收尾-工程化整合+资产上云
工程化整合是什么“整洁的代码”不仅仅是能运行而是要具备模块化和可配置性。我们将把 API Key 等敏感信息提取到配置文件中并使用类Class或清晰的函数结构重新组织代码。为什么如果代码里到处硬编码Hardcode了你的 API Key一旦传到 GitHub全世界都能白嫖你的额度甚至造成账号风险。怎么做具体步骤创建配置文件.env在项目根目录新建一个文件专门存敏感信息。API_KEY你的真实Key BASE_URLhttps://api.siliconflow.cn/v1 MODEL_NAMEQwen/Qwen2.5-7B-Instruct安装依赖pip install python-dotenv用于读取 .env 文件。编写chat.py将第五天的异步逻辑与第四天的记忆逻辑整合。示例代码结构importosimportasynciofromopenaiimportAsyncOpenAIfromdotenvimportload_dotenv# 加载配置load_dotenv()classAIChatBot:def__init__(self):self.clientAsyncOpenAI(api_keyos.getenv(API_KEY),base_urlos.getenv(BASE_URL))self.history[{role:system,content:你是一个严谨的科研助手。}]asyncdefget_response(self,user_input):self.history.append({role:user,content:user_input})try:responseawaitself.client.chat.completions.create(modelos.getenv(MODEL_NAME),messagesself.history)replyresponse.choices[0].message.content self.history.append({role:assistant,content:reply})returnreplyexceptExceptionase:returnfError:{e}asyncdefmain():botAIChatBot()print( AI 助手已就绪输入 exit 退出)whileTrue:textinput(\n 用户: )iftext.lower()exit:breakreplyawaitbot.get_response(text)print(f AI:{reply})if__name____main__:asyncio.run(main())资产上云 —— Git 实战1. Git 基础命令与仓库推送是什么Git 是代码的版本控制工具GitHub 是代码的社交/托管平台。它是程序员的“作品集”。操作步骤初始化本地库在项目文件夹打开终端输入git init。创建.gitignore关键 新建文件命名为.gitignore内容写上venv/ .env __pycache__/注这样 Git 就不会把你的虚拟环境文件夹和包含 API Key 的隐私文件传上网。提交代码git add .暂存所有文件git commit -m feat: 完成第一周AI对话机器人基础功能推送至 GitHub去 github.com 新建一个名为my-first-ai-chat的仓库。按照 GitHub 给出的提示类似git remote add origin ...关联并推送代码。附源码链接https://github.com/aivinma/my-first-ai-chat.git