Skip to content

Commit 77671b5

Browse files
authored
Merge pull request #166 from dongri/add-models-api
Add models api
2 parents 14b13d6 + 66b1271 commit 77671b5

File tree

8 files changed

+78
-16
lines changed

8 files changed

+78
-16
lines changed

examples/chat_completion.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,7 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
2323
println!("Content: {:?}", result.choices[0].message.content);
2424

2525
// print response headers
26-
for (key, value) in client.headers.unwrap().iter() {
26+
for (key, value) in client.response_headers.unwrap().iter() {
2727
println!("{}: {:?}", key, value);
2828
}
2929

examples/model.rs

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
use openai_api_rs::v1::api::OpenAIClient;
2+
use std::env;
3+
4+
#[tokio::main]
5+
async fn main() -> Result<(), Box<dyn std::error::Error>> {
6+
let api_key = env::var("OPENAI_API_KEY").unwrap().to_string();
7+
let mut client = OpenAIClient::builder().with_api_key(api_key).build()?;
8+
9+
let result = client.list_models().await?;
10+
let models = result.data;
11+
12+
for model in models {
13+
println!("Model id: {:?}", model.id);
14+
}
15+
16+
let result = client.retrieve_model("gpt-4.1".to_string()).await?;
17+
println!("Model id: {:?}", result.id);
18+
println!("Model object: {:?}", result.object);
19+
20+
Ok(())
21+
}
22+
23+
// OPENAI_API_KEY=xxxx cargo run --package openai-api-rs --example model

examples/openrouter.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,7 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
2424

2525
let result = client.chat_completion(req).await?;
2626
println!("Content: {:?}", result.choices[0].message.content);
27-
println!("Response Headers: {:?}", client.headers);
27+
println!("Response Headers: {:?}", client.response_headers);
2828

2929
Ok(())
3030
}

src/v1/api.rs

