Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .speakeasy/gen.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@ typescript:
envVarPrefix: MISTRAL
flattenGlobalSecurity: true
flatteningOrder: body-first
generateExamples: true
imports:
option: openapi
paths:
Expand Down
7 changes: 6 additions & 1 deletion examples/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,11 +9,13 @@ Below is a guide how to run the examples if you have cloned this repo.
## How to run the examples locally

### Install the npm dependencies or the repository and the `examples` directory

```properties
npm install && npm install --prefix examples
```

### Set your environment variables

```properties
cp examples/.env.template examples/.env
# Edit your .env file
Expand All @@ -22,18 +24,21 @@ cp examples/.env.template examples/.env
### [Dev only] Link the local `mistralai` package

If you want to use the local `mistralai` package, you can link it to the examples directory. From the repository's root:

```properties
npm run build
npm link
(cd examples/src && npm link @mistralai/mistralai)
```

### Run the examples

```properties
npm run test --prefix examples
```

If you just want to run one example file, you can do so with:

```properties
npm run test --prefix examples -- --files src/stag_async_moderation.ts
```
```
17 changes: 16 additions & 1 deletion examples/package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

10 changes: 6 additions & 4 deletions examples/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,8 @@
"gcp": "npm run script -- ./src/gcp/async_chat_no_streaming.ts",
"azure": "npm run script -- ./src/azure/async_chat_no_streaming.ts",
"format": "prettier --write .",
"test": "tsx ./test.ts"
"test": "tsx ./test.ts",
"build:examples": "echo 'skipping build examples'"
},
"keywords": [],
"author": "",
Expand All @@ -22,9 +23,10 @@
"yargs": "^17.0.0"
},
"devDependencies": {
"glob": "^11.0.0",
"@types/node": "^20.11.4",
"glob": "^11.0.0",
"prettier": "3.3.3",
"tsx": "^4.7.0"
"tsx": "^4.7.0",
"typescript": "^5.9.2"
}
}
}
10 changes: 5 additions & 5 deletions examples/src/async_audio_transcription_stream.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,17 +2,17 @@ import { Mistral } from "@mistralai/mistralai";

const apiKey = process.env["MISTRAL_API_KEY"];
if (!apiKey) {
throw new Error("missing MISTRAL_API_KEY environment variable");
throw new Error("missing MISTRAL_API_KEY environment variable");
}

const mistral = new Mistral({ apiKey: apiKey });

const stream = await mistral.audio.transcriptions.stream({
model: "voxtral-mini-latest",
fileUrl: "https://docs.mistral.ai/audio/bcn_weather.mp3",
model: "voxtral-mini-latest",
fileUrl: "https://docs.mistral.ai/audio/bcn_weather.mp3",
});

for await (const event of stream) {
process.stdout.write(JSON.stringify(event));
process.stdout.write("\n");
process.stdout.write(JSON.stringify(event));
process.stdout.write("\n");
}
8 changes: 4 additions & 4 deletions examples/src/async_chat_prediction.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,12 +22,12 @@ const chatResponse = await client.chat.complete({
model: "codestral-latest",
messages: [
{ role: "user", content: refactorPrompt },
{ role: "user", content: code }
{ role: "user", content: code },
],
prediction: {
type: "content",
content: code
}
content: code,
},
});

console.log(chatResponse.choices[0].message.content);
console.log(chatResponse.choices[0]?.message.content);
4 changes: 2 additions & 2 deletions examples/src/async_files.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import * as fs from "fs";
import { Mistral } from "@mistralai/mistralai";
import path from 'path';
import path from "path";
import { fileURLToPath } from "url";

const apiKey = process.env["MISTRAL_API_KEY"];
Expand All @@ -19,7 +19,7 @@ const filePath = path.join(__dirname, "file.jsonl");
const blob = new Blob([fs.readFileSync(filePath)], {
type: "application/json",
});
const createdFile = await client.files.upload({ file: blob, });
const createdFile = await client.files.upload({ file: blob });

