资讯动态

generative-ai-for-beginners 第 20 课实战指南:用 Mistral Large / Small / NeMo 构建生成式 AI 应用

发布时间:2026/9/7 18:44:08 来源:尧图企业网站定制
generative-ai-for-beginners 第 20 课实战指南用 Mistral Large / Small / NeMo 构建生成式 AI 应用【免费下载链接】generative-ai-for-beginners21 Lessons, Get Started Building with Generative AI项目地址: https://gitcode.com/GitHub_Trending/ge/generative-ai-for-beginners本文基于 generative-ai-for-beginners 课程第 20 课《Building with Mistral Models》保加利亚语译本见 translations/bg/20-mistral/README.md展开带你系统走查 Mistral 家族的三款模型——Mistral Large、Mistral Small和Mistral NeMo先理解各自的定位与适用场景再用可复制的 Python 代码完成三组实战——基于 Mistral Large 2 的 RAG检索增强生成问答、Small 与 Large 的延迟/风格对比实验以及 NeMo 与 Large 的 tokenizer 效率实测。学完本篇你能独立完成选模型 → 配环境 → 跑通代码 → 读懂输出的完整流程并在仓库配套的 Notebook 中复现全部结果。本课学习目标按课程文档20-mistral/README.md的定义本课覆盖三个目标探索 Mistral 的不同模型Exploring the different Mistral Models理解每个模型的用例与适用场景通过示例代码展示每个模型的独特能力。仓库根目录 README.md 中第 20 课的条目也概括了这一点Learn: The features and differences of the Mistral Family Models学习 Mistral 家族模型的特性与差异。三款 Mistral 模型总览本课聚焦三款模型它们均可在模型市场免费调用本课代码会直接调用这些模型运行模型定位关键特点典型场景Mistral Large 2 (2407)旗舰模型面向企业128k 上下文窗口、原生 Function Calling、多语言13 种RAG、代码生成、工具调用Mistral Small小型语言模型SLM价格低约 80%、低延迟、部署灵活摘要/情感分析/翻译、高频请求、代码评审建议Mistral NeMo开源模型Apache 2.0Tekken tokenizer、支持微调、原生函数调用需要微调或自托管的场景平台说明本课保加利亚语译本中模型被标注为可在 GitHub Model marketplace 免费使用代码使用GITHUB_TOKEN环境变量鉴权。需要注意仓库英文版课程文档20-mistral/README.md及其配套 Notebook 中已注明GitHub Models 将于 2026 年 7 月底退役建议改用 Microsoft Foundry Models 进行 AI 模型原型开发且 Notebook 中已改用AZURE_INFERENCE_ENDPOINT/AZURE_INFERENCE_CREDENTIAL环境变量。若你按本文档旧版代码运行后遇到鉴权或端点问题优先参照仓库 Notebook 中的最新环境变量写法。Mistral Large 2 (2407)旗舰模型的能力规格Mistral Large 2 目前是 Mistral 的旗舰模型面向企业级使用。相较初代 Mistral Large文档列出了三点升级更大的上下文窗口128k tokens对比初代的 32k4 倍更强的数学与编程能力平均准确率 76.9%对比初代的 60.4%该数据来自课程文档转述的模型评测口径增强的多语言能力覆盖英语、法语、德语、西班牙语、意大利语、葡萄牙语、荷兰语、俄语、中文、日语、韩语、阿拉伯语和印地语共 13 种语言。凭借这些特性Mistral Large 在以下三类任务上表现突出RAG检索增强生成得益于更大的上下文窗口可以塞入更多检索到的文档片段Function Calling原生支持函数调用可与外部工具和 API 集成调用既支持并行也支持顺序执行代码生成在 Python、Java、TypeScript 和 C 代码生成上表现优秀。实战一用 Mistral Large 2 构建 RAG 问答下面这个示例使用 Mistral Large 2 对一篇纯文本文档做 RAG 问答。问题是韩语写的询问作者上大学之前主要从事的两项活动——这恰好同时验证了多语言能力和检索质量。技术栈要点使用Cohere Embeddings模型cohere-embed-v3-multilingual对文档切片和问题分别生成向量使用faissPython 包作为向量存储IndexFlatL2欧氏距离精确索引做近邻检索发给 Mistral 模型的 prompt 同时包含问题与检索到的相似文本片段模型基于上下文输出自然语言答案。先安装依赖pip install faiss-cpu完整代码如下继承自课程文档可直接运行import requests import numpy as np import faiss import os from azure.ai.inference import ChatCompletionsClient from azure.ai.inference.models import SystemMessage, UserMessage from azure.core.credentials import AzureKeyCredential from azure.ai.inference import EmbeddingsClient endpoint https://models.inference.ai.azure.com model_name Mistral-large token os.environ[GITHUB_TOKEN] client ChatCompletionsClient( endpointendpoint, credentialAzureKeyCredential(token), ) # 拉取 Paul Graham 的随笔原文作为检索语料 response requests.get(https://raw.githubusercontent.com/run-llama/llama_index/main/docs/docs/examples/data/paul_graham/paul_graham_essay.txt) text response.text # 按固定长度 2048 字符切片 chunk_size 2048 chunks [text[i:i chunk_size] for i in range(0, len(text), chunk_size)] len(chunks) embed_model_name cohere-embed-v3-multilingual embed_client EmbeddingsClient( endpointendpoint, credentialAzureKeyCredential(token) ) # 对全部文本切片批量生成向量 embed_response embed_client.embed( inputchunks, modelembed_model_name ) text_embeddings [] for item in embed_response.data: length len(item.embedding) text_embeddings.append(item.embedding) text_embeddings np.array(text_embeddings) # d 为向量维度IndexFlatL2 表示基于欧氏距离的精确索引 d text_embeddings.shape[1] index faiss.IndexFlatL2(d) index.add(text_embeddings) # 韩语问题作者上大学前主要从事的两件事是什么 question 저자가 대학에 오기 전에 주로 했던 두 가지 일은 무엇이었나요? question_embedding embed_client.embed( input[question], modelembed_model_name ) question_embeddings np.array(question_embedding.data[0].embedding) # k2 表示检索最相似的 2 个片段D 为距离I 为命中索引 D, I index.search(question_embeddings.reshape(1, -1), k2) # 距离、索引 retrieved_chunks [chunks[i] for i in I.tolist()[0]] prompt f Context information is below. --------------------- {retrieved_chunks} --------------------- Given the context information and not prior knowledge, answer the query. Query: {question} Answer: chat_response client.complete( messages[ SystemMessage(contentYou are a helpful assistant.), UserMessage(contentprompt), ], temperature1.0, top_p1.0, max_tokens1000, modelmodel_name ) print(chat_response.choices[0].message.content)几个值得注意的实现细节切片策略chunk_size 2048是按字符定长切片的最简方案。课程文档没有做句子边界切分或重叠overlap这在长文档生产场景中是常见的后续优化点检索参数index.search(..., k2)只取最相似的 2 个片段送入 prompt——上下文窗口足够大128k时增加 k 值以纳入更多证据通常是安全的这也是大上下文模型做 RAG 的天然优势采样参数temperature1.0、top_p1.0、max_tokens1000沿用文档默认配置RAG 场景下回答风格偏照资料回答温度取值对事实性影响有限prompt 约束Given the context information and not prior knowledge 明确要求模型只依据检索上下文作答这是抑制幻觉的常用提示词约束。仓库中已运行的 Notebook 给出了该示例的真实输出Mistral Large 用英文回答作者大学前主要从事写作写短篇故事和编程13、14 岁时在 IBM 1401 上用早期 Fortran 通过打孔卡写程序。韩语提问、英文语料、英文作答与模型多语言特性描述一致。Mistral Small低成本、低延迟的 SLMMistral Small 同样属于 Mistral 家族中的 premier/enterprise 类别但顾名思义它是一个小型语言模型Small Language Model, SLM。课程文档总结了使用它的三点优势成本节省相比 Mistral Large、NeMo 等 LLM价格下降约 80%文档口径低延迟响应速度比 Mistral 的大模型更快灵活可在资源受限的不同环境中部署约束更少。对应的适用场景文本类任务摘要、情感分析、翻译高频请求类应用成本效益高低延迟代码任务代码评审与代码建议。实战二Small 与 Large 的延迟与风格对比课程设计了一个对照实验用完全相同的 promptCan you write a Python function to the fizz buzz test?分别请求两个模型观察响应时间差文档预期约 3–5 秒以及回答的长度与风格差异。Mistral Small 版本import os endpoint https://models.inference.ai.azure.com model_name Mistral-small token os.environ[GITHUB_TOKEN] client ChatCompletionsClient( endpointendpoint, credentialAzureKeyCredential(token), ) response client.complete( messages[ SystemMessage(contentYou are a helpful coding assistant.), UserMessage(contentCan you write a Python function to the fizz buzz test?), ], temperature1.0, top_p1.0, max_tokens1000, modelmodel_name ) print(response.choices[0].message.content)Mistral Large 版本仅model_name不同其余完全一致import os from azure.ai.inference import ChatCompletionsClient from azure.ai.inference.models import SystemMessage, UserMessage from azure.core.credentials import AzureKeyCredential endpoint https://models.inference.ai.azure.com model_name Mistral-large token os.environ[GITHUB_TOKEN] client ChatCompletionsClient( endpointendpoint, credentialAzureKeyCredential(token), ) response client.complete( messages[ SystemMessage(contentYou are a helpful coding assistant.), UserMessage(contentCan you write a Python function to the fizz buzz test?), ], temperature1.0, top_p1.0, max_tokens1000, modelmodel_name ) print(response.choices[0].message.content)运行两个单元格的要点分别记录两次请求的返回耗时验证 Small 的响应时间优势文档给出的参考区间是 3–5 秒差距实际数值会随网络与平台负载浮动对比两段回答的长度与风格同一提示下两个模型的输出详略、注释习惯和结构组织可能不同——这是选模型时质量/延迟/成本三角最直观的体感来源。提示仓库 Notebook 中这两个单元格的endpoint已改用os.environ[AZURE_INFERENCE_ENDPOINT]token改用os.environ[AZURE_INFERENCE_CREDENTIAL]见 20-mistral/python/githubmodels-assignment.ipynb。Mistral NeMo唯一的 Apache 2.0 免费开源模型与本课另外两款模型相比Mistral NeMo 是唯一采用 Apache 2.0 许可的免费模型被视为 Mistral 早期开源 LLMMistral 7B的升级。文档还列出了 NeMo 的三个特性更高效的 tokenization使用 Tekken tokenizer替代更常见的 tiktoken在更多语言和代码场景下表现更好支持微调Finetuning基础模型开放用于微调为需要定制的用例提供了灵活性原生函数调用与 Mistral Large 一样在函数调用上经过训练是首批具备该能力的开源模型之一。实战三Tokenizer 效率实测NeMo vs Largetokenization 效率直接影响成本多数 API 按 token 计费与上下文利用率。课程用一个巧妙的设计来量化这一点把函数调用工具定义 用户消息打包成一个完整的ChatCompletionRequest分别用 NeMo 与 Large 的 tokenizer 编码同一个请求再比较 token 数。先安装pip install mistral-commonMistral NeMo 的 tokenizer 测试# Import needed packages: from mistral_common.protocol.instruct.messages import ( UserMessage, ) from mistral_common.protocol.instruct.request import ChatCompletionRequest from mistral_common.protocol.instruct.tool_calls import ( Function, Tool, ) from mistral_common.tokens.tokenizers.mistral import MistralTokenizer # Load Mistral tokenizer model_name open-mistral-nemo tokenizer MistralTokenizer.from_model(model_name) # Tokenize a list of messages tokenized tokenizer.encode_chat_completion( ChatCompletionRequest( tools[ Tool( functionFunction( nameget_current_weather, descriptionGet the current weather, parameters{ type: object, properties: { location: { type: string, description: The city and state, e.g. San Francisco, CA, }, format: { type: string, enum: [celsius, fahrenheit], description: The temperature unit to use. Infer this from the users location., }, }, required: [location, format], }, ) ) ], messages[ UserMessage(contentWhats the weather like today in Paris), ], modelmodel_name, ) ) tokens, text tokenized.tokens, tokenized.text # Count the number of tokens print(len(tokens))Mistral Large 的对照测试同样请求结构仅model_name换成mistral-large-latest# Import needed packages: from mistral_common.protocol.instruct.messages import ( UserMessage, ) from mistral_common.protocol.instruct.request import ChatCompletionRequest from mistral_common.protocol.instruct.tool_calls import ( Function, Tool, ) from mistral_common.tokens.tokenizers.mistral import MistralTokenizer # Load Mistral tokenizer model_name mistral-large-latest tokenizer MistralTokenizer.from_model(model_name) # Tokenize a list of messages tokenized tokenizer.encode_chat_completion( ChatCompletionRequest( tools[ Tool( functionFunction( nameget_current_weather, descriptionGet the current weather, parameters{ type: object, properties: { location: { type: string, description: The city and state, e.g. San Francisco, CA, }, format: { type: string, enum: [celsius, fahrenheit], description: The temperature unit to use. Infer this from the users location., }, }, required: [location, format], }, ) ) ], messages[ UserMessage(contentWhats the weather like today in Paris), ], modelmodel_name, ) ) tokens, text tokenized.tokens, tokenized.text # Count the number of tokens print(len(tokens))设计上有两处值得说明为什么把tools也放进编码请求工具定义JSON Schema通常占据大量 token。把函数调用工具 一句话提问整体编码模拟的正是 Function Calling 应用的真实请求形态——这正是 NeMo原生函数调用 高效 tokenization两大特性的交汇处MistralTokenizer.from_model(...)mistral-common会按模型名自动加载对应 tokenizer 配置因此同一份代码只需改model_name即可横向比较不同模型的编码效率。仓库中已运行完成的 Notebook 给出了真实执行结果open-mistral-nemoNeMo tokenizer128 tokensmistral-large-latestLarge tokenizer135 tokens。即同样一个天气查询函数 提问的请求NeMo 的 tokenizer 产出的 token 更少验证了课程文档NeMo returns fewer tokens than Mistral Large的结论。token 越少在按量计费与上下文占用上越占优这也是tokenizer 效率这一特性可被直接量化的原因。运行环境依赖与验证记录汇总本课全部代码块所需的环境以仓库 Notebook 的实际运行记录为准Python 3.12依赖用途Notebook 中的实际版本azure-ai-inferenceChatCompletionsClient/EmbeddingsClientpip install azure-ai-inference随代码环境预装faiss-cpu向量索引IndexFlatL21.8.0.post1numpy向量数组运算1.26.4faiss-cpu 要求2.0requests拉取文本语料随环境预装mistral-commonMistralTokenizer本地编码1.4.4自动带上tiktoken 0.7.0、sentencepiece 0.2.0鉴权方面本课文档保加利亚语译本使用GITHUB_TOKEN环境变量仓库当前 Notebook 已切换到AZURE_INFERENCE_ENDPOINTAZURE_INFERENCE_CREDENTIAL见上文平台说明。运行前请确保所用平台对应的环境变量已设置否则os.environ[...]会直接抛出KeyError。小结与延伸本课以 Mistral 三款模型为主线完成了一次模型选型 能力验证的完整闭环Mistral Large 2大上下文128k、原生函数调用、13 种语言适合 RAG 与复杂代码生成——实战一中你用cohere-embed-v3-multilingual faiss 搭起了最小可用的 RAG 链路Mistral Small约 80% 的价格降幅与更低延迟适合高频、低延迟场景——实战二的 Fizz Buzz 对照实验让你对延迟/风格差异有直接体感Mistral NeMoApache 2.0、可微调、原生函数调用Tekken tokenizer 使其在同一请求下产出更少 token128 vs 135仓库 Notebook 实测——实战三展示了如何量化 tokenizer 效率。如果希望继续深入可在同一仓库中延伸阅读第 16 课 开源模型与 Hugging Face开源模型选型背景、第 15 课 RAG 与向量数据库RAG 的更完整框架实现本课的 RAG 示例正是其中嵌入 近邻检索 受约束 prompt三要素的最小化落地。【免费下载链接】generative-ai-for-beginners21 Lessons, Get Started Building with Generative AI项目地址: https://gitcode.com/GitHub_Trending/ge/generative-ai-for-beginners创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考

读完文章,也想定制专属网站?

尧图设计师 24 小时内与您沟通定制方案

免费获取报价