使用 Instructor 蒸馏 Python 函数:面向 LLM 微调与函数级蒸馏实战指南 使用 Instructor 蒸馏 Python 函数面向 LLM 微调与函数级蒸馏实战指南【免费下载链接】instructorstructured outputs for llms项目地址: https://gitcode.com/GitHub_Trending/in/instructor本指南聚焦 Instructor 项目中的Instructions蒸馏能力通过一个装饰器自动把任意返回 Pydantic 模型的 Python 函数录制为可用于 OpenAI function calling 微调的 JSONL 数据集并在训练完成后以dispatch模式无缝切换为微调模型执行同时保持原函数调用签名向后兼容。读完本文你将掌握从数据采集、日志落盘、CLI 提交微调任务到模型上线替换的完整蒸馏工作流。为什么需要函数级蒸馏想象你在开发一个后端服务它混合了新老两代机器学习实践既有传统规则、校验与数据处理管线又有大语言模型调用。这种系统往往包含多步函数调用、反复校验和繁重的数据处理维护成本很高。Instructor 的蒸馏特性正是为这类场景设计的它给函数加上一个装饰器自动为微调生成数据集并允许你在不改动调用方代码的前提下用微调后的模型替换原函数实现。用大白话说先把一个写得对但太慢/太重的 Python 函数蒸馏成一个更快、更便宜、可无限并发的模型调用同时保留原有的函数签名和返回类型。在 examples/distilations 目录下仓库提供了完整的可运行示例three_digit_mul.py负责采集数据、three_digit_mul_dispatch.py负责调度微调模型下文所有代码均可在该目录中直接运行。快速上手一分钟生成微调数据集蒸馏的核心 API 是from instructor import Instructions。先看最小可运行示例import logging import random from pydantic import BaseModel from instructor import Instructions # pip install instructor # Logging setup logging.basicConfig(levellogging.INFO) instructions Instructions( namethree_digit_multiply, finetune_formatmessages, # log handler is used to save the data to a file # you can imagine saving it to a database or other storage # based on your needs! log_handlers[logging.FileHandler(math_finetunes.jsonl)], ) class Multiply(BaseModel): a: int b: int result: int # Define a function with distillation # The decorator will automatically generate a dataset for fine-tuning # They must return a pydantic model to leverage function calling instructions.distil def fn(a: int, b: int) - Multiply: resp a * b return Multiply(aa, bb, resultresp) # Generate some data for _ in range(10): a random.randint(100, 999) b random.randint(100, 999) print(fn(a, b)) # a268 b548 result146864 # a774 b447 result345978 # a154 b902 result138908 # a304 b808 result245632 # a980 b104 result101920 # a725 b455 result329875 # a206 b386 result79516 # a488 b920 result448960 # a989 b889 result879221 # a815 b343 result279545运行这段脚本每次调用fn(a, b)时真实函数照常执行并返回Multiply实例同时其函数签名 调用参数 结构化输出会被自动记录到math_finetunes.jsonl。你只需用随机或真实业务参数多调用几次一个用于微调的训练集就诞生了——这正是 examples/distilations/three_digit_mul.py 的完整逻辑。使用前提返回类型必须是 Pydantic 模型装饰器能工作有一个硬性约束被装饰函数必须声明返回pydantic.BaseModel子类的类型注解。在源码 instructor/distil.py 中is_return_type_base_model_or_instance会通过inspect.signature检查返回注解def is_return_type_base_model_or_instance(func: Callable[..., Any]) - bool: return_type inspect.signature(func).return_annotation assert return_type ! inspect.Signature.empty, ( Must have a return type hint that is a pydantic BaseModel ) return inspect.isclass(return_type) and issubclass(return_type, BaseModel)缺少返回类型注解会直接抛出AssertionError: Must have a return type hint that is a pydantic BaseModel返回类型不是BaseModel子类例如int会被拒绝见测试 tests/coverage/test_legacy_distil_coverage.py。这是因为蒸馏依赖 Pydantic 模型既充当结构化输出契约又充当 OpenAI function calling 的 schema 来源——返回值会被序列化为模型 JSON才能构成一条标准的 function-call 训练样本。Instructions 构造参数详解对照 instructor/distil.py 的构造函数Instructions提供以下参数参数类型默认值说明namestr \| NoneNone指令名称同时作为内部logginglogger 名称idstr \| NoneNone指令 ID不传则自动生成uuid4log_handlerslist[logging.Handler] \| NoneNone日志处理器列表负责把微调样本写入文件、数据库或任意存储finetune_formatFinetuneFormatFinetuneFormat.MESSAGES微调数据格式messages或rawindentint2记录 function call arguments 时的 JSON 缩进include_code_bodyboolFalse是否在 system prompt 中携带完整函数体含源码openai_clientOpenAIOpenAI()自定义 OpenAI 客户端dispatch 模式使用关键设计点log_handlers是可插拔的。示例用logging.FileHandler写入本地 JSONL但按源码 instructor/distil.py任意logging.Handler都可以接入——你可以换成数据库写入、云存储上传或监控系统实现持续化数据采集include_code_body控制提示词信息量。为False时system prompt 只包含函数签名与 docstringget_signature_from_fn为True时会通过inspect.getsource把函数体源码一并嵌入format_function让模型学到更多实现细节。该逻辑见 instructor/distil.py函数文档字符串docstring会自动进入提示词。测试 tests/coverage/test_legacy_distil_coverage.py 验证了带 docstring 的函数会被格式化为def fn(...) ... ...的形式。FinetuneFormat两种数据形态FinetuneFormat是定义在 instructor/distil.py 的枚举class FinetuneFormat(enum.Enum): MESSAGES messages RAW rawMESSAGES默认生成 OpenAI chat completion 格式的样本含messagessystem / user / assistant function_call和functionsOpenAI 函数 schema可直接喂给 OpenAI 微调 APIRAW生成更简单的结构化记录函数名、函数表示、args、kwargs、resp、JSON schema适合自定义微调管线或需要完全掌控数据结构时使用。日志输出长什么样以MESSAGES格式为例一条写入math_finetunes.jsonl的样本如下{ messages: [ {role: system, content: Predict the results of this function: ...}, {role: user, content: Return fn(133, b539)}, { role: assistant, function_call: { name: Multiply, arguments: {a:133,b:539,result:89509}, }, }, ], functions: [ {name: Multiply, description: Correctly extracted Multiply...} ], }更完整的样例可以直接查看 examples/distilations/three_digit_mul.py 中注释掉的log_lines字典其中的functions数组包含由 Pydantic schema 转换而来的完整 OpenAI 函数定义parameters.properties、required等这正是微调时模型要学习模仿的 function calling 形态。从源码看这段结构由Instructions.trackinstructor/distil.py拼装用response_schema(base_model)把 Pydantic 模型转为 OpenAI function schema构造 system 提示Predict the results of this function: ... 函数签名与 user 提示Return fn(...)参数由位置参数与关键字参数拼装如133, b539追加 assistant 的function_callarguments为响应模型的 JSON dump缩进由indent控制通过 logger 以 JSON 行写出。若使用RAW格式输出的结构则形如{ fn_name: three_digit_multiply, fn_repr: def fn(a: int, b: int) - Multiply:\n ..., args: [133], kwargs: {b: 539}, resp: {a: 133, b: 539, result: 89509}, schema: {properties: {...}, required: [...]} }两种格式在 tests/coverage/test_legacy_distil_coverage.py 中都有对应的录制断言例如MESSAGES格式下 user 消息应为Return \lookup_user(7, regioneu)且 assistantfunction_call与functions 均正确生成。提交微调任务instructor CLI前置条件!!! note annotate Dont forget to set your OpenAI Key as an environment variable所有 instructor jobs 命令都假定你在 shell 中设置了 OPENAI_API_KEY 环境变量可通过 export OPENAI_API_KEYInsert API Key Here 完成设置。数据采集完成后一条命令即可提交微调任务instructor jobs create-from-file math_finetunes.jsonlcreate-from-file会先上传文件等待文件被处理为processed状态再创建微调任务并自动进入监控界面该流程实现在 instructor/cli/jobs.py。完整的 CLI 帮助文档见 docs/cli/finetune.md。完整参数一览instructor jobs create-from-file支持以下选项参数类型默认值说明fileTEXT必填微调数据文件路径--modelTEXTgpt-5.4-mini用于微调的基础模型--pollINTEGER2轮询间隔秒--n-epochsINTEGER—训练轮数--batch-sizeTEXT—批量大小--learning-rate-multiplierTEXT—学习率倍率--validation-fileTEXTNone验证集文件路径--model-suffixTEXTNone模型后缀标识带验证集的高级用法instructor jobs create-from-file math_finetunes.jsonl --validation-file math_finetunes_val.jsonl --n-epochs 3 --batch-size 16 --learning-rate-multiplier 0.5这与 examples/distilations/readme.md 中的验证集示例--n-epochs 4 --validation-file math_finetunes_val.jsonl一致。仓库还提供了验证数据样例 examples/distilations/math_finetunes_val.jsonl 供直接测试。更多管理命令instructor jobs list以 Rich 表格实时监控最近任务状态自动每 5 秒刷新⏳ running/✅ succeeded/❌ failed/ cancelled按CtrlC退出实现见 instructor/cli/jobs.pyinstructor jobs create-from-id file_id使用已上传文件的 ID 创建任务适合先instructor files upload transformed_data.jsonl再分步执行instructor jobs cancel job_id取消进行中的任务instructor files list查看已上传的微调文件size、创建时间、filename、purpose。蒸馏的两种模式distil 与 dispatchdistil装饰器在 instructor/distil.py 中支持两种模式mode参数仅允许distil或dispatch非法值会触发断言模式一distil默认采集数据instructions.distil包一层真实函数调用时函数体照常执行返回值原样返回给调用方同时把这次调用录制为微调样本。这是训练前的数据采集阶段业务代码零感知。模式二dispatch上线替换微调完成后把mode改为dispatch并传入微调模型 ID函数体将被短路——不再执行原 Python 代码而是调用 OpenAI 接口由微调模型直接生成结构化输出from instructor import Instructions, patch patch() # 用 patch() 启用 Instructor 的响应序列化能力 class Multiply(BaseModel): a: int b: int result: int instructions Instructions( namethree_digit_multiply, ) instructions.distil(modelgpt-5.4-mini:finetuned-123, modedispatch) def fn(a: int, b: int) - Multiply: resp a b # 这段代码将不再执行仅保留签名作为契约 return Multiply(aa, bb, resultresp)两点关键说明记得调用patch()它由 Instructor 包提供帮助把 OpenAI 返回的内容自动反序列化为我们期望的Pydantic模型模型 ID 替换请将示例中的模型 ID 替换为你自己的微调模型 ID。OpenAI 在 Fine-tuning 面板上以ft:gpt-5.4-mini:personal::id形式标识微调模型。从源码看dispatch模式下 instructor/distil.py 会构造同样的函数签名 调用参数提示词然后调用self.client.chat.completions.create并额外传入response_modelreturn_base_model与model参数让输出直接解析为目标 Pydantic 模型。测试 tests/coverage/test_legacy_distil_coverage.py 用RecordingClient验证了 dispatch 的关键行为原函数体永远不会被执行测试函数体内直接raise AssertionError且请求中正确携带model、response_model和提示词。仓库的 dispatch 完整示例见 examples/distilations/three_digit_mul_dispatch.py它用instructor.from_openai(OpenAI())构造客户端、开启include_code_bodyTrue并展示了微调模型的实际运行输出——多数样本结果与真实乘法一致个别样本会暴露模型的误差这正是用原函数做 evals 对比的价值所在972 * 508 493056, expected 493776 145 * 369 53505, expected 53505 940 * 440 413600, expected 413600两个核心收益效率与集成Instructor 蒸馏能力的两大价值效率Efficiency把函数的实现要求蒸馏进模型权重最终只保留函数签名 几行调用代码显著简化管线、降低推理成本集成Integration为传统机器学习与语言模型之间提供统一接口——函数是天然的语言模型替换点只需包裹既有函数即可渐进式地把规则逻辑迁移到模型驱动。因为distil/dispatch共用同一函数签名切换是无感的调用方代码完全不需要改动。你甚至可以针对不同任务使用不同微调模型或者同时保留原函数用于验证evals——用原函数的结果与蒸馏结果对比持续评估蒸馏质量。完整工作流总结定义返回 Pydantic 模型的函数签名即契约用instructions.distil装饰用真实/随机数据多次调用函数通过log_handlers自动生成math_finetunes.jsonl设置OPENAI_API_KEY运行instructor jobs create-from-file math_finetunes.jsonl可按需附--n-epochs、--validation-file等参数用instructor jobs list监控任务直到状态变为✅ succeeded记录微调模型 ID将mode改为dispatch并填入微调模型 ID函数即被模型接管且保持向后兼容用原函数与蒸馏模型做并行对比evals持续验证与迭代。整个过程从函数到模型再到无感替换只涉及一个装饰器与几条 CLI 命令这也是Instructions蒸馏特性在 Instructor 项目中承担的核心角色。相关实现与文档可进一步查阅instructor/distil.py、docs/concepts/distillation.md、docs/cli/finetune.md 与示例目录 examples/distilations。【免费下载链接】instructorstructured outputs for llms项目地址: https://gitcode.com/GitHub_Trending/in/instructor创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考