跳到主要内容

MistralAI

MistralAI 文档

项目设置

要将 langchain4j 安装到您的项目中,请添加以下依赖:

对于 Maven 项目的 pom.xml


<dependency>
<groupId>dev.langchain4j</groupId>
<artifactId>langchain4j</artifactId>
<version>1.18.1</version>
</dependency>

<dependency>
<groupId>dev.langchain4j</groupId>
<artifactId>langchain4j-mistral-ai</artifactId>
<version>1.18.1</version>
</dependency>

对于 Gradle 项目的 build.gradle

implementation 'dev.langchain4j:langchain4j:1.18.1'
implementation 'dev.langchain4j:langchain4j-mistral-ai:1.18.1'

API Key 设置

将您的 MistralAI API 密钥添加到项目中,您可以创建一个类 ApiKeys.java,代码如下

public class ApiKeys {
public static final String MISTRALAI_API_KEY = System.getenv("MISTRAL_AI_API_KEY");
}

不要忘记将 API 密钥设置为环境变量。

export MISTRAL_AI_API_KEY=your-api-key #For Unix OS based
SET MISTRAL_AI_API_KEY=your-api-key #For Windows OS

有关如何获取 MistralAI API 密钥的更多详情,请见 此处

模型选择

您可以使用 MistralAiChatModelNameMistralAiFimModelName Java 枚举,为您的用例找到合适的模型名称。 MistralAI 根据性能与成本权衡更新了新的模型选择与分类。

模型名称部署或可用来源描述
open-mistral-7b- Mistral AI La Plateforme.
- Cloud platforms (Azure, AWS, GCP).
- Hugging Face.
- Self-hosted (On-premise, IaaS, docker, local).
OpenSource
Mistral AI 发布的首个稠密模型,
非常适合实验、
定制和快速迭代。

最大 token 32K

Java Enum
MistralAiChatModelName.OPEN_MISTRAL_7B
open-mixtral-8x7b- Mistral AI La Plateforme.
- Cloud platforms (Azure, AWS, GCP).
- Hugging Face.
- Self-hosted (On-premise, IaaS, docker, local).
OpenSource
适合处理多语言操作、
代码生成与微调。
出色的成本/性能权衡。

最大 token 32K

Java Enum
MistralAiChatModelName.OPEN_MIXTRAL_8x7B
open-mixtral-8x22b- Mistral AI La Plateforme.
- Cloud platforms (Azure, AWS, GCP).
- Hugging Face.
- Self-hosted (On-premise, IaaS, docker, local).
OpenSource
具备 Mixtral-8x7B 的全部能力,并在数学
与编码方面更强,原生支持函数调用

最大 token 64K。

Java Enum
MistralAiChatModelName.OPEN_MIXTRAL_8X22B
open-mistral-nemo- Mistral AI La Plateforme.
- Cloud platforms (Azure, AWS, GCP).
- Hugging Face.
- Self-hosted (On-premise, IaaS, docker, local).
OpenSource
与 NVIDIA 合作构建的 12B 模型。
其推理、世界知识与编码准确度在同尺寸类别中处于前沿水平。

最大 token 128K。

Java Enum
MistralAiChatModelName.OPEN_MISTRAL_NEMO
open-codestral-mamba- Mistral AI La Plateforme.
- Cloud platforms (Azure, AWS, GCP).
- Hugging Face.
- Self-hosted (On-premise, IaaS, docker, local).
OpenSource
专精于代码生成的 Mamba2 语言模型。
经过高级代码与推理能力训练,使其可与基于 transformer 的 SOTA 模型媲美。

最大 token 256K。

Java Enum
MistralAiFimModelName.OPEN_CODESTRAL_MAMBA
mistral-small-latest- Mistral AI La Plateforme.
- Cloud platforms (Azure, AWS, GCP).
Commercial
适合可批量完成的简单任务
(分类、客户支持或文本生成)。

最大 token 32K

Java Enum
MistralAiChatModelName.MISTRAL_SMALL_LATEST
mistral-medium-latest- Mistral AI La Plateforme.
- Cloud platforms (Azure, AWS, GCP).
Commercial
适合需要中等推理能力的中间任务
(数据提取、摘要、
撰写邮件、撰写描述)。

