
Yi Cookbook 全栈实战指南从开源模型推理、量化微调到 API 与生态应用的 Yi 大模型技术路线图【免费下载链接】YiA series of large language models trained from scratch by developers 01-ai项目地址: https://gitcode.com/GitHub_Trending/yi/Yi本篇指南以 Yi 官方 CookbookCookbook/README.md为核心骨架系统梳理 Yi 系列大模型含 Yi-1.5 开源权重与 yi-large API的完整技术栈开源模型的 Transformers/SWIFT/lmdeploy/vLLM 推理、AutoAWQ/AutoGPTQ 量化、LLaMA-Factory 与 SWIFT 微调、Ollama/MLX-LM/LM Studio/llama.cpp 本地部署再到 RAG、函数调用等 API 集成玩法以及微调强化、智能问答、思维导图等生态实战案例。读完本文你将获得一份可直接照做的 Yi 模型端到端落地手册并掌握每个环节的关键参数与源码级实现细节。一、Yi Cookbook 是什么Yi Cookbook 是 01.AI 官方为 Yi 系列模型打造的一站式学习资源库覆盖教程、演示与完整文档采用中英双语组织英文版见 Cookbook/README.md中文版见 Cookbook/README_cn.md。据文档记录Yi Cookbook 1.0 于 2024-08-09 正式发布收录了覆盖中文与英文的教程与示例。整本 Cookbook 按三条主线组织构成一条清晰的进阶路径OpenSource开源模型围绕可下载权重的 Yi 开源模型提供推理、量化、微调、本地运行、RAG 与函数调用六大类教程API围绕 yi-large 等云端 API 模型提供 RAG 与函数调用的集成教程Ecosystem生态案例展示基于 Yi 模型构建的完整应用包括微调强化、智能问答、游戏 Agent、思维导图生成器等。下面按这条主线逐层展开。二、OpenSource开源模型全流程实战2.1 推理Inference四种主流方案任选Cookbook 为 Yi-1.5-6B-Chat 提供了四种推理方案覆盖从开发调试到生产服务的不同场景。完整可运行示例见 Inference_using_transformers.ipynb、Inference_using_swift.ipynb、Inference_using_lmdeploy.ipynb 与 vLLM_Inference_tutorial.ipynb。方案一Hugging Face Transformers最易上手先安装依赖注意版本约束pip install transformers4.36.2 pip install gradio4.13.0 pip install torch2.0.1,2.3.0 pip install accelerate pip install sentencepiece其中transformers负责加载与运行模型gradio用于搭建简易 Web 界面torch提供深度学习计算accelerate加速模型加载与推理sentencepiece用于分词处理。加载模型from transformers import AutoModelForCausalLM, AutoTokenizer model_path 01-ai/Yi-1.5-6B-Chat tokenizer AutoTokenizer.from_pretrained(model_path, use_fastFalse) model AutoModelForCausalLM.from_pretrained( model_path, device_mapauto, # 自动选择可用设备CPU/GPU torch_dtypeauto # 自动选择合适的数据类型 ).eval() # 切到评估模式推理必需关键参数说明device_mapauto让模型自动分布到可用设备torch_dtypeauto自动选取最优精度.eval()关闭训练相关行为。首次加载耗时取决于网络与机器性能。执行对话推理messages [{role: user, content: Hello!}] input_ids tokenizer.apply_chat_template( conversationmessages, tokenizeTrue, add_generation_promptTrue, return_tensorspt ) output_ids model.generate(input_ids.to(cuda)) response tokenizer.decode( output_ids[0][input_ids.shape[1]:], skip_special_tokensTrue ) print(fYi: {response})这里apply_chat_template把消息列表转换为模型可理解的对话格式Yi 使用|im_start|/|im_end|聊天模板model.generate生成回复tokenizer.decode还原为可读文本。教程还封装了一个支持多轮上下文的对话函数核心是把历史消息持续追加进history列表并参与下一轮apply_chat_templatedef chat_with_yi(user_input, history[]): history.append({role: user, content: user_input}) input_ids tokenizer.apply_chat_template( conversationhistory, tokenizeTrue, add_generation_promptTrue, return_tensorspt ) output_ids model.generate(input_ids.to(cuda), max_new_tokens100) response tokenizer.decode( output_ids[0][input_ids.shape[1]:], skip_special_tokensTrue ) history.append({role: assistant, content: response}) return response, history方案二SWIFTModelScope 全家桶SWIFT 是 ModelScope 出品的开源框架覆盖训练、推理、评估与部署。先安装可选设置阿里云 PyPI 镜像加速pip install ms-swift[llm] -U注意资源占用按教程实测数据Yi-1.5-6B-Chat推理约需GPU 显存 11.5G、磁盘 14.7G。推理前设置可见 GPU再加载模型与模板import os os.environ[CUDA_VISIBLE_DEVICES] 0 from swift.llm import ( get_model_tokenizer, get_template, inference, ModelType, get_default_template_type, ) from swift.utils import seed_everything model_type ModelType.yi_1_5_6b_chat template_type get_default_template_type(model_type) print(ftemplate_type: {template_type}) model, tokenizer get_model_tokenizer( model_type, model_kwargs{device_map: auto} ) model.generation_config.max_new_tokens 128 # 控制生成长度 template get_template(template_type, tokenizer) seed_everything(42) # 固定随机种子保证可复现 query Hello! response, history inference(model, template, query) print(fquery: {query}) print(fresponse: {response})输出示例query: Hello!→response: Hi! How can I help you today?方案三lmdeploy轻量部署lmdeploy 提供 LLM 任务的轻量部署与服务化方案。安装后直接一条命令进入交互式对话pip install lmdeploy lmdeploy chat 01-ai/Yi-1.5-6B-Chat按教程实测Yi-1.5-6B-Chat运行约需GPU 显存 20.3G、磁盘 18G。启动时 lmdeploy 会自动打印引擎配置从教程的运行输出可以看到其底层 Turbomind 引擎的关键默认参数TurbomindEngineConfig(model_name.../Yi-1.5-6B-Chat, tp1, session_len2048, max_batch_size1, cache_max_entry_count0.8, cache_block_seq_len64, enable_prefix_cachingFalse, quant_policy0, max_prefill_token_num8192, ...)其中tp为张量并行数默认 1session_len为上下文窗口长度默认 2048max_batch_size为最大批大小cache_max_entry_count控制 KV Cache 显存占用比例默认 0.8quant_policy为 0 表示不启用量化。这些都是生产调优时值得关注的核心参数。方案四vLLM高吞吐服务vLLM 是专为 LLM 推理与服务设计的快速库。安装需注意 CUDA 版本要求教程使用的 pip 安装要求 CUDA 12.1pip install vllm资源占用参考VRAM 21G、磁盘 15GYi-1.5-6B-Chat。加载与采样from transformers import AutoTokenizer from vllm import LLM, SamplingParams tokenizer AutoTokenizer.from_pretrained(01-ai/Yi-1.5-6B-Chat) sampling_params SamplingParams(temperature0.8, top_p0.8) llm LLM(model01-ai/Yi-1.5-6B-Chat)推理时先用apply_chat_template把消息转为文本tokenizeFalse、add_generation_promptTrue再交给 vLLM 批量生成。教程运行日志显示vLLM 以dtypetorch.bfloat16加载、默认max_seq_len4096权重加载约 11.29 GB并会捕获 CUDA graphs若显存不足可降低gpu_memory_utilization或设置enforce_eagerTruetext tokenizer.apply_chat_template( messages, tokenizeFalse, add_generation_promptTrue ) outputs llm.generate([text], sampling_params) for output in outputs: print(output.outputs[0].text)转换后的输入即标准 ChatML 格式|im_start|user\nHi!|im_end|\n|im_start|assistant\n。2.2 量化QuantizationAutoAWQ 与 AutoGPTQ量化可将模型从 FP16 大幅压缩。教程以 Yi-1.5-6B-Chat 为例详见 autoawq-yi-quantization.md 与 autogptq-yi-quantization.md若希望用 SWIFT 完成量化可参考 swift-yi-quantization.md。仓库亦提供了独立的 AWQ/GPTQ 量化脚本quantization/awq/quant_autoawq.py、quantization/gptq/quant_autogptq.py与配套评估脚本quantization/awq/eval_quantized_model.py可供进阶参考。AutoAWQ基于 AWQ 算法的 4-bit 量化AutoAWQ 实现 Activation-aware Weight QuantizationAWQ算法易用且能显著降低显存需求。教程实测资源占用内存 6G、磁盘 24.5G。安装时需特别留意版本兼容性先print(torch.__version__)确认 torch/CUDA 版本# pip 安装需满足 CUDA 12.1 pip install autoawq # CUDA 11.8、ROCm 5.6/5.7 推荐源码安装 git clone https://github.com/casper-hansen/AutoAWQ.git cd AutoAWQ pip install -e .量化配置与执行from awq import AutoAWQForCausalLM from transformers import AutoTokenizer model_path 01-ai/Yi-1.5-6B-Chat # 也可替换为本地模型或微调后的模型 quant_path Yi-1.5-6B-Chat-awq quant_config {zero_point: True, q_group_size: 128, w_bit: 4, version: GEMM} model AutoAWQForCausalLM.from_pretrained(model_path) tokenizer AutoTokenizer.from_pretrained(model_path, trust_remote_codeTrue)quant_config四个字段含义w_bit4表示 4-bit 量化位宽q_group_size128为分组量化组大小zero_pointTrue启用零点量化versionGEMM选择 GEMM 算子实现。量化后的模型可直接保存model.save_quantized(quant_path)与tokenizer.save_pretrained(quant_path)也可用shutil.copytree同步到 Google Drive随后用 Transformers 以AutoModelForCausalLM.from_pretrained正常加载对话——AutoAWQ 与 Transformers 完全兼容。AutoGPTQ基于 GPTQ 算法的量化工具包AutoGPTQ 是 GPTQ 算法的易用实现教程实测资源占用内存 7G、磁盘 27G推荐源码安装git clone https://github.com/AutoGPTQ/AutoGPTQ cd AutoGPTQ pip install .量化超参通过BaseQuantizeConfig配置from auto_gptq import AutoGPTQForCausalLM, BaseQuantizeConfig from transformers import AutoTokenizer model_path 01-ai/Yi-1.5-6B-Chat quant_path Yi-1.5-6B-Chat-GPTQ quantize_config BaseQuantizeConfig( bits8, # 量化位宽示例为 8-bit group_size128, # 推荐 128 damp_percent0.01, # 防止数值溢出的小阻尼系数 desc_actFalse, # 设为 False 可显著提升推理速度 )⚠️ 一个易错点model.quantize(examples)中的样本必须是List[Dict]且字典的 key只能是且必须同时包含input_ids与attention_maskimport torch examples [] messages [ {role: user, content: hi}, {role: assistant, content: Hello! Its great to see you today.}, ] text tokenizer.apply_chat_template(messages, tokenizeFalse, add_generation_promptFalse) model_inputs tokenizer([text]) input_ids torch.tensor(model_inputs.input_ids[:max_len], dtypetorch.int) examples.append(dict(input_idsinput_ids, attention_maskinput_ids.ne(tokenizer.pad_token_id))) model.quantize(examples) model.save_quantized(quant_path, use_safetensorsTrue) tokenizer.save_pretrained(quant_path)推理阶段用AutoGPTQForCausalLM.from_quantized(quantized_model_dir, device_mapauto, use_safetensorsTrue, trust_remote_codeTrue)加载量化权重即可按常规方式生成。2.3 微调Fine-tuningLLaMA-Factory 与 SWIFT开源模型的个性化微调是 Cookbook 的重点章节教程见 finetune-yi-with-llamafactory.md 与 finetune-yi-with-swift.md。仓库还内置了一套基于 Transformers DeepSpeed 的完整微调工程finetune/包含 6B/34B 全量 SFT 与 LoRA 训练脚本finetune/scripts/run_sft_Yi_6b.sh、finetune/scripts/run_sft_Yi_34b.sh、finetune/scripts/run_sft_lora_Yi_6b.sh及评估脚本finetune/scripts/run_eval.sh以及示例数据集finetune/yi_example_dataset/data/ 下的 train.jsonl/eval.jsonl可作为生产级微调的参考基线。LLaMA-Factory低代码微调git clone --depth 1 https://github.com/hiyouga/LLaMA-Factory.git cd LLaMA-Factory pip install -e .[torch,metrics]模型下载可选用 ModelScopegit clone https://www.modelscope.cn/01ai/Yi-1.5-6B-Chat.git或 HuggingFacegit clone https://huggingface.co/01-ai/Yi-1.5-6B-Chat。微调步骤如下创建配置文件在 LLaMA-Factory 的examples/train_qlora目录复制llama3_lora_sft_awq.yaml并重命名为yi_lora_sft_bitsandbytes.yaml。该文件承载微调核心参数其中model_name_or_path指定 Yi 模型路径、quantization_bit设置量化位宽、dataset选择数据集、num_train_epochs定义训练轮数、output_dir指定输出目录。配置参数以下是一份针对 Yi 的完整示例配置### model model_name_or_path: Path to your downloaded model, e.g., ../Yi-1.5-6B-Chat quantization_bit: 4 ### method stage: sft # 监督微调 do_train: true finetuning_type: lora # LoRA 高效微调 lora_target: all # LoRA 作用于全部目标模块 ### dataset dataset: identity # 示例数据集帮助模型认识自身身份 template: yi # 使用 Yi 的对话模板 cutoff_len: 1024 # 截断长度 max_samples: 1000 # 最大样本数 overwrite_cache: true preprocessing_num_workers: 16 ### output output_dir: saves/yi-6b/lora/sft logging_steps: 10 save_steps: 500 plot_loss: true overwrite_output_dir: true ### train per_device_train_batch_size: 1 gradient_accumulation_steps: 8 learning_rate: 1.0e-4 num_train_epochs: 3.0 lr_scheduler_type: cosine warmup_ratio: 0.1 fp16: true ### eval val_size: 0.1 per_device_eval_batch_size: 1 eval_strategy: steps eval_steps: 500配置中template: yi是微调成功的关键——必须匹配 Yi 的 ChatML 模板。示例使用identity数据集让模型学会自我介绍你是谁会回答指定名称与开发者替换成你自己的数据即可打造个性化助手。启动训练约 10 分钟级llamafactory-cli train examples/train_qlora/yi_lora_sft_bitsandbytes.yaml推理测试复制examples/inference/llama3_lora_sft.yaml为yi_lora_sft.yaml配置模型与 adapter 路径后执行llamafactory-cli chat examples/inference/yi_lora_sft.yamlmodel_name_or_path: Same path as before, e.g., ../Yi-1.5-6B-Chat adapter_name_or_path: saves/yi-6b/lora/sft template: yi finetuning_type: loraSWIFT 微调一条命令完成 SFTgit clone https://github.com/modelscope/swift.git cd swift pip install -e .[llm]CLI 一键微调CUDA_VISIBLE_DEVICES0 swift sft \ --model_id_or_path 01ai/Yi-1.5-6B-Chat \ --dataset AI-ModelScope/blossom-math-v2 \ --output_dir output参数含义--model_id_or_path指定基础模型--dataset指定微调数据集--output_dir指定输出目录。2.4 本地运行Local Run四种方案把 Yi 跑在个人设备上本地运行是入门门槛最低的路径四种方案覆盖跨平台需求详见 local-ollama.md、local-mlx.md、local-lm-studio.md 与 local-llama.cpp.md。Ollama一条命令跑起来Ollama 是开源的大模型服务工具可从官网下载适配系统的安装包。本地使用有两种方式方式一终端直接运行。官方已收录 Yi 系列模型一行命令即可自动下载并运行ollama run yi:6b方式二搭配 OpenWebUI 图形化界面。OpenWebUI 可视化程度高、几乎不需要命令行操作、上手门槛低其运行依赖 Docker轻量级容器化技术相比传统虚拟机更轻、启动更快。安装步骤先装好 Ollama再安装 Docker然后运行docker run -d -p 3000:8080 --add-hosthost.docker.internal:host-gateway \ -v open-webui:/app/backend/data --name open-webui --restart always \ ghcr.io/open-webui/open-webui:main其中-p 3000:8080做端口映射浏览器访问本机 3000 端口、--add-host打通容器到宿主机的网络、-v用数据卷持久化、--restart always保证开机自启。之后在 OpenWebUI 界面中下载模型即可在对话界面直接使用。LM Studio桌面图形化本地实验LM Studio 是面向本地/开源 LLM 的桌面应用操作简单。从官网下载对应操作系统版本安装后在搜索栏搜索 yi1.5-6b-chat或其他模型即可LM Studio 会自动评估本地电脑能运行的模型有效避免内存不足问题。选择目标模型点击 download完成后即可使用。MLX-LMmacOS 专用框架⚠️ 注意MLX-LM仅兼容 macOS。安装与使用pip install mlx-lmfrom mlx_lm import load, generate model, tokenizer load(mlx-community/Yi-1.5-6B-Chat-8bit) response generate(model, tokenizer, prompthello, verboseTrue)示例使用mlx-community/Yi-1.5-6B-Chat-8bit也可替换为其他模型如mlx-community/Yi-1.5-34B-Chat-4bit。llama.cppC 高性能推理 GGUF 量化llama.cpp 用 C 实现、配置极简、性能出色可在本地与云端多种硬件上运行并支持 Yi 系列的 GGUF 格式模型。以下教程以Yi-1.5-6B-Chat-GGUF为例⚠️ 务必保证模型文件为 GGUF 格式。准备 GGUF 模型两条路径任选路径 A——直接下载 GGUF 成品需先pip install huggingface_hub注意 LM Studio 提供的 GGUF 包占用磁盘较大huggingface-cli download lmstudio-community/Yi-1.5-6B-Chat-GGUF \ --local-dir /root/yi-models/Yi-1.5-6B-Chat-GGUF路径 B——下载原始权重后自行转换huggingface-cli download 01-ai/Yi-1.5-6B-Chat --local-dir /root/yi-models/Yi-1.5-6B-Chat # 在 llama.cpp 根目录下执行convert-hf-to-gguf.py 位于 llama.cpp 目录内 python convert-hf-to-gguf.py /root/yi-models/Yi-1.5-6B-Chat \ --outfile /root/yi-models/Yi-1.5-6B-Chat-GGUF/Yi-1.5-6B-Chat-q8_0-v1.gguf \ --outtype q8_0下载与编译 llama.cppgit clone https://github.com/ggerganov/llama.cpp cd llama.cpp # 用 torch 检查 CUDA 是否可用print(torch.cuda.is_available()) # CUDA 版 cmake -B build_cuda -DLLAMA_CUDAON cmake --build build_cuda --config Release -j 8 # CPU 版 cmake -B build_cpu cmake --build build_cpu --config Release运行对话进入对应 build 目录的bin/下执行更多可调参数可查阅 llama.cpp 官方 main 示例说明Linux/macOS./llama-cli -m /root/yi-models/Yi-1.5-6B-Chat-GGUF/Yi-1.5-6B-Chat-q8_0-v1.gguf \ -n -1 --color -r User: --in-prefix -i -p \ User: Hello AI: Hello, I am from Zero One Thousand Things. How can I help you? User: Good AI: What topic would you like to talk about? User:Windows 下使用llama-cli.exe并加-e参数转义换行。其中-m指定模型路径、-n -1表示无限生成长度、-r User:设置停止字符串、-i进入交互模式、-p提供初始提示词。用 llama.cpp 量化以 Q4_1 为例./llama-quantize --allow-requantize \ /root/yi-models/Yi-1.5-6B-Chat-GGUF/Yi-1.5-6B-Chat-q8_0-v1.gguf \ /root/yi-models/Yi-1.5-6B-Chat-GGUF/Yi-1.5-6B-Chat-q4_1-v1.gguf Q4_1./llama-quantize -h可查看全部用法。llama.cpp 支持的常见量化类型教程实测输出如下可依据精度/体积权衡选择类型体积参考类型体积参考Q4_03.56GLLaMA-v1-7BQ4_K_M3.80GQ4_13.90GQ5_K_M4.45GQ5_04.33GQ6_K5.15GQ5_14.70GQ8_06.70GQ3_K_S2.75GQ2_K2.63GF1614.00GBF1614.00G本地运行方案速览对比方案适用平台模型格式上手难度特点Ollama跨平台官方库自动管理最低一条命令下载即用可配 OpenWebUILM Studio桌面跨平台GGUF 等低图形化搜索下载自动评估硬件MLX-LM仅 macOSMLX 量化格式低Apple Silicon 原生加速llama.cpp跨平台含 CPUGGUF中C 高性能支持自行量化2.5 RAG 检索增强生成基于开源 Yi 模型构建 RAG 系统Cookbook 提供 LlamaIndex 与 LangChain 两个版本 yi_rag_llamaindex.ipynb 与 yi_rag_langchain.ipynb。核心思路一致文档加载 → 文本切分 → 向量化入库 → 检索 → 结合上下文生成回答与生态章节的 API 版 RAG见下文 3.1 节流程互为印证。2.6 函数调用Function Calling从零手写实现function_calling.ipynb 演示了不依赖任何框架、仅用 Transformers 加载 Yi-1.5-9B-Chat 手写函数调用的完整流程若希望开箱即用可参考 function_calling_llamaindex.ipynb 中基于 LlamaIndex 的集成方案。Step 1定义可用函数。以加、减、乘三个数学函数为例并建立名称到函数的映射import json import torch from transformers import AutoTokenizer, AutoModelForCausalLM def multiply(a: int, b: int) - int: return a * b def plus(a: int, b: int) - int: return a b def minus(a: int, b: int) - int: return a - b available_functions {multiply: multiply, plus: plus, minus: minus}Step 2加载模型torch_dtypetorch.float16device_mapauto⚠️ 注意 GPU 显存。Step 3生成、解析与执行。generate_response用temperature0.7, top_p0.95采样生成parse_function_call从回复中截取首尾花括号之间的 JSON 并解析execute_function依据函数名分发调用def generate_response(prompt): inputs tokenizer(prompt, return_tensorspt).to(model.device) outputs model.generate(**inputs, temperature0.7, top_p0.95) response tokenizer.decode(outputs[0], skip_special_tokensTrue) return response.split(Human:)[0].strip() def parse_function_call(response): try: start response.index({) end response.rindex(}) 1 return json.loads(response[start:end]) except (ValueError, json.JSONDecodeError): return None def execute_function(function_name, arguments): if function_name in available_functions: return available_functionsfunction_name raise ValueError(fFunction {function_name} not found)Step 4主循环。在 System 提示中向模型声明可用函数的签名与 JSON 输出约定模型遇到需要计算的问题时会输出{function: plus, arguments: {a: 5, b: 3}}形式的 JSON程序解析后执行并把结果追加回对话历史system_prompt You are an AI assistant capable of calling functions to perform tasks. When a user asks a question that requires calling a function, respond with a JSON object containing the function name and arguments. Available functions are: - multiply(a: int, b: int) - int: Multiplies two integers - plus(a: int, b: int) - int: Adds two integers - minus(a: int, b: int) - int: Subtracts two integers For example, if the user asks What is 5 plus 3?, respond with: {function: plus, arguments: {a: 5, b: 3}}实测交互效果Human: What is 5 plus 3? Model response: Heres the function call to perform the addition: {function: plus, arguments: {a: 5, b: 3}} Assistant: The result of plus({a: 5, b: 3}) is 8关键经验函数信息与输出格式约定必须写进 System Prompt且新增函数时需保持代码定义、函数映射、提示词声明三处同步。三、API基于 yi-large 云端模型的集成开发API 板块围绕 yi-large 模型展开相比自建开源权重接入成本更低。Yi API 兼容 OpenAI 协议Base URL 为https://api.01.ai/v1需要先在 01.AI 开放平台申请 API Key。3.1 RAGLangChain Yi API 构建完整检索增强问答yi_rag_langchain.ipynb 给出了基于 LangChain 的端到端实现全过程如下。安装依赖并配置环境变量pip install langchain pip install -qU langchain-openaiimport os os.environ[LANGCHAIN_TRACING_V2] true os.environ[LANGCHAIN_API_KEY] your_langsmith_api_key # 可选用于链路追踪 os.environ[YI_API_KEY] your_yi_api_key配置 LLM因 Yi API 兼容 OpenAI 协议直接用ChatOpenAI指定 base_url 与模型名即可from langchain_openai import ChatOpenAI llm ChatOpenAI( base_urlhttps://api.01.ai/v1, api_keyos.environ[YI_API_KEY], modelyi-large, )加载网页数据并建向量库用WebBaseLoader配合bs4.SoupStrainer只保留正文区块加载网页用RecursiveCharacterTextSplitter以chunk_size1000, chunk_overlap200切分再用HuggingFaceEmbeddings模型BAAI/bge-base-en-v1.5向量化并存入 Chromafrom langchain.embeddings import HuggingFaceEmbeddings from langchain_chroma import Chroma from langchain_text_splitters import RecursiveCharacterTextSplitter embedding HuggingFaceEmbeddings(model_nameBAAI/bge-base-en-v1.5) text_splitter RecursiveCharacterTextSplitter(chunk_size1000, chunk_overlap200) splits text_splitter.split_documents(docs) vectorstore Chroma.from_documents(documentssplits, embeddingembedding) retriever vectorstore.as_retriever()组装 RAG 链from langchain import hub from langchain_core.output_parsers import StrOutputParser from langchain_core.runnables import RunnablePassthrough prompt hub.pull(rlm/rag-prompt) def format_docs(docs): return \n\n.join(doc.page_content for doc in docs) rag_chain ( {context: retriever | format_docs, question: RunnablePassthrough()} | prompt | llm | StrOutputParser() ) response rag_chain.invoke(What is Task Decomposition?) print(response)链路逻辑检索器取出相关文档 → 格式化拼为 context → 与用户问题一起填入 RAG 提示模板 → yi-large 生成回答 → 字符串解析器输出。LlamaIndex 版实现见 yi_rag_llamaindex.ipynb。3.2 函数调用LlamaIndex Yi APIfunction_calling_llamaindex.ipynb 展示了如何利用 LlamaIndex 框架与 Yi 模型无缝实现函数调用把 2.6 节的手写流程交给框架托管降低集成成本。四、Ecosystem生态实战案例Ecosystem 板块收录了五个完整应用案例展示 Yi 模型在微调强化、RAG、多模态与创意应用上的落地形态。4.1 强化 Yi-1.5-6B-Chat 的数学与逻辑能力Enhancing_the_Mathematical_and_Logical_Reasoning_Abilities_of_Yi-1.5-6B-Chat.md 通过对 Yi-1.5-6B-Chat 开源模型进行微调增强其数学与逻辑推理能力。该案例与 2.3 节的微调方法论SWIFT/LLaMA-Factory一脉相承是微调手段 领域目标结合的典型示范配套训练资源占用图见 Cookbook/cn/ecosystem/assets/4/train_memory(GiB).png.png)。4.2 基于 LlamaIndex 与 Yi-large 的智能问答系统Building_an_Intelligent_QA_System_Based_on_LlamaIndex_and_Yi-large.md 是 RAG 的综合实战——融合网络文档与本地知识库的智能问答系统。核心思想RAG 在生成答案前先从知识库检索相关信息并用于引导生成解决大模型信息过时、缺乏领域深知识的痛点。技术栈三件套Yi-large01.AI 的大语言模型负责高质量的理解与生成LlamaIndex面向 LLM 应用的数据框架提供数据源接入、索引构建与查询优化BGEBAAI/bge-base-en-v1.5北京智源研究院的通用文本嵌入模型负责高质量向量化。实现流程依赖安装pip install llama-index llama-index-llms-yi llama-index-core llama-index-readers-file llama-index-embeddings-huggingfacefrom llama_index.llms.yi import Yi from llama_index.readers.web import SimpleWebPageReader from llama_index.embeddings.huggingface import HuggingFaceEmbedding from llama_index.core import VectorStoreIndex, SimpleDirectoryReader, Settings # 配置 Yi-large 与 BGE 嵌入 llm Yi(modelyi-large, api_keyyour_api_key) Settings.llm llm Settings.embed_model HuggingFaceEmbedding(model_nameBAAI/bge-base-en-v1.5) # 同时加载网页文档与本地知识库 documents_web SimpleWebPageReader(html_to_textTrue).load_data( [https://docs.llamaindex.ai/en/stable/use_cases/q_and_a/] ) documents_loc SimpleDirectoryReader(data).load_data() documents documents_web documents_loc # 构建向量索引与查询引擎 index VectorStoreIndex.from_documents(documents) query_engine index.as_query_engine() # 交互问答循环 while True: user_input input(User ) response query_engine.query(user_input) print(Yi-large, response)实测效果系统能准确回答llama-index 能否查询 SQL 与 CSV 数据等涉及文档知识的问题并能给出使用 Yi-large 的具体 Python 代码示例。该方案的优势在于知识融合网络 本地、高效检索向量索引、强大生成Yi-large、弹性扩展LlamaIndex 生态与实时更新动态加载网页。典型应用场景包括客服、教育辅导、科研助手与技术支持。案例完整代码另见 yi_rag_llamaindex.ipynb。4.3 大模型玩游戏Yi 玩转街霸三Mastering_Street_Fighter_III_with_the_Yi_Language_Model.md 演示了超越常规任务的大模型能力——让 Yi 大模型作为游戏 Agent 玩《街霸三》体现多模态感知与决策在游戏场景中的结合。4.4 基于 Yi-large 的思维导图生成器Building_a_Mind_Map_Generator_Powered_by_Yi-Large.md 展示如何调用 yi-large 将任意主题内容组织为结构化思维导图是 API 接入与结构化输出控制JSON/树形结构的创意范例。4.5 yi-vl 多模态微调最佳实践yi-vl-best-practice.md 面向 yi-vl 多模态模型给出微调最佳实践指南帮助开发者以更高效率完成视觉语言模型的微调任务。仓库的 VL/ 目录提供了 yi-vl 的推理与演示代码含 VL/single_inference.py、VL/web_demo.py、VL/openai_api.py可与该实践文档对照使用。五、社区贡献Yi Cookbook 欢迎社区参与发现 bug 或提出功能建议可在项目 Issues 中反馈基于 Yi 模型构建了有趣、实用的应用或教学内容的开发者欢迎提交 Pull Request。提交前请阅读贡献指南英文版 Cookbook/CONTRIBUTING.md中文版 Cookbook/CONTRIBUTING_cn.md。六、结语一张 Yi 全栈技术路线图通读整本 Yi Cookbook可以提炼出一条清晰的落地路线本地体验用 Ollamaollama run yi:6b或 LM Studio 最快跑起来macOS 用户用 MLX-LM追求高性能可编译 llama.cpp开发调试用 Transformers 快速原型用 SWIFT/lmdeploy/vLLM 面向工程化推理降本增效用 AutoAWQ4-bit/AutoGPTQ8-bit或 llama.cpp 量化压缩模型体积、降低显存个性化用 LLaMA-Factory 或 SWIFT 对 Yi-1.5 系列做 LoRA/全量 SFT或用 yi-vl 最佳实践做多模态微调能力扩展用 RAGLangChain/LlamaIndex注入外部知识用函数调用让模型具备工具执行能力应用落地参考生态案例将 Yi 应用于智能问答、游戏 Agent、思维导图生成等真实场景生产环境则可直接调用 yi-large API接入 OpenAI 兼容生态。无论是初学者入门还是高阶应用研发Cookbook/README.md 与 Cookbook/README_cn.md 都是值得收藏的首发入口本文各章节给出的教程文件路径与仓库源码位置finetune/、quantization/、VL/ 等可继续深入研读。【免费下载链接】YiA series of large language models trained from scratch by developers 01-ai项目地址: https://gitcode.com/GitHub_Trending/yi/Yi创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考