Lines changed: 30 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
use crate::v1::assistant::{
2-
AssistantFileObject, AssistantFileRequest, AssistantObject, AssistantRequest, DeletionStatus,
3-
ListAssistant, ListAssistantFile,
2+
AssistantFileObject, AssistantFileRequest, AssistantObject, AssistantRequest, ListAssistant,
3+
ListAssistantFile,
44
};
55
use crate::v1::audio::{
66
AudioSpeechRequest, AudioSpeechResponse, AudioTranscriptionRequest, AudioTranscriptionResponse,
@@ -30,6 +30,7 @@ use crate::v1::message::{
3030
CreateMessageRequest, ListMessage, ListMessageFile, MessageFileObject, MessageObject,
3131
ModifyMessageRequest,
3232
};
33+
use crate::v1::model::{ModelResponse, ModelsResponse};
3334
use crate::v1::moderation::{CreateModerationRequest, CreateModerationResponse};
3435
use crate::v1::run::{
3536
CreateRunRequest, CreateThreadAndRunRequest, ListRun, ListRunStep, ModifyRunRequest, RunObject,
@@ -70,7 +71,8 @@ pub struct OpenAIClient {
7071
organization: Option<String>,
7172
proxy: Option<String>,
7273
timeout: Option<u64>,
73-
pub headers: Option<HeaderMap>,
74+
headers: Option<HeaderMap>,
75+
pub response_headers: Option<HeaderMap>,
7476
}
7577

7678
impl OpenAIClientBuilder {
@@ -124,6 +126,7 @@ impl OpenAIClientBuilder {
124126
proxy: self.proxy,
125127
timeout: self.timeout,
126128
headers: self.headers,
129+
response_headers: None,
127130
})
128131
}
129132
}
@@ -237,7 +240,7 @@ impl OpenAIClient {
237240
let text = response.text().await.unwrap_or_else(|_| "".to_string());
238241
match serde_json::from_str::<T>(&text) {
239242
Ok(parsed) => {
240-
self.headers = Some(headers);
243+
self.response_headers = Some(headers);
241244
Ok(parsed)
242245
}
243246
Err(e) => Err(APIError::CustomError {
@@ -507,7 +510,7 @@ impl OpenAIClient {
507510
pub async fn delete_assistant(
508511
&mut self,
509512
assistant_id: String,
510-
) -> Result<DeletionStatus, APIError> {
513+
) -> Result<common::DeletionStatus, APIError> {
511514
self.delete(&format!("assistants/{}", assistant_id)).await
512515
}
513516

@@ -544,7 +547,7 @@ impl OpenAIClient {
544547
&mut self,
545548
assistant_id: String,
546549
file_id: String,
547-
) -> Result<DeletionStatus, APIError> {
550+
) -> Result<common::DeletionStatus, APIError> {
548551
self.delete(&format!("assistants/{}/files/{}", assistant_id, file_id))
549552
.await
550553
}
@@ -586,7 +589,10 @@ impl OpenAIClient {
586589
self.post(&format!("threads/{}", thread_id), &req).await
587590
}
588591

589-
pub async fn delete_thread(&mut self, thread_id: String) -> Result<DeletionStatus, APIError> {
592+
pub async fn delete_thread(
593+
&mut self,
594+
thread_id: String,
595+
) -> Result<common::DeletionStatus, APIError> {
590596
self.delete(&format!("threads/{}", thread_id)).await
591597
}
592598

@@ -781,6 +787,22 @@ impl OpenAIClient {
781787
let url = Self::query_params(limit, None, after, None, "batches".to_string());
782788
self.get(&url).await
783789
}
790+
791+
pub async fn list_models(&mut self) -> Result<ModelsResponse, APIError> {
792+
self.get("models").await
793+
}
794+
795+
pub async fn retrieve_model(&mut self, model_id: String) -> Result<ModelResponse, APIError> {
796+
self.get(&format!("models/{}", model_id)).await
797+
}
798+
799+
pub async fn delete_model(
800+
&mut self,
801+
model_id: String,
802+
) -> Result<common::DeletionStatus, APIError> {
803+
self.delete(&format!("models/{}", model_id)).await
804+
}
805+
784806
fn build_url_with_preserved_query(&self, path: &str) -> Result<String, url::ParseError> {
785807
let (base, query_opt) = match self.api_endpoint.split_once('?') {
786808
Some((b, q)) => (b.trim_end_matches('/'), Some(q)),
@@ -797,6 +819,7 @@ impl OpenAIClient {
797819
}
798820
Ok(url.to_string())
799821
}
822+
800823
fn query_params(
801824
limit: Option<i64>,
802825
order: Option<String>,

src/v1/assistant.rs

Lines changed: 0 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -95,13 +95,6 @@ pub struct VectorStores {
9595
pub metadata: Option<HashMap<String, String>>,
9696
}
9797

98-
#[derive(Debug, Deserialize, Serialize)]
99-
pub struct DeletionStatus {
100-
pub id: String,
101-
pub object: String,
102-
pub deleted: bool,
103-
}
104-
10598
#[derive(Debug, Deserialize, Serialize)]
10699
pub struct ListAssistant {
107100
pub object: String,

src/v1/common.rs

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,13 @@ pub struct Usage {
77
pub total_tokens: i32,
88
}
99

10+
#[derive(Debug, Deserialize, Serialize)]
11+
pub struct DeletionStatus {
12+
pub id: String,
13+
pub object: String,
14+
pub deleted: bool,
15+
}
16+
1017
#[macro_export]
1118
macro_rules! impl_builder_methods {
1219
($builder:ident, $($field:ident: $field_type:ty),*) => {

src/v1/mod.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@ pub mod embedding;
1111
pub mod file;
1212
pub mod fine_tuning;
1313
pub mod image;
14+
pub mod model;
1415
pub mod moderation;
1516

1617
// beta

src/v1/model.rs

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
use serde::{Deserialize, Serialize};
2+
3+
#[derive(Debug, Deserialize, Serialize)]
4+
pub struct ModelsResponse {
5+
pub object: String,
6+
pub data: Vec<ModelResponse>,
7+
}
8+
9+
#[derive(Debug, Deserialize, Serialize)]
10+
pub struct ModelResponse {
11+
pub id: String,
12+
pub object: String,
13+
pub created: i64,
14+
pub owned_by: String,
15+
}

0 commit comments

Comments
 (0)