教程演示用 Oxlo.ai + DeepSeek-V3.2 构建深度推理 Debug Agent,自动分析 Python 代码逻辑错误、输出结构化修复方案,配合 CI 使用可降低人工排查成本。
我们要构建一个深度推理 debug agent,它可以分析 Python 代码中的细微逻辑错误、解释思维链,并返回结构化的修复方案。这对于希望在 CI 中实现自动化推理的团队很有价值——无需为长堆栈跟踪或完整文件上下文支付按 token 计费的费用。因为 Oxlo.ai 采用按请求 flat 计费模式,无论长度如何,将整个模块喂给推理模型的成本都一样。详情见 https://oxlo.ai/pricing。
依赖安装:
pip install openai
需要一个来自 https://portal.oxlo.ai 的 Oxlo.ai API key。
同时建议将 key 设置为名为 OXLO_API_KEY 的环境变量,这样就不必硬编码凭据。
首先导入 OpenAI SDK 并将其指向 Oxlo.ai。我使用 deepseek-v3.2,因为它在编码和推理方面表现出色,而且在 Oxlo.ai 免费层可用。
import os
from openai import OpenAI
client = OpenAI(
base_url="https://api.oxlo.ai/v1",
api_key=os.environ.get("OXLO_API_KEY"),
)
# Quick connectivity check
response = client.chat.completions.create(
model="deepseek-v3.2",
messages=[{"role": "user", "content": "Say 'Oxlo.ai client ready'"}],
)
print(response.choices[0].message.content)
深度推理在强制模型外化其思维时效果最佳。我使用一个 system prompt,要求在任何结论之前进行逐步分析。
SYSTEM_PROMPT = """You are a senior software engineer performing a deep reasoning code review.
When given code and a context description, follow these steps exactly:
1. Restate the intended behavior in your own words.
2. Trace through the execution path line by line.
3. Identify any logic errors, race conditions, or edge cases.
4. Explain the root cause of each issue.
5. Provide a corrected code snippet.
Return your analysis as a JSON object with keys: restatement, trace, issues, root_causes, fixed_code."""
我把这个调用封装成一个函数,接受代码块和 bug 报告,将它们注入用户消息,然后打印原始推理跟踪。
def analyze_code(code: str, context: str) -> str:
user_message = (
f"Context: {context}\n\n"
f"Code:\n\n```python\n{code}\n```\n\n"
"Perform your step-by-step analysis."
)
response = client.chat.completions.create(
model="deepseek-v3.2",
messages=[
{"role": "system", "content": SYSTEM_PROMPT},
{"role": "user", "content": user_message},
],
temperature=0.2,
)
return response.choices[0].message.content
# Example buggy code with a race condition
buggy_code = '''
import threading
class Counter:
def __init__(self):
self.value = 0
def increment(self):
self.value += 1
def worker(counter):
for _ in range(100000):
counter.increment()
counter = Counter()
t1 = threading.Thread(target=worker, args=(counter,))
t2 = threading.Thread(target=worker, args=(counter,))
t1.start()
t2.start()
t1.join()
t2.join()
print(counter.value)
'''
context = (
"This script is supposed to count to 200000 "
"but often prints a lower number. Explain why."
)
result = analyze_code(buggy_code, context)
print(result)
原始文本适合调试,但我需要机器可读的结果,以便存储或在 CI 中做门控。我启用 JSON 模式并用标准库解析输出。Oxlo.ai 在 deepseek-v3.2 等模型上支持 JSON 模式,所以我添加 response_format 并在 prompt 中加入一个小 schema 提醒。
import json
# Same buggy example from Step 3
buggy_code = '''
import threading
class Counter:
def __init__(self):
self.value = 0
def increment(self):
self.value += 1
def worker(counter):
for _ in range(100000):
counter.increment()
counter = Counter()
t1 = threading.Thread(target=worker, args=(counter,))
t2 = threading.Thread(target=worker, args=(counter,))
t1.start()
t2.start()
t1.join()
t2.join()
print(counter.value)
'''
context = (
"This script is supposed to count to 200000 "
"but often prints a lower number. Explain why."
)
def analyze_code_structured(code: str, context: str) -> dict:
user_message = (
f"Context: {context}\n\n"
f"Code:\n\n```python\n{code}\n```\n\n"
"Return your analysis as valid JSON with exactly these keys: "
"restatement (string), trace (string), issues (list of strings), "
"root_causes (list of strings), fixed_code (string)."
)
response = client.chat.completions.create(
model="deepseek-v3.2",
messages=[
{"role": "system", "content": SYSTEM_PROMPT},
{"role": "user", "content": user_message},
],
temperature=0.2,
response_format={"type": "json_object"},
)
content = response.choices[0].message.content
return json.loads(content)
analysis = analyze_code_structured(buggy_code, context)
print(json.dumps(analysis, indent=2))
将完整脚本保存为 reasoning_agent.py 并运行。你会看到一个 JSON 对象,它重述了问题、跟踪了非原子的 increment 操作、标记了竞态条件,并提供了一个使用 threading.Lock 的线程安全修复方案。
$ python reasoning_agent.py
{
"restatement": "The script attempts to increment a shared counter from two threads until the total reaches 200000.",
"trace": "1. Thread A reads self.value (e.g., 100). 2. Thread B reads self.value (100). 3. Thread A increments locally to 101. 4. Thread B increments locally to 101. 5. Thread A writes 101. 6. Thread B writes 101. One increment is lost.",
"issues": [
"Race condition in Counter.increment",
"Non-atomic read-modify-write on self.value"
],
"root_causes": [
"The += operator compiles to multiple bytecode instructions that can interleave across threads without synchronization."
],
"fixed_code": "import threading\n\nclass Counter:\n def __init__(self):\n self.value = 0\n self._lock = threading.Lock()\n\n def increment(self):\n with self._lock:\n self.value += 1\n\ndef worker(counter):\n for _ in range(100000):\n counter.increment()\n\ncounter = Counter()\nt1 = threading.Thread(target=worker, args=(counter,))\nt2 = threading.Thread(target=worker, args=(counter,))\nt1.start()\nt2.start()\nt1.join()\nt2.join()\nprint(counter.value)"
}
如果切换模型到 deepseek-r1-671b 或 kimi-k2.6,会得到更深入的思维链推理。在 Oxlo.ai 上,按请求计费模式保持长上下文 review 的成本可预测,这在开始向模型传入整个模块或堆栈跟踪时尤为重要。
你现在有了一个可用的深度推理 agent,它可以外化思维并返回结构化修复方案。有两种具体方式可以扩展它:第一,将 agent 接入 GitHub Action,自动在 pull request 上评论。第二,当需要推理大型架构变更或多文件重构时,切换到 deepseek-r1-671b 或 kimi-k2.6。Oxlo.ai 的按请求计费模式使长上下文 review 的成本可控,当你开始向模型传入整个模块或堆栈跟踪时,这一点至关重要。