Skip to main content
Open In ColabOpen on GitHub

ChatMistralAI

这将帮助您开始使用Mistral 聊天模型。有关所有ChatMistralAI功能和配置的详细文档,请访问API参考ChatMistralAI类构建在Mistral API之上。有关Mistral支持的所有模型的列表,请查看此页面

概述

集成详情

本地可序列化JS 支持包下载量包最新版本
ChatMistralAIlangchain_mistralai测试版PyPI - 下载量PyPI - 版本

模型特性

工具调用结构化输出JSON模式图像输入音频输入视频输入令牌级流式传输原生异步令牌使用Logprobs

设置

要访问ChatMistralAI模型,您需要创建一个Mistral账户,获取一个API密钥,并安装langchain_mistralai集成包。

凭证

需要一个有效的API key来与API进行通信。完成此操作后,请设置MISTRAL_API_KEY环境变量:

import getpass
import os

if "MISTRAL_API_KEY" not in os.environ:
os.environ["MISTRAL_API_KEY"] = getpass.getpass("Enter your Mistral API key: ")

如果你想获取模型调用的自动追踪,你也可以通过取消注释以下内容来设置你的LangSmith API密钥:

# os.environ["LANGSMITH_API_KEY"] = getpass.getpass("Enter your LangSmith API key: ")
# os.environ["LANGSMITH_TRACING"] = "true"

安装

LangChain Mistral 集成位于 langchain_mistralai 包中:

%pip install -qU langchain_mistralai

实例化

现在我们可以实例化我们的模型对象并生成聊天完成:

from langchain_mistralai import ChatMistralAI

llm = ChatMistralAI(
model="mistral-large-latest",
temperature=0,
max_retries=2,
# other params...
)
API Reference:ChatMistralAI

调用

messages = [
(
"system",
"You are a helpful assistant that translates English to French. Translate the user sentence.",
),
("human", "I love programming."),
]
ai_msg = llm.invoke(messages)
ai_msg
AIMessage(content='Sure, I\'d be happy to help you translate that sentence into French! The English sentence "I love programming" translates to "J\'aime programmer" in French. Let me know if you have any other questions or need further assistance!', response_metadata={'token_usage': {'prompt_tokens': 32, 'total_tokens': 84, 'completion_tokens': 52}, 'model': 'mistral-small', 'finish_reason': 'stop'}, id='run-64bac156-7160-4b68-b67e-4161f63e021f-0', usage_metadata={'input_tokens': 32, 'output_tokens': 52, 'total_tokens': 84})
print(ai_msg.content)
Sure, I'd be happy to help you translate that sentence into French! The English sentence "I love programming" translates to "J'aime programmer" in French. Let me know if you have any other questions or need further assistance!

链式调用

我们可以像这样将我们的模型与提示模板接起来:

from langchain_core.prompts import ChatPromptTemplate

prompt = ChatPromptTemplate.from_messages(
[
(
"system",
"You are a helpful assistant that translates {input_language} to {output_language}.",
),
("human", "{input}"),
]
)

chain = prompt | llm
chain.invoke(
{
"input_language": "English",
"output_language": "German",
"input": "I love programming.",
}
)
API Reference:ChatPromptTemplate
AIMessage(content='Ich liebe Programmierung. (German translation)', response_metadata={'token_usage': {'prompt_tokens': 26, 'total_tokens': 38, 'completion_tokens': 12}, 'model': 'mistral-small', 'finish_reason': 'stop'}, id='run-dfd4094f-e347-47b0-9056-8ebd7ea35fe7-0', usage_metadata={'input_tokens': 26, 'output_tokens': 12, 'total_tokens': 38})

API参考

前往API参考以获取所有属性和方法的详细文档。


这个页面有帮助吗?