Skip to main content

MistralAI

MistralAI Documentation

Project setup

To install langchain4j to your project, add the following dependency:

For Maven project pom.xml


<dependency>
<groupId>dev.langchain4j</groupId>
<artifactId>langchain4j</artifactId>
<version>{your-version}</version> <!-- Specify your version here -->
</dependency>

<dependency>
<groupId>dev.langchain4j</groupId>
<artifactId>langchain4j-mistral-ai</artifactId>
<version>{your-version}</version>
</dependency>

For Gradle project build.gradle

implementation 'dev.langchain4j:langchain4j:{your-version}'
implementation 'dev.langchain4j:langchain4j-mistral-ai:{your-version}'

API Key setup

Add your MistralAI API key to your project, you can create a class ApiKeys.java with the following code

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

Don't forget set your API key as an environment variable.

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

More details on how to get your MistralAI API key can be found here

Model Selection

You can use MistralAiChatModelName.class enum class to found appropriate model names for your use case. MistralAI updated a new selection and classification of models according to performance and cost trade-offs.

Here a list of available models:

  • open-mistral-7b (aka mistral-tiny-2312)
  • open-mixtral-8x7b (aka mistral-small-2312)
  • mistral-small-latest (aka mistral-small-2402)
  • mistral-medium-latest (aka mistral-medium-2312)
  • mistral-large-latest (aka mistral-large-2402)
  • mistral-tiny (@Deprecated)
  • mistral-small (@Deprecated)
  • mistral-medium (@Deprecated)

You can find more detail and types of use cases with their respective Mistral model here

Chat Completion

The chat models allow you to generate human-like responses with a model fined-tuned on conversational data.

Synchronous

Create a class and add the following code.

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

public class HelloWorld {
public static void main(String[] args) {
ChatLanguageModel model = MistralAiChatModel
.withApiKey(ApiKeys.MISTRALAI_API_KEY);

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

Running the program will generate a variant of the following output

Hello World! How can I assist you today?

Streaming

Create a class and add the following code.

import dev.langchain4j.data.message.AiMessage;
import dev.langchain4j.model.StreamingResponseHandler;
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
.withApiKey(ApiKeys.MISTRALAI_API_KEY);

CompletableFuture<Response<AiMessage>> futureResponse = new CompletableFuture<>();
model.generate("Tell me a joke about Java", new StreamingResponseHandler() {
@Override
public void onNext(String token) {
System.out.print(token);
}

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

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

futureResponse.join();
}
}

You will receive each chunk of text (token) as it is generated by the LLM on the onNext method.

You can see that output below is streamed in real-time.

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

Of course, you can combine MistralAI chat completion with other features like Set Model Parameters and Chat Memory to get more accurate responses.

In Chat Memory you will learn how to pass along your chat history, so the LLM knows what has been said before. If you don't pass the chat history, like in this simple example, the LLM will not know what has been said before, so it won't be able to correctly answer the second question ('What did I just ask?').

A lot of parameters are set behind the scenes, such as timeout, model type and model parameters. In Set Model Parameters you will learn how to set these parameters explicitly.

Function Calling

Function calling allows Mistral chat models (synchronous and streaming) to connect to external tools. For example, you can call a Tool to get the payment transaction status as shown in the Mistral AI function calling tutorial.

1. Define a Tool class and how get the payment data

Let's assume you have a dataset of payment transaction like this. In real applications you should inject a database source or REST API client to get the data.

import java.util.*;

public class PaymentTransactionTool {

private final Map<String, List<String>> paymentData = Map.of(
"transaction_id", Arrays.asList("T1001", "T1002", "T1003", "T1004", "T1005"),
"customer_id", Arrays.asList("C001", "C002", "C003", "C002", "C001"),
"payment_amount", Arrays.asList("125.50", "89.99", "120.00", "54.30", "210.20"),
"payment_date", Arrays.asList("2021-10-05", "2021-10-06", "2021-10-07", "2021-10-05", "2021-10-08"),
"payment_status", Arrays.asList("Paid", "Unpaid", "Paid", "Paid", "Pending"));

...
}

Next, let's define two methods retrievePaymentStatus and retrievePaymentDate to get the payment status and payment date from the Tool class.

// 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";
}
}

It uses a @Tool annotation to define the function description and @P annotation to define the parameter description of the package dev.langchain4j.agent.tool.*.

2. Define an interface as an agent to send chat messages.

Create an interface 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. Define a main application class to chat with the MistralAI chat model

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

public class PaymentDataAssistantApp {

ChatLanguageModel mistralAiModel = MistralAiChatModel.builder()
.apiKey(System.getenv("MISTRAL_AI_API_KEY")) // Please use your own Mistral AI API key
.modelName(MistralAiChatModelName.MISTRAL_LARGE_LATEST)
.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)
.chatLanguageModel(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);
}
}

and expect an answer like this:

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

More examples

If you want to check more MistralAI examples, you can find them in the langchain4j-examples/mistral-ai-examples project.