Skip to main content

langfuse_client_base/apis/
scores_api.rs

1/*
2 * server
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_create`]
17#[derive(Debug, Clone, Serialize, Deserialize)]
18#[serde(untagged)]
19pub enum ScoresCreateError {
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_by_id`]
29#[derive(Debug, Clone, Serialize, Deserialize)]
30#[serde(untagged)]
31pub enum ScoresGetByIdError {
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/// struct for typed errors of method [`scores_get_many`]
41#[derive(Debug, Clone, Serialize, Deserialize)]
42#[serde(untagged)]
43pub enum ScoresGetManyError {
44    Status400(serde_json::Value),
45    Status401(serde_json::Value),
46    Status403(serde_json::Value),
47    Status404(serde_json::Value),
48    Status405(serde_json::Value),
49    UnknownValue(serde_json::Value),
50}
51
52/// Create a score (supports trace, observation, session, and dataset run scores)
53#[bon::builder]
54pub async fn scores_create(
55    configuration: &configuration::Configuration,
56    create_score_request: models::CreateScoreRequest,
57) -> Result<models::CreateScoreResponse, Error<ScoresCreateError>> {
58    // add a prefix to parameters to efficiently prevent name collisions
59    let p_body_create_score_request = create_score_request;
60
61    let uri_str = format!("{}/api/public/scores", configuration.base_path);
62    let mut req_builder = configuration
63        .client
64        .request(reqwest::Method::POST, &uri_str);
65
66    if let Some(ref user_agent) = configuration.user_agent {
67        req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone());
68    }
69    if let Some(ref auth_conf) = configuration.basic_auth {
70        req_builder = req_builder.basic_auth(auth_conf.0.to_owned(), auth_conf.1.to_owned());
71    };
72    req_builder = req_builder.json(&p_body_create_score_request);
73
74    let req = req_builder.build()?;
75    let resp = configuration.client.execute(req).await?;
76
77    let status = resp.status();
78    let content_type = resp
79        .headers()
80        .get("content-type")
81        .and_then(|v| v.to_str().ok())
82        .unwrap_or("application/octet-stream");
83    let content_type = super::ContentType::from(content_type);
84
85    if !status.is_client_error() && !status.is_server_error() {
86        let content = resp.text().await?;
87        match content_type {
88            ContentType::Json => serde_json::from_str(&content).map_err(Error::from),
89            ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `models::CreateScoreResponse`"))),
90            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::CreateScoreResponse`")))),
91        }
92    } else {
93        let content = resp.text().await?;
94        let entity: Option<ScoresCreateError> = serde_json::from_str(&content).ok();
95        Err(Error::ResponseError(ResponseContent {
96            status,
97            content,
98            entity,
99        }))
100    }
101}
102
103/// **Deprecated.** Use `GET /api/public/v3/scores` with the `id` filter instead. This endpoint is no longer available on Langfuse v4 and later.  Get a score (supports both trace and session scores)
104#[bon::builder]
105pub async fn scores_get_by_id(
106    configuration: &configuration::Configuration,
107    score_id: &str,
108) -> Result<models::Score, Error<ScoresGetByIdError>> {
109    // add a prefix to parameters to efficiently prevent name collisions
110    let p_path_score_id = score_id;
111
112    let uri_str = format!(
113        "{}/api/public/v2/scores/{scoreId}",
114        configuration.base_path,
115        scoreId = crate::apis::urlencode(p_path_score_id)
116    );
117    let mut req_builder = configuration.client.request(reqwest::Method::GET, &uri_str);
118
119    if let Some(ref user_agent) = configuration.user_agent {
120        req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone());
121    }
122    if let Some(ref auth_conf) = configuration.basic_auth {
123        req_builder = req_builder.basic_auth(auth_conf.0.to_owned(), auth_conf.1.to_owned());
124    };
125
126    let req = req_builder.build()?;
127    let resp = configuration.client.execute(req).await?;
128
129    let status = resp.status();
130    let content_type = resp
131        .headers()
132        .get("content-type")
133        .and_then(|v| v.to_str().ok())
134        .unwrap_or("application/octet-stream");
135    let content_type = super::ContentType::from(content_type);
136
137    if !status.is_client_error() && !status.is_server_error() {
138        let content = resp.text().await?;
139        match content_type {
140            ContentType::Json => serde_json::from_str(&content).map_err(Error::from),
141            ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `models::Score`"))),
142            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`")))),
143        }
144    } else {
145        let content = resp.text().await?;
146        let entity: Option<ScoresGetByIdError> = serde_json::from_str(&content).ok();
147        Err(Error::ResponseError(ResponseContent {
148            status,
149            content,
150            entity,
151        }))
152    }
153}
154
155/// **Deprecated.** Use `GET /api/public/v3/scores` instead. This endpoint is no longer available on Langfuse v4 and later.  Get a list of scores (supports both trace and session scores)
156#[bon::builder]
157pub async fn scores_get_many(
158    configuration: &configuration::Configuration,
159    page: Option<i32>,
160    limit: Option<i32>,
161    user_id: Option<&str>,
162    name: Option<&str>,
163    from_timestamp: Option<chrono::DateTime<chrono::FixedOffset>>,
164    to_timestamp: Option<chrono::DateTime<chrono::FixedOffset>>,
165    environment: Option<Vec<String>>,
166    source: Option<models::ScoreSource>,
167    operator: Option<&str>,
168    value: Option<f64>,
169    score_ids: Option<&str>,
170    config_id: Option<&str>,
171    session_id: Option<&str>,
172    dataset_run_id: Option<&str>,
173    trace_id: Option<&str>,
174    observation_id: Option<&str>,
175    queue_id: Option<&str>,
176    data_type: Option<models::ScoreDataType>,
177    trace_tags: Option<Vec<String>>,
178    fields: Option<&str>,
179    filter: Option<&str>,
180) -> Result<models::GetScoresResponse, Error<ScoresGetManyError>> {
181    // add a prefix to parameters to efficiently prevent name collisions
182    let p_query_page = page;
183    let p_query_limit = limit;
184    let p_query_user_id = user_id;
185    let p_query_name = name;
186    let p_query_from_timestamp = from_timestamp;
187    let p_query_to_timestamp = to_timestamp;
188    let p_query_environment = environment;
189    let p_query_source = source;
190    let p_query_operator = operator;
191    let p_query_value = value;
192    let p_query_score_ids = score_ids;
193    let p_query_config_id = config_id;
194    let p_query_session_id = session_id;
195    let p_query_dataset_run_id = dataset_run_id;
196    let p_query_trace_id = trace_id;
197    let p_query_observation_id = observation_id;
198    let p_query_queue_id = queue_id;
199    let p_query_data_type = data_type;
200    let p_query_trace_tags = trace_tags;
201    let p_query_fields = fields;
202    let p_query_filter = filter;
203
204    let uri_str = format!("{}/api/public/v2/scores", configuration.base_path);
205    let mut req_builder = configuration.client.request(reqwest::Method::GET, &uri_str);
206
207    if let Some(ref param_value) = p_query_page {
208        req_builder = req_builder.query(&[("page", &param_value.to_string())]);
209    }
210    if let Some(ref param_value) = p_query_limit {
211        req_builder = req_builder.query(&[("limit", &param_value.to_string())]);
212    }
213    if let Some(ref param_value) = p_query_user_id {
214        req_builder = req_builder.query(&[("userId", &param_value.to_string())]);
215    }
216    if let Some(ref param_value) = p_query_name {
217        req_builder = req_builder.query(&[("name", &param_value.to_string())]);
218    }
219    if let Some(ref param_value) = p_query_from_timestamp {
220        req_builder = req_builder.query(&[("fromTimestamp", &param_value.to_string())]);
221    }
222    if let Some(ref param_value) = p_query_to_timestamp {
223        req_builder = req_builder.query(&[("toTimestamp", &param_value.to_string())]);
224    }
225    if let Some(ref param_value) = p_query_environment {
226        req_builder = match "multi" {
227            "multi" => req_builder.query(
228                &param_value
229                    .into_iter()
230                    .map(|p| ("environment".to_owned(), p.to_string()))
231                    .collect::<Vec<(std::string::String, std::string::String)>>(),
232            ),
233            _ => req_builder.query(&[(
234                "environment",
235                &param_value
236                    .into_iter()
237                    .map(|p| p.to_string())
238                    .collect::<Vec<String>>()
239                    .join(",")
240                    .to_string(),
241            )]),
242        };
243    }
244    if let Some(ref param_value) = p_query_source {
245        req_builder = req_builder.query(&[("source", &param_value.to_string())]);
246    }
247    if let Some(ref param_value) = p_query_operator {
248        req_builder = req_builder.query(&[("operator", &param_value.to_string())]);
249    }
250    if let Some(ref param_value) = p_query_value {
251        req_builder = req_builder.query(&[("value", &param_value.to_string())]);
252    }
253    if let Some(ref param_value) = p_query_score_ids {
254        req_builder = req_builder.query(&[("scoreIds", &param_value.to_string())]);
255    }
256    if let Some(ref param_value) = p_query_config_id {
257        req_builder = req_builder.query(&[("configId", &param_value.to_string())]);
258    }
259    if let Some(ref param_value) = p_query_session_id {
260        req_builder = req_builder.query(&[("sessionId", &param_value.to_string())]);
261    }
262    if let Some(ref param_value) = p_query_dataset_run_id {
263        req_builder = req_builder.query(&[("datasetRunId", &param_value.to_string())]);
264    }
265    if let Some(ref param_value) = p_query_trace_id {
266        req_builder = req_builder.query(&[("traceId", &param_value.to_string())]);
267    }
268    if let Some(ref param_value) = p_query_observation_id {
269        req_builder = req_builder.query(&[("observationId", &param_value.to_string())]);
270    }
271    if let Some(ref param_value) = p_query_queue_id {
272        req_builder = req_builder.query(&[("queueId", &param_value.to_string())]);
273    }
274    if let Some(ref param_value) = p_query_data_type {
275        req_builder = req_builder.query(&[("dataType", &param_value.to_string())]);
276    }
277    if let Some(ref param_value) = p_query_trace_tags {
278        req_builder = match "multi" {
279            "multi" => req_builder.query(
280                &param_value
281                    .into_iter()
282                    .map(|p| ("traceTags".to_owned(), p.to_string()))
283                    .collect::<Vec<(std::string::String, std::string::String)>>(),
284            ),
285            _ => req_builder.query(&[(
286                "traceTags",
287                &param_value
288                    .into_iter()
289                    .map(|p| p.to_string())
290                    .collect::<Vec<String>>()
291                    .join(",")
292                    .to_string(),
293            )]),
294        };
295    }
296    if let Some(ref param_value) = p_query_fields {
297        req_builder = req_builder.query(&[("fields", &param_value.to_string())]);
298    }
299    if let Some(ref param_value) = p_query_filter {
300        req_builder = req_builder.query(&[("filter", &param_value.to_string())]);
301    }
302    if let Some(ref user_agent) = configuration.user_agent {
303        req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone());
304    }
305    if let Some(ref auth_conf) = configuration.basic_auth {
306        req_builder = req_builder.basic_auth(auth_conf.0.to_owned(), auth_conf.1.to_owned());
307    };
308
309    let req = req_builder.build()?;
310    let resp = configuration.client.execute(req).await?;
311
312    let status = resp.status();
313    let content_type = resp
314        .headers()
315        .get("content-type")
316        .and_then(|v| v.to_str().ok())
317        .unwrap_or("application/octet-stream");
318    let content_type = super::ContentType::from(content_type);
319
320    if !status.is_client_error() && !status.is_server_error() {
321        let content = resp.text().await?;
322        match content_type {
323            ContentType::Json => serde_json::from_str(&content).map_err(Error::from),
324            ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `models::GetScoresResponse`"))),
325            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`")))),
326        }
327    } else {
328        let content = resp.text().await?;
329        let entity: Option<ScoresGetManyError> = serde_json::from_str(&content).ok();
330        Err(Error::ResponseError(ResponseContent {
331            status,
332            content,
333            entity,
334        }))
335    }
336}