LLM 开发工程师不是训练大模型的算法岗,而是把模型能力工程化为可靠产品的人:检索、编排、结构化输出、评估、成本与延迟优化。入行的分水岭只有一条——能不能交付一个可评估、可回滚、成本可控的 LLM 应用。下面按能力栈给出可复现的代码与学习路径。
必备四块:Prompt 与结构化输出、RAG 检索增强、工具调用/Agent 编排、评估与可观测性。加分项:微调、量化部署、流式与并发。语言以 Python 为主,工程侧要懂 FastAPI、Redis、向量库与 Docker。
入门第一课是把模型输出变成程序可用的对象。优先用原生 function calling 或 JSON Schema 约束,退而求其次才用“输出 JSON”提示词 + 校验重试。
from openai import OpenAI
import json, jsonschema
client = OpenAI()
SCHEMA = {
"type": "object",
"properties": {
"intent": {"enum": ["refund", "logistics", "other"]},
"order_no": {"type": "string"},
"confidence": {"type": "number", "minimum": 0, "maximum": 1},
},
"required": ["intent", "confidence"],
}
def parse_intent(text: str, retries=2) -> dict:
for _ in range(retries + 1):
r = client.chat.completions.create(
model="gpt-4o-mini",
temperature=0,
response_format={"type": "json_object"},
messages=[
{"role": "system", "content": f"只输出符合此 schema 的 JSON: {json.dumps(SCHEMA)}"},
{"role": "user", "content": text},
],
)
try:
data = json.loads(r.choices[0].message.content)
jsonschema.validate(data, SCHEMA) # 校验,不通过就重试
return data
except (json.JSONDecodeError, jsonschema.ValidationError):
continue
raise ValueError("结构化输出失败")要点:temperature=0、校验失败重试、把校验错误回传给模型自我修正。这一套是后续一切功能的地基。
RAG 的坑 90% 在检索,不在生成。按语义边界分块、带元数据、混合检索(向量 + 关键词),是入门就该建立的习惯。
from langchain_text_splitters import RecursiveCharacterTextSplitter
import chromadb
splitter = RecursiveCharacterTextSplitter(
chunk_size=500, chunk_overlap=80,
separators=["\n\n", "\n", "。", " ", ""],
)
def build_index(docs: list[dict], col: chromadb.Collection):
for d in docs:
for i, chunk in enumerate(splitter.split_text(d["text"])):
col.add(
ids=[f"{d['id']}-{i}"],
documents=[chunk],
metadatas=[{"source": d["id"], "chunk": i}],
)
def retrieve(col, query: str, k=5):
res = col.query(query_texts=[query], n_results=k)
return list(zip(res["documents"][0], res["metadatas"][0]))生成侧要求模型只依据检索片段回答、并给出引用,无依据就说“不知道”——这比调参更能压住幻觉。
把业务函数注册成工具,模型决定何时调用、传什么参数。生产上必须加超时、参数校验和最大步数。
import json
TOOLS = {
"query_order": {
"fn": lambda order_no: db.orders.find_one({"order_no": order_no}),
"schema": {"type": "object", "properties": {"order_no": {"type": "string"}},
"required": ["order_no"]},
},
}
def run_agent(user_input: str, max_steps=5):
msgs = [{"role": "user", "content": user_input}]
for _ in range(max_steps):
r = client.chat.completions.create(
model="gpt-4o-mini", messages=msgs,
tools=[{"type": "function", "function": {"name": n, **v["schema"]}}
for n, v in TOOLS.items()],
)
msg = r.choices[0].message
if not msg.tool_calls:
return msg.content
msgs.append(msg)
for call in msg.tool_calls:
args = json.loads(call.function.arguments) # 需校验
result = TOOLS[call.function.name]["fn"](**args)
msgs.append({"role": "tool", "tool_call_id": call.id,
"content": json.dumps(result, ensure_ascii=False)})
return "超出最大步数"没有评估集,就没有工程。至少建 50–100 条带标准答案的样本,用 LLM-as-judge + 规则双轨打分。
def evaluate(pipeline, cases, judge):
passed = 0
for c in cases:
out = pipeline(c["input"])
# 规则:关键字段是否命中
rule_ok = all(k in out for k in c["must_contain"])
# 模型裁判:语义是否等价
score = judge(f"问题:{c['input']}\n标准:{c['expected']}\n回答:{out}\n给0-1分")
passed += rule_ok and float(score) >= 0.7
return passed / len(cases)同时记录每次调用的 token 数、延迟、成本与失败原因——这是从“能跑”到“能上线”的分界。
作品集比证书有用得多:一个带评估报告、监控指标、成本分析的 GitHub 项目,抵得上一沓课程证明。
只堆 prompt 不建评估;把 RAG 当银弹却不好好分块;忽略 token 成本与延迟;不做幻觉兜底;盲目微调而不先优化检索与提示。记住:LLM 应用 80% 的稳定性来自检索质量、结构化校验和评估闭环,而不是模型参数。能把这三件事做扎实的人,就是市场真正缺的 LLM 开发工程师。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。