第二十章:使用Mistral模型构建


文档摘要

使用Mistral模型构建 简介 本课程将涵盖以下内容: 探索不同的Mistral模型 理解每个模型的使用场景和案例 代码示例展示了每个模型的独特功能。 Mistral模型 在本课程中,我们将探索三个不同的Mistral模型:Mistral Large、Mistral Small 和 Mistral NeMo。 这些模型都可以在GitHub模型市场免费获取。本笔记本中的代码将使用这些模型来运行代码。有关如何使用GitHub模型进行AI模型原型设计的更多信息,请参阅文档。 Mistral Large 2(2407) Mistral Large 2是目前Mistral的旗舰模型,专为企业使用而设计。

使用Mistral模型构建

简介

本课程将涵盖以下内容:

  • 探索不同的Mistral模型
  • 理解每个模型的使用场景和案例
  • 代码示例展示了每个模型的独特功能。

Mistral模型

在本课程中,我们将探索三个不同的Mistral模型:Mistral LargeMistral SmallMistral NeMo

这些模型都可以在GitHub模型市场免费获取。本笔记本中的代码将使用这些模型来运行代码。有关如何使用GitHub模型进行AI模型原型设计的更多信息,请参阅文档。

Mistral Large 2(2407)

Mistral Large 2是目前Mistral的旗舰模型,专为企业使用而设计。

该模型通过以下方式升级了原始的Mistral Large:

  • 更大的上下文窗口——128k vs 32k
  • 在数学和编码任务上表现更好——平均准确率为76.9% vs 60.4%
  • 提升多语言性能——支持的语言包括:英语、法语、德语、西班牙语、意大利语、葡萄牙语、荷兰语、俄语、中文、日语、韩语、阿拉伯语和印地语。

凭借这些功能,Mistral Large在以下方面表现出色:

  • 检索增强生成(RAG)——由于更大的上下文窗口
  • 函数调用——此模型具有原生函数调用功能,允许与外部工具和API集成。这些调用可以并行或顺序执行。
  • 代码生成——此模型擅长生成Python、Java、TypeScript和C++代码。

使用Mistral Large 2的RAG示例

在此示例中,我们使用Mistral Large 2在一个文本文档上运行RAG模式。问题是用韩语写的,询问作者在大学前的活动。

它使用Cohere嵌入模型为文本文档和问题创建嵌入。对于这个样本,它使用faiss Python包作为向量存储。

发送给Mistral模型的提示包括问题以及与问题相似的检索片段。模型随后提供自然语言响应。

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( endpoint=endpoint, credential=AzureKeyCredential(token), ) 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 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( endpoint=endpoint, credential=AzureKeyCredential(token) ) embed_response = embed_client.embed( input=chunks, model=embed_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 = text_embeddings.shape[1] index = faiss.IndexFlatL2(d) index.add(text_embeddings) question = "저자가 대학에 오기 전에 주로 했던 두 가지 일은 무엇이었나요??" question_embedding = embed_client.embed( input=[question], model=embed_model_name ) question_embeddings = np.array(question_embedding.data[0].embedding) D, I = index.search(question_embeddings.reshape(1, -1), k=2) # distance, index 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(content="You are a helpful assistant."), UserMessage(content=prompt), ], temperature=1.0, top_p=1.0, max_tokens=1000, model=model_name ) print(chat_response.choices[0].message.content)

Mistral Small

Mistral Small是Mistral系列模型中的另一个模型,属于高级/企业类别。顾名思义,这是一个小型语言模型(SLM)。使用Mistral Small的优点在于:

  • 相比Mistral LLM(如Mistral Large和NeMo)更具成本效益——价格下降了80%
  • 低延迟——相比Mistral的LLM更快响应
  • 灵活——可以在不同的环境中部署,并对所需资源的限制较少。

Mistral Small适用于:

  • 基于文本的任务,如摘要、情感分析和翻译。
  • 需要频繁请求的应用程序,因为它具有成本效益。
  • 低延迟的代码任务,如代码审查和建议。

比较Mistral Small和Mistral Large

为了展示Mistral Small和Large之间的延迟差异,请运行下面的单元格。

你应该能看到大约3-5秒的响应时间差异。同时注意相同提示下的响应长度和风格。

import os endpoint = "https://models.inference.ai.azure.com" model_name = "Mistral-small" token = os.environ["GITHUB_TOKEN"] client = ChatCompletionsClient( endpoint=endpoint, credential=AzureKeyCredential(token), ) response = client.complete( messages=[ SystemMessage(content="You are a helpful coding assistant."), UserMessage(content="Can you write a Python function to the fizz buzz test?"), ], temperature=1.0, top_p=1.0, max_tokens=1000, model=model_name ) print(response.choices[0].message.content)
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( endpoint=endpoint, credential=AzureKeyCredential(token), ) response = client.complete( messages=[ SystemMessage(content="You are a helpful coding assistant."), UserMessage(content="Can you write a Python function to the fizz buzz test?"), ], temperature=1.0, top_p=1.0, max_tokens=1000, model=model_name ) print(response.choices[0].message.content)

Mistral NeMo

与其他两个在本课程中讨论的模型相比,Mistral NeMo是唯一一个具有Apache2许可证的免费模型。

它被视为对Mistral早期开源LLM(Mistral 7B)的升级。

NeMo模型的其他一些特性包括:

  • 更高效的分词:该模型使用Tekken分词器而不是更常用的tiktoken。这使得它在更多语言和代码上的性能更好。
  • 微调:基础模型可供微调。这使得在需要微调的场景下更加灵活。
  • 原生函数调用——与Mistral Large一样,该模型经过了函数调用训练。这使其成为首批开放源码模型之一。

比较分词器

在此示例中,我们将比较Mistral NeMo与Mistral Large的分词处理。

两个示例使用相同的提示,但你应该看到NeMo返回的标记数少于Mistral Large。

pip install mistral-common
# 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( function=Function( name="get_current_weather", description="Get 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(content="What's the weather like today in Paris"), ], model=model_name, ) ) tokens, text = tokenized.tokens, tokenized.text # Count the number of tokens print(len(tokens))
# 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( function=Function( name="get_current_weather", description="Get 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(content="What's the weather like today in Paris"), ], model=model_name, ) ) tokens, text = tokenized.tokens, tokenized.text # Count the number of tokens print(len(tokens))

学习不会停止在这里,继续你的旅程

完成本课程后,查看我们的生成式AI学习集合,以继续提升你的生成式AI知识!

声明:
本文件灏天文库团队进行了翻译。尽管我们力求准确,但请注意,翻译可能包含错误或不准确之处。原文档以其原始语言为准。我们不对因使用此翻译而产生的任何误解或误译负责。


发布者: 作者: 转发
评论区 (0)
U