最大 token 32K

Java Enum
MistralAiChatModelName.MISTRAL_MEDIUM_LATEST
mistral-large-latest- Mistral AI La Plateforme.
- Cloud platforms (Azure, AWS, GCP).
Commercial
适合需要强大推理能力或高度专业化的复杂任务
(文本生成、代码生成、RAG 或 Agents)。

最大 token 128K

Java Enum
MistralAiChatModelName.MISTRAL_LARGE_LATEST
mistral-embed- Mistral AI La Plateforme.
- Cloud platforms (Azure, AWS, GCP).
Commercial
将文本转换为 1024 维的
数值向量嵌入。
嵌入模型支持检索与 RAG 应用。

最大 token 8K

Java Enum
MistralAiEmbeddingModelName.MISTRAL_EMBED
codestral-latest- Mistral AI La Plateforme.
- Cloud platforms (Azure, AWS, GCP).
- Hugging Face.
- Self-hosted (On-premise, IaaS, docker, local).
OpenSource(非生产许可)与 Commercial
专为代码生成任务(包括 fill-in-the-middle 与代码补全)设计并优化的前沿生成式模型。

最大 token 32K

Java Enum
MistralAiFimModelName.CODESTRAL_LATEST

@Deprecated 模型:

  • mistral-tiny (@Deprecated)
  • mistral-small (@Deprecated)
  • mistral-medium (@Deprecated)

您可以在 此处 找到更多详情以及各 Mistral 模型对应的用例类型

聊天补全

聊天模型允许您使用在对话数据上微调的模型生成类人响应。

同步

创建一个类并添加以下代码。

import dev.langchain4j.model.chat.ChatModel;
import dev.langchain4j.model.mistralai.MistralAiChatModel;

public class HelloWorld {
public static void main(String[] args) {
ChatModel model = MistralAiChatModel.builder()
.apiKey(ApiKeys.MISTRALAI_API_KEY)
.modelName(MistralAiChatModelName.MISTRAL_SMALL_LATEST)
.build();

String response = model.chat("Say 'Hello World'");
System.out.println(response);
}
}

运行程序将生成类似如下的输出变体

Hello World! How can I assist you today?

流式

创建一个类并添加以下代码。

import dev.langchain4j.data.message.AiMessage;
import dev.langchain4j.model.chat.response.StreamingChatResponseHandler;
import dev.langchain4j.model.mistralai.MistralAiStreamingChatModel;
import dev.langchain4j.model.output.Response;

import java.util.concurrent.CompletableFuture;

public class HelloWorld {
public static void main(String[] args) {
MistralAiStreamingChatModel model = MistralAiStreamingChatModel.builder()
.apiKey(ApiKeys.MISTRALAI_API_KEY)
.modelName(MistralAiChatModelName.MISTRAL_SMALL_LATEST)
.build();

CompletableFuture<ChatResponse> futureResponse = new CompletableFuture<>();
model.chat("Tell me a joke about Java", new StreamingChatResponseHandler() {

@Override
public void onPartialResponse(String partialResponse) {
System.out.print(partialResponse);
}

@Override
public void onCompleteResponse(ChatResponse completeResponse) {
futureResponse.complete(completeResponse);
}

@Override
public void onError(Throwable error) {
futureResponse.completeExceptionally(error);
}
});

futureResponse.join();
}
}

您将在 onPartialResponse 方法中接收 LLM 生成的每一个文本块(token)。

您可以看到下方输出是实时流式返回的。

"Why do Java developers wear glasses? Because they can't C#"

当然,您可以将 MistralAI 聊天补全与 设置模型参数聊天记忆 等其他功能结合,以获得更准确的响应。

聊天记忆 中,您将学习如何传递聊天历史,以便 LLM 知道之前说过什么。如果像本简单示例这样不传递聊天历史,LLM 将不知道之前说过什么,因此无法正确回答第二个问题('What did I just ask?')。

许多参数在幕后已设置,例如超时、模型类型和模型参数。 在 设置模型参数 中,您将学习如何显式设置这些参数。

函数调用

