openai_api_rust/apis/
models.rs

1// List and describe the various models available in the API.
2// You can refer to the Models documentation to understand
3// what models are available and the differences between them.
4// See: https://platform.openai.com/docs/api-reference/models
5
6//! Models API
7use crate::requests::Requests;
8use crate::*;
9use serde::{Deserialize, Serialize};
10
11use super::MODELS_LIST;
12use super::MODELS_RETRIEVE;
13
14/// List and describe the various models available in the API.
15/// You can refer to the [Models](https://platform.openai.com/docs/models) documentation
16/// to understand what models are available and the differences between them.
17#[derive(Debug, Serialize, Deserialize)]
18pub struct Model {
19	pub id: String,
20	pub object: Option<String>,
21	pub owned_by: Option<String>,
22}
23
24pub trait ModelsApi {
25	/// Lists the currently available models,
26	/// and provides basic information about each one such as the owner and availability.
27	fn models_list(&self) -> ApiResult<Vec<Model>>;
28	/// Retrieves a model instance,
29	/// providing basic information about the model such as the owner and permissioning.
30	fn models_retrieve(&self, model_id: &str) -> ApiResult<Model>;
31}
32
33impl ModelsApi for OpenAI {
34	fn models_list(&self) -> ApiResult<Vec<Model>> {
35		let res: Json = self.get(MODELS_LIST)?;
36		let data = res.as_object().unwrap().get("data");
37		if let Some(data) = data {
38			let models: Vec<Model> = serde_json::from_value(data.clone()).unwrap();
39			return Ok(models);
40		}
41		Err(Error::ApiError("No data".to_string()))
42	}
43
44	fn models_retrieve(&self, model_id: &str) -> ApiResult<Model> {
45		let res: Json = self.get(&(MODELS_RETRIEVE.to_owned() + model_id))?;
46		let model: Model = serde_json::from_value(res).unwrap();
47		Ok(model)
48	}
49}
50
51#[cfg(test)]
52mod tests {
53	use crate::{apis::models::ModelsApi, openai::new_test_openai};
54
55	#[test]
56	fn test_models() {
57		let openai = new_test_openai();
58		let models = openai.models_list().unwrap();
59		assert!(!models.is_empty());
60	}
61
62	#[test]
63	fn test_get_model() {
64		let openai = new_test_openai();
65		let model = openai.models_retrieve("babbage-002").unwrap();
66		assert_eq!("babbage-002", model.id);
67	}
68}