|
| 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