函数调用允许 Mistral 聊天模型(同步流式)连接到外部工具。例如,您可以调用 Tool 获取支付交易状态,如 Mistral AI 函数调用 教程 所示。

支持哪些 mistral 模型?
备注

目前,以下模型支持函数调用:

  • Mistral Small MistralAiChatModelName.MISTRAL_SMALL_LATEST
  • Mistral Large MistralAiChatModelName.MISTRAL_LARGE_LATEST
  • Mixtral 8x22B MistralAiChatModelName.OPEN_MIXTRAL_8X22B
  • Mistral Nemo MistralAiChatModelName.OPEN_MISTRAL_NEMO

1. 定义 Tool 类以及如何获取支付数据

假设您有如下支付交易数据集。在实际应用中,您应注入数据库源或 REST API 客户端来获取数据。

import java.util.*;

public class PaymentTransactionTool {

private final Map<String, List<String>> paymentData = Map.of(
"transaction_id", List.of("T1001", "T1002", "T1003", "T1004", "T1005"),
"customer_id", List.of("C001", "C002", "C003", "C002", "C001"),
"payment_amount", List.of("125.50", "89.99", "120.00", "54.30", "210.20"),
"payment_date", List.of("2021.18.15", "2021.18.16", "2021.18.17", "2021.18.15", "2021.18.18"),
"payment_status", List.of("Paid", "Unpaid", "Paid", "Paid", "Pending"));

...
}

接下来,让我们定义两个方法 retrievePaymentStatusretrievePaymentDate,从 Tool 类获取支付状态和支付日期。

// Tool to be executed to get payment status
@Tool("Get payment status of a transaction") // function description
String retrievePaymentStatus(@P("Transaction id to search payment data") String transactionId) {
return getPaymentData(transactionId, "payment_status");
}

// Tool to be executed to get payment date
@Tool("Get payment date of a transaction") // function description
String retrievePaymentDate(@P("Transaction id to search payment data") String transactionId) {
return getPaymentData(transactionId, "payment_date");
}

private String getPaymentData(String transactionId, String data) {
List<String> transactionIds = paymentData.get("transaction_id");
List<String> paymentData = paymentData.get(data);

int index = transactionIds.indexOf(transactionId);
if (index != -1) {
return paymentData.get(index);
} else {
return "Transaction ID not found";
}
}

它使用 @Tool 注解定义函数描述,使用 @P 注解定义 dev.langchain4j.agent.tool.* 包中的参数描述。更多信息见 此处

2. 定义一个作为 agent 的接口以发送聊天消息。

创建接口 PaymentTransactionAgent

import dev.langchain4j.service.SystemMessage;

interface PaymentTransactionAgent {
@SystemMessage({
"You are a payment transaction support agent.",
"You MUST use the payment transaction tool to search the payment transaction data.",
"If there a date convert it in a human readable format."
})
String chat(String userMessage);
}

3. 定义一个 main 应用程序类以与 MistralAI 聊天模型对话

import dev.langchain4j.memory.chat.MessageWindowChatMemory;
import dev.langchain4j.model.chat.ChatModel;
import dev.langchain4j.model.mistralai.MistralAiChatModel;
import dev.langchain4j.model.mistralai.MistralAiChatModelName;
import dev.langchain4j.service.AiServices;

public class PaymentDataAssistantApp {

ChatModel mistralAiModel = MistralAiChatModel.builder()
.apiKey(System.getenv("MISTRAL_AI_API_KEY")) // Please use your own Mistral AI API key
.modelName(MistralAiChatModelName.MISTRAL_LARGE_LATEST) // Also you can use MistralAiChatModelName.OPEN_MIXTRAL_8X22B as open source model
.logRequests(true)
.logResponses(true)
.build();

public static void main(String[] args) {
// STEP 1: User specify tools and query
PaymentTransactionTool paymentTool = new PaymentTransactionTool();
String userMessage = "What is the status and the payment date of transaction T1005?";

// STEP 2: User asks the agent and AiServices call to the functions
PaymentTransactionAgent agent = AiServices.builder(PaymentTransactionAgent.class)
.chatModel(mistralAiModel)
.tools(paymentTool)
.chatMemory(MessageWindowChatMemory.withMaxMessages(10))
.build();

// STEP 3: User gets the final response from the agent
String answer = agent.chat(userMessage);
System.out.println(answer);
}
}

