跳至主要内容

Mistral Medium 3 教程:构建具备代理能力的应用

在 DataLab 环境中,使用 LangGraph、Tavily、Python 工具和 Mistral AI API 开发多工具代理应用。
· 5分钟 阅读

使用 AI 探索

Mistral Medium 3 以显著低于许多替代方案的价格提供高性能。目前可通过 Mistral AI API 使用,输入端仅 $0.40/百万 token,输出端 $2/百万 token。无论是 API 还是自部署系统,这一定价都优于诸如 DeepSeek v3 等领先竞争对手。总之,您可以在各类基准上获得高达 Claude Sonnet 3.7 90% 的性能,同时大幅节省成本。

在本教程中,我们将学习如何配置 Mistral API,并使用 Python 客户端访问模型。随后,我们将使用 LangGraph 构建一个具备代理能力的应用,通过网页搜索和 Python REPL 工具来生成答案。

使用 Mistral Medium 3 构建代理应用 特色图片

作者供图

从零开始使用 Mistral Medium 3

本节将学习如何生成 API 密钥、将其保存为环境变量,然后使用 Python 客户端访问 Mistral Medium 3 以完成文本生成和图像理解。

1. 生成 Mistral AI API 密钥

注册 La Plateforme: Mistral AI,然后前往 Billing 分区,使用信用卡/借记卡充值 $5。本项目只需用到几美分。随后前往 API keys 选项卡生成新的 API 密钥。

2. 环境配置

在 DataLab 中设置环境变量非常简单。进入“Environment”选项卡,选择“Environment Variables”,新增名为“MISTRAL_API_KEY”的变量并填入您的 API 密钥。保存更改后,请确保将其连接。

在 Datalab 中设置环境变量

在 DataLab 中,新建一个 Python 单元并安装 Mistral AI 的 Python 软件包。

!pip install -U mistralai 

3. 文本生成

在编写代码前,务必通过 Models Overview 页面确认 Mistral Medium 3 的 API 端点名称。根据文档,端点名称为 mistral-medium-latest。

阅读文档以获取最新模型名称。

来源:Models Overview | Mistral AI Large Language Models

接下来,我们将使用 API 密钥创建 Mistral AI 客户端,并针对用户查询生成流式响应。

import osfrom mistralai import Mistralapi_key = os.environ["MISTRAL_API_KEY"]model = "mistral-medium-latest"client = Mistral(api_key=api_key)stream_response = client.chat.stream(    model = model,    messages = [        {            "role": "user",            "content": "What is the best course to take from DataCamp?",        },    ])for chunk in stream_response:    print(chunk.data.choices[0].delta.content, end="" )

响应非常准确,而且几乎不花什么钱。

Mistral AI 生成的输出

4. 图像理解

为测试模型的多模态能力,我们将截取 DataCamp 博客首页的屏幕,并连同用户提示一同提供给模型。

DataCamp 博客页面截图

来源:Blog | Data Science Articles | DataCamp

由于模型无法直接访问图像文件,我们需要先加载图像并将其转换为 Base64 编码的字符串。

import base64import requestsdef encode_image(image_path):    """Encode the image to base64."""    try:        with open(image_path, "rb") as image_file:            return base64.b64encode(image_file.read()).decode('utf-8')    except FileNotFoundError:        print(f"Error: The file {image_path} was not found.")        return None    except Exception as e:  # Added general exception handling        print(f"Error: {e}")        return None# Path to your imageimage_path = "datacamp_fp.png"# Getting the base64 stringbase64_image = encode_image(image_path)

现在我们将把 Base64 编码后的图像与用户查询一并发送给 Mistral AI 的聊天补全客户端。

# Define the messages for the chatmessages = [    {        "role": "user",        "content": [            {                "type": "text",                "text": "Explain the image in a Donald Trump style."            },            {                "type": "image_url",                "image_url": f"data:image/png;base64,{base64_image}"             }        ]    }]stream_response = client.chat.stream(    model = model,    messages = messages)for chunk in stream_response:    print(chunk.data.choices[0].delta.content, end="" )

