Skip to main content

langfuse_client_base/apis/
observations_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 [`observations_get_many`]
17#[derive(Debug, Clone, Serialize, Deserialize)]
18#[serde(untagged)]
19pub enum ObservationsGetManyError {
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/// Get a list of observations with cursor-based pagination and flexible field selection.  Together with OpenTelemetry ingestion and Metrics API v2, this is the only real-time read path. Other public API endpoints can delay data by about 10 minutes.  ## Cursor-based Pagination This endpoint uses cursor-based pagination for efficient traversal of large datasets. The cursor is returned in the response metadata and should be passed in subsequent requests to retrieve the next page of results.  ## Field Selection Use the `fields` parameter to control which observation fields are returned: - `core` - Always included: id, traceId, startTime, endTime, projectId, parentObservationId, type - `basic` - name, level, statusMessage, version, environment, bookmarked, public, userId, sessionId, isRootObservation - `time` - completionStartTime, createdAt, updatedAt - `io` - input, output - `metadata` - metadata (truncated to 200 chars by default, use `expandMetadata` to get full values) - `model` - model, internalModelId, modelParameters - `usage` - usageDetails, costDetails, totalCost, usagePricingTierName - `prompt` - promptId, promptName, promptVersion - `metrics` - latency, timeToFirstToken - `trace_context` - tags, release, traceName  If not specified, `core` and `basic` field groups are returned.  ## Filters Multiple filtering options are available via query parameters or the structured `filter` parameter. When using the `filter` parameter, it takes precedence over individual query parameter filters.
29#[bon::builder]
30pub async fn observations_get_many(
31    configuration: &configuration::Configuration,
32    fields: Option<&str>,
33    expand_metadata: Option<&str>,
34    limit: Option<i32>,
35    cursor: Option<&str>,
36    parse_io_as_json: Option<bool>,
37    name: Option<&str>,
38    user_id: Option<&str>,
39    session_id: Option<&str>,
40    r#type: Option<&str>,
41    trace_id: Option<&str>,
42    level: Option<models::ObservationLevel>,
43    parent_observation_id: Option<&str>,
44    is_root_observation: Option<bool>,
45    environment: Option<Vec<String>>,
46    from_start_time: Option<chrono::DateTime<chrono::FixedOffset>>,
47    to_start_time: Option<chrono::DateTime<chrono::FixedOffset>>,
48    version: Option<&str>,
49    filter: Option<&str>,
50) -> Result<models::ObservationsV2Response, Error<ObservationsGetManyError>> {
51    // add a prefix to parameters to efficiently prevent name collisions
52    let p_query_fields = fields;
53    let p_query_expand_metadata = expand_metadata;
54    let p_query_limit = limit;
55    let p_query_cursor = cursor;
56    let p_query_parse_io_as_json = parse_io_as_json;
57    let p_query_name = name;
58    let p_query_user_id = user_id;
59    let p_query_session_id = session_id;
60    let p_query_type = r#type;
61    let p_query_trace_id = trace_id;
62    let p_query_level = level;
63    let p_query_parent_observation_id = parent_observation_id;
64    let p_query_is_root_observation = is_root_observation;
65    let p_query_environment = environment;
66    let p_query_from_start_time = from_start_time;
67    let p_query_to_start_time = to_start_time;
68    let p_query_version = version;
69    let p_query_filter = filter;
70
71    let uri_str = format!("{}/api/public/v2/observations", configuration.base_path);
72    let mut req_builder = configuration.client.request(reqwest::Method::GET, &uri_str);
73
74    if let Some(ref param_value) = p_query_fields {
75        req_builder = req_builder.query(&[("fields", &param_value.to_string())]);
76    }
77    if let Some(ref param_value) = p_query_expand_metadata {
78        req_builder = req_builder.query(&[("expandMetadata", &param_value.to_string())]);
79    }
80    if let Some(ref param_value) = p_query_limit {
81        req_builder = req_builder.query(&[("limit", &param_value.to_string())]);
82    }
83    if let Some(ref param_value) = p_query_cursor {
84        req_builder = req_builder.query(&[("cursor", &param_value.to_string())]);
85    }
86    if let Some(ref param_value) = p_query_parse_io_as_json {
87        req_builder = req_builder.query(&[("parseIoAsJson", &param_value.to_string())]);
88    }
89    if let Some(ref param_value) = p_query_name {
90        req_builder = req_builder.query(&[("name", &param_value.to_string())]);
91    }
92    if let Some(ref param_value) = p_query_user_id {
93        req_builder = req_builder.query(&[("userId", &param_value.to_string())]);
94    }
95    if let Some(ref param_value) = p_query_session_id {
96        req_builder = req_builder.query(&[("sessionId", &param_value.to_string())]);
97    }
98    if let Some(ref param_value) = p_query_type {
99        req_builder = req_builder.query(&[("type", &param_value.to_string())]);
100    }
101    if let Some(ref param_value) = p_query_trace_id {
102        req_builder = req_builder.query(&[("traceId", &param_value.to_string())]);
103    }
104    if let Some(ref param_value) = p_query_level {
105        req_builder = req_builder.query(&[("level", &param_value.to_string())]);
106    }
107    if let Some(ref param_value) = p_query_parent_observation_id {
108        req_builder = req_builder.query(&[("parentObservationId", &param_value.to_string())]);
109    }
110    if let Some(ref param_value) = p_query_is_root_observation {
111        req_builder = req_builder.query(&[("isRootObservation", &param_value.to_string())]);
112    }
113    if let Some(ref param_value) = p_query_environment {
114        req_builder = match "multi" {
115            "multi" => req_builder.query(
116                &param_value
117                    .into_iter()
118                    .map(|p| ("environment".to_owned(), p.to_string()))
119                    .collect::<Vec<(std::string::String, std::string::String)>>(),
120            ),
121            _ => req_builder.query(&[(
122                "environment",
123                &param_value
124                    .into_iter()
125                    .map(|p| p.to_string())
126                    .collect::<Vec<String>>()
127                    .join(",")
128                    .to_string(),
129            )]),
130        };
131    }
132    if let Some(ref param_value) = p_query_from_start_time {
133        req_builder = req_builder.query(&[("fromStartTime", &param_value.to_string())]);
134    }
135    if let Some(ref param_value) = p_query_to_start_time {
136        req_builder = req_builder.query(&[("toStartTime", &param_value.to_string())]);
137    }
138    if let Some(ref param_value) = p_query_version {
139        req_builder = req_builder.query(&[("version", &param_value.to_string())]);
140    }
141    if let Some(ref param_value) = p_query_filter {
142        req_builder = req_builder.query(&[("filter", &param_value.to_string())]);
143    }
144    if let Some(ref user_agent) = configuration.user_agent {
145        req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone());
146    }
147    if let Some(ref auth_conf) = configuration.basic_auth {
148        req_builder = req_builder.basic_auth(auth_conf.0.to_owned(), auth_conf.1.to_owned());
149    };
150
151    let req = req_builder.build()?;
152    let resp = configuration.client.execute(req).await?;
153
154    let status = resp.status();
155    let content_type = resp
156        .headers()
157        .get("content-type")
158        .and_then(|v| v.to_str().ok())
159        .unwrap_or("application/octet-stream");
160    let content_type = super::ContentType::from(content_type);
161
162    if !status.is_client_error() && !status.is_server_error() {
163        let content = resp.text().await?;
164        match content_type {
165            ContentType::Json => serde_json::from_str(&content).map_err(Error::from),
166            ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `models::ObservationsV2Response`"))),
167            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::ObservationsV2Response`")))),
168        }
169    } else {
170        let content = resp.text().await?;
171        let entity: Option<ObservationsGetManyError> = serde_json::from_str(&content).ok();
172        Err(Error::ResponseError(ResponseContent {
173            status,
174            content,
175            entity,
176        }))
177    }
178}