并期望得到类似这样的回答:

The status of transaction T1005 is Pending. The payment date is October 8, 2021.

JSON 模式

您也可以使用 JSON 模式以 JSON 格式获取响应。为此,需要在 MistralAiChatModel 构建器或 MistralAiStreamingChatModel 构建器中将 responseFormat 参数设置为 ResponseFormat.JSON

同步示例:

ChatModel model = MistralAiChatModel.builder()
.apiKey(System.getenv("MISTRAL_AI_API_KEY")) // Please use your own Mistral AI API key
.responseFormat(ResponseFormat.JSON)
.build();

String userMessage = "Return JSON with two fields: transactionId and status with the values T123 and paid.";
String json = model.chat(userMessage);

System.out.println(json); // {"transactionId":"T123","status":"paid"}

流式示例:

StreamingChatModel streamingModel = MistralAiStreamingChatModel.builder()
.apiKey(System.getenv("MISTRAL_AI_API_KEY")) // Please use your own Mistral AI API key
.responseFormat(MistralAiResponseFormatType.JSON_OBJECT)
.build();

String userMessage = "Return JSON with two fields: transactionId and status with the values T123 and paid.";

CompletableFuture<ChatResponse> futureResponse = new CompletableFuture<>();

streamingModel.chat(userMessage, new StreamingChatResponseHandler() {

@Override
public void onPartialResponse(String partialResponse) {
System.out.print(partialResponse);
}

@Override
public void onCompleteResponse(ChatResponse completeResponse) {
futureResponse.complete(completeResponse);
}

@Override
public void onError(Throwable error) {
futureResponse.completeExceptionally(error);
}
});

String json = futureResponse.get().content().text();

System.out.println(json); // {"transactionId":"T123","status":"paid"}

结构化输出

结构化输出确保模型的响应遵循 JSON schema。

备注

在 LangChain4j 中使用结构化输出的文档见 此处,下方章节包含 MistralAI 特有信息。

如需要,可为模型配置默认 JSON Schema,在请求未提供 schema 时作为回退使用。

ChatModel model = MistralAiChatModel.builder()
.apiKey(System.getenv("MISTRAL_AI_API_KEY"))
.modelName(MISTRAL_SMALL_LATEST)
.supportedCapabilities(Set.of(Capability.RESPONSE_FORMAT_JSON_SCHEMA)) // Enable structured outputs
.responseFormat(ResponseFormat.builder() // Set the fallback JSON Schema (optional)
.type(ResponseFormatType.JSON)
.jsonSchema(JsonSchema.builder().rootElement(JsonObjectSchema.builder()
.addProperty("name", JsonStringSchema.builder().build())
.addProperty("capital", JsonStringSchema.builder().build())
.addProperty(
"languages",
JsonArraySchema.builder()
.items(JsonStringSchema.builder().build())
.build())
.required("name", "capital", "languages")
.build())
.build())
.build())
.strictJsonSchema(true)
.build();

护栏(Guardrailing)

护栏是一种限制模型行为的方式,以防止其生成有害或不需要的内容。您可以在 MistralAiChatModel 构建器或 MistralAiStreamingChatModel 构建器中可选设置 safePrompt 参数。

同步示例:

ChatModel model = MistralAiChatModel.builder()
.apiKey(System.getenv("MISTRAL_AI_API_KEY"))
.safePrompt(true)
.build();

String userMessage = "What is the best French cheese?";
String response = model.chat(userMessage);

流式示例:

StreamingChatModel streamingModel = MistralAiStreamingChatModel.builder()
.apiKey(System.getenv("MISTRAL_AI_API_KEY"))
.safePrompt(true)
.build();

String userMessage = "What is the best French cheese?";

CompletableFuture<ChatResponse> futureResponse = new CompletableFuture<>();

