Skip to content

Commit 2cc095e

Browse files
committed
fix(mistral): handle breaking import change in mistralai v2.0.0
1 parent e3105a4 commit 2cc095e

2 files changed

Lines changed: 58 additions & 1 deletion

File tree

instructor/providers/mistral/client.py

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,10 @@
22
from __future__ import annotations
33

44

5-
from mistralai import Mistral
5+
try:
6+
from mistralai.client import Mistral # New v2 path
7+
except ImportError:
8+
from mistralai import Mistral # Old v1 path
69
import instructor
710
from typing import overload, Any, Literal
811

Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
import os
2+
import pytest
3+
from pydantic import BaseModel
4+
import instructor
5+
6+
try:
7+
# mistralai v2.0.0+
8+
from mistralai.client import Mistral
9+
except ImportError:
10+
# mistralai v1.x
11+
from mistralai import Mistral
12+
13+
14+
class UserDetail(BaseModel):
15+
name: str
16+
age: int
17+
18+
19+
def test_mistral_client_init():
20+
"""Test that we can initialize and patch the Mistral client successfully."""
21+
# We use a dummy API key for instantiation test if one isn't provided
22+
api_key = os.environ.get("MISTRAL_API_KEY", "dummy-key-for-test")
23+
24+
mistral_client = Mistral(api_key=api_key)
25+
26+
# We just want to ensure patching doesn't raise an exception
27+
# due to strict type checks returning False for Mistral v2.0 clients
28+
client = instructor.from_mistral(mistral_client)
29+
30+
assert client is not None
31+
assert hasattr(client, "chat")
32+
33+
34+
@pytest.mark.skipif(
35+
not os.environ.get("MISTRAL_API_KEY"), reason="MISTRAL_API_KEY must be set"
36+
)
37+
def test_mistral_extraction():
38+
"""Test a live extraction if the API key is provided."""
39+
mistral_client = Mistral(api_key=os.environ.get("MISTRAL_API_KEY"))
40+
client = instructor.from_mistral(mistral_client)
41+
42+
user = client.chat.completions.create(
43+
model="mistral-large-latest",
44+
response_model=UserDetail,
45+
messages=[
46+
{
47+
"role": "user",
48+
"content": "Kitan is a 18 year old engineer living in Alapere.",
49+
}
50+
],
51+
)
52+
53+
assert user.name == "Kitan"
54+
assert user.age == 18

0 commit comments

Comments
 (0)