console.log(createdFile);

Expand Down
3 changes: 1 addition & 2 deletions examples/src/async_function_calling_streaming.ts
Original file line number Diff line number Diff line change
Expand Up @@ -131,7 +131,6 @@ stream = await client.chat.stream({
let full_tool_call: ToolCall[] = [];

for await (const event of stream) {

const toolCalls = event.data?.choices[0]?.delta.toolCalls;
if (!toolCalls) {
continue;
Expand Down Expand Up @@ -177,4 +176,4 @@ for await (const event of stream) {

process.stdout.write(content);
}
console.log("\ndone")
console.log("\ndone");
6 changes: 4 additions & 2 deletions examples/src/async_jobs.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import * as fs from "fs";
import { Mistral } from "@mistralai/mistralai";
import path from 'path';
import path from "path";
import { fileURLToPath } from "url";

const apiKey = process.env["MISTRAL_API_KEY"];
Expand Down Expand Up @@ -39,7 +39,9 @@ const jobs = await mistral.fineTuning.jobs.list();
console.log(jobs);

// Retrieve a job
const retrievedJob = await mistral.fineTuning.jobs.get({ jobId: createdJob.id });
const retrievedJob = await mistral.fineTuning.jobs.get({
jobId: createdJob.id,
});
console.log(retrievedJob);

// Cancel a job
Expand Down
33 changes: 16 additions & 17 deletions examples/src/async_ocr_process_from_file.ts
Original file line number Diff line number Diff line change
@@ -1,34 +1,33 @@
import { Mistral } from '@mistralai/mistralai';
import fs from 'fs';
import path from 'path';
import { Mistral } from "@mistralai/mistralai";
import fs from "fs";
import path from "path";
import { fileURLToPath } from "url";

const apiKey = process.env.MISTRAL_API_KEY;

const client = new Mistral({ apiKey: apiKey });


// Get the absolute directory path
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const filePath = path.join(__dirname, "ocr.pdf")
const filePath = path.join(__dirname, "ocr.pdf");

// Upload the file and run ocr
const uploaded_file = fs.readFileSync(filePath);
const uploaded_pdf = await client.files.upload({
file: {
fileName: "uploaded_file.pdf",
content: uploaded_file,
},
purpose: "ocr"
file: {
fileName: "uploaded_file.pdf",
content: uploaded_file,
},
purpose: "ocr",
});

const ocrResponse = await client.ocr.process({
model: "mistral-ocr-latest",
document: {
type: "file",
fileId: uploaded_pdf.id
},
includeImageBase64: true
model: "mistral-ocr-latest",
document: {
type: "file",
fileId: uploaded_pdf.id,
},
includeImageBase64: true,
});
console.log("OCR ", ocrResponse);
console.log("OCR ", ocrResponse);
16 changes: 8 additions & 8 deletions examples/src/async_ocr_process_from_url.ts
Original file line number Diff line number Diff line change
@@ -1,15 +1,15 @@
import { Mistral } from '@mistralai/mistralai';
import { Mistral } from "@mistralai/mistralai";

const apiKey = process.env.MISTRAL_API_KEY;
const client = new Mistral({ apiKey: apiKey });

const ocrResponse = await client.ocr.process({
model: "mistral-ocr-latest",
document: {
type: "document_url",
documentUrl: "https://arxiv.org/pdf/2201.04234.pdf"
},
includeImageBase64: true
model: "mistral-ocr-latest",
document: {
type: "document_url",
documentUrl: "https://arxiv.org/pdf/2201.04234.pdf",
},
includeImageBase64: true,
});

console.log("OCR:", ocrResponse);
console.log("OCR:", ocrResponse);
38 changes: 24 additions & 14 deletions examples/src/async_structured_outputs.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,14 +7,14 @@ if (!apiKey) {
}

const Explanation = z.object({
explanation: z.string(),
output: z.string(),
});
explanation: z.string(),
output: z.string(),
});

const MathDemonstration = z.object({
steps: z.array(Explanation),
final_answer: z.string(),
});
steps: z.array(Explanation),
final_answer: z.string(),
});