streamingModel.chat(userMessage, new StreamingChatResponseHandler() {

@Override
public void onPartialResponse(String partialResponse) {
System.out.print(partialResponse);
}

@Override
public void onCompleteResponse(ChatResponse completeResponse) {
futureResponse.complete(completeResponse);
}

@Override
public void onError(Throwable error) {
futureResponse.completeExceptionally(error);
}
});

futureResponse.join();

启用 safe prompt 会在您的消息前添加以下 @SystemMessage

Always assist with care, respect, and truth. Respond with utmost utility yet securely. Avoid harmful, unethical, prejudiced, or negative content. Ensure replies promote fairness and positivity.

按请求参数

Mistral 特有选项(safePromptrandomSeedsendThinkingreturnThinking)也可通过 MistralAiChatRequestParameters 按请求设置,从而覆盖模型构建器上配置的值。 这使单个共享模型实例可以在各次调用间改变这些选项——例如,对一次请求启用 safePrompt 而对另一次不启用,或设置 randomSeed 以获得可复现的补全,而无需 构建第二个模型:

ChatModel model = MistralAiChatModel.builder()
.apiKey(System.getenv("MISTRAL_AI_API_KEY"))
.modelName("mistral-small-latest")
.build();

MistralAiChatRequestParameters parameters = MistralAiChatRequestParameters.builder()
.safePrompt(true)
.randomSeed(42)
.build();

ChatRequest chatRequest = ChatRequest.builder()
.messages(UserMessage.from("What is the best French cheese?"))
.parameters(parameters)
.build();

ChatResponse chatResponse = model.chat(chatRequest);

思考 / 推理

MistralAiChatModelMistralAiStreamingChatModel 都支持 使用 Magistral 推理模型 进行推理。

通过以下参数配置:

  • returnThinking:启用后,模型产生的推理文本将从 API 响应中解析, 并存储在 AiMessage.thinking() 中。对于流式,还会调用 StreamingChatResponseHandler.onPartialThinking()TokenStream.onPartialThinking() 回调。 默认禁用。
  • sendThinking:启用后,先前响应中的推理文本(存储在 AiMessage.thinking() 中) 将包含在发给 LLM 的后续请求中。 默认禁用。

以下是配置推理的示例:

ChatModel model = MistralAiChatModel.builder()
.apiKey(System.getenv("MISTRAL_AI_API_KEY"))
.modelName(MistralAiChatModelName.MAGISTRAL_MEDIUM_LATEST)
.returnThinking(true)
.sendThinking(true)
.build();

内容审核

这是一个可用于检测文本中有害内容的分类模型。

内容审核示例:

ModerationModel model = new MistralAiModerationModel.Builder()
.apiKey(System.getenv("MISTRAL_AI_API_KEY"))
.modelName(MistralAiModerationModelName.MISTRAL_MODERATION_LATEST)
.logRequests(true)
.logResponses(false)
.build();
// I want to check if the text contains harmful content
Moderation moderation = model.moderate("I want to kill them.").content();

代码补全

Fill-in-the-Middle(FIM)模型允许您生成代码补全,用户可使用 prompt 定义代码起点,使用可选的 suffix 和可选的 stop 定义代码终点。

FIM 同步

与聊天补全类似,FIM 端点同样可用。您可以通过添加以下代码进行测试。

import dev.langchain4j.model.mistralai.MistralAiFimModel;
import dev.langchain4j.model.output.Response;

public class HelloWorld {
public static void main(String[] args) {
MistralAiFimModel codestral = MistralAiFimModel.builder()
.apiKey(System.getenv("MISTRAL_AI_API_KEY"))
.modelName(MistralAiFimModelName.CODESTRAL_LATEST)
.stop(List.of("}")) // must stop at the first occurrence of "}"
.build();

// I want to generate a code completion for a simple hello world program using MistralAI of LangChain4j framework.
String codePrompt = """
public static void main(String[] args) {
// Create a function to multiply two numbers
""";
String suffix = """
System.out.println(result);
}
""";

// Asking to Codestral model to complete the code with given prompt and suffix
Response<String> response = codestral.generate(prompt, suffix);

System.out.println(
String.format(
"%s%s%s",
prompt, // print code prompt (prefix)
response.content(), // print code filled-in-the-middle
suffix)); // print code suffix
}
}