模型成功理解了图像,并以 Donald Trump 的风格生成了回答,展示了其多模态理解能力。

Mistral AI 生成的输出

使用 Mistral Medium 3 构建代理应用

在本项目中,我们将结合 Mistral Medium 3 与 LangGraph 构建一个具备代理能力的应用。该应用将使用 Tavily API 进行网页搜索,并通过 Python REPL 基于用户提示执行代码。

初次接触 LangGraph?没问题!请参阅我们的 LangGraph 教程,了解该框架所需的一切基础知识。

1. 配置 Tavily API

在开始实现前,我们需要通过创建账户并生成 API 密钥来配置 Tavily AI。流程非常简单,且无需提供付款信息或信用卡。

获得 API 密钥后,请将其保存为名为 TAVILY_API_KEY 的环境变量,可在本地或 DataLab 中按前文示例进行设置。

2. 安装 Python 软件包

接下来,我们将安装必要的 Python 软件包,以便在 LangChain 生态中创建工具与代理。

%%capture!pip install -U \    mistralai \    langchain langchain-mistralai \    langchain-experimental \    langgraph  \    tavily-python

3. 创建 LLM 客户端

我们将通过指定模型名称、temperature,并启用流式响应,来创建 LangChain 的 ChatMistralAI 大语言模型(LLM)客户端。

from langchain_mistralai import ChatMistralAIllm = ChatMistralAI(    model="mistral-medium-latest",       temperature=0.2,                     streaming=True          )

4. 初始化工具

现在为代理配置工具。我们无需手工编写工具,可直接使用 LangChain 生态中的现成工具,例如 Tavily 搜索与 Python REPL。

from langchain_community.tools import TavilySearchResultsfrom langchain_experimental.tools.python.tool import PythonREPLToolsearch_tool = TavilySearchResults(max_results=5, include_answer=True)code_tool   = PythonREPLTool()tools = [search_tool, code_tool]

5. 设置代理

LLM 客户端与工具就绪后,我们即可使用 LangGraph 创建 React Agent。

from langgraph.prebuilt import create_react_agentagent = create_react_agent(    model=llm,           tools=tools,      )    

LangGraph Studio 是 LangGraph 框架的可视化开发环境;请参阅 LangGraph Studio 指南:安装、设置与用例 以了解更多信息。

6. 提取工具名称

在执行代理前,我们将定义一个 Python 函数,用于提取代理在生成响应时调用的工具名称,帮助我们识别被调用的工具。

def extract_tool_names(conversation: dict) -> list[str]:    """    Given a conversation dict with a 'messages' list (where each message    may be a dict or a Pydantic model), extract all unique tool names    used in any tool call.    """    tool_names = set()    for msg in conversation.get('messages', []):        # 1) Try direct attribute access (for Pydantic models)        calls = []        if hasattr(msg, 'tool_calls'):            calls = getattr(msg, 'tool_calls') or []        # 2) If that fails, the message might be a dict        elif isinstance(msg, dict):            calls = msg.get('tool_calls')            # also check nested in additional_kwargs            if not calls and isinstance(msg.get('additional_kwargs'), dict):                calls = msg['additional_kwargs'].get('tool_calls')        # 3) Finally, check additional_kwargs on objects        else:            ak = getattr(msg, 'additional_kwargs', None)            if isinstance(ak, dict):                calls = ak.get('tool_calls', [])        # Normalize to list        calls = calls or []        # Extract names        for call in calls:            # dict-style tool call            if isinstance(call, dict):                # top-level 'name'                if 'name' in call:                    tool_names.add(call['name'])                # nested under 'function'                elif 'function' in call and isinstance(call['function'], dict):                    fn = call['function']                    if 'name' in fn:                        tool_names.add(fn['name'])    return sorted(tool_names)

