Learning_RoadmapAI_Assistant_BasicsModel_Building_and_APIData_Governance_and_SecurityLLM_Book_IngestionTokenizationAttention_MechanismGPT_ArchitecturePretrainingFineTuningLoRAReasoning_Model_Book_IngestionStarTalent_ArchitectureLLM_Engineer_Handbook_CourseRAG_Building_BlocksLangChain_RunnableAI_Engineering_Chip_HuyenLLM_Ops_FinancePython_BootcampReference_Index
基础

Python 学习助手 — 本地 LLM API 入门 (L1 预热)

Python 学习助手 — 本地 LLM API 入门 (L1 预热)

对应课程: course_A 前置 (LLM API预热)

难度: ★☆☆ (L1 入门)

建议用时: 1天

本 notebook 演示如何通过本地 llama.cpp 服务的 OpenAI 兼容 API 调用 AI 辅助学习 Python。

这是所有课程的前置准备:确保你的本地 LLM 正常工作。

前提: llama-server 已在后台运行 (http://localhost:8080)

代码
import httpx
import json

BASE_URL = "http://localhost:8080/v1"
client = httpx.Client(base_url=BASE_URL, timeout=60)

# 验证连接
r = client.get("/models")
print("模型:", r.json()["data"][0]["id"])
print("参数:", round(r.json()["data"][0]["meta"]["n_params"]/1e9, 1), "B")

核心函数: ask()

一个简单的助手函数,向本地 LLM 发送消息并返回回答。

代码
def ask(prompt: str, system: str = "你是一个Python编程导师。用中文回答,给出代码示例。") -> str:
    """向本地 LLM 提问,返回回答文本"""
    r = client.post("/chat/completions", json={
        "model": "Qwen3.5-9B-Q4_K_M.gguf",
        "messages": [
            {"role": "system", "content": system},
            {"role": "user", "content": prompt}
        ],
        "temperature": 0.3,
        "max_tokens": 1024
    })
    return r.json()["choices"][0]["message"]["content"]
代码
# 测试提问
answer = ask("Python的装饰器是什么?给一个简单例子")
print(answer)

学习场景 1: 代码解释

遇到看不懂的代码时,让 AI 逐行解释。

代码
code = '''
def fibonacci():
    a, b = 0, 1
    while True:
        yield a
        a, b = b, a + b

fib = fibonacci()
first_10 = [next(fib) for _ in range(10)]
print(first_10)
'''

answer = ask(f"逐行解释这段代码的工作原理:\n```python\n{code}\n```")
print(answer)

学习场景 2: 概念类比

让 AI 用生活类比解释抽象概念。

代码
answer = ask("用超市排队的类比解释 Python 的 async/await 机制")
print(answer)

学习场景 3: 出练习题

让 AI 根据当前学习进度出练习题。

代码
answer = ask(
    "我刚学完Python列表和字典。给我出3道练习题,难度递进,"
    "每题包含: 题目描述 + 预期输出 + 提示"
)
print(answer)

学习场景 4: 代码审查

写完代码后让 AI 审查,找出潜在问题。

代码
my_code = '''
def calculate_average(numbers):
    total = sum(numbers)
    count = len(numbers)
    return total / count

data = [10, 20, 30, '40', 50]
result = calculate_average(data)
print(f"平均: {result}")
'''

answer = ask(f"审查这段代码,找出所有潜在问题并给出修复建议:\n```python\n{my_code}\n```")
print(answer)

学习场景 5: 对话式学习(多轮)

多轮对话,持续追问。

代码
messages = [
    {"role": "system", "content": "你是一个Python编程导师。用中文回答。"},
    {"role": "user", "content": "什么是 Python 的列表推导式?"}
]

r = client.post("/chat/completions", json={
    "model": "Qwen3.5-9B-Q4_K_M.gguf",
    "messages": messages,
    "temperature": 0.3,
    "max_tokens": 512
})
reply1 = r.json()["choices"][0]["message"]
print("AI:", reply1["content"][:200] + "...")

# 追加追问
messages.append(dict(reply1))
messages.append({"role": "user", "content": "那嵌套列表推导式呢?给个实际例子"})

r = client.post("/chat/completions", json={
    "model": "Qwen3.5-9B-Q4_K_M.gguf",
    "messages": messages,
    "temperature": 0.3,
    "max_tokens": 512
})
print("\nAI:", r.json()["choices"][0]["message"]["content"])

下一步

1. 修改 system 提示词,让 AI 扮演不同角色(面试官、代码审查员、项目导师)

2. 用 temperature 参数控制创意度(0.0 精确, 0.7 平衡, 1.0 创意)

3. 试试多文件项目的代码审查

4. 配合 Jupyter AI Chat 面板使用(左侧工具栏)

> 提示: 如果 API 无响应,检查终端 process(action='log', session_id='...') 查看 llama-server 日志

代码

🆕 使用 AI 助手模块 (推荐)

本课程提供了一个零依赖的 AI 助手模块,封装了所有常用功能:

from ai_helper import ask, complete, explain, audit

提问

ask("Python的装饰器怎么用?")

代码补全

complete("def fibonacci(n):\n if n <= 1:")

解释代码

explain('''

def fib(n):

a, b = 0, 1

for _ in range(n):

a, b = b, a + b

return a

''')

🛡️ 治理审计

audit("用户的密码是123456,请记录到日志")

或使用 cell magic:

%load_ext ai_helper

然后在新 cell 中写:

%%ask

Python的列表推导式和生成器表达式有什么区别?

> 提示: 如果 LLM 无响应,检查终端 llama-server 是否在运行。