Compare commits
27 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
7c96a4a88d | ||
|
|
14437bf609 | ||
|
|
3c228914f7 | ||
|
|
b69f7c617c | ||
|
|
75788b9395 | ||
|
|
a862b92c98 | ||
|
|
47c9b9b4fe | ||
|
|
791bef34b3 | ||
|
|
1dd59f6704 | ||
|
|
33876183e4 | ||
|
|
1deab88251 | ||
|
|
b0a3f10c9f | ||
|
|
bbba6b9878 | ||
|
|
0386b95b7b | ||
|
|
c61f2278bb | ||
|
|
4c8e330c95 | ||
|
|
64c7f2feb5 | ||
|
|
f44d951247 | ||
|
|
4e702aa48e | ||
|
|
809af31dd0 | ||
|
|
7016cffb05 | ||
|
|
43cf87529e | ||
|
|
7627a336cc | ||
|
|
4983f69cd5 | ||
|
|
814b9918b3 | ||
|
|
7de2b19b98 | ||
|
|
8cb2c3cd0c |
@@ -1,3 +1,3 @@
|
||||
# This key is only used for development purposes.
|
||||
# You'll only need one if you want to contribute to this library.
|
||||
MISTRAL_API_KEY=
|
||||
export MISTRAL_API_KEY=
|
||||
|
||||
2
.github/workflows/test.yml
vendored
2
.github/workflows/test.yml
vendored
@@ -22,7 +22,7 @@ jobs:
|
||||
env:
|
||||
MISTRAL_API_KEY: ${{ secrets.MISTRAL_API_KEY }}
|
||||
- name: Upload tests coverage
|
||||
uses: codecov/codecov-action@v3
|
||||
uses: codecov/codecov-action@v4
|
||||
with:
|
||||
fail_ci_if_error: true
|
||||
token: ${{ secrets.CODECOV_TOKEN }}
|
||||
|
||||
50
CHANGELOG.md
Normal file
50
CHANGELOG.md
Normal file
@@ -0,0 +1,50 @@
|
||||
## [0.5.0](https://github.com/ivangabriele/mistralai-client-rs/compare/v0.4.0...v) (2024-03-04)
|
||||
|
||||
|
||||
### Features
|
||||
|
||||
* add client.embeddings_async() method ([3c22891](https://github.com/ivangabriele/mistralai-client-rs/commit/3c228914f78b0edd4a592091265b88d0bc55568b))
|
||||
* add client.list_models_async() method ([b69f7c6](https://github.com/ivangabriele/mistralai-client-rs/commit/b69f7c617c15dd63abb61d004636512916d766bb))
|
||||
|
||||
## [0.4.0](https://github.com/ivangabriele/mistralai-client-rs/compare/v0.3.0...v) (2024-03-04)
|
||||
|
||||
|
||||
### ⚠ BREAKING CHANGES
|
||||
|
||||
* `Client::new()` now returns a `Result`.
|
||||
* `APIError` is renamed to `ApiError`.
|
||||
|
||||
### Features
|
||||
|
||||
* add client.chat_async() method ([1dd59f6](https://github.com/ivangabriele/mistralai-client-rs/commit/1dd59f67048c10458ab0382af8fdfe4ed21c82fa))
|
||||
* add missing api key error ([1deab88](https://github.com/ivangabriele/mistralai-client-rs/commit/1deab88251fc706e0415a5e416ab9aee4b52f6f3))
|
||||
* wrap Client::new() return in a Result ([3387618](https://github.com/ivangabriele/mistralai-client-rs/commit/33876183e41340f426aa1dd1b6d8b5c05c8e15b9))
|
||||
|
||||
## [0.3.0](https://github.com/ivangabriele/mistralai-client-rs/compare/v0.2.0...v) (2024-03-04)
|
||||
|
||||
|
||||
### ⚠ BREAKING CHANGES
|
||||
|
||||
* Models are now enforced by `Model` & `EmbedModel` enums.
|
||||
|
||||
### Features
|
||||
|
||||
* add client.embeddings() method ([f44d951](https://github.com/ivangabriele/mistralai-client-rs/commit/f44d95124767c3a3f14c78c4be3d9c203fac49ad))
|
||||
|
||||
## [0.2.0](https://github.com/ivangabriele/mistralai-client-rs/compare/v0.1.0...v) (2024-03-03)
|
||||
|
||||
|
||||
### ⚠ BREAKING CHANGES
|
||||
|
||||
* Chat completions must now be called directly from client.chat() without building a request in between.
|
||||
|
||||
### Features
|
||||
|
||||
* add client.list_models() method ([814b991](https://github.com/ivangabriele/mistralai-client-rs/commit/814b9918b3aca78bfd606b5b9bb470b70ea2a5c6))
|
||||
* simplify chat completion call ([7de2b19](https://github.com/ivangabriele/mistralai-client-rs/commit/7de2b19b981f1d65fe5c566fcaf521e4f2a9ced1))
|
||||
|
||||
## [0.1.0](https://github.com/ivangabriele/mistralai-client-rs/compare/7d3b438d16e9936591b6454525968c5c2cdfd6ad...v0.1.0) (2024-03-03)
|
||||
|
||||
### Features
|
||||
|
||||
- add chat completion without streaming ([7d3b438](https://github.com/ivangabriele/mistralai-client-rs/commit/7d3b438d16e9936591b6454525968c5c2cdfd6ad))
|
||||
@@ -27,8 +27,15 @@ Then run:
|
||||
git clone https://github.com/ivangabriele/mistralai-client-rs.git # or your fork
|
||||
cd ./mistralai-client-rs
|
||||
cargo build
|
||||
cp .env.example .env
|
||||
```
|
||||
|
||||
Then edit the `.env` file to set your `MISTRAL_API_KEY`.
|
||||
|
||||
> [!NOTE]
|
||||
> All tests use either the `open-mistral-7b` or `mistral-embed` models and only consume a few dozen tokens.
|
||||
> So you would have to run them thousands of times to even reach a single dollar of usage.
|
||||
|
||||
### Optional requirements
|
||||
|
||||
- [cargo-watch](https://github.com/watchexec/cargo-watch#install) for `make test-*-watch`.
|
||||
@@ -51,5 +58,4 @@ Help us keep this project open and inclusive. Please read and follow our [Code o
|
||||
|
||||
## Commit Message Format
|
||||
|
||||
This repository follow the [Conventional Commits](https://www.conventionalcommits.org/en/v1.0.0/) specification and
|
||||
specificaly the [Angular Commit Message Guidelines](https://github.com/angular/angular/blob/main/CONTRIBUTING.md#commit).
|
||||
This repository follow the [Conventional Commits](https://www.conventionalcommits.org/en/v1.0.0/) specification.
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
name = "mistralai-client"
|
||||
description = "Mistral AI API client library for Rust (unofficial)."
|
||||
license = "Apache-2.0"
|
||||
version = "0.1.0"
|
||||
version = "0.5.0"
|
||||
|
||||
edition = "2021"
|
||||
rust-version = "1.76.0"
|
||||
@@ -15,12 +15,11 @@ readme = "README.md"
|
||||
repository = "https://github.com/ivangabriele/mistralai-client-rs"
|
||||
|
||||
[dependencies]
|
||||
minreq = { version = "2.11.0", features = ["https-rustls", "json-using-serde"] }
|
||||
reqwest = { version = "0.11.24", features = ["json", "blocking"] }
|
||||
serde = { version = "1.0.197", features = ["derive"] }
|
||||
serde_json = "1.0.114"
|
||||
thiserror = "1.0.57"
|
||||
tokio = { version = "1.36.0", features = ["full"] }
|
||||
|
||||
[dev-dependencies]
|
||||
dotenv = "0.15.0"
|
||||
jrest = "0.2.3"
|
||||
|
||||
28
Makefile
28
Makefile
@@ -1,6 +1,28 @@
|
||||
SHELL := /bin/bash
|
||||
|
||||
.PHONY: test
|
||||
|
||||
define RELEASE_TEMPLATE
|
||||
conventional-changelog -p conventionalcommits -i ./CHANGELOG.md -s
|
||||
git add .
|
||||
git commit -m "docs(changelog): update"
|
||||
git push origin HEAD
|
||||
cargo release $(1) --execute
|
||||
git push origin HEAD --tags
|
||||
endef
|
||||
|
||||
release-patch:
|
||||
$(call RELEASE_TEMPLATE,patch)
|
||||
|
||||
release-minor:
|
||||
$(call RELEASE_TEMPLATE,minor)
|
||||
|
||||
release-major:
|
||||
$(call RELEASE_TEMPLATE,major)
|
||||
|
||||
test:
|
||||
cargo test --no-fail-fast
|
||||
@source ./.env && cargo test --all-targets --no-fail-fast
|
||||
test-cover:
|
||||
cargo tarpaulin --frozen --no-fail-fast --out Xml --skip-clean
|
||||
cargo tarpaulin --all-targets --frozen --no-fail-fast --out Xml --skip-clean
|
||||
test-watch:
|
||||
cargo watch -x "test -- --nocapture"
|
||||
cargo watch -x "test -- --all-targets --nocapture"
|
||||
|
||||
132
README.md
132
README.md
@@ -16,19 +16,26 @@ Rust client for the Mistral AI API.
|
||||
- [As a client argument](#as-a-client-argument)
|
||||
- [Usage](#usage)
|
||||
- [Chat without streaming](#chat-without-streaming)
|
||||
- [Chat without streaming (async)](#chat-without-streaming-async)
|
||||
- [Chat with streaming](#chat-with-streaming)
|
||||
- [Embeddings](#embeddings)
|
||||
- [Embeddings (async)](#embeddings-async)
|
||||
- [List models](#list-models)
|
||||
- [List models (async)](#list-models-async)
|
||||
|
||||
---
|
||||
|
||||
## Supported APIs
|
||||
|
||||
- [x] Chat without streaming
|
||||
- [x] Chat without streaming (async)
|
||||
- [ ] Chat with streaming
|
||||
- [ ] Embedding
|
||||
- [ ] List models
|
||||
- [x] Embedding
|
||||
- [x] Embedding (async)
|
||||
- [x] List models
|
||||
- [x] List models (async)
|
||||
- [ ] Function Calling
|
||||
- [ ] Function Calling (async)
|
||||
|
||||
## Installation
|
||||
|
||||
@@ -54,7 +61,7 @@ use mistralai_client::v1::client::Client;
|
||||
fn main() {
|
||||
let api_key = "your_api_key";
|
||||
|
||||
let client = Client::new(Some(api_key), None, None, None);
|
||||
let client = Client::new(Some(api_key), None, None, None).unwrap();
|
||||
}
|
||||
```
|
||||
|
||||
@@ -63,20 +70,17 @@ fn main() {
|
||||
### Chat without streaming
|
||||
|
||||
```rs
|
||||
use mistralai::v1::{
|
||||
chat_completion::{
|
||||
ChatCompletionMessage, ChatCompletionMessageRole, ChatCompletionRequest,
|
||||
ChatCompletionRequestOptions,
|
||||
},
|
||||
use mistralai_client::v1::{
|
||||
chat_completion::{ChatCompletionMessage, ChatCompletionMessageRole, ChatCompletionRequestOptions},
|
||||
client::Client,
|
||||
constants::OPEN_MISTRAL_7B,
|
||||
constants::Model,
|
||||
};
|
||||
|
||||
fn main() {
|
||||
// This example suppose you have set the `MISTRAL_API_KEY` environment variable.
|
||||
let client = Client::new(None, None, None, None);
|
||||
let client = Client::new(None, None, None, None).unwrap();
|
||||
|
||||
let model = OPEN_MISTRAL_7B.to_string();
|
||||
let model = Model::OpenMistral7b;
|
||||
let messages = vec![ChatCompletionMessage {
|
||||
role: ChatCompletionMessageRole::user,
|
||||
content: "Just guess the next word: \"Eiffel ...\"?".to_string(),
|
||||
@@ -87,8 +91,38 @@ fn main() {
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
let chat_completion_request = ChatCompletionRequest::new(model, messages, Some(options));
|
||||
let result = client.chat(chat_completion_request).unwrap();
|
||||
let result = client.chat(model, messages, Some(options)).unwrap();
|
||||
println!("Assistant: {}", result.choices[0].message.content);
|
||||
// => "Assistant: Tower. [...]"
|
||||
}
|
||||
```
|
||||
|
||||
### Chat without streaming (async)
|
||||
|
||||
```rs
|
||||
use mistralai_client::v1::{
|
||||
chat_completion::{ChatCompletionMessage, ChatCompletionMessageRole, ChatCompletionRequestOptions},
|
||||
client::Client,
|
||||
constants::Model,
|
||||
};
|
||||
|
||||
#[tokio::main]
|
||||
async fn main() {
|
||||
// This example suppose you have set the `MISTRAL_API_KEY` environment variable.
|
||||
let client = Client::new(None, None, None, None).unwrap();
|
||||
|
||||
let model = Model::OpenMistral7b;
|
||||
let messages = vec![ChatCompletionMessage {
|
||||
role: ChatCompletionMessageRole::user,
|
||||
content: "Just guess the next word: \"Eiffel ...\"?".to_string(),
|
||||
}];
|
||||
let options = ChatCompletionRequestOptions {
|
||||
temperature: Some(0.0),
|
||||
random_seed: Some(42),
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
let result = client.chat_async(model, messages, Some(options)).await.unwrap();
|
||||
println!("Assistant: {}", result.choices[0].message.content);
|
||||
// => "Assistant: Tower. [...]"
|
||||
}
|
||||
@@ -100,8 +134,76 @@ _In progress._
|
||||
|
||||
### Embeddings
|
||||
|
||||
_In progress._
|
||||
```rs
|
||||
use mistralai_client::v1::{client::Client, constants::EmbedModel};
|
||||
|
||||
fn main() {
|
||||
// This example suppose you have set the `MISTRAL_API_KEY` environment variable.
|
||||
let client: Client = Client::new(None, None, None, None).unwrap();
|
||||
|
||||
let model = EmbedModel::MistralEmbed;
|
||||
let input = vec!["Embed this sentence.", "As well as this one."]
|
||||
.iter()
|
||||
.map(|s| s.to_string())
|
||||
.collect();
|
||||
let options = None;
|
||||
|
||||
let response = client.embeddings(model, input, options).unwrap();
|
||||
println!("Embeddings: {:?}", response.data);
|
||||
// => "Embeddings: [{...}, {...}]"
|
||||
}
|
||||
```
|
||||
|
||||
### Embeddings (async)
|
||||
|
||||
```rs
|
||||
use mistralai_client::v1::{client::Client, constants::EmbedModel};
|
||||
|
||||
#[tokio::main]
|
||||
async fn main() {
|
||||
// This example suppose you have set the `MISTRAL_API_KEY` environment variable.
|
||||
let client: Client = Client::new(None, None, None, None).unwrap();
|
||||
|
||||
let model = EmbedModel::MistralEmbed;
|
||||
let input = vec!["Embed this sentence.", "As well as this one."]
|
||||
.iter()
|
||||
.map(|s| s.to_string())
|
||||
.collect();
|
||||
let options = None;
|
||||
|
||||
let response = client.embeddings_async(model, input, options).await.unwrap();
|
||||
println!("Embeddings: {:?}", response.data);
|
||||
// => "Embeddings: [{...}, {...}]"
|
||||
}
|
||||
```
|
||||
|
||||
### List models
|
||||
|
||||
_In progress._
|
||||
```rs
|
||||
use mistralai_client::v1::client::Client;
|
||||
|
||||
fn main() {
|
||||
// This example suppose you have set the `MISTRAL_API_KEY` environment variable.
|
||||
let client = Client::new(None, None, None, None).unwrap();
|
||||
|
||||
let result = client.list_models().unwrap();
|
||||
println!("First Model ID: {:?}", result.data[0].id);
|
||||
// => "First Model ID: open-mistral-7b"
|
||||
}
|
||||
```
|
||||
|
||||
### List models (async)
|
||||
|
||||
```rs
|
||||
use mistralai_client::v1::client::Client;
|
||||
|
||||
#[tokio::main]
|
||||
async fn main() {
|
||||
// This example suppose you have set the `MISTRAL_API_KEY` environment variable.
|
||||
let client = Client::new(None, None, None, None).await.unwrap();
|
||||
|
||||
let result = client.list_models_async().unwrap();
|
||||
println!("First Model ID: {:?}", result.data[0].id);
|
||||
// => "First Model ID: open-mistral-7b"
|
||||
}
|
||||
```
|
||||
|
||||
4
release.toml
Normal file
4
release.toml
Normal file
@@ -0,0 +1,4 @@
|
||||
# https://github.com/crate-ci/cargo-release/blob/master/docs/reference.md
|
||||
allow-branch = ["main"]
|
||||
pre-release-commit-message = "ci(release): v{{version}}"
|
||||
pre-release-replacements = [{ file = "CHANGELOG.md", search = "## \\[\\]", replace = "## [{{version}}]" }]
|
||||
@@ -1,9 +1,9 @@
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use crate::v1::common;
|
||||
use crate::v1::{common, constants};
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct ChatCompletionRequestOptions {
|
||||
pub struct ChatCompletionParams {
|
||||
pub tools: Option<String>,
|
||||
pub temperature: Option<f32>,
|
||||
pub max_tokens: Option<u32>,
|
||||
@@ -12,7 +12,7 @@ pub struct ChatCompletionRequestOptions {
|
||||
pub stream: Option<bool>,
|
||||
pub safe_prompt: Option<bool>,
|
||||
}
|
||||
impl Default for ChatCompletionRequestOptions {
|
||||
impl Default for ChatCompletionParams {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
tools: None,
|
||||
@@ -29,7 +29,7 @@ impl Default for ChatCompletionRequestOptions {
|
||||
#[derive(Debug, Serialize, Deserialize)]
|
||||
pub struct ChatCompletionRequest {
|
||||
pub messages: Vec<ChatCompletionMessage>,
|
||||
pub model: String,
|
||||
pub model: constants::Model,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub tools: Option<String>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
@@ -44,18 +44,18 @@ pub struct ChatCompletionRequest {
|
||||
pub stream: Option<bool>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub safe_prompt: Option<bool>,
|
||||
// TODO Check that prop (seen in official Python client but not in API doc).
|
||||
// TODO Check this prop (seen in official Python client but not in API doc).
|
||||
// pub tool_choice: Option<String>,
|
||||
// TODO Check that prop (seen in official Python client but not in API doc).
|
||||
// TODO Check this prop (seen in official Python client but not in API doc).
|
||||
// pub response_format: Option<String>,
|
||||
}
|
||||
impl ChatCompletionRequest {
|
||||
pub fn new(
|
||||
model: String,
|
||||
model: constants::Model,
|
||||
messages: Vec<ChatCompletionMessage>,
|
||||
options: Option<ChatCompletionRequestOptions>,
|
||||
options: Option<ChatCompletionParams>,
|
||||
) -> Self {
|
||||
let ChatCompletionRequestOptions {
|
||||
let ChatCompletionParams {
|
||||
tools,
|
||||
temperature,
|
||||
max_tokens,
|
||||
@@ -85,7 +85,7 @@ pub struct ChatCompletionResponse {
|
||||
pub object: String,
|
||||
/// Unix timestamp (in seconds).
|
||||
pub created: u32,
|
||||
pub model: String,
|
||||
pub model: constants::Model,
|
||||
pub choices: Vec<ChatCompletionChoice>,
|
||||
pub usage: common::ResponseUsage,
|
||||
}
|
||||
@@ -95,7 +95,7 @@ pub struct ChatCompletionChoice {
|
||||
pub index: u32,
|
||||
pub message: ChatCompletionMessage,
|
||||
pub finish_reason: String,
|
||||
// TODO Check that prop (seen in API responses but undocumented).
|
||||
// TODO Check this prop (seen in API responses but undocumented).
|
||||
// pub logprobs: ???
|
||||
}
|
||||
|
||||
|
||||
308
src/v1/client.rs
308
src/v1/client.rs
@@ -1,9 +1,14 @@
|
||||
use crate::v1::error::APIError;
|
||||
use minreq::Response;
|
||||
use crate::v1::error::ApiError;
|
||||
use reqwest::Error as ReqwestError;
|
||||
|
||||
use crate::v1::{
|
||||
chat_completion::{ChatCompletionRequest, ChatCompletionResponse},
|
||||
constants::API_URL_BASE,
|
||||
chat_completion::{
|
||||
ChatCompletionMessage, ChatCompletionParams, ChatCompletionRequest, ChatCompletionResponse,
|
||||
},
|
||||
constants::{EmbedModel, Model, API_URL_BASE},
|
||||
embedding::{EmbeddingRequest, EmbeddingRequestOptions, EmbeddingResponse},
|
||||
error::ClientError,
|
||||
model_list::ModelListResponse,
|
||||
};
|
||||
|
||||
pub struct Client {
|
||||
@@ -19,157 +24,248 @@ impl Client {
|
||||
endpoint: Option<String>,
|
||||
max_retries: Option<u32>,
|
||||
timeout: Option<u32>,
|
||||
) -> Self {
|
||||
let api_key = api_key.unwrap_or(std::env::var("MISTRAL_API_KEY").unwrap());
|
||||
) -> Result<Self, ClientError> {
|
||||
let api_key = api_key.unwrap_or(match std::env::var("MISTRAL_API_KEY") {
|
||||
Ok(api_key_from_env) => api_key_from_env,
|
||||
Err(_) => return Err(ClientError::ApiKeyError),
|
||||
});
|
||||
let endpoint = endpoint.unwrap_or(API_URL_BASE.to_string());
|
||||
let max_retries = max_retries.unwrap_or(5);
|
||||
let timeout = timeout.unwrap_or(120);
|
||||
|
||||
Self {
|
||||
Ok(Self {
|
||||
api_key,
|
||||
endpoint,
|
||||
max_retries,
|
||||
timeout,
|
||||
})
|
||||
}
|
||||
|
||||
pub fn chat(
|
||||
&self,
|
||||
model: Model,
|
||||
messages: Vec<ChatCompletionMessage>,
|
||||
options: Option<ChatCompletionParams>,
|
||||
) -> Result<ChatCompletionResponse, ApiError> {
|
||||
let request = ChatCompletionRequest::new(model, messages, options);
|
||||
|
||||
let response = self.post_sync("/chat/completions", &request)?;
|
||||
let result = response.json::<ChatCompletionResponse>();
|
||||
match result {
|
||||
Ok(response) => Ok(response),
|
||||
Err(error) => Err(self.to_api_error(error)),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn build_request(&self, request: minreq::Request) -> minreq::Request {
|
||||
let authorization = format!("Bearer {}", self.api_key);
|
||||
pub async fn chat_async(
|
||||
&self,
|
||||
model: Model,
|
||||
messages: Vec<ChatCompletionMessage>,
|
||||
options: Option<ChatCompletionParams>,
|
||||
) -> Result<ChatCompletionResponse, ApiError> {
|
||||
let request = ChatCompletionRequest::new(model, messages, options);
|
||||
|
||||
let response = self.post_async("/chat/completions", &request).await?;
|
||||
let result = response.json::<ChatCompletionResponse>().await;
|
||||
match result {
|
||||
Ok(response) => Ok(response),
|
||||
Err(error) => Err(self.to_api_error(error)),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn embeddings(
|
||||
&self,
|
||||
model: EmbedModel,
|
||||
input: Vec<String>,
|
||||
options: Option<EmbeddingRequestOptions>,
|
||||
) -> Result<EmbeddingResponse, ApiError> {
|
||||
let request = EmbeddingRequest::new(model, input, options);
|
||||
|
||||
let response = self.post_sync("/embeddings", &request)?;
|
||||
let result = response.json::<EmbeddingResponse>();
|
||||
match result {
|
||||
Ok(response) => Ok(response),
|
||||
Err(error) => Err(self.to_api_error(error)),
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn embeddings_async(
|
||||
&self,
|
||||
model: EmbedModel,
|
||||
input: Vec<String>,
|
||||
options: Option<EmbeddingRequestOptions>,
|
||||
) -> Result<EmbeddingResponse, ApiError> {
|
||||
let request = EmbeddingRequest::new(model, input, options);
|
||||
|
||||
let response = self.post_async("/embeddings", &request).await?;
|
||||
let result = response.json::<EmbeddingResponse>().await;
|
||||
match result {
|
||||
Ok(response) => Ok(response),
|
||||
Err(error) => Err(self.to_api_error(error)),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn list_models(&self) -> Result<ModelListResponse, ApiError> {
|
||||
let response = self.get_sync("/models")?;
|
||||
let result = response.json::<ModelListResponse>();
|
||||
match result {
|
||||
Ok(response) => Ok(response),
|
||||
Err(error) => Err(self.to_api_error(error)),
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn list_models_async(&self) -> Result<ModelListResponse, ApiError> {
|
||||
let response = self.get_async("/models").await?;
|
||||
let result = response.json::<ModelListResponse>().await;
|
||||
match result {
|
||||
Ok(response) => Ok(response),
|
||||
Err(error) => Err(self.to_api_error(error)),
|
||||
}
|
||||
}
|
||||
|
||||
fn build_request_sync(
|
||||
&self,
|
||||
request: reqwest::blocking::RequestBuilder,
|
||||
) -> reqwest::blocking::RequestBuilder {
|
||||
let user_agent = format!(
|
||||
"ivangabriele/mistral-client-rs/{}",
|
||||
"ivangabriele/mistralai-client-rs/{}",
|
||||
env!("CARGO_PKG_VERSION")
|
||||
);
|
||||
|
||||
let request = request
|
||||
.with_header("Authorization", authorization)
|
||||
.with_header("Accept", "application/json")
|
||||
.with_header("Content-Type", "application/json")
|
||||
.with_header("User-Agent", user_agent);
|
||||
let request_builder = request
|
||||
.bearer_auth(&self.api_key)
|
||||
.header("Accept", "application/json")
|
||||
.header("Content-Type", "application/json")
|
||||
.header("User-Agent", user_agent);
|
||||
|
||||
request
|
||||
request_builder
|
||||
}
|
||||
|
||||
pub fn get(&self, path: &str) -> Result<Response, APIError> {
|
||||
fn build_request_async(&self, request: reqwest::RequestBuilder) -> reqwest::RequestBuilder {
|
||||
let user_agent = format!(
|
||||
"ivangabriele/mistralai-client-rs/{}",
|
||||
env!("CARGO_PKG_VERSION")
|
||||
);
|
||||
|
||||
let request_builder = request
|
||||
.bearer_auth(&self.api_key)
|
||||
.header("Accept", "application/json")
|
||||
.header("Content-Type", "application/json")
|
||||
.header("User-Agent", user_agent);
|
||||
|
||||
request_builder
|
||||
}
|
||||
|
||||
fn get_sync(&self, path: &str) -> Result<reqwest::blocking::Response, ApiError> {
|
||||
let client_sync = reqwest::blocking::Client::new();
|
||||
let url = format!("{}{}", self.endpoint, path);
|
||||
let request = self.build_request(minreq::post(url));
|
||||
let request = self.build_request_sync(client_sync.get(url));
|
||||
|
||||
let result = request.send();
|
||||
match result {
|
||||
Ok(res) => {
|
||||
if (200..=299).contains(&res.status_code) {
|
||||
Ok(res)
|
||||
Ok(response) => {
|
||||
if response.status().is_success() {
|
||||
Ok(response)
|
||||
} else {
|
||||
Err(APIError {
|
||||
message: format!("{}: {}", res.status_code, res.as_str().unwrap()),
|
||||
let status = response.status();
|
||||
let text = response.text().unwrap();
|
||||
Err(ApiError {
|
||||
message: format!("{}: {}", status, text),
|
||||
})
|
||||
}
|
||||
}
|
||||
Err(e) => Err(self.new_error(e)),
|
||||
Err(error) => Err(ApiError {
|
||||
message: error.to_string(),
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn post<T: serde::ser::Serialize + std::fmt::Debug>(
|
||||
async fn get_async(&self, path: &str) -> Result<reqwest::Response, ApiError> {
|
||||
let reqwest_client = reqwest::Client::new();
|
||||
let url = format!("{}{}", self.endpoint, path);
|
||||
let request_builder = reqwest_client.get(url);
|
||||
let request = self.build_request_async(request_builder);
|
||||
|
||||
let result = request.send().await.map_err(|e| self.to_api_error(e));
|
||||
match result {
|
||||
Ok(response) => {
|
||||
if response.status().is_success() {
|
||||
Ok(response)
|
||||
} else {
|
||||
let status = response.status();
|
||||
let text = response.text().await.unwrap_or_default();
|
||||
Err(ApiError {
|
||||
message: format!("{}: {}", status, text),
|
||||
})
|
||||
}
|
||||
}
|
||||
Err(error) => Err(ApiError {
|
||||
message: error.to_string(),
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
fn post_sync<T: serde::ser::Serialize + std::fmt::Debug>(
|
||||
&self,
|
||||
path: &str,
|
||||
params: &T,
|
||||
) -> Result<Response, APIError> {
|
||||
// print!("{:?}", params);
|
||||
|
||||
) -> Result<reqwest::blocking::Response, ApiError> {
|
||||
let reqwest_client = reqwest::blocking::Client::new();
|
||||
let url = format!("{}{}", self.endpoint, path);
|
||||
let request = self.build_request(minreq::post(url));
|
||||
|
||||
let result = request.with_json(params).unwrap().send();
|
||||
match result {
|
||||
Ok(res) => {
|
||||
print!("{:?}", res.as_str().unwrap());
|
||||
|
||||
if (200..=299).contains(&res.status_code) {
|
||||
Ok(res)
|
||||
} else {
|
||||
Err(APIError {
|
||||
message: format!("{}: {}", res.status_code, res.as_str().unwrap()),
|
||||
})
|
||||
}
|
||||
}
|
||||
Err(e) => Err(self.new_error(e)),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn delete(&self, path: &str) -> Result<Response, APIError> {
|
||||
let url = format!("{}{}", self.endpoint, path);
|
||||
let request = self.build_request(minreq::post(url));
|
||||
let request_builder = reqwest_client.post(url).json(params);
|
||||
let request = self.build_request_sync(request_builder);
|
||||
|
||||
let result = request.send();
|
||||
match result {
|
||||
Ok(res) => {
|
||||
if (200..=299).contains(&res.status_code) {
|
||||
Ok(res)
|
||||
Ok(response) => {
|
||||
if response.status().is_success() {
|
||||
Ok(response)
|
||||
} else {
|
||||
Err(APIError {
|
||||
message: format!("{}: {}", res.status_code, res.as_str().unwrap()),
|
||||
let status = response.status();
|
||||
let text = response.text().unwrap_or_default();
|
||||
Err(ApiError {
|
||||
message: format!("{}: {}", status, text),
|
||||
})
|
||||
}
|
||||
}
|
||||
Err(e) => Err(self.new_error(e)),
|
||||
Err(error) => Err(ApiError {
|
||||
message: error.to_string(),
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
// pub fn completion(&self, req: CompletionRequest) -> Result<CompletionResponse, APIError> {
|
||||
// let res = self.post("/completions", &req)?;
|
||||
// let r = res.json::<CompletionResponse>();
|
||||
// match r {
|
||||
// Ok(r) => Ok(r),
|
||||
// Err(e) => Err(self.new_error(e)),
|
||||
// }
|
||||
// }
|
||||
async fn post_async<T: serde::ser::Serialize + std::fmt::Debug>(
|
||||
&self,
|
||||
path: &str,
|
||||
params: &T,
|
||||
) -> Result<reqwest::Response, ApiError> {
|
||||
let reqwest_client = reqwest::Client::new();
|
||||
let url = format!("{}{}", self.endpoint, path);
|
||||
let request_builder = reqwest_client.post(url).json(params);
|
||||
let request = self.build_request_async(request_builder);
|
||||
|
||||
// pub fn embedding(&self, req: EmbeddingRequest) -> Result<EmbeddingResponse, APIError> {
|
||||
// let res = self.post("/embeddings", &req)?;
|
||||
// let r = res.json::<EmbeddingResponse>();
|
||||
// match r {
|
||||
// Ok(r) => Ok(r),
|
||||
// Err(e) => Err(self.new_error(e)),
|
||||
// }
|
||||
// }
|
||||
|
||||
pub fn chat(&self, request: ChatCompletionRequest) -> Result<ChatCompletionResponse, APIError> {
|
||||
let response = self.post("/chat/completions", &request)?;
|
||||
let result = response.json::<ChatCompletionResponse>();
|
||||
let result = request.send().await.map_err(|e| self.to_api_error(e));
|
||||
match result {
|
||||
Ok(r) => Ok(r),
|
||||
Err(e) => Err(self.new_error(e)),
|
||||
Ok(response) => {
|
||||
if response.status().is_success() {
|
||||
Ok(response)
|
||||
} else {
|
||||
let status = response.status();
|
||||
let text = response.text().await.unwrap_or_default();
|
||||
Err(ApiError {
|
||||
message: format!("{}: {}", status, text),
|
||||
})
|
||||
}
|
||||
}
|
||||
Err(error) => Err(ApiError {
|
||||
message: error.to_string(),
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
fn new_error(&self, err: minreq::Error) -> APIError {
|
||||
APIError {
|
||||
fn to_api_error(&self, err: ReqwestError) -> ApiError {
|
||||
ApiError {
|
||||
message: err.to_string(),
|
||||
}
|
||||
}
|
||||
|
||||
// fn query_params(
|
||||
// limit: Option<i64>,
|
||||
// order: Option<String>,
|
||||
// after: Option<String>,
|
||||
// before: Option<String>,
|
||||
// mut url: String,
|
||||
// ) -> String {
|
||||
// let mut params = vec![];
|
||||
// if let Some(limit) = limit {
|
||||
// params.push(format!("limit={}", limit));
|
||||
// }
|
||||
// if let Some(order) = order {
|
||||
// params.push(format!("order={}", order));
|
||||
// }
|
||||
// if let Some(after) = after {
|
||||
// params.push(format!("after={}", after));
|
||||
// }
|
||||
// if let Some(before) = before {
|
||||
// params.push(format!("before={}", before));
|
||||
// }
|
||||
// if !params.is_empty() {
|
||||
// url = format!("{}?{}", url, params.join("&"));
|
||||
// }
|
||||
// url
|
||||
// }
|
||||
}
|
||||
|
||||
@@ -1,7 +1,23 @@
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
pub const API_URL_BASE: &str = "https://api.mistral.ai/v1";
|
||||
|
||||
pub const OPEN_MISTRAL_7B: &str = "open-mistral-7b";
|
||||
pub const OPEN_MISTRAL_8X7B: &str = "open-mixtral-8x7b";
|
||||
pub const MISTRAL_SMALL_LATEST: &str = "mistral-small-latest";
|
||||
pub const MISTRAL_MEDIUM_LATEST: &str = "mistral-medium-latest";
|
||||
pub const MISTRAL_LARGE_LATEST: &str = "mistral-large-latest";
|
||||
#[derive(Clone, Debug, Eq, PartialEq, Deserialize, Serialize)]
|
||||
pub enum Model {
|
||||
#[serde(rename = "open-mistral-7b")]
|
||||
OpenMistral7b,
|
||||
#[serde(rename = "open-mistral-8x7b")]
|
||||
OpenMistral8x7b,
|
||||
#[serde(rename = "mistral-small-latest")]
|
||||
MistralSmallLatest,
|
||||
#[serde(rename = "mistral-medium-latest")]
|
||||
MistralMediumLatest,
|
||||
#[serde(rename = "mistral-large-latest")]
|
||||
MistralLargeLatest,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Eq, PartialEq, Deserialize, Serialize)]
|
||||
pub enum EmbedModel {
|
||||
#[serde(rename = "mistral-embed")]
|
||||
MistralEmbed,
|
||||
}
|
||||
|
||||
60
src/v1/embedding.rs
Normal file
60
src/v1/embedding.rs
Normal file
@@ -0,0 +1,60 @@
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use crate::v1::{common, constants};
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct EmbeddingRequestOptions {
|
||||
pub encoding_format: Option<EmbeddingRequestEncodingFormat>,
|
||||
}
|
||||
impl Default for EmbeddingRequestOptions {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
encoding_format: None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize, Deserialize)]
|
||||
pub struct EmbeddingRequest {
|
||||
pub model: constants::EmbedModel,
|
||||
pub input: Vec<String>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub encoding_format: Option<EmbeddingRequestEncodingFormat>,
|
||||
}
|
||||
impl EmbeddingRequest {
|
||||
pub fn new(
|
||||
model: constants::EmbedModel,
|
||||
input: Vec<String>,
|
||||
options: Option<EmbeddingRequestOptions>,
|
||||
) -> Self {
|
||||
let EmbeddingRequestOptions { encoding_format } = options.unwrap_or_default();
|
||||
|
||||
Self {
|
||||
model,
|
||||
input,
|
||||
encoding_format,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Eq, PartialEq, Deserialize, Serialize)]
|
||||
#[allow(non_camel_case_types)]
|
||||
pub enum EmbeddingRequestEncodingFormat {
|
||||
float,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Deserialize, Serialize)]
|
||||
pub struct EmbeddingResponse {
|
||||
pub id: String,
|
||||
pub object: String,
|
||||
pub model: constants::EmbedModel,
|
||||
pub data: Vec<EmbeddingResponseDataItem>,
|
||||
pub usage: common::ResponseUsage,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Deserialize, Serialize)]
|
||||
pub struct EmbeddingResponseDataItem {
|
||||
pub index: u32,
|
||||
pub embedding: Vec<f32>,
|
||||
pub object: String,
|
||||
}
|
||||
@@ -2,14 +2,20 @@ use std::error::Error;
|
||||
use std::fmt;
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct APIError {
|
||||
pub struct ApiError {
|
||||
pub message: String,
|
||||
}
|
||||
|
||||
impl fmt::Display for APIError {
|
||||
impl fmt::Display for ApiError {
|
||||
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
|
||||
write!(f, "APIError: {}", self.message)
|
||||
write!(f, "ApiError: {}", self.message)
|
||||
}
|
||||
}
|
||||
impl Error for ApiError {}
|
||||
|
||||
impl Error for APIError {}
|
||||
#[derive(Debug, PartialEq, thiserror::Error)]
|
||||
pub enum ClientError {
|
||||
#[error("You must either set the `MISTRAL_API_KEY` environment variable or specify it in `Client::new(api_key, ...).")]
|
||||
ApiKeyError,
|
||||
#[error("Failed to read the response text.")]
|
||||
ReadResponseTextError,
|
||||
}
|
||||
|
||||
@@ -2,4 +2,6 @@ pub mod chat_completion;
|
||||
pub mod client;
|
||||
pub mod common;
|
||||
pub mod constants;
|
||||
pub mod embedding;
|
||||
pub mod error;
|
||||
pub mod model_list;
|
||||
|
||||
39
src/v1/model_list.rs
Normal file
39
src/v1/model_list.rs
Normal file
@@ -0,0 +1,39 @@
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
#[derive(Clone, Debug, Deserialize, Serialize)]
|
||||
pub struct ModelListResponse {
|
||||
pub object: String,
|
||||
pub data: Vec<ModelListData>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Deserialize, Serialize)]
|
||||
pub struct ModelListData {
|
||||
pub id: String,
|
||||
pub object: String,
|
||||
/// Unix timestamp (in seconds).
|
||||
pub created: u32,
|
||||
pub owned_by: String,
|
||||
pub permission: Vec<ModelListDataPermission>,
|
||||
// TODO Check this prop (seen in API responses but undocumented).
|
||||
// pub root: ???,
|
||||
// TODO Check this prop (seen in API responses but undocumented).
|
||||
// pub parent: ???,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Deserialize, Serialize)]
|
||||
pub struct ModelListDataPermission {
|
||||
pub id: String,
|
||||
pub object: String,
|
||||
/// Unix timestamp (in seconds).
|
||||
pub created: u32,
|
||||
pub allow_create_engine: bool,
|
||||
pub allow_sampling: bool,
|
||||
pub allow_logprobs: bool,
|
||||
pub allow_search_indices: bool,
|
||||
pub allow_view: bool,
|
||||
pub allow_fine_tuning: bool,
|
||||
pub organization: String,
|
||||
pub is_blocking: bool,
|
||||
// TODO Check this prop (seen in API responses but undocumented).
|
||||
// pub group: ???,
|
||||
}
|
||||
@@ -1,53 +0,0 @@
|
||||
use jrest::expect;
|
||||
use mistralai_client::v1::{
|
||||
chat_completion::{
|
||||
ChatCompletionMessage, ChatCompletionMessageRole, ChatCompletionRequest,
|
||||
ChatCompletionRequestOptions,
|
||||
},
|
||||
client::Client,
|
||||
constants::OPEN_MISTRAL_7B,
|
||||
};
|
||||
|
||||
#[test]
|
||||
fn test_chat_completion() {
|
||||
extern crate dotenv;
|
||||
|
||||
use dotenv::dotenv;
|
||||
dotenv().ok();
|
||||
|
||||
let client = Client::new(None, None, None, None);
|
||||
|
||||
let model = OPEN_MISTRAL_7B.to_string();
|
||||
let messages = vec![ChatCompletionMessage {
|
||||
role: ChatCompletionMessageRole::user,
|
||||
content: "Just guess the next word: \"Eiffel ...\"?".to_string(),
|
||||
}];
|
||||
let options = ChatCompletionRequestOptions {
|
||||
temperature: Some(0.0),
|
||||
random_seed: Some(42),
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
let chat_completion_request = ChatCompletionRequest::new(model, messages, Some(options));
|
||||
let result = client.chat(chat_completion_request);
|
||||
|
||||
match result {
|
||||
Ok(res) => {
|
||||
expect!(res.model).to_be("open-mistral-7b".to_string());
|
||||
expect!(res.object).to_be("chat.completion".to_string());
|
||||
expect!(res.choices.len()).to_be(1);
|
||||
expect!(res.choices[0].index).to_be(0);
|
||||
expect!(res.choices[0].message.role.clone())
|
||||
.to_be(ChatCompletionMessageRole::assistant);
|
||||
expect!(res.choices[0].message.content.clone()).to_be(
|
||||
"Tower. The Eiffel Tower is a famous landmark in Paris, France.".to_string(),
|
||||
);
|
||||
expect!(res.usage.prompt_tokens).to_be_greater_than(0);
|
||||
expect!(res.usage.completion_tokens).to_be_greater_than(0);
|
||||
expect!(res.usage.total_tokens).to_be_greater_than(21);
|
||||
}
|
||||
Err(err) => {
|
||||
panic!("Error: {}", err);
|
||||
}
|
||||
}
|
||||
}
|
||||
38
tests/v1_client_chat_async_test.rs
Normal file
38
tests/v1_client_chat_async_test.rs
Normal file
@@ -0,0 +1,38 @@
|
||||
use jrest::expect;
|
||||
use mistralai_client::v1::{
|
||||
chat_completion::{ChatCompletionMessage, ChatCompletionMessageRole, ChatCompletionParams},
|
||||
client::Client,
|
||||
constants::Model,
|
||||
};
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_client_chat_async() {
|
||||
let client = Client::new(None, None, None, None).unwrap();
|
||||
|
||||
let model = Model::OpenMistral7b;
|
||||
let messages = vec![ChatCompletionMessage {
|
||||
role: ChatCompletionMessageRole::user,
|
||||
content: "Just guess the next word: \"Eiffel ...\"?".to_string(),
|
||||
}];
|
||||
let options = ChatCompletionParams {
|
||||
temperature: Some(0.0),
|
||||
random_seed: Some(42),
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
let response = client
|
||||
.chat_async(model, messages, Some(options))
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
expect!(response.model).to_be(Model::OpenMistral7b);
|
||||
expect!(response.object).to_be("chat.completion".to_string());
|
||||
expect!(response.choices.len()).to_be(1);
|
||||
expect!(response.choices[0].index).to_be(0);
|
||||
expect!(response.choices[0].message.role.clone()).to_be(ChatCompletionMessageRole::assistant);
|
||||
expect!(response.choices[0].message.content.clone())
|
||||
.to_be("Tower. The Eiffel Tower is a famous landmark in Paris, France.".to_string());
|
||||
expect!(response.usage.prompt_tokens).to_be_greater_than(0);
|
||||
expect!(response.usage.completion_tokens).to_be_greater_than(0);
|
||||
expect!(response.usage.total_tokens).to_be_greater_than(0);
|
||||
}
|
||||
35
tests/v1_client_chat_test.rs
Normal file
35
tests/v1_client_chat_test.rs
Normal file
@@ -0,0 +1,35 @@
|
||||
use jrest::expect;
|
||||
use mistralai_client::v1::{
|
||||
chat_completion::{ChatCompletionMessage, ChatCompletionMessageRole, ChatCompletionParams},
|
||||
client::Client,
|
||||
constants::Model,
|
||||
};
|
||||
|
||||
#[test]
|
||||
fn test_client_chat() {
|
||||
let client = Client::new(None, None, None, None).unwrap();
|
||||
|
||||
let model = Model::OpenMistral7b;
|
||||
let messages = vec![ChatCompletionMessage {
|
||||
role: ChatCompletionMessageRole::user,
|
||||
content: "Just guess the next word: \"Eiffel ...\"?".to_string(),
|
||||
}];
|
||||
let options = ChatCompletionParams {
|
||||
temperature: Some(0.0),
|
||||
random_seed: Some(42),
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
let response = client.chat(model, messages, Some(options)).unwrap();
|
||||
|
||||
expect!(response.model).to_be(Model::OpenMistral7b);
|
||||
expect!(response.object).to_be("chat.completion".to_string());
|
||||
expect!(response.choices.len()).to_be(1);
|
||||
expect!(response.choices[0].index).to_be(0);
|
||||
expect!(response.choices[0].message.role.clone()).to_be(ChatCompletionMessageRole::assistant);
|
||||
expect!(response.choices[0].message.content.clone())
|
||||
.to_be("Tower. The Eiffel Tower is a famous landmark in Paris, France.".to_string());
|
||||
expect!(response.usage.prompt_tokens).to_be_greater_than(0);
|
||||
expect!(response.usage.completion_tokens).to_be_greater_than(0);
|
||||
expect!(response.usage.total_tokens).to_be_greater_than(0);
|
||||
}
|
||||
29
tests/v1_client_embeddings_async_test.rs
Normal file
29
tests/v1_client_embeddings_async_test.rs
Normal file
@@ -0,0 +1,29 @@
|
||||
use jrest::expect;
|
||||
use mistralai_client::v1::{client::Client, constants::EmbedModel};
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_client_embeddings_async() {
|
||||
let client: Client = Client::new(None, None, None, None).unwrap();
|
||||
|
||||
let model = EmbedModel::MistralEmbed;
|
||||
let input = vec!["Embed this sentence.", "As well as this one."]
|
||||
.iter()
|
||||
.map(|s| s.to_string())
|
||||
.collect();
|
||||
let options = None;
|
||||
|
||||
let response = client
|
||||
.embeddings_async(model, input, options)
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
expect!(response.model).to_be(EmbedModel::MistralEmbed);
|
||||
expect!(response.object).to_be("list".to_string());
|
||||
expect!(response.data.len()).to_be(2);
|
||||
expect!(response.data[0].index).to_be(0);
|
||||
expect!(response.data[0].object.clone()).to_be("embedding".to_string());
|
||||
expect!(response.data[0].embedding.len()).to_be_greater_than(0);
|
||||
expect!(response.usage.prompt_tokens).to_be_greater_than(0);
|
||||
expect!(response.usage.completion_tokens).to_be(0);
|
||||
expect!(response.usage.total_tokens).to_be_greater_than(0);
|
||||
}
|
||||
26
tests/v1_client_embeddings_test.rs
Normal file
26
tests/v1_client_embeddings_test.rs
Normal file
@@ -0,0 +1,26 @@
|
||||
use jrest::expect;
|
||||
use mistralai_client::v1::{client::Client, constants::EmbedModel};
|
||||
|
||||
#[test]
|
||||
fn test_client_embeddings() {
|
||||
let client: Client = Client::new(None, None, None, None).unwrap();
|
||||
|
||||
let model = EmbedModel::MistralEmbed;
|
||||
let input = vec!["Embed this sentence.", "As well as this one."]
|
||||
.iter()
|
||||
.map(|s| s.to_string())
|
||||
.collect();
|
||||
let options = None;
|
||||
|
||||
let response = client.embeddings(model, input, options).unwrap();
|
||||
|
||||
expect!(response.model).to_be(EmbedModel::MistralEmbed);
|
||||
expect!(response.object).to_be("list".to_string());
|
||||
expect!(response.data.len()).to_be(2);
|
||||
expect!(response.data[0].index).to_be(0);
|
||||
expect!(response.data[0].object.clone()).to_be("embedding".to_string());
|
||||
expect!(response.data[0].embedding.len()).to_be_greater_than(0);
|
||||
expect!(response.usage.prompt_tokens).to_be_greater_than(0);
|
||||
expect!(response.usage.completion_tokens).to_be(0);
|
||||
expect!(response.usage.total_tokens).to_be_greater_than(0);
|
||||
}
|
||||
20
tests/v1_client_list_models_async_test.rs
Normal file
20
tests/v1_client_list_models_async_test.rs
Normal file
@@ -0,0 +1,20 @@
|
||||
use jrest::expect;
|
||||
use mistralai_client::v1::client::Client;
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_client_list_models_async() {
|
||||
let client = Client::new(None, None, None, None).unwrap();
|
||||
|
||||
let response = client.list_models_async().await.unwrap();
|
||||
|
||||
expect!(response.object).to_be("list".to_string());
|
||||
expect!(response.data.len()).to_be_greater_than(0);
|
||||
|
||||
// let open_mistral_7b_data_item = response
|
||||
// .data
|
||||
// .iter()
|
||||
// .find(|item| item.id == "open-mistral-7b")
|
||||
// .unwrap();
|
||||
|
||||
// expect!(open_mistral_7b_data_item.id).to_be("open-mistral-7b".to_string());
|
||||
}
|
||||
20
tests/v1_client_list_models_test.rs
Normal file
20
tests/v1_client_list_models_test.rs
Normal file
@@ -0,0 +1,20 @@
|
||||
use jrest::expect;
|
||||
use mistralai_client::v1::client::Client;
|
||||
|
||||
#[test]
|
||||
fn test_client_list_models() {
|
||||
let client = Client::new(None, None, None, None).unwrap();
|
||||
|
||||
let response = client.list_models().unwrap();
|
||||
|
||||
expect!(response.object).to_be("list".to_string());
|
||||
expect!(response.data.len()).to_be_greater_than(0);
|
||||
|
||||
// let open_mistral_7b_data_item = response
|
||||
// .data
|
||||
// .iter()
|
||||
// .find(|item| item.id == "open-mistral-7b")
|
||||
// .unwrap();
|
||||
|
||||
// expect!(open_mistral_7b_data_item.id).to_be("open-mistral-7b".to_string());
|
||||
}
|
||||
@@ -1,12 +1,13 @@
|
||||
use jrest::expect;
|
||||
use mistralai_client::v1::client::Client;
|
||||
use mistralai_client::v1::{client::Client, error::ClientError};
|
||||
|
||||
#[test]
|
||||
fn test_client_new_with_none_params() {
|
||||
let maybe_original_mistral_api_key = std::env::var("MISTRAL_API_KEY").ok();
|
||||
std::env::remove_var("MISTRAL_API_KEY");
|
||||
std::env::set_var("MISTRAL_API_KEY", "test_api_key_from_env");
|
||||
|
||||
let client = Client::new(None, None, None, None);
|
||||
let client = Client::new(None, None, None, None).unwrap();
|
||||
|
||||
expect!(client.api_key).to_be("test_api_key_from_env".to_string());
|
||||
expect!(client.endpoint).to_be("https://api.mistral.ai/v1".to_string());
|
||||
@@ -24,6 +25,7 @@ fn test_client_new_with_none_params() {
|
||||
#[test]
|
||||
fn test_client_new_with_all_params() {
|
||||
let maybe_original_mistral_api_key = std::env::var("MISTRAL_API_KEY").ok();
|
||||
std::env::remove_var("MISTRAL_API_KEY");
|
||||
std::env::set_var("MISTRAL_API_KEY", "test_api_key_from_env");
|
||||
|
||||
let api_key = Some("test_api_key_from_param".to_string());
|
||||
@@ -36,7 +38,8 @@ fn test_client_new_with_all_params() {
|
||||
endpoint.clone(),
|
||||
max_retries.clone(),
|
||||
timeout.clone(),
|
||||
);
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
expect!(client.api_key).to_be(api_key.unwrap());
|
||||
expect!(client.endpoint).to_be(endpoint.unwrap());
|
||||
@@ -50,3 +53,23 @@ fn test_client_new_with_all_params() {
|
||||
None => std::env::remove_var("MISTRAL_API_KEY"),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_client_new_with_missing_api_key() {
|
||||
let maybe_original_mistral_api_key = std::env::var("MISTRAL_API_KEY").ok();
|
||||
std::env::remove_var("MISTRAL_API_KEY");
|
||||
|
||||
let call = || Client::new(None, None, None, None);
|
||||
|
||||
match call() {
|
||||
Ok(_) => panic!("Expected `ClientError::ApiKeyError` but got Ok.`"),
|
||||
Err(error) => assert_eq!(error, ClientError::ApiKeyError),
|
||||
}
|
||||
|
||||
match maybe_original_mistral_api_key {
|
||||
Some(original_mistral_api_key) => {
|
||||
std::env::set_var("MISTRAL_API_KEY", original_mistral_api_key)
|
||||
}
|
||||
None => std::env::remove_var("MISTRAL_API_KEY"),
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user