LangGraph Studio 是 LangGraph 框架的可视化开发环境;请参阅 LangGraph Studio 指南:安装、设置与用例 以了解更多信息。

7. 测试代理

让我们通过一个突发新闻相关的问题来测试该代理。

question = "What are the top 5 breaking news stories?"def run_agent(question):    result = agent.invoke(        {            "messages": [                {"role": "user", "content": question}            ]        }    )    tool_name = extract_tool_names(result)    # The LLM’s final answer is always in the last message    raw_answer = result["messages"][-1].content    clean_text = "".join(part for part in raw_answer if isinstance(part, str))    return tool_name, clean_texttool_name, clean_text = run_agent(question)print("Tool used ⫸", tool_name, "\n")print(clean_text)

该代理使用了 Tavily 搜索工具来生成有关突发新闻的回答。

代理应用生成的输出

接着,让我们通过要求代理生成并执行 Python 代码来测试 Python REPL 工具。

question = "Write a code to display the stars in a triangle. Please execute the code too."tool_name, clean_text = run_agent(question)print("Tool used ⫸", tool_name, "\n")print(clean_text)

该代理使用了 Mistral Medium 3 进行代码生成,并通过 Python REPL 执行了代码。

代理应用生成的输出

最后,让我们测试一个需要代理按顺序使用两种工具的查询。

question = "Get the latest gold price data for the past 7 days and use it to generate a line plot"tool_name, clean_text = run_agent(question)print("Tool used ⫸", tool_name, "\n")print(clean_text)

代理将使用 Tavily 搜索获取黄金价格数据,使用 Mistral Medium 3 生成数据可视化代码,并通过 Python REPL 执行该代码。最终结果将包含高精度的图表以及所用工具的摘要。

Tool used ⫸ ['Python_REPL', 'tavily_search_results_json'] The code generates a line plot showing the gold price per gram in USD over the last 7 days, with the x-axis representing dates and the y-axis representing the gold price. The plot includes markers for each data point, a title, labeled axes, a grid, and rotated x-axis labels for better readability.

使用网页搜索和 Python Repl 工具生成的代理应用输出

如果运行代码时遇到任何问题,请参阅 Mistral Medium 3 — DataLab 笔记本以获取更多指导。

您也可以使用 Haystack 生态来构建更强大且更易实施的代理应用。请参阅以下教程以了解更多: Haystack AI 教程:构建具备代理能力的工作流。

总结

在试用 Mistral AI API 并构建代理测试多种应用后,最令人印象深刻的一点是——即便使用了 161,075 个 token,我也一分钱没花。该模型价格亲民、速度快、准确性高、上手极其容易。它是其他昂贵 API(如 DeepSeek)的绝佳替代品,同时提供相近的功能。

AI 生态显然正朝着更小、更快、更准且更具性价比的模型发展。这一趋势尤为利好初创公司和中小企业(SMEs)。这些组织往往高度依赖 LLM 提供商,随着模型变得更实惠,它们将显著受益于更高的利润率。

学习 Developing Large Language Models 技能路径,使用 PyTorch 与 Hugging Face 以及最新的深度学习与 NLP 技术,构建您自己的 LLM。

Abid Ali Awan

作者

Abid Ali Awan

作为一名持证的数据科学家,我热衷于利用前沿技术打造创新的机器学习应用。凭借在语音识别、数据分析与报告、MLOps、对话式人工智能以及自然语言处理方面的扎实背景,我不断打磨构建智能系统的能力,力求带来切实影响。除技术专长外,我也擅长沟通,能够将复杂概念提炼为清晰、简明的表述。因此,我成为数据科学领域备受关注的博主,与不断壮大的数据专业人士社区分享洞见与实践经验。目前,我专注于内容创作与编辑,借助大语言模型打造有力且吸引人的内容,帮助企业与个人更好地发挥数据价值。

主题