const client = new Mistral({ apiKey: apiKey });

Expand All @@ -25,13 +25,17 @@ const client = new Mistral({ apiKey: apiKey });
const stream = await client.chat.parseStream({
model: "mistral-tiny-latest",
messages: [
{ role: "system", content: "You are a helpful math tutor. You will be provided with a math problem, and your goal will be to output a step by step solution, along with a final answer. For each step, just provide the output as an equation use the explanation field to detail the reasoning." },
{ role: "user", content: "How can I solve 8x + 7 = -23" }
{
role: "system",
content:
"You are a helpful math tutor. You will be provided with a math problem, and your goal will be to output a step by step solution, along with a final answer. For each step, just provide the output as an equation use the explanation field to detail the reasoning.",
},
{ role: "user", content: "How can I solve 8x + 7 = -23" },
],
responseFormat: MathDemonstration,
});

let accumulatedStream = '';
let accumulatedStream = "";
for await (const event of stream) {
const content = event.data?.choices[0]?.delta.content;
if (!content) {
Expand All @@ -42,19 +46,25 @@ for await (const event of stream) {
}

// Parse the accumulated stream back to the initial zod object.
let parsedAccumulatedStream = MathDemonstration.safeParse(JSON.parse(accumulatedStream)).data;
console.log('\n', parsedAccumulatedStream);
let parsedAccumulatedStream = MathDemonstration.safeParse(
JSON.parse(accumulatedStream),
).data;
console.log("\n", parsedAccumulatedStream);

// Structured Output using the parse method
// This method will return the response parsed back to the initial Zod object.

const chatResponse = await client.chat.parse({
model: "mistral-tiny-latest",
messages: [
{ role: "system", content: "You are a helpful math tutor. You will be provided with a math problem, and your goal will be to output a step by step solution, along with a final answer. For each step, just provide the output as an equation use the explanation field to detail the reasoning." },
{ role: "user", content: "How can I solve 8x + 7 = -23" }
{
role: "system",
content:
"You are a helpful math tutor. You will be provided with a math problem, and your goal will be to output a step by step solution, along with a final answer. For each step, just provide the output as an equation use the explanation field to detail the reasoning.",
},
{ role: "user", content: "How can I solve 8x + 7 = -23" },
],
responseFormat: MathDemonstration,
});

console.log('\n', chatResponse.choices[0].message.parsed);
console.log("\n", chatResponse.choices[0].message.parsed);
48 changes: 24 additions & 24 deletions examples/src/error_handling.ts
Original file line number Diff line number Diff line change
@@ -1,31 +1,31 @@
import {Mistral} from "@mistralai/mistralai";
import {SDKError} from "../../models/errors/index.js";
import { Mistral } from "@mistralai/mistralai";
import { SDKError } from "../../models/errors/index.js";

const apiKey = process.env["MISTRAL_API_KEY"];
if (!apiKey) {
throw new Error("missing MISTRAL_API_KEY environment variable");
throw new Error("missing MISTRAL_API_KEY environment variable");
}

const client = new Mistral({apiKey: apiKey});
const client = new Mistral({ apiKey: apiKey });

try{
const chatResponse = await client.chat.complete({
model: "pixtral-12b",
messages: [
{
role: "user",
content: "hello"
},
{
role: "assistant",
content: "hey"
}
],
});
} catch (e){
if (e instanceof SDKError) {
process.stdout.write(e.message)
} else {
throw e
}
try {
const chatResponse = await client.chat.complete({
model: "pixtral-12b",
messages: [
{
role: "user",
content: "hello",
},
{
role: "assistant",
content: "hey",
},
],
});
} catch (e) {
if (e instanceof SDKError) {
process.stdout.write(e.message);
} else {
throw e;
}
}
Loading