Skip to main content

MistralAI

This notebook covers how to get started with MistralAI chat models, via their API.

A valid API key is needed to communicate with the API.

Head to the API reference for detailed documentation of all attributes and methods.

Setup

You will need the langchain-core and langchain-mistralai package to use the API. You can install these with:

pip install -U langchain-core langchain-mistralai

We'll also need to get a [Mistral API key](https://console.mistral.ai/users/api-keys/)


```python
import getpass

api_key = getpass.getpass()

Usage

from langchain_core.messages import HumanMessage
from langchain_mistralai.chat_models import ChatMistralAI
# If api_key is not passed, default behavior is to use the `MISTRAL_API_KEY` environment variable.
chat = ChatMistralAI(api_key=api_key)
messages = [HumanMessage(content="knock knock")]
chat.invoke(messages)
AIMessage(content="Who's there? I was just about to ask the same thing! How can I assist you today?")

Async

await chat.ainvoke(messages)
AIMessage(content='Who\'s there?\n\n(You can then continue the "knock knock" joke by saying the name of the person or character who should be responding. For example, if I say "Banana," you could respond with "Banana who?" and I would say "Banana bunch! Get it? Because a group of bananas is called a \'bunch\'!" and then we would both laugh and have a great time. But really, you can put anything you want in the spot where I put "Banana" and it will still technically be a "knock knock" joke. The possibilities are endless!)')

Streaming

for chunk in chat.stream(messages):
print(chunk.content, end="")
Who's there?

(After this, the conversation can continue as a call and response "who's there" joke. Here is an example of how it could go:

You say: Orange.
I say: Orange who?
You say: Orange you glad I didn't say banana!?)

But since you asked for a knock knock joke specifically, here's one for you:

Knock knock.

Me: Who's there?

You: Lettuce.

Me: Lettuce who?

You: Lettuce in, it's too cold out here!

I hope this brings a smile to your face! Do you have a favorite knock knock joke you'd like to share? I'd love to hear it.

Batch

chat.batch([messages])
[AIMessage(content="Who's there? I was just about to ask the same thing! Go ahead and tell me who's there. I love a good knock-knock joke.")]

Chaining

You can also easily combine with a prompt template for easy structuring of user input. We can do this using LCEL

from langchain_core.prompts import ChatPromptTemplate

prompt = ChatPromptTemplate.from_template("Tell me a joke about {topic}")
chain = prompt | chat

API Reference:

chain.invoke({"topic": "bears"})
AIMessage(content='Why do bears hate shoes so much? They like to run around in their bear feet.')

Was this page helpful?


You can leave detailed feedback on GitHub.