【AI大模型应用开发工程师特训笔记】第04讲(第五章):条件判断与流程控制
上一章我们学习了运算符能够对数据进行计算和比较。但程序真正的“智能”来自于根据不同的条件执行不同的代码—就像 AI 模型根据你的输入内容决定如何回复根据 token 数量决定是否截断根据温度系数决定输出的随机程度。本章将学习if条件判断、else、elif以及循环控制for、while所有例子都紧扣 AI 大模型的实际开发场景。4.1 布尔表达式条件判断的“是非题”在正式学习if之前你需要理解什么是“条件”。任何条件最终都会变成一个布尔值True真或False假。比较运算符和逻辑运算符产生的结果就是布尔值。4.1.1 什么是布尔表达式简单说就是一个可以回答“是”或“否”的问题。temperature 0.8 is_creative temperature 0.5 # True is_too_random temperature 1.5 # False model_name gpt-4 is_premium (model_name gpt-4) # True在 AI 开发中布尔表达式常用来检查 API 返回是否成功判断生成文本是否包含禁忌词验证用户输入是否符合格式4.2 if 语句如果……就……if语句是最基本的流程控制它的意思是如果某个条件成立就执行一段代码。4.2.1 基本语法if 条件: 条件成立时执行的代码块注意条件后面要加冒号:代码块必须缩进通常用 4 个空格表示这行代码属于if管辖4.2.2 AI 场景实例# 例1检查 temperature 是否合法 temperature 1.8 if temperature 2.0: print(警告温度超过最大值 2.0模型输出可能不稳定) # 例2检查是否达到最大 token 限制 used_tokens 3800 max_tokens 4096 if used_tokens max_tokens: print(已达到上下文长度上限将停止生成。) # 例3检查 API 密钥是否存在 api_key if api_key : print(错误未设置 API 密钥请检查环境变量。) 如果条件为False代码块会被跳过什么也不执行。4.3 if-else 语句如果……否则……if-else提供了两种选择条件成立时做 A不成立时做 B。4.3.1 基本语法if 条件: 条件成立时执行 else: 条件不成立时执行4.3.2 AI 场景实例# 例1根据 temperature 决定回复风格 temperature 0.2 if temperature 0.5: print(模型将采用确定性输出答案更保守。) else: print(模型将引入更多随机性答案更多样。) # 例2检查模型是否支持函数调用 model_family gpt-3.5 if model_family gpt-4: print(支持函数调用和并行工具使用。) else: print(仅支持基本对话功能。) # 例3判断是否需要截断提示词 prompt_length 8500 max_context 8192 if prompt_length max_context: print(f提示词过长将自动截断至 {max_context} 字符。) else: print(提示词长度合适无需截断。)4.4 if-elif-else 语句多分支判断当你有多个互斥的条件需要判断时使用elifelse if 的缩写。4.4.1 基本语法if 条件1: 条件1成立时执行 elif 条件2: 条件1不成立但条件2成立时执行 elif 条件3: 条件1、2都不成立但条件3成立时执行 else: 所有条件都不成立时执行你可以写任意多个elifelse是可选的。4.4.2 AI 场景实例# 例1根据温度系数区间设定输出描述 temperature 1.2 if temperature 0.3: description 非常保守几乎总是选择最高概率的 token elif temperature 0.7: description 平衡在确定性和创造性之间折中 elif temperature 1.2: description 较有创造性输出更多样 else: description 高度随机可能产生出乎意料的内容 print(f当前温度 {temperature} - {description}) # 例2根据错误码处理 API 异常 error_code 429 if error_code 200: print(请求成功) elif error_code 401: print(认证失败请检查 API 密钥) elif error_code 429: print(请求频率超限请稍后重试) elif error_code 500: print(服务器内部错误建议重试) else: print(f未知错误码{error_code}) # 例3根据用户消息意图选择不同的处理方式极简版本 message 帮我写一首诗 if 翻译 in message: print(调用翻译模型) elif 写诗 in message or 作诗 in message: print(使用创意写作模型) elif 解释 in message or 是什么 in message: print(使用知识库问答模型) else: print(使用通用对话模型)4.5 嵌套条件判断条件里面还有条件有时你需要在一个条件判断内部再做更细致的判断。这就是嵌套if。4.5.1 基本语法if 外部条件: if 内部条件: 内外都满足时执行 else: 外部满足但内部不满足 else: 外部不满足4.5.2 AI 场景实例# 例1检查模型调用是否成功再检查返回结果是否有效 api_success True response_text if api_success: if response_text: print(f回复内容{response_text}) else: print(API 调用成功但返回内容为空) else: print(API 调用失败请检查网络) # 例2先判断模型是否支持流式输出再判断用户是否请求流式 model_supports_stream True user_wants_stream True if model_supports_stream: if user_wants_stream: print(启用流式输出逐词返回) else: print(模型支持流式但用户选择不使用) else: print(当前模型不支持流式输出将一次性返回完整结果) 嵌套层次不宜过深超过 3 层否则代码可读性变差。复杂的条件可以用and/or简化。4.6 条件表达式三元运算符一行简写当你只需要根据条件给变量赋不同的值时可以用更简洁的一行写法。4.6.1 语法变量 值1 if 条件 else 值2如果条件为真取值1否则取值2。4.6.2 AI 场景实例# 例1设定温度默认值 user_temp None temperature user_temp if user_temp is not None else 0.7 # 上面等价于 temperature 0.7 if user_temp is None else user_temp # 例2根据是否超出限制决定截断标志 token_count 5000 limit 4096 need_truncate True if token_count limit else False # 当然也可以直接写 need_truncate token_count limit这里仅演示语法 # 例3选择回复风格 style creative if temperature 1.0 else conservative print(f回复风格{style})4.7 for 循环遍历数据集循环让程序重复执行一段代码。for循环通常用于遍历一个序列比如列表、字符串、范围对每个元素执行相同的操作。4.7.1 遍历列表AI 中常用# 例1依次处理多个提示词 prompts [介绍Python, 什么是AI, 写一首诗] for prompt in prompts: print(f正在处理{prompt}) # 这里可以调用 API 并获取回复# 例2批量检查模型是否在允许列表中 allowed_models [gpt-4, gpt-3.5, claude-3] user_models [gpt-4, llama-2, claude-3] for m in user_models: if m in allowed_models: print(f✅ {m} 可用) else: print(f❌ {m} 不可用)4.7.2 遍历字符串处理提示词中的每个字符prompt 你好AI for ch in prompt: print(f字符{ch})4.7.3 使用range()进行数字循环range(n)生成从 0 到 n-1 的整数序列。常用于重复执行固定次数。# 例1重复调用模型 3 次展示不同 temperature 的效果 for i in range(3): temp 0.2 i * 0.4 # 0.2, 0.6, 1.0 print(f第 {i1} 次温度 {temp})# 例2批量处理 token 块 total_tokens 1500 batch_size 500 for start in range(0, total_tokens, batch_size): end min(start batch_size, total_tokens) print(f处理 token 区间 [{start}:{end}])4.7.4for与enumerate()同时获取索引和值当你既需要元素又需要它的位置索引时使用。messages [你好, 请介绍AI, 谢谢] for idx, msg in enumerate(messages): print(f第 {idx1} 条消息{msg})4.8 while 循环当条件满足时持续执行while循环在条件为True时不断重复执行代码块直到条件变为False。适用于直到某个状态改变才停止的场景。4.8.1 基本语法while 条件: 循环体⚠️ 一定要确保条件最终会变为False否则会变成无限循环程序卡死。4.8.2 AI 场景实例# 例1模拟重试机制API 调用失败时最多重试 3 次 retries 0 success False while retries 3 and not success: print(f第 {retries1} 次尝试调用 API...) # 假设调用结果 if retries 2: # 第三次成功 success True else: print(调用失败重试中...) retries 1 if success: print(API 调用成功) else: print(重试次数用尽请稍后重试)# 例2等待用户输入有效的温度值 temp None while temp is None: user_input input(请输入温度系数0~2) if user_input : print(不能为空请重新输入) continue try: val float(user_input) if 0 val 2: temp val else: print(请输入 0 到 2 之间的数字) except ValueError: print(请输入有效的数字) print(f已设置温度{temp})# 例3逐步减少剩余 token 直到用完 remaining_tokens 1024 while remaining_tokens 0: # 每次消耗 100~200 token chunk min(200, remaining_tokens) print(f发送 {chunk} 个 token) remaining_tokens - chunk print(f剩余 {remaining_tokens}) print(Token 已用完)4.9 循环控制breakcontinueelse4.9.1break立即退出整个循环常用于找到目标后提前结束。# 例检查提示词中是否包含敏感词一旦发现立即停止 sensitive [暴力, 色情] prompt 请介绍一下暴力美学 found False for word in sensitive: if word in prompt: print(f检测到敏感词{word}) found True break # 不再检查剩余词 if not found: print(提示词通过安全检查)4.9.2continue跳过本次循环剩余代码进入下一次迭代# 例处理消息列表忽略空消息 messages [你好, , 请介绍AI, , 谢谢] for msg in messages: if msg : continue # 跳过空消息 print(f处理消息{msg})4.9.3for-else和while-elseelse块在循环正常结束没有被break中断后执行。如果循环被break退出则跳过else。# 例检查模型是否在允许列表中 allowed [gpt-4, claude-3] model llama-2 for m in allowed: if model m: print(模型可用) break else: print(模型不在允许列表中拒绝请求) # 因为没有 break 才会执行4.10 综合实战AI 对话请求处理器将if、for、while等知识融合成一个能处理用户请求、校验参数、重试 API 调用的脚本。import time # 模拟的模型 API 调用函数这里只打印信息 def call_model(prompt, temperature, max_tokens): print(f[调用模型] prompt{prompt[:20]}... temp{temperature}, max_tokens{max_tokens}) # 假设有时会失败用随机数模拟 import random if random.random() 0.2: # 20% 失败率 return None, 服务器繁忙 else: return 这是模拟的回复内容。, None # 用户请求配置 user_prompts [ 请解释一下大语言模型的工作原理, 写一首关于人工智能的短诗, 介绍一下 Transformer 架构, ] # 全局参数 default_temperature 0.7 max_retries 2 # 处理每个提示词 for idx, prompt in enumerate(user_prompts, 1): print(f\n--- 处理第 {idx} 个请求 ---) # 1. 参数校验if-elif if len(prompt) 0: print(错误提示词为空跳过) continue elif len(prompt) 8000: print(提示词过长截断至 8000 字符) prompt prompt[:8000] # 2. 温度设置三元表达式 temperature default_temperature if default_temperature is None else default_temperature # 3. 重试循环while retry_count 0 success False response None error None while retry_count max_retries and not success: print(f尝试 {retry_count1}/{max_retries1}) response, error call_model(prompt, temperature, max_tokens1024) if response is not None: success True break else: print(f调用失败{error}) retry_count 1 if retry_count max_retries: wait 2 ** retry_count # 指数退避 print(f等待 {wait} 秒后重试...) time.sleep(wait) # 4. 最终结果处理if-else if success: print(f✅ 回复{response[:100]}...) # 可以继续检查回复中是否包含结束标志 if [END] in response: print(检测到结束标记停止进一步处理) else: print(f❌ 请求失败已重试 {max_retries} 次) print(\n所有请求处理完毕)输出如下内容tianpengDESKTOP-4L1UF5S:~/my-ai-service$ poetry run python src/my_ai_service/loop.py --- 处理第 1 个请求 --- 尝试 1/3 [调用模型] prompt请解释一下大语言模型的工作原理... temp0.7, max_tokens1024 ✅ 回复这是模拟的回复内容。... --- 处理第 2 个请求 --- 尝试 1/3 [调用模型] prompt写一首关于人工智能的短诗... temp0.7, max_tokens1024 ✅ 回复这是模拟的回复内容。... --- 处理第 3 个请求 --- 尝试 1/3 [调用模型] prompt介绍一下 Transformer 架构... temp0.7, max_tokens1024 调用失败服务器繁忙 等待 2 秒后重试... 尝试 2/3 [调用模型] prompt介绍一下 Transformer 架构... temp0.7, max_tokens1024 ✅ 回复这是模拟的回复内容。... 所有请求处理完毕4.11 本章小结流程控制结构作用AI 典型应用if条件成立时执行参数合法性检查if-else二选一模型是否支持某功能if-elif-else多分支选择根据错误码分类处理、根据温度区间确定风格嵌套if多重条件细化先判断调用成功再判断返回内容三元运算符简洁的条件赋值默认值设置for循环遍历序列批量处理 prompt、检查敏感词列表while循环条件满足时重复API 重试机制、等待用户有效输入break提前结束循环找到敏感词后停止continue跳过本次迭代忽略空消息for-else循环未被打断时执行检查没有匹配项后执行默认动作