<!-- markdown css tag --><section id="nice" data-tool="mdnice编辑器" data-website="https://www.mdnice.com" style="font-size: 16px; color: black; padding: 0 10px; line-height: 1.6; word-spacing: 0px; letter-spacing: 0px; word-break: break-word; word-wrap: break-word; text-align: left; font-family: PingFangSC-Light;"><figure data-tool="mdnice编辑器" style="margin: 0; margin-top: 10px; margin-bottom: 10px; display: flex; flex-direction: column; justify-content: center; align-items: center;"><img src="https://file.haoxueai.cn/haoxue/img/fa7c814b-79a9-4476-949c-c87019d5909f.png" alt style="max-width: 100%; border-radius: 0px 0px 5px 5px; display: block; margin: 20px auto; width: 85%; height: 100%; ob ject-fit: contain; box-shadow: #84A1A8 0px 10px 15px;"></figure>
<h2 data-tool="mdnice编辑器" style="margin-top: 30px; margin-bottom: 15px; padding: 0px; font-weight: bold; color: black; font-size: 22px; text-align: left; margin: 20px 10px 0px 0px;"><span class="prefix" style="display: none;"></span><span class="content" style="font-family: STHeitiSC-Light; font-size: 18px; font-weight: bolder; display: inline-block; padding-left: 10px; border-left: 5px solid rgb(248,57,41);">简介</span><span class="suffix"></span></h2>
<p data-tool="mdnice编辑器" style="padding-top: 8px; padding-bottom: 8px; color: black; margin: 10px 10px; line-height: 1.75; letter-spacing: 0.2em; font-size: 14px; word-spacing: 0.1em;">如果你曾构建过这样的AI智能体——在笔记本中运行完美无缺,可一旦部署到生产环境就彻底崩溃,那么你并不孤单。API调用超时、大语言模型(LLM)返回格式错乱、限流在最关键的时刻触发,这些都是部署AI智能体时的常见痛点。</p>
<p data-tool="mdnice编辑器" style="padding-top: 8px; padding-bottom: 8px; color: black; margin: 10px 10px; line-height: 1.75; letter-spacing: 0.2em; font-size: 14px; word-spacing: 0.1em;">部署智能体的现实往往混乱不堪,而大部分麻烦都源于如何优雅地处理失败。但关键在于:你无需庞大的框架来解决这些问题。这5个Python装饰器曾帮我解决了无数头疼的问题,相信它们也能帮到你。</p>
<h2 data-tool="mdnice编辑器" style="margin-top: 30px; margin-bottom: 15px; padding: 0px; font-weight: bold; color: black; font-size: 22px; text-align: left; margin: 20px 10px 0px 0px;"><span class="prefix" style="display: none;"></span><span class="content" style="font-family: STHeitiSC-Light; font-size: 18px; font-weight: bolder; display: inline-block; padding-left: 10px; border-left: 5px solid rgb(248,57,41);">1. 带指数退避的自动重试装饰器</span><span class="suffix"></span></h2>
<p data-tool="mdnice编辑器" style="padding-top: 8px; padding-bottom: 8px; color: black; margin: 10px 10px; line-height: 1.75; letter-spacing: 0.2em; font-size: 14px; word-spacing: 0.1em;">每个AI智能体都会与外部API交互,而所有外部API终究会出现故障。可能是OpenAI返回429状态码(触发限流),也可能是短暂的网络波动。无论哪种情况,你的智能体都不应该在第一次失败时就直接放弃。</p>
<p data-tool="mdnice编辑器" style="padding-top: 8px; padding-bottom: 8px; color: black; margin: 10px 10px; line-height: 1.75; letter-spacing: 0.2em; font-size: 14px; word-spacing: 0.1em;">@retry装饰器可以包裹任何函数,当函数抛出特定异常时,它会等待一段时间后重试。其中,指数退避(exponential backoff)至关重要——重试等待时间会随每次尝试递增:第一次重试等待1秒,第二次等待2秒,第三次等待4秒,以此类推。这样可以避免持续请求本就处于故障状态的API,减轻其负担。</p>
<p data-tool="mdnice编辑器" style="padding-top: 8px; padding-bottom: 8px; color: black; margin: 10px 10px; line-height: 1.75; letter-spacing: 0.2em; font-size: 14px; word-spacing: 0.1em;">你可以使用time.sleep()和循环自行编写简单的包装器,也可以直接使用Tenacity库——它提供了经过实战检验的@retry装饰器,开箱即用。关键是要配置正确的异常类型:对于有问题的提示词(每次都会失败),无需重试;但对于连接错误和限流响应,绝对需要重试。</p>
<p data-tool="mdnice编辑器" style="padding-top: 8px; padding-bottom: 8px; color: black; margin: 10px 10px; line-height: 1.75; letter-spacing: 0.2em; font-size: 14px; word-spacing: 0.1em;">示例(基于Tenacity库):</p>
<pre class="custom" data-tool="mdnice编辑器" style="margin-top: 10px; margin-bottom: 10px;"><code class="hljs" style="overflow-x: auto; padding: 16px; color: #abb2bf; background: #282c34; display: -webkit-box; font-family: Operator Mono, Consolas, Monaco, Menlo, monospace; border-radius: 0px; font-size: 12px; -webkit-overflow-scrolling: touch;"><span class="hljs-keyword" style="color: #c678dd; line-height: 26px;">from</span> tenacity <span class="hljs-keyword" style="color: #c678dd; line-height: 26px;">import</span> retry, stop_after_attempt, wait_exponential, retry_if_exception_type<br><span class="hljs-keyword" style="color: #c678dd; line-height: 26px;">import</span> requests<br><br><span class="hljs-comment" style="color: #5c6370; font-style: italic; line-height: 26px;"># 配置:最多重试3次,等待时间1s、2s、4s</span><br><span class="hljs-me ta" style="color: #61aeee; line-height: 26px;">@retry(</span><br> stop=stop_after_attempt(<span class="hljs-number" style="color: #d19a66; line-height: 26px;">3</span>),<br> wait=wait_exponential(multiplier=<span class="hljs-number" style="color: #d19a66; line-height: 26px;">1</span>, min=<span class="hljs-number" style="color: #d19a66; line-height: 26px;">1</span>, max=<span class="hljs-number" style="color: #d19a66; line-height: 26px;">10</span>),<br> retry=retry_if_exception_type((requests.exceptions.Connection error, requests.exceptions.HTTPError))<br>)<br><span class="hljs-function" style="line-height: 26px;"><span class="hljs-keyword" style="color: #c678dd; line-height: 26px;">def</span> <span class="hljs-title" style="color: #61aeee; line-height: 26px;">call_openai_api</span><span class="hljs-params" style="line-height: 26px;">(prompt)</span>:</span><br> response = requests.post(<br> <span class="hljs-string" style="color: #98c379; line-height: 26px;">"https://api.openai.com/v1/chat/completions"</span>,<br> json={<span class="hljs-string" style="color: #98c379; line-height: 26px;">"model"</span>: <span class="hljs-string" style="color: #98c379; line-height: 26px;">"gpt-4"</span>, <span class="hljs-string" style="color: #98c379; line-height: 26px;">"messages"</span>: [{<span class="hljs-string" style="color: #98c379; line-height: 26px;">"role"</span>: <span class="hljs-string" style="color: #98c379; line-height: 26px;">"user"</span>, <span class="hljs-string" style="color: #98c379; line-height: 26px;">"content"</span>: prompt}]},<br> headers={<span class="hljs-string" style="color: #98c379; line-height: 26px;">"Authorization"</span>: <span class="hljs-string" style="color: #98c379; line-height: 26px;">"Bearer YOUR_API_KEY"</span>}<br> )<br> response.raise_for_status() <span class="hljs-comment" style="color: #5c6370; font-style: italic; line-height: 26px;"># 触发HTTP错误(如429)</span><br> <span class="hljs-keyword" style="color: #c678dd; line-height: 26px;">return</span> response.json()<br><br><span class="hljs-comment" style="color: #5c6370; font-style: italic; line-height: 26px;"># 调用函数,自动重试限流/连接错误</span><br><span class="hljs-keyword" style="color: #c678dd; line-height: 26px;">try</span>:<br> result = call_openai_api(<span class="hljs-string" style="color: #98c379; line-height: 26px;">"Explain Python decorators in simple terms."</span>)<br> print(result)<br><span class="hljs-keyword" style="color: #c678dd; line-height: 26px;">except</span> Exception <span class="hljs-keyword" style="color: #c678dd; line-height: 26px;">as</span> e:<br> print(<span class="hljs-string" style="color: #98c379; line-height: 26px;">f"Failed after retries: <span class="hljs-subst" style="color: #e06c75; line-height: 26px;">{e}</span>"</span>)<br></code></pre>
<h2 data-tool="mdnice编辑器" style="margin-top: 30px; margin-bottom: 15px; padding: 0px; font-weight: bold; color: black; font-size: 22px; text-align: left; margin: 20px 10px 0px 0px;"><span class="prefix" style="display: none;"></span><span class="content" style="font-family: STHeitiSC-Light; font-size: 18px; font-weight: bolder; display: inline-block; padding-left: 10px; border-left: 5px solid rgb(248,57,41);">2. 超时保护装饰器</span><span class="suffix"></span></h2>
<p data-tool="mdnice编辑器" style="padding-top: 8px; padding-bottom: 8px; color: black; margin: 10px 10px; line-height: 1.75; letter-spacing: 0.2em; font-size: 14px; word-spacing: 0.1em;">LLM调用可能会挂起。这种情况不常发生,但一旦发生,你的智能体就会陷入停滞,用户只能盯着加载动画等待。更糟的是,如果你并行运行多个智能体,一个挂起的调用可能会成为整个流水线的瓶颈。</p>
<p data-tool="mdnice编辑器" style="padding-top: 8px; padding-bottom: 8px; color: black; margin: 10px 10px; line-height: 1.75; letter-spacing: 0.2em; font-size: 14px; word-spacing: 0.1em;">@timeout装饰器为函数运行设置了硬性上限。例如,如果函数在30秒内未返回,装饰器会抛出TimeoutError,你可以捕获该异常并优雅处理。对于同步代码,通常使用Python的signal模块实现;如果是异步场景,则使用asyncio.wait_for()。</p>
<p data-tool="mdnice编辑器" style="padding-top: 8px; padding-bottom: 8px; color: black; margin: 10px 10px; line-height: 1.75; letter-spacing: 0.2em; font-size: 14px; word-spacing: 0.1em;">将它与重试装饰器结合,会形成强大的组合:如果调用挂起,超时机制会终止它,然后重试逻辑会启动新的尝试。仅此一点,就能消除大部分生产环境中的故障。</p>
<p data-tool="mdnice编辑器" style="padding-top: 8px; padding-bottom: 8px; color: black; margin: 10px 10px; line-height: 1.75; letter-spacing: 0.2em; font-size: 14px; word-spacing: 0.1em;">示例(同步代码超时装饰器):</p>
<pre class="custom" data-tool="mdnice编辑器" style="margin-top: 10px; margin-bottom: 10px;"><code class="hljs" style="overflow-x: auto; padding: 16px; color: #abb2bf; background: #282c34; display: -webkit-box; font-family: Operator Mono, Consolas, Monaco, Menlo, monospace; border-radius: 0px; font-size: 12px; -webkit-overflow-scrolling: touch;"><span class="hljs-keyword" style="color: #c678dd; line-height: 26px;">import</span> signal<br><span class="hljs-keyword" style="color: #c678dd; line-height: 26px;">from</span> functools <span class="hljs-keyword" style="color: #c678dd; line-height: 26px;">import</span> wraps<br><br><span class="hljs-function" style="line-height: 26px;"><span class="hljs-keyword" style="color: #c678dd; line-height: 26px;">def</span> <span class="hljs-title" style="color: #61aeee; line-height: 26px;">timeout</span><span class="hljs-params" style="line-height: 26px;">(seconds=<span class="hljs-number" style="color: #d19a66; line-height: 26px;">30</span>)</span>:</span><br> <span class="hljs-function" style="line-height: 26px;"><span class="hljs-keyword" style="color: #c678dd; line-height: 26px;">def</span> <span class="hljs-title" style="color: #61aeee; line-height: 26px;">decorator</span><span class="hljs-params" style="line-height: 26px;">(func)</span>:</span><br> <span class="hljs-function" style="line-height: 26px;"><span class="hljs-keyword" style="color: #c678dd; line-height: 26px;">def</span> <span class="hljs-title" style="color: #61aeee; line-height: 26px;">_handle_timeout</span><span class="hljs-params" style="line-height: 26px;">(signum, fr ame)</span>:</span><br> <span class="hljs-keyword" style="color: #c678dd; line-height: 26px;">raise</span> TimeoutError(<span class="hljs-string" style="color: #98c379; line-height: 26px;">f"Function <span class="hljs-subst" style="color: #e06c75; line-height: 26px;">{func.__name__}</span> timed out after <span class="hljs-subst" style="color: #e06c75; line-height: 26px;">{seconds}</span> seconds"</span>)<br> <br><span class="hljs-me ta" style="color: #61aeee; line-height: 26px;"> @wraps(func)</span><br> <span class="hljs-function" style="line-height: 26px;"><span class="hljs-keyword" style="color: #c678dd; line-height: 26px;">def</span> <span class="hljs-title" style="color: #61aeee; line-height: 26px;">wrapper</span><span class="hljs-params" style="line-height: 26px;">(*args, **kwargs)</span>:</span><br> <span class="hljs-comment" style="color: #5c6370; font-style: italic; line-height: 26px;"># 注册信号处理器</span><br> signal.signal(signal.SIGALRM, _handle_timeout)<br> signal.alarm(seconds) <span class="hljs-comment" style="color: #5c6370; font-style: italic; line-height: 26px;"># 设置超时时间</span><br> <span class="hljs-keyword" style="color: #c678dd; line-height: 26px;">try</span>:<br> <span class="hljs-keyword" style="color: #c678dd; line-height: 26px;">return</span> func(*args, **kwargs)<br> <span class="hljs-keyword" style="color: #c678dd; line-height: 26px;">finally</span>:<br> signal.alarm(<span class="hljs-number" style="color: #d19a66; line-height: 26px;">0</span>) <span class="hljs-comment" style="color: #5c6370; font-style: italic; line-height: 26px;"># 取消超时</span><br> <span class="hljs-keyword" style="color: #c678dd; line-height: 26px;">return</span> wrapper<br> <span class="hljs-keyword" style="color: #c678dd; line-height: 26px;">return</span> decorator<br><br><span class="hljs-comment" style="color: #5c6370; font-style: italic; line-height: 26px;"># 应用超时装饰器(限制10秒)</span><br><span class="hljs-me ta" style="color: #61aeee; line-height: 26px;">@timeout(seconds=10)</span><br><span class="hljs-function" style="line-height: 26px;"><span class="hljs-keyword" style="color: #c678dd; line-height: 26px;">def</span> <span class="hljs-title" style="color: #61aeee; line-height: 26px;">call_llm</span><span class="hljs-params" style="line-height: 26px;">(prompt)</span>:</span><br> <span class="hljs-comment" style="color: #5c6370; font-style: italic; line-height: 26px;"># 模拟耗时的LLM调用</span><br> <span class="hljs-keyword" style="color: #c678dd; line-height: 26px;">import</span> time<br> time.sleep(<span class="hljs-number" style="color: #d19a66; line-height: 26px;">15</span>) <span class="hljs-comment" style="color: #5c6370; font-style: italic; line-height: 26px;"># 超过超时时间,会触发TimeoutError</span><br> <span class="hljs-keyword" style="color: #c678dd; line-height: 26px;">return</span> <span class="hljs-string" style="color: #98c379; line-height: 26px;">"LLM response: "</span> + prompt<br><br><span class="hljs-keyword" style="color: #c678dd; line-height: 26px;">try</span>:<br> call_llm(<span class="hljs-string" style="color: #98c379; line-height: 26px;">"Write a short story."</span>)<br><span class="hljs-keyword" style="color: #c678dd; line-height: 26px;">except</span> TimeoutError <span class="hljs-keyword" style="color: #c678dd; line-height: 26px;">as</span> e:<br> print(e) <span class="hljs-comment" style="color: #5c6370; font-style: italic; line-height: 26px;"># 输出:Function call_llm timed out after 10 seconds</span><br></code></pre>
<h2 data-tool="mdnice编辑器" style="margin-top: 30px; margin-bottom: 15px; padding: 0px; font-weight: bold; color: black; font-size: 22px; text-align: left; margin: 20px 10px 0px 0px;"><span class="prefix" style="display: none;"></span><span class="content" style="font-family: STHeitiSC-Light; font-size: 18px; font-weight: bolder; display: inline-block; padding-left: 10px; border-left: 5px solid rgb(248,57,41);">3. 响应缓存装饰器</span><span class="suffix"></span></h2>
<p data-tool="mdnice编辑器" style="padding-top: 8px; padding-bottom: 8px; color: black; margin: 10px 10px; line-height: 1.75; letter-spacing: 0.2em; font-size: 14px; word-spacing: 0.1em;">这是一个能大幅降低API成本的技巧。如果你的智能体多次使用相同的参数调用同一个函数(这种情况很常见,尤其是在多步推理循环中),就没有必要为同一个响应支付两次费用。</p>
<p data-tool="mdnice编辑器" style="padding-top: 8px; padding-bottom: 8px; color: black; margin: 10px 10px; line-height: 1.75; letter-spacing: 0.2em; font-size: 14px; word-spacing: 0.1em;">@cache装饰器会根据函数的输入参数存储调用结果。下次函数使用相同参数被调用时,装饰器会立即返回存储的结果。Python内置的functools.lru_cache适用于简单场景,但对于智能体工作流,你需要支持生存时间(TTL)的缓存——让缓存的响应在合理的时间窗口后过期。</p>
<p data-tool="mdnice编辑器" style="padding-top: 8px; padding-bottom: 8px; color: black; margin: 10px 10px; line-height: 1.75; letter-spacing: 0.2em; font-size: 14px; word-spacing: 0.1em;">这一点比你想象的更重要。使用工具调用模式的智能体,常常会重新验证之前的结果或重新获取已经拿到的上下文。缓存这些调用不仅能加快执行速度,还能减少月末的API账单。</p>
<p data-tool="mdnice编辑器" style="padding-top: 8px; padding-bottom: 8px; color: black; margin: 10px 10px; line-height: 1.75; letter-spacing: 0.2em; font-size: 14px; word-spacing: 0.1em;">示例(带TTL的缓存装饰器):</p>
<pre class="custom" data-tool="mdnice编辑器" style="margin-top: 10px; margin-bottom: 10px;"><code class="hljs" style="overflow-x: auto; padding: 16px; color: #abb2bf; background: #282c34; display: -webkit-box; font-family: Operator Mono, Consolas, Monaco, Menlo, monospace; border-radius: 0px; font-size: 12px; -webkit-overflow-scrolling: touch;"><span class="hljs-keyword" style="color: #c678dd; line-height: 26px;">from</span> functools <span class="hljs-keyword" style="color: #c678dd; line-height: 26px;">import</span> wraps<br><span class="hljs-keyword" style="color: #c678dd; line-height: 26px;">import</span> time<br><span class="hljs-keyword" style="color: #c678dd; line-height: 26px;">from</span> typing <span class="hljs-keyword" style="color: #c678dd; line-height: 26px;">import</span> Dict, Tuple<br><br><span class="hljs-function" style="line-height: 26px;"><span class="hljs-keyword" style="color: #c678dd; line-height: 26px;">def</span> <span class="hljs-title" style="color: #61aeee; line-height: 26px;">ttl_cache</span><span class="hljs-params" style="line-height: 26px;">(ttl_seconds=<span class="hljs-number" style="color: #d19a66; line-height: 26px;">3600</span>)</span>:</span><br> cache: Dict[Tuple, Tuple[float, any]] = {} <span class="hljs-comment" style="color: #5c6370; font-style: italic; line-height: 26px;"># 缓存格式:(参数) -> (时间戳, 结果)</span><br> <br> <span class="hljs-function" style="line-height: 26px;"><span class="hljs-keyword" style="color: #c678dd; line-height: 26px;">def</span> <span class="hljs-title" style="color: #61aeee; line-height: 26px;">decorator</span><span class="hljs-params" style="line-height: 26px;">(func)</span>:</span><br><span class="hljs-me ta" style="color: #61aeee; line-height: 26px;"> @wraps(func)</span><br> <span class="hljs-function" style="line-height: 26px;"><span class="hljs-keyword" style="color: #c678dd; line-height: 26px;">def</span> <span class="hljs-title" style="color: #61aeee; line-height: 26px;">wrapper</span><span class="hljs-params" style="line-height: 26px;">(*args, **kwargs)</span>:</span><br> <span class="hljs-comment" style="color: #5c6370; font-style: italic; line-height: 26px;"># 将参数转为可哈希的元组,作为缓存键</span><br> key = (args, frozenset(kwargs.items()))<br> now = time.time()<br> <br> <span class="hljs-comment" style="color: #5c6370; font-style: italic; line-height: 26px;"># 检查缓存是否存在且未过期</span><br> <span class="hljs-keyword" style="color: #c678dd; line-height: 26px;">if</span> key <span class="hljs-keyword" style="color: #c678dd; line-height: 26px;">in</span> cache:<br> cache_time, result = cache[key]<br> <span class="hljs-keyword" style="color: #c678dd; line-height: 26px;">if</span> now - cache_time < ttl_seconds:<br> <span class="hljs-keyword" style="color: #c678dd; line-height: 26px;">return</span> result<br> <br> <span class="hljs-comment" style="color: #5c6370; font-style: italic; line-height: 26px;"># 执行函数并缓存结果</span><br> result = func(*args, **kwargs)<br> cache[key] = (now, result)<br> <span class="hljs-keyword" style="color: #c678dd; line-height: 26px;">return</span> result<br> <span class="hljs-keyword" style="color: #c678dd; line-height: 26px;">return</span> wrapper<br> <span class="hljs-keyword" style="color: #c678dd; line-height: 26px;">return</span> decorator<br><br><span class="hljs-comment" style="color: #5c6370; font-style: italic; line-height: 26px;"># 应用缓存(缓存1小时)</span><br><span class="hljs-me ta" style="color: #61aeee; line-height: 26px;">@ttl_cache(ttl_seconds=3600)</span><br><span class="hljs-function" style="line-height: 26px;"><span class="hljs-keyword" style="color: #c678dd; line-height: 26px;">def</span> <span class="hljs-title" style="color: #61aeee; line-height: 26px;">get_weather</span><span class="hljs-params" style="line-height: 26px;">(city)</span>:</span><br> <span class="hljs-comment" style="color: #5c6370; font-style: italic; line-height: 26px;"># 模拟调用天气API(耗时且有成本)</span><br> <span class="hljs-keyword" style="color: #c678dd; line-height: 26px;">import</span> requests<br> response = requests.get(<span class="hljs-string" style="color: #98c379; line-height: 26px;">f"https://api.weatherapi.com/v1/current.json?key=YOUR_KEY&q=<span class="hljs-subst" style="color: #e06c75; line-height: 26px;">{city}</span>"</span>)<br> <span class="hljs-keyword" style="color: #c678dd; line-height: 26px;">return</span> response.json()<br><br><span class="hljs-comment" style="color: #5c6370; font-style: italic; line-height: 26px;"># 第一次调用:执行API请求并缓存</span><br>print(get_weather(<span class="hljs-string" style="color: #98c379; line-height: 26px;">"London"</span>))<br><span class="hljs-comment" style="color: #5c6370; font-style: italic; line-height: 26px;"># 1小时内再次调用:直接返回缓存结果,不发起API请求</span><br>print(get_weather(<span class="hljs-string" style="color: #98c379; line-height: 26px;">"London"</span>))<br></code></pre>
<h2 data-tool="mdnice编辑器" style="margin-top: 30px; margin-bottom: 15px; padding: 0px; font-weight: bold; color: black; font-size: 22px; text-align: left; margin: 20px 10px 0px 0px;"><span class="prefix" style="display: none;"></span><span class="content" style="font-family: STHeitiSC-Light; font-size: 18px; font-weight: bolder; display: inline-block; padding-left: 10px; border-left: 5px solid rgb(248,57,41);">4. 输入输出验证装饰器</span><span class="suffix"></span></h2>
<p data-tool="mdnice编辑器" style="padding-top: 8px; padding-bottom: 8px; color: black; margin: 10px 10px; line-height: 1.75; letter-spacing: 0.2em; font-size: 14px; word-spacing: 0.1em;">大语言模型本质上是不可预测的。你发送一个精心设计的、要求返回JSON的提示词,但有时得到的却是带有尾随逗号的Markdown代码块,导致解析失败。@validate装饰器会在边界处捕获这些问题,防止错误数据流入智能体的深层逻辑。</p>
<p data-tool="mdnice编辑器" style="padding-top: 8px; padding-bottom: 8px; color: black; margin: 10px 10px; line-height: 1.75; letter-spacing: 0.2em; font-size: 14px; word-spacing: 0.1em;">在输入侧,装饰器检查函数接收的参数是否符合预期的类型和约束;在输出侧,它验证返回值是否符合预设的模式——而Pydantic库能让这个过程变得极其简洁。你只需将预期的响应定义为Pydantic模型,装饰器就会尝试将LLM输出解析为该模型。如果验证失败,你可以重试调用、应用修复函数,或回退到默认值。</p>
<p data-tool="mdnice编辑器" style="padding-top: 8px; padding-bottom: 8px; color: black; margin: 10px 10px; line-height: 1.75; letter-spacing: 0.2em; font-size: 14px; word-spacing: 0.1em;">真正的优势在于:验证装饰器能将隐性的数据损坏转化为显性的、可捕获的错误。你可以在几分钟内调试完问题,而不是花费数小时。</p>
<p data-tool="mdnice编辑器" style="padding-top: 8px; padding-bottom: 8px; color: black; margin: 10px 10px; line-height: 1.75; letter-spacing: 0.2em; font-size: 14px; word-spacing: 0.1em;">示例(基于Pydantic的验证装饰器):</p>
<pre class="custom" data-tool="mdnice编辑器" style="margin-top: 10px; margin-bottom: 10px;"><code class="hljs" style="overflow-x: auto; padding: 16px; color: #abb2bf; background: #282c34; display: -webkit-box; font-family: Operator Mono, Consolas, Monaco, Menlo, monospace; border-radius: 0px; font-size: 12px; -webkit-overflow-scrolling: touch;"><span class="hljs-keyword" style="color: #c678dd; line-height: 26px;">from</span> functools <span class="hljs-keyword" style="color: #c678dd; line-height: 26px;">import</span> wraps<br><span class="hljs-keyword" style="color: #c678dd; line-height: 26px;">from</span> pydantic <span class="hljs-keyword" style="color: #c678dd; line-height: 26px;">import</span> BaseModel, Validation error<br><br><span class="hljs-comment" style="color: #5c6370; font-style: italic; line-height: 26px;"># 定义LLM输出的预期模型</span><br><span class="hljs-class" style="line-height: 26px;"><span class="hljs-keyword" style="color: #c678dd; line-height: 26px;">class</span> <span class="hljs-title" style="color: #e6c07b; line-height: 26px;">LLMResponse</span><span class="hljs-params" style="line-height: 26px;">(BaseModel)</span>:</span><br> answer: str<br> confidence: float <span class="hljs-comment" style="color: #5c6370; font-style: italic; line-height: 26px;"># 0-1之间的置信度</span><br> sources: list[str] <span class="hljs-comment" style="color: #5c6370; font-style: italic; line-height: 26px;"># 引用来源列表</span><br><br><span class="hljs-function" style="line-height: 26px;"><span class="hljs-keyword" style="color: #c678dd; line-height: 26px;">def</span> <span class="hljs-title" style="color: #61aeee; line-height: 26px;">validate_output</span><span class="hljs-params" style="line-height: 26px;">(model)</span>:</span><br> <span class="hljs-function" style="line-height: 26px;"><span class="hljs-keyword" style="color: #c678dd; line-height: 26px;">def</span> <span class="hljs-title" style="color: #61aeee; line-height: 26px;">decorator</span><span class="hljs-params" style="line-height: 26px;">(func)</span>:</span><br><span class="hljs-me ta" style="color: #61aeee; line-height: 26px;"> @wraps(func)</span><br> <span class="hljs-function" style="line-height: 26px;"><span class="hljs-keyword" style="color: #c678dd; line-height: 26px;">def</span> <span class="hljs-title" style="color: #61aeee; line-height: 26px;">wrapper</span><span class="hljs-params" style="line-height: 26px;">(*args, **kwargs)</span>:</span><br> result = func(*args, **kwargs)<br> <span class="hljs-keyword" style="color: #c678dd; line-height: 26px;">try</span>:<br> <span class="hljs-comment" style="color: #5c6370; font-style: italic; line-height: 26px;"># 尝试将结果解析为指定模型</span><br> <span class="hljs-keyword" style="color: #c678dd; line-height: 26px;">return</span> model(**result)<br> <span class="hljs-keyword" style="color: #c678dd; line-height: 26px;">except</span> Validation error <span class="hljs-keyword" style="color: #c678dd; line-height: 26px;">as</span> e:<br> print(<span class="hljs-string" style="color: #98c379; line-height: 26px;">f"Output validation failed: <span class="hljs-subst" style="color: #e06c75; line-height: 26px;">{e}</span>"</span>)<br> <span class="hljs-comment" style="color: #5c6370; font-style: italic; line-height: 26px;"># 验证失败时的处理:重试、修复或回退</span><br> <span class="hljs-keyword" style="color: #c678dd; line-height: 26px;">raise</span> <span class="hljs-comment" style="color: #5c6370; font-style: italic; line-height: 26px;"># 此处简化为抛出异常,实际可替换为重试逻辑</span><br> <span class="hljs-keyword" style="color: #c678dd; line-height: 26px;">return</span> wrapper<br> <span class="hljs-keyword" style="color: #c678dd; line-height: 26px;">return</span> decorator<br><br><span class="hljs-comment" style="color: #5c6370; font-style: italic; line-height: 26px;"># 应用输出验证装饰器</span><br><span class="hljs-me ta" style="color: #61aeee; line-height: 26px;">@validate_output(LLMResponse)</span><br><span class="hljs-function" style="line-height: 26px;"><span class="hljs-keyword" style="color: #c678dd; line-height: 26px;">def</span> <span class="hljs-title" style="color: #61aeee; line-height: 26px;">call_llm_for_answer</span><span class="hljs-params" style="line-height: 26px;">(prompt)</span>:</span><br> <span class="hljs-comment" style="color: #5c6370; font-style: italic; line-height: 26px;"># 模拟LLM返回(正常情况)</span><br> <span class="hljs-comment" style="color: #5c6370; font-style: italic; line-height: 26px;"># return {"answer": "Python decorators are useful.", "confidence": 0.95, "sources": ["Python Docs"]}</span><br> <br> <span class="hljs-comment" style="color: #5c6370; font-style: italic; line-height: 26px;"># 模拟LLM返回格式错误(confidence为字符串,sources缺失)</span><br> <span class="hljs-keyword" style="color: #c678dd; line-height: 26px;">return</span> {<span class="hljs-string" style="color: #98c379; line-height: 26px;">"answer"</span>: <span class="hljs-string" style="color: #98c379; line-height: 26px;">"Python decorators are useful."</span>, <span class="hljs-string" style="color: #98c379; line-height: 26px;">"confidence"</span>: <span class="hljs-string" style="color: #98c379; line-height: 26px;">"high"</span>}<br><br><span class="hljs-keyword" style="color: #c678dd; line-height: 26px;">try</span>:<br> response = call_llm_for_answer(<span class="hljs-string" style="color: #98c379; line-height: 26px;">"What are Python decorators?"</span>)<br> print(response.answer)<br><span class="hljs-keyword" style="color: #c678dd; line-height: 26px;">except</span> Validation error:<br> print(<span class="hljs-string" style="color: #98c379; line-height: 26px;">"Failed to get valid LLM response."</span>)<br></code></pre>
<h2 data-tool="mdnice编辑器" style="margin-top: 30px; margin-bottom: 15px; padding: 0px; font-weight: bold; color: black; font-size: 22px; text-align: left; margin: 20px 10px 0px 0px;"><span class="prefix" style="display: none;"></span><span class="content" style="font-family: STHeitiSC-Light; font-size: 18px; font-weight: bolder; display: inline-block; padding-left: 10px; border-left: 5px solid rgb(248,57,41);">5. 回退链装饰器</span><span class="suffix"></span></h2>
<p data-tool="mdnice编辑器" style="padding-top: 8px; padding-bottom: 8px; color: black; margin: 10px 10px; line-height: 1.75; letter-spacing: 0.2em; font-size: 14px; word-spacing: 0.1em;">生产环境中的智能体需要备用方案。如果主模型宕机、向量数据库无法访问、工具API返回无效数据,你的智能体应该优雅降级,而不是直接崩溃。</p>
<p data-tool="mdnice编辑器" style="padding-top: 8px; padding-bottom: 8px; color: black; margin: 10px 10px; line-height: 1.75; letter-spacing: 0.2em; font-size: 14px; word-spacing: 0.1em;">@fallback装饰器允许你定义一系列备选函数。装饰器首先尝试调用主函数,如果主函数抛出异常,则依次调用链中的下一个函数。你可以设置这样的回退逻辑:从GPT-5.4到Claude,再到本地的Llama模型;或者从实时数据库查询到缓存快照,再到硬编码的默认值。</p>
<p data-tool="mdnice编辑器" style="padding-top: 8px; padding-bottom: 8px; color: black; margin: 10px 10px; line-height: 1.75; letter-spacing: 0.2em; font-size: 14px; word-spacing: 0.1em;">实现方式很简单:装饰器接收一个备选可调用对象列表,在主函数失败时迭代调用它们。你还可以添加日志记录,跟踪每一次回退的层级,明确系统降级的原因和位置。这种模式在生产级机器学习系统中随处可见,将其封装为装饰器,可以让回退逻辑与业务代码分离,保持代码整洁。</p>
<p data-tool="mdnice编辑器" style="padding-top: 8px; padding-bottom: 8px; color: black; margin: 10px 10px; line-height: 1.75; letter-spacing: 0.2em; font-size: 14px; word-spacing: 0.1em;">示例(回退链装饰器):</p>
<pre class="custom" data-tool="mdnice编辑器" style="margin-top: 10px; margin-bottom: 10px;"><code class="hljs" style="overflow-x: auto; padding: 16px; color: #abb2bf; background: #282c34; display: -webkit-box; font-family: Operator Mono, Consolas, Monaco, Menlo, monospace; border-radius: 0px; font-size: 12px; -webkit-overflow-scrolling: touch;"><span class="hljs-keyword" style="color: #c678dd; line-height: 26px;">from</span> functools <span class="hljs-keyword" style="color: #c678dd; line-height: 26px;">import</span> wraps<br><span class="hljs-keyword" style="color: #c678dd; line-height: 26px;">import</span> logging<br><br>logging.basicConfig(level=logging.INFO)<br><br><span class="hljs-function" style="line-height: 26px;"><span class="hljs-keyword" style="color: #c678dd; line-height: 26px;">def</span> <span class="hljs-title" style="color: #61aeee; line-height: 26px;">fallback</span><span class="hljs-params" style="line-height: 26px;">(*fallback_funcs)</span>:</span><br> <span class="hljs-function" style="line-height: 26px;"><span class="hljs-keyword" style="color: #c678dd; line-height: 26px;">def</span> <span class="hljs-title" style="color: #61aeee; line-height: 26px;">decorator</span><span class="hljs-params" style="line-height: 26px;">(func)</span>:</span><br><span class="hljs-me ta" style="color: #61aeee; line-height: 26px;"> @wraps(func)</span><br> <span class="hljs-function" style="line-height: 26px;"><span class="hljs-keyword" style="color: #c678dd; line-height: 26px;">def</span> <span class="hljs-title" style="color: #61aeee; line-height: 26px;">wrapper</span><span class="hljs-params" style="line-height: 26px;">(*args, **kwargs)</span>:</span><br> <span class="hljs-comment" style="color: #5c6370; font-style: italic; line-height: 26px;"># 先尝试主函数</span><br> <span class="hljs-keyword" style="color: #c678dd; line-height: 26px;">try</span>:<br> result = func(*args, **kwargs)<br> logging.info(<span class="hljs-string" style="color: #98c379; line-height: 26px;">f"Successfully executed primary function: <span class="hljs-subst" style="color: #e06c75; line-height: 26px;">{func.__name__}</span>"</span>)<br> <span class="hljs-keyword" style="color: #c678dd; line-height: 26px;">return</span> result<br> <span class="hljs-keyword" style="color: #c678dd; line-height: 26px;">except</span> Exception <span class="hljs-keyword" style="color: #c678dd; line-height: 26px;">as</span> e:<br> logging.warning(<span class="hljs-string" style="color: #98c379; line-height: 26px;">f"Primary function <span class="hljs-subst" style="color: #e06c75; line-height: 26px;">{func.__name__}</span> failed: <span class="hljs-subst" style="color: #e06c75; line-height: 26px;">{e}</span>"</span>)<br> <br> <span class="hljs-comment" style="color: #5c6370; font-style: italic; line-height: 26px;"># 依次尝试备选函数</span><br> <span class="hljs-keyword" style="color: #c678dd; line-height: 26px;">for</span> fallback_func <span class="hljs-keyword" style="color: #c678dd; line-height: 26px;">in</span> fallback_funcs:<br> <span class="hljs-keyword" style="color: #c678dd; line-height: 26px;">try</span>:<br> result = fallback_func(*args, **kwargs)<br> logging.info(<span class="hljs-string" style="color: #98c379; line-height: 26px;">f"Fell back to <span class="hljs-subst" style="color: #e06c75; line-height: 26px;">{fallback_func.__name__}</span>"</span>)<br> <span class="hljs-keyword" style="color: #c678dd; line-height: 26px;">return</span> result<br> <span class="hljs-keyword" style="color: #c678dd; line-height: 26px;">except</span> Exception <span class="hljs-keyword" style="color: #c678dd; line-height: 26px;">as</span> e:<br> logging.warning(<span class="hljs-string" style="color: #98c379; line-height: 26px;">f"Fallback function <span class="hljs-subst" style="color: #e06c75; line-height: 26px;">{fallback_func.__name__}</span> failed: <span class="hljs-subst" style="color: #e06c75; line-height: 26px;">{e}</span>"</span>)<br> <br> <span class="hljs-comment" style="color: #5c6370; font-style: italic; line-height: 26px;"># 所有函数都失败时抛出异常</span><br> <span class="hljs-keyword" style="color: #c678dd; line-height: 26px;">raise</span> Exception(<span class="hljs-string" style="color: #98c379; line-height: 26px;">"All primary and fallback functions failed"</span>)<br> <span class="hljs-keyword" style="color: #c678dd; line-height: 26px;">return</span> wrapper<br> <span class="hljs-keyword" style="color: #c678dd; line-height: 26px;">return</span> decorator<br><br><span class="hljs-comment" style="color: #5c6370; font-style: italic; line-height: 26px;"># 定义主函数和备选函数</span><br><span class="hljs-function" style="line-height: 26px;"><span class="hljs-keyword" style="color: #c678dd; line-height: 26px;">def</span> <span class="hljs-title" style="color: #61aeee; line-height: 26px;">call_gpt</span><span class="hljs-params" style="line-height: 26px;">(prompt)</span>:</span><br> <span class="hljs-comment" style="color: #5c6370; font-style: italic; line-height: 26px;"># 模拟主模型(GPT-5.4)失败</span><br> <span class="hljs-keyword" style="color: #c678dd; line-height: 26px;">raise</span> Exception(<span class="hljs-string" style="color: #98c379; line-height: 26px;">"GPT-5.4 is down"</span>)<br><br><span class="hljs-function" style="line-height: 26px;"><span class="hljs-keyword" style="color: #c678dd; line-height: 26px;">def</span> <span class="hljs-title" style="color: #61aeee; line-height: 26px;">call_claude</span><span class="hljs-params" style="line-height: 26px;">(prompt)</span>:</span><br> <span class="hljs-comment" style="color: #5c6370; font-style: italic; line-height: 26px;"># 模拟备选模型(Claude)正常运行</span><br> <span class="hljs-keyword" style="color: #c678dd; line-height: 26px;">return</span> <span class="hljs-string" style="color: #98c379; line-height: 26px;">f"Claude response to: <span class="hljs-subst" style="color: #e06c75; line-height: 26px;">{prompt}</span>"</span><br><br><span class="hljs-function" style="line-height: 26px;"><span class="hljs-keyword" style="color: #c678dd; line-height: 26px;">def</span> <span class="hljs-title" style="color: #61aeee; line-height: 26px;">call_llama</span><span class="hljs-params" style="line-height: 26px;">(prompt)</span>:</span><br> <span class="hljs-comment" style="color: #5c6370; font-style: italic; line-height: 26px;"># 模拟第二个备选模型(本地Llama)</span><br> <span class="hljs-keyword" style="color: #c678dd; line-height: 26px;">return</span> <span class="hljs-string" style="color: #98c379; line-height: 26px;">f"Llama response to: <span class="hljs-subst" style="color: #e06c75; line-height: 26px;">{prompt}</span>"</span><br><br><span class="hljs-comment" style="color: #5c6370; font-style: italic; line-height: 26px;"># 应用回退装饰器:主函数call_gpt,备选函数call_claude、call_llama</span><br><span class="hljs-me ta" style="color: #61aeee; line-height: 26px;">@fallback(call_claude, call_llama)</span><br><span class="hljs-function" style="line-height: 26px;"><span class="hljs-keyword" style="color: #c678dd; line-height: 26px;">def</span> <span class="hljs-title" style="color: #61aeee; line-height: 26px;">get_llm_response</span><span class="hljs-params" style="line-height: 26px;">(prompt)</span>:</span><br> <span class="hljs-keyword" style="color: #c678dd; line-height: 26px;">return</span> call_gpt(prompt)<br><br><span class="hljs-comment" style="color: #5c6370; font-style: italic; line-height: 26px;"># 调用函数,会自动回退到第一个可用的备选函数</span><br>response = get_llm_response(<span class="hljs-string" style="color: #98c379; line-height: 26px;">"Explain quantum computing simply."</span>)<br>print(response)<br></code></pre>
<h2 data-tool="mdnice编辑器" style="margin-top: 30px; margin-bottom: 15px; padding: 0px; font-weight: bold; color: black; font-size: 22px; text-align: left; margin: 20px 10px 0px 0px;"><span class="prefix" style="display: none;"></span><span class="content" style="font-family: STHeitiSC-Light; font-size: 18px; font-weight: bolder; display: inline-block; padding-left: 10px; border-left: 5px solid rgb(248,57,41);">结论</span><span class="suffix"></span></h2>
<p data-tool="mdnice编辑器" style="padding-top: 8px; padding-bottom: 8px; color: black; margin: 10px 10px; line-height: 1.75; letter-spacing: 0.2em; font-size: 14px; word-spacing: 0.1em;">在构建可靠的AI智能体时,装饰器是Python中最被低估的特性之一。本文介绍的5种装饰器模式,解决了智能体离开Jupyter笔记本、进入生产环境后最常见的故障场景。</p>
<p data-tool="mdnice编辑器" style="padding-top: 8px; padding-bottom: 8px; color: black; margin: 10px 10px; line-height: 1.75; letter-spacing: 0.2em; font-size: 14px; word-spacing: 0.1em;">而且它们可以完美组合:将@retry、@timeout和@validate叠加使用,你就能得到一个不会挂起、不会轻易放弃、不会悄悄传递错误数据的函数。从今天开始,为你的API调用添加重试逻辑吧。一旦你感受到错误处理变得多么简洁,你会希望在所有地方都用上装饰器。</p>
<h3 data-tool="mdnice编辑器" style="margin-top: 30px; margin-bottom: 15px; padding: 0px; font-weight: bold; color: black; font-size: 20px;"><span class="prefix" style="display: none;"></span><span class="content" style="font-size: 14px; color: rgb(165,213,93);">推荐学习书籍 《<strong style="font-weight: border; color: rgb(248,57,41);">CDA一级教材</strong>》适合CDA一级考生备考,也适合业务及数据分析岗位的从业者提升自我。完整电子版已上线CDA网校,累计已有10万+在读~ !</span><span class="suffix" style="display: none;"></span></h3>
<figure data-tool="mdnice编辑器" style="margin: 0; margin-top: 10px; margin-bottom: 10px; display: flex; flex-direction: column; justify-content: center; align-items: center;"><img src="https://file.haoxueai.cn/haoxue/img/4502d41c-fb3a-43a8-bf50-9e14aedde094.png" alt style="max-width: 100%; border-radius: 0px 0px 5px 5px; display: block; margin: 20px auto; width: 85%; height: 100%; ob ject-fit: contain; box-shadow: #84A1A8 0px 10px 15px;"></figure>
<h3 data-tool="mdnice编辑器" style="margin-top: 30px; margin-bottom: 15px; padding: 0px; font-weight: bold; color: black; font-size: 20px;"><span class="prefix" style="display: none;"></span><span class="content" style="font-size: 14px; color: rgb(165,213,93);">免费加入阅读:<a href="https://edu.cda.cn/goods/show/3151?targetId=5147&preview=0" style="text-decoration: none; word-wrap: break-word; font-weight: bold; color: rgb(248,57,41); border-bottom: 1px solid #ff3502; font-family: STHeitiSC-Light;">https://edu.cda.cn/goods/show/3151?targetId=5147&preview=0</a></span><span class="suffix" style="display: none;"></span></h3>
</section>


雷达卡





京公网安备 11010802022788号