运行程序将打印如下输出

public static void main(String[] args) {
// Create a function to multiply two numbers
int result = multiply(5, 3);
System.out.println(result);
}

FIM 流式

创建一个类并添加以下代码。

import dev.langchain4j.model.StreamingResponseHandler;
import dev.langchain4j.model.language.StreamingLanguageModel;
import dev.langchain4j.model.mistralai.MistralAiStreamingFimModel;
import dev.langchain4j.model.output.Response;

import java.util.concurrent.CompletableFuture;

public class HelloWorld {
public static void main(String[] args) {
StreamingLanguageModel codestralStream = MistralAiStreamingFimModel.builder()
.apiKey(ApiKeys.MISTRALAI_API_KEY)
.modelName(MistralAiFimModelName.CODESTRAL_LATEST)
.build();

// I want to generate a code completion for a simple hello world program.
String prompt = "public static void main(String[] args) {";

CompletableFuture<Response<String>> futureResponse = new CompletableFuture<>();
codestral.generate(prompt, new StreamingResponseHandler() {
@Override
public void onNext(String token) {
System.out.print(token);
}

@Override
public void onComplete(Response<String> response) {
futureResponse.complete(response);
}

@Override
public void onError(Throwable error) {
futureResponse.completeExceptionally(error);
}
});

futureResponse.join();
}
}

您将在 onNext 方法中接收 LLM 生成的每一个文本块(token)。

您可以看到下方输出是实时流式返回的。

public static void main(String[] args) {

int[] arr = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
int sum = 0;

for (int i = 0; i < arr.length; i++) {
sum += arr[i];
}

System.out.println("Sum of all elements in the array: " + sum);
}
}

访问原始 HTTP 响应和 Server-Sent Events(SSE)

使用 MistralAiChatModel 时,您可以访问原始 HTTP 响应:

SuccessfulHttpResponse rawHttpResponse = ((MistralAiChatResponseMetadata) chatResponse.metadata()).rawHttpResponse();
System.out.println(rawHttpResponse.body());
System.out.println(rawHttpResponse.headers());
System.out.println(rawHttpResponse.statusCode());

使用 MistralAiStreamingChatModel 时,您可以访问原始 HTTP 响应(见上方)以及原始 Server-Sent Events:

List<ServerSentEvent> rawServerSentEvents = ((MistralAiChatResponseMetadata) chatResponse.metadata()).rawServerSentEvents();
System.out.println(rawServerSentEvents.get(0).data());
System.out.println(rawServerSentEvents.get(0).event());

批处理

MistralAiBatchChatModel 实现核心 BatchChatModel 接口,通过 Mistral Batch API 异步处理大量聊天请求,价格为标准按 token 计费的 50%。批次中的所有请求 都针对批处理模型上配置的单一模型运行。

提交批次,轮询直至达到终态,然后读取按请求的结果(保持 提交顺序):

MistralAiBatchChatModel batchModel = MistralAiBatchChatModel.builder()
.apiKey(System.getenv("MISTRAL_AI_API_KEY"))
.modelName("mistral-small-latest")
.build();

BatchResponse<ChatResponse> submitted = batchModel.submit(new BatchRequest<>(List.of(
ChatRequest.builder().messages(UserMessage.from("What is the capital of France?")).build(),
ChatRequest.builder().messages(UserMessage.from("What is the capital of Germany?")).build())));

String batchId = submitted.batchId();

// Poll until the batch reaches a terminal state (SUCCEEDED, FAILED, CANCELLED, EXPIRED).
BatchResponse<ChatResponse> batch = batchModel.retrieve(batchId);
while (!batch.state().isTerminal()) {
Thread.sleep(Duration.ofSeconds(30).toMillis());
batch = batchModel.retrieve(batchId);
}

for (BatchItemResult<ChatResponse> result : batch.results()) {
if (result.isSuccess()) {
System.out.println(result.response().aiMessage().text());
} else {
System.out.println("Failed: " + result.error().message());
}
}

可以取消正在运行的批次,也可以分页列出已有批次:

batchModel.cancel(batchId);

BatchPage<ChatResponse> page = batchModel.list(new BatchPagination(20, null));

示例