Skip to content

Commit a70af2e

Browse files
committed
fix: add mistralé
1 parent 4983785 commit a70af2e

3 files changed

Lines changed: 157 additions & 0 deletions

File tree

copyme-ai/mistral/README.md

Lines changed: 84 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,84 @@
1+
# MistralRephraser
2+
3+
A simple Python class to rephrase sentences using the Mistral AI API. Perfect for generating dynamic feedback
4+
5+
## Quick Setup
6+
7+
1. **Add your API key** in a `.env` file at your project root:
8+
9+
```
10+
MISTRAL_API_KEY=your_mistral_api_key
11+
```
12+
13+
## Usage
14+
15+
### 1. Import and create the rephraser
16+
17+
```python
18+
from mistral import MistralRephraser
19+
20+
rephraser = MistralRephraser() # Uses key from .env
21+
# or
22+
# rephraser = MistralRephraser(api_key="your_mistral_api_key")
23+
```
24+
25+
### 2. Rephrase a sentence
26+
27+
```python
28+
sentence = "The cat is on the mat."
29+
instruction = "Rephrase this sentence in a more formal way."
30+
result = rephraser.rephrase(sentence, instruction)
31+
print(result)
32+
```
33+
or with json file
34+
35+
```python
36+
# Example usage:
37+
rephraser = MistralRephraser()
38+
feedback_json = {
39+
"phase": "shot_release",
40+
"corrections": [
41+
{"joint": "elbow", "correction": 20, "unit": "deg"},
42+
{"joint": "knee", "correction": -10, "unit": "deg"}
43+
]
44+
}
45+
instruction = "Rephrase this feedback in a motivating and clear way for the user."
46+
print(rephraser.rephrase(feedback_json, instruction))
47+
```
48+
49+
### 3. Change the model (optional)
50+
51+
```python
52+
rephraser.set_model("mistral-large-latest")
53+
```
54+
55+
### 4. Check if your API key is valid
56+
57+
```python
58+
if not rephraser.is_api_key_valid():
59+
print("Invalid API key!")
60+
```
61+
62+
## Example: FastAPI Endpoint
63+
64+
```python
65+
from fastapi import FastAPI, HTTPException
66+
from mistral import MistralRephraser
67+
68+
app = FastAPI()
69+
rephraser = MistralRephraser()
70+
71+
@app.post("/rephrase")
72+
def rephrase_endpoint(data: dict):
73+
sentence = data["sentence"]
74+
instruction = data["instruction"]
75+
try:
76+
result = rephraser.rephrase(sentence, instruction)
77+
return {"result": result}
78+
except Exception as e:
79+
raise HTTPException(status_code=500, detail=str(e))
80+
```
81+
82+
---
83+
84+
**Ressource:** [https://github.com/mistralai/client-python](https://github.com/mistralai/client-python)

copyme-ai/mistral/metadata.json

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
{
2+
"phase": "shot_release",
3+
"corrections": [
4+
{
5+
"joint": "elbow",
6+
"correction": 20,
7+
"unit": "deg"
8+
},
9+
{
10+
"joint": "knee",
11+
"correction": -10,
12+
"unit": "deg"
13+
}
14+
]
15+
}

copyme-ai/mistral/mistral.py

Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
1+
from mistralai import Mistral, models
2+
import os
3+
from dotenv import load_dotenv
4+
import json
5+
6+
load_dotenv()
7+
8+
class MistralRephraser:
9+
def __init__(self, api_key: str = None, model: str = "mistral-small-latest"):
10+
self.api_key = api_key or os.getenv("MISTRAL_API_KEY")
11+
if not self.api_key:
12+
raise ValueError("MISTRAL_API_KEY is not set. Please add it to your .env file.")
13+
self.model = model
14+
self.client = Mistral(api_key=self.api_key)
15+
16+
def rephrase(self, original_sentence, instruction: str) -> str:
17+
"""
18+
Rephrase a sentence or a JSON object according to the instruction.
19+
:param original_sentence: str or dict (JSON-like)
20+
:param instruction: str
21+
:return: str
22+
"""
23+
if isinstance(original_sentence, dict):
24+
original_sentence_str = json.dumps(original_sentence, ensure_ascii=False, indent=2)
25+
else:
26+
original_sentence_str = str(original_sentence)
27+
28+
messages = [
29+
{"role": "system", "content": instruction},
30+
{"role": "user", "content": original_sentence_str}
31+
]
32+
try:
33+
response = self.client.chat.complete(
34+
model=self.model,
35+
messages=messages
36+
)
37+
return response.choices[0].message.content.strip()
38+
except models.SDKError as e:
39+
raise RuntimeError(f"Mistral API error: {e.message}") from e
40+
except Exception as e:
41+
raise RuntimeError(f"Unexpected error: {str(e)}") from e
42+
43+
def set_model(self, model: str):
44+
"""
45+
Change the model used (e.g., 'mistral-large-latest').
46+
"""
47+
self.model = model
48+
49+
def is_api_key_valid(self) -> bool:
50+
"""
51+
Check if the API key is valid (by listing the models).
52+
"""
53+
try:
54+
self.client.models.list()
55+
return True
56+
except Exception:
57+
return False
58+

0 commit comments

Comments
 (0)