Skip to main content

langfuse_client_base/apis/
scores_api.rs

1/*
2 * server
3 *
4 * ## Real-time data  The only real-time path to get tracing data is to ingest via OpenTelemetry (`POST /api/public/otel/v1/traces`) and retrieve via Observations API v2 (`GET /api/public/v2/observations`) and Metrics API v2 (`GET /api/public/v2/metrics`). Other public API write and read endpoints can delay data by about 10 minutes. Direct OpenTelemetry exporters must send the `x-langfuse-ingestion-version: 4` header; current Python and JS SDKs already do. See the [Public API docs](https://langfuse.com/docs/api-and-data-platform/features/public-api) and [real-time ingestion](https://langfuse.com/integrations/native/opentelemetry.md#real-time-ingestion).  ## 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 - Self-hosted deployments: interactive API reference at `/api/docs` and OpenAPI spec at `/api/openapi.yaml`
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:** On Langfuse Cloud, Langfuse v3 is deprecated and this endpoint will be removed on November 16, 2026. Use `GET /api/public/v3/scores` with the `id` filter instead. Self-hosted deployments are unaffected by this date; the endpoint becomes unavailable when they upgrade to Langfuse v4. See the [Langfuse v3 to v4 upgrade guide](https://langfuse.com/self-hosting/upgrade/upgrade-guides/upgrade-v3-to-v4).  Get a score (supports both trace and session scores)
104#[deprecated]
105#[bon::builder]
106pub async fn scores_get_by_id(
107    configuration: &configuration::Configuration,
108    score_id: &str,
109) -> Result<models::Score, Error<ScoresGetByIdError>> {
110    // add a prefix to parameters to efficiently prevent name collisions
111    let p_path_score_id = score_id;
112
113    let uri_str = format!(
114        "{}/api/public/v2/scores/{scoreId}",
115        configuration.base_path,
116        scoreId = crate::apis::urlencode(p_path_score_id)
117    );
118    let mut req_builder = configuration.client.request(reqwest::Method::GET, &uri_str);
119
120    if let Some(ref user_agent) = configuration.user_agent {
121        req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone());
122    }
123    if let Some(ref auth_conf) = configuration.basic_auth {
124        req_builder = req_builder.basic_auth(auth_conf.0.to_owned(), auth_conf.1.to_owned());
125    };
126
127    let req = req_builder.build()?;
128    let resp = configuration.client.execute(req).await?;
129
130    let status = resp.status();
131    let content_type = resp
132        .headers()
133        .get("content-type")
134        .and_then(|v| v.to_str().ok())
135        .unwrap_or("application/octet-stream");
136    let content_type = super::ContentType::from(content_type);
137
138    if !status.is_client_error() && !status.is_server_error() {
139        let content = resp.text().await?;
140        match content_type {
141            ContentType::Json => serde_json::from_str(&content).map_err(Error::from),
142            ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `models::Score`"))),
143            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`")))),
144        }
145    } else {
146        let content = resp.text().await?;
147        let entity: Option<ScoresGetByIdError> = serde_json::from_str(&content).ok();
148        Err(Error::ResponseError(ResponseContent {
149            status,
150            content,
151            entity,
152        }))
153    }
154}
155
156/// **Deprecated:** On Langfuse Cloud, Langfuse v3 is deprecated and this endpoint will be removed on November 16, 2026. Use `GET /api/public/v3/scores` instead. Self-hosted deployments are unaffected by this date; the endpoint becomes unavailable when they upgrade to Langfuse v4. See the [Langfuse v3 to v4 upgrade guide](https://langfuse.com/self-hosting/upgrade/upgrade-guides/upgrade-v3-to-v4).  Get a list of scores (supports both trace and session scores)
157#[deprecated]
158#[bon::builder]
159pub async fn scores_get_many(
160    configuration: &configuration::Configuration,
161    page: Option<i32>,
162    limit: Option<i32>,
163    user_id: Option<&str>,
164    name: Option<&str>,
165    from_timestamp: Option<chrono::DateTime<chrono::FixedOffset>>,
166    to_timestamp: Option<chrono::DateTime<chrono::FixedOffset>>,
167    environment: Option<Vec<String>>,
168    source: Option<models::ScoreSource>,
169    operator: Option<&str>,
170    value: Option<f64>,
171    score_ids: Option<&str>,
172    config_id: Option<&str>,
173    session_id: Option<&str>,
174    dataset_run_id: Option<&str>,
175    trace_id: Option<&str>,
176    observation_id: Option<&str>,
177    queue_id: Option<&str>,
178    data_type: Option<models::ScoreDataType>,
179    trace_tags: Option<Vec<String>>,
180    fields: Option<&str>,
181    filter: Option<&str>,
182) -> Result<models::GetScoresResponse, Error<ScoresGetManyError>> {
183    // add a prefix to parameters to efficiently prevent name collisions
184    let p_query_page = page;
185    let p_query_limit = limit;
186    let p_query_user_id = user_id;
187    let p_query_name = name;
188    let p_query_from_timestamp = from_timestamp;
189    let p_query_to_timestamp = to_timestamp;
190    let p_query_environment = environment;
191    let p_query_source = source;
192    let p_query_operator = operator;
193    let p_query_value = value;
194    let p_query_score_ids = score_ids;
195    let p_query_config_id = config_id;
196    let p_query_session_id = session_id;
197    let p_query_dataset_run_id = dataset_run_id;
198    let p_query_trace_id = trace_id;
199    let p_query_observation_id = observation_id;
200    let p_query_queue_id = queue_id;
201    let p_query_data_type = data_type;
202    let p_query_trace_tags = trace_tags;
203    let p_query_fields = fields;
204    let p_query_filter = filter;
205
206    let uri_str = format!("{}/api/public/v2/scores", configuration.base_path);
207    let mut req_builder = configuration.client.request(reqwest::Method::GET, &uri_str);
208
209    if let Some(ref param_value) = p_query_page {
210        req_builder = req_builder.query(&[("page", &param_value.to_string())]);
211    }
212    if let Some(ref param_value) = p_query_limit {
213        req_builder = req_builder.query(&[("limit", &param_value.to_string())]);
214    }
215    if let Some(ref param_value) = p_query_user_id {
216        req_builder = req_builder.query(&[("userId", &param_value.to_string())]);
217    }
218    if let Some(ref param_value) = p_query_name {
219        req_builder = req_builder.query(&[("name", &param_value.to_string())]);
220    }
221    if let Some(ref param_value) = p_query_from_timestamp {
222        req_builder = req_builder.query(&[("fromTimestamp", &param_value.to_string())]);
223    }
224    if let Some(ref param_value) = p_query_to_timestamp {
225        req_builder = req_builder.query(&[("toTimestamp", &param_value.to_string())]);
226    }
227    if let Some(ref param_value) = p_query_environment {
228        req_builder = match "multi" {
229            "multi" => req_builder.query(
230                &param_value
231                    .into_iter()
232                    .map(|p| ("environment".to_owned(), p.to_string()))
233                    .collect::<Vec<(std::string::String, std::string::String)>>(),
234            ),
235            _ => req_builder.query(&[(
236                "environment",
237                &param_value
238                    .into_iter()
239                    .map(|p| p.to_string())
240                    .collect::<Vec<String>>()
241                    .join(",")
242                    .to_string(),
243            )]),
244        };
245    }
246    if let Some(ref param_value) = p_query_source {
247        req_builder = req_builder.query(&[("source", &param_value.to_string())]);
248    }
249    if let Some(ref param_value) = p_query_operator {
250        req_builder = req_builder.query(&[("operator", &param_value.to_string())]);
251    }
252    if let Some(ref param_value) = p_query_value {
253        req_builder = req_builder.query(&[("value", &param_value.to_string())]);
254    }
255    if let Some(ref param_value) = p_query_score_ids {
256        req_builder = req_builder.query(&[("scoreIds", &param_value.to_string())]);
257    }
258    if let Some(ref param_value) = p_query_config_id {
259        req_builder = req_builder.query(&[("configId", &param_value.to_string())]);
260    }
261    if let Some(ref param_value) = p_query_session_id {
262        req_builder = req_builder.query(&[("sessionId", &param_value.to_string())]);
263    }
264    if let Some(ref param_value) = p_query_dataset_run_id {
265        req_builder = req_builder.query(&[("datasetRunId", &param_value.to_string())]);
266    }
267    if let Some(ref param_value) = p_query_trace_id {
268        req_builder = req_builder.query(&[("traceId", &param_value.to_string())]);
269    }
270    if let Some(ref param_value) = p_query_observation_id {
271        req_builder = req_builder.query(&[("observationId", &param_value.to_string())]);
272    }
273    if let Some(ref param_value) = p_query_queue_id {
274        req_builder = req_builder.query(&[("queueId", &param_value.to_string())]);
275    }
276    if let Some(ref param_value) = p_query_data_type {
277        req_builder = req_builder.query(&[("dataType", &param_value.to_string())]);
278    }
279    if let Some(ref param_value) = p_query_trace_tags {
280        req_builder = match "multi" {
281            "multi" => req_builder.query(
282                &param_value
283                    .into_iter()
284                    .map(|p| ("traceTags".to_owned(), p.to_string()))
285                    .collect::<Vec<(std::string::String, std::string::String)>>(),
286            ),
287            _ => req_builder.query(&[(
288                "traceTags",
289                &param_value
290                    .into_iter()
291                    .map(|p| p.to_string())
292                    .collect::<Vec<String>>()
293                    .join(",")
294                    .to_string(),
295            )]),
296        };
297    }
298    if let Some(ref param_value) = p_query_fields {
299        req_builder = req_builder.query(&[("fields", &param_value.to_string())]);
300    }
301    if let Some(ref param_value) = p_query_filter {
302        req_builder = req_builder.query(&[("filter", &param_value.to_string())]);
303    }
304    if let Some(ref user_agent) = configuration.user_agent {
305        req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone());
306    }
307    if let Some(ref auth_conf) = configuration.basic_auth {
308        req_builder = req_builder.basic_auth(auth_conf.0.to_owned(), auth_conf.1.to_owned());
309    };
310
311    let req = req_builder.build()?;
312    let resp = configuration.client.execute(req).await?;
313
314    let status = resp.status();
315    let content_type = resp
316        .headers()
317        .get("content-type")
318        .and_then(|v| v.to_str().ok())
319        .unwrap_or("application/octet-stream");
320    let content_type = super::ContentType::from(content_type);
321
322    if !status.is_client_error() && !status.is_server_error() {
323        let content = resp.text().await?;
324        match content_type {
325            ContentType::Json => serde_json::from_str(&content).map_err(Error::from),
326            ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `models::GetScoresResponse`"))),
327            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`")))),
328        }
329    } else {
330        let content = resp.text().await?;
331        let entity: Option<ScoresGetManyError> = serde_json::from_str(&content).ok();
332        Err(Error::ResponseError(ResponseContent {
333            status,
334            content,
335            entity,
336        }))
337    }
338}