Skip to main content

langfuse_client_base/apis/
scores_api.rs

1/*
2 * langfuse
3 *
4 * ## Authentication  Authenticate with the API using [Basic Auth](https://en.wikipedia.org/wiki/Basic_access_authentication), get API keys in the project settings:  - username: Langfuse Public Key - password: Langfuse Secret Key  ## Exports  - OpenAPI spec: https://cloud.langfuse.com/generated/api/openapi.yml
5 *
6 * The version of the OpenAPI document:
7 *
8 * Generated by: https://openapi-generator.tech
9 */
10
11use super::{configuration, ContentType, Error};
12use crate::{apis::ResponseContent, models};
13use reqwest;
14use serde::{de::Error as _, Deserialize, Serialize};
15
16/// struct for typed errors of method [`scores_get_by_id`]
17#[derive(Debug, Clone, Serialize, Deserialize)]
18#[serde(untagged)]
19pub enum ScoresGetByIdError {
20    Status400(serde_json::Value),
21    Status401(serde_json::Value),
22    Status403(serde_json::Value),
23    Status404(serde_json::Value),
24    Status405(serde_json::Value),
25    UnknownValue(serde_json::Value),
26}
27
28/// struct for typed errors of method [`scores_get_many`]
29#[derive(Debug, Clone, Serialize, Deserialize)]
30#[serde(untagged)]
31pub enum ScoresGetManyError {
32    Status400(serde_json::Value),
33    Status401(serde_json::Value),
34    Status403(serde_json::Value),
35    Status404(serde_json::Value),
36    Status405(serde_json::Value),
37    UnknownValue(serde_json::Value),
38}
39
40/// Get a score (supports both trace and session scores)
41#[bon::builder]
42pub async fn scores_get_by_id(
43    configuration: &configuration::Configuration,
44    score_id: &str,
45) -> Result<models::Score, Error<ScoresGetByIdError>> {
46    // add a prefix to parameters to efficiently prevent name collisions
47    let p_path_score_id = score_id;
48
49    let uri_str = format!(
50        "{}/api/public/v2/scores/{scoreId}",
51        configuration.base_path,
52        scoreId = crate::apis::urlencode(p_path_score_id)
53    );
54    let mut req_builder = configuration.client.request(reqwest::Method::GET, &uri_str);
55
56    if let Some(ref user_agent) = configuration.user_agent {
57        req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone());
58    }
59    if let Some(ref auth_conf) = configuration.basic_auth {
60        req_builder = req_builder.basic_auth(auth_conf.0.to_owned(), auth_conf.1.to_owned());
61    };
62
63    let req = req_builder.build()?;
64    let resp = configuration.client.execute(req).await?;
65
66    let status = resp.status();
67    let content_type = resp
68        .headers()
69        .get("content-type")
70        .and_then(|v| v.to_str().ok())
71        .unwrap_or("application/octet-stream");
72    let content_type = super::ContentType::from(content_type);
73
74    if !status.is_client_error() && !status.is_server_error() {
75        let content = resp.text().await?;
76        match content_type {
77            ContentType::Json => serde_json::from_str(&content).map_err(Error::from),
78            ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `models::Score`"))),
79            ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `models::Score`")))),
80        }
81    } else {
82        let content = resp.text().await?;
83        let entity: Option<ScoresGetByIdError> = serde_json::from_str(&content).ok();
84        Err(Error::ResponseError(ResponseContent {
85            status,
86            content,
87            entity,
88        }))
89    }
90}
91
92/// Get a list of scores (supports both trace and session scores)
93#[bon::builder]
94pub async fn scores_get_many(
95    configuration: &configuration::Configuration,
96    page: Option<i32>,
97    limit: Option<i32>,
98    user_id: Option<&str>,
99    name: Option<&str>,
100    from_timestamp: Option<String>,
101    to_timestamp: Option<String>,
102    environment: Option<Vec<String>>,
103    source: Option<models::ScoreSource>,
104    operator: Option<&str>,
105    value: Option<f64>,
106    score_ids: Option<&str>,
107    config_id: Option<&str>,
108    session_id: Option<&str>,
109    dataset_run_id: Option<&str>,
110    trace_id: Option<&str>,
111    observation_id: Option<&str>,
112    queue_id: Option<&str>,
113    data_type: Option<models::ScoreDataType>,
114    trace_tags: Option<Vec<String>>,
115    fields: Option<&str>,
116    filter: Option<&str>,
117) -> Result<models::GetScoresResponse, Error<ScoresGetManyError>> {
118    // add a prefix to parameters to efficiently prevent name collisions
119    let p_query_page = page;
120    let p_query_limit = limit;
121    let p_query_user_id = user_id;
122    let p_query_name = name;
123    let p_query_from_timestamp = from_timestamp;
124    let p_query_to_timestamp = to_timestamp;
125    let p_query_environment = environment;
126    let p_query_source = source;
127    let p_query_operator = operator;
128    let p_query_value = value;
129    let p_query_score_ids = score_ids;
130    let p_query_config_id = config_id;
131    let p_query_session_id = session_id;
132    let p_query_dataset_run_id = dataset_run_id;
133    let p_query_trace_id = trace_id;
134    let p_query_observation_id = observation_id;
135    let p_query_queue_id = queue_id;
136    let p_query_data_type = data_type;
137    let p_query_trace_tags = trace_tags;
138    let p_query_fields = fields;
139    let p_query_filter = filter;
140
141    let uri_str = format!("{}/api/public/v2/scores", configuration.base_path);
142    let mut req_builder = configuration.client.request(reqwest::Method::GET, &uri_str);
143
144    if let Some(ref param_value) = p_query_page {
145        req_builder = req_builder.query(&[("page", &param_value.to_string())]);
146    }
147    if let Some(ref param_value) = p_query_limit {
148        req_builder = req_builder.query(&[("limit", &param_value.to_string())]);
149    }
150    if let Some(ref param_value) = p_query_user_id {
151        req_builder = req_builder.query(&[("userId", &param_value.to_string())]);
152    }
153    if let Some(ref param_value) = p_query_name {
154        req_builder = req_builder.query(&[("name", &param_value.to_string())]);
155    }
156    if let Some(ref param_value) = p_query_from_timestamp {
157        req_builder = req_builder.query(&[("fromTimestamp", &param_value.to_string())]);
158    }
159    if let Some(ref param_value) = p_query_to_timestamp {
160        req_builder = req_builder.query(&[("toTimestamp", &param_value.to_string())]);
161    }
162    if let Some(ref param_value) = p_query_environment {
163        req_builder = match "multi" {
164            "multi" => req_builder.query(
165                &param_value
166                    .into_iter()
167                    .map(|p| ("environment".to_owned(), p.to_string()))
168                    .collect::<Vec<(std::string::String, std::string::String)>>(),
169            ),
170            _ => req_builder.query(&[(
171                "environment",
172                &param_value
173                    .into_iter()
174                    .map(|p| p.to_string())
175                    .collect::<Vec<String>>()
176                    .join(",")
177                    .to_string(),
178            )]),
179        };
180    }
181    if let Some(ref param_value) = p_query_source {
182        req_builder = req_builder.query(&[("source", &param_value.to_string())]);
183    }
184    if let Some(ref param_value) = p_query_operator {
185        req_builder = req_builder.query(&[("operator", &param_value.to_string())]);
186    }
187    if let Some(ref param_value) = p_query_value {
188        req_builder = req_builder.query(&[("value", &param_value.to_string())]);
189    }
190    if let Some(ref param_value) = p_query_score_ids {
191        req_builder = req_builder.query(&[("scoreIds", &param_value.to_string())]);
192    }
193    if let Some(ref param_value) = p_query_config_id {
194        req_builder = req_builder.query(&[("configId", &param_value.to_string())]);
195    }
196    if let Some(ref param_value) = p_query_session_id {
197        req_builder = req_builder.query(&[("sessionId", &param_value.to_string())]);
198    }
199    if let Some(ref param_value) = p_query_dataset_run_id {
200        req_builder = req_builder.query(&[("datasetRunId", &param_value.to_string())]);
201    }
202    if let Some(ref param_value) = p_query_trace_id {
203        req_builder = req_builder.query(&[("traceId", &param_value.to_string())]);
204    }
205    if let Some(ref param_value) = p_query_observation_id {
206        req_builder = req_builder.query(&[("observationId", &param_value.to_string())]);
207    }
208    if let Some(ref param_value) = p_query_queue_id {
209        req_builder = req_builder.query(&[("queueId", &param_value.to_string())]);
210    }
211    if let Some(ref param_value) = p_query_data_type {
212        req_builder = req_builder.query(&[("dataType", &param_value.to_string())]);
213    }
214    if let Some(ref param_value) = p_query_trace_tags {
215        req_builder = match "multi" {
216            "multi" => req_builder.query(
217                &param_value
218                    .into_iter()
219                    .map(|p| ("traceTags".to_owned(), p.to_string()))
220                    .collect::<Vec<(std::string::String, std::string::String)>>(),
221            ),
222            _ => req_builder.query(&[(
223                "traceTags",
224                &param_value
225                    .into_iter()
226                    .map(|p| p.to_string())
227                    .collect::<Vec<String>>()
228                    .join(",")
229                    .to_string(),
230            )]),
231        };
232    }
233    if let Some(ref param_value) = p_query_fields {
234        req_builder = req_builder.query(&[("fields", &param_value.to_string())]);
235    }
236    if let Some(ref param_value) = p_query_filter {
237        req_builder = req_builder.query(&[("filter", &param_value.to_string())]);
238    }
239    if let Some(ref user_agent) = configuration.user_agent {
240        req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone());
241    }
242    if let Some(ref auth_conf) = configuration.basic_auth {
243        req_builder = req_builder.basic_auth(auth_conf.0.to_owned(), auth_conf.1.to_owned());
244    };
245
246    let req = req_builder.build()?;
247    let resp = configuration.client.execute(req).await?;
248
249    let status = resp.status();
250    let content_type = resp
251        .headers()
252        .get("content-type")
253        .and_then(|v| v.to_str().ok())
254        .unwrap_or("application/octet-stream");
255    let content_type = super::ContentType::from(content_type);
256
257    if !status.is_client_error() && !status.is_server_error() {
258        let content = resp.text().await?;
259        match content_type {
260            ContentType::Json => serde_json::from_str(&content).map_err(Error::from),
261            ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `models::GetScoresResponse`"))),
262            ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `models::GetScoresResponse`")))),
263        }
264    } else {
265        let content = resp.text().await?;
266        let entity: Option<ScoresGetManyError> = serde_json::from_str(&content).ok();
267        Err(Error::ResponseError(ResponseContent {
268            status,
269            content,
270            entity,
271        }))
272    }
273}