use langfuse_core::error::LangfuseError;
use langfuse_core::types::{ScoreBody, ScoreValue};
use opentelemetry::Context;
use opentelemetry::trace::TraceContextExt;
use super::context::{get_current_observation_id, get_current_trace_id};
use super::generation::LangfuseGeneration;
use super::span::LangfuseSpan;
use crate::client::Langfuse;
pub fn update_current_span(f: impl FnOnce(&LangfuseSpan)) {
let cx = Context::current();
let span = cx.span();
let sc = span.span_context();
if sc.is_valid() {
let langfuse_span = LangfuseSpan::from_context(cx.clone());
f(&langfuse_span);
}
}
pub fn update_current_generation(f: impl FnOnce(&LangfuseGeneration)) {
let cx = Context::current();
let span = cx.span();
if span.span_context().is_valid() {
let generation = LangfuseGeneration::from_context(cx.clone());
f(&generation);
}
}
pub fn score_current_span(name: &str, value: ScoreValue) -> Result<(), LangfuseError> {
let trace_id =
get_current_trace_id().ok_or_else(|| LangfuseError::Otel("no active span".into()))?;
let obs_id =
get_current_observation_id().ok_or_else(|| LangfuseError::Otel("no active span".into()))?;
let langfuse = Langfuse::try_get()
.ok_or_else(|| LangfuseError::Otel("Langfuse not initialized".into()))?;
langfuse
.scores
.score_observation(&trace_id, &obs_id, name, value);
Ok(())
}
pub fn score_current_span_with(mut body: ScoreBody) -> Result<(), LangfuseError> {
let trace_id =
get_current_trace_id().ok_or_else(|| LangfuseError::Otel("no active span".into()))?;
let obs_id =
get_current_observation_id().ok_or_else(|| LangfuseError::Otel("no active span".into()))?;
let langfuse = Langfuse::try_get()
.ok_or_else(|| LangfuseError::Otel("Langfuse not initialized".into()))?;
body.trace_id = Some(trace_id);
body.observation_id = Some(obs_id);
langfuse.scores.score(body);
Ok(())
}
pub fn score_current_trace(name: &str, value: ScoreValue) -> Result<(), LangfuseError> {
let trace_id =
get_current_trace_id().ok_or_else(|| LangfuseError::Otel("no active span".into()))?;
let langfuse = Langfuse::try_get()
.ok_or_else(|| LangfuseError::Otel("Langfuse not initialized".into()))?;
langfuse.scores.score_trace(&trace_id, name, value);
Ok(())
}
pub fn get_current_trace_url() -> Result<String, LangfuseError> {
let trace_id =
get_current_trace_id().ok_or_else(|| LangfuseError::Otel("no active span".into()))?;
let langfuse = Langfuse::try_get()
.ok_or_else(|| LangfuseError::Otel("Langfuse not initialized".into()))?;
Ok(langfuse.get_trace_url(&trace_id))
}
pub fn set_current_trace_as_public() {
let cx = Context::current();
let span = cx.span();
if span.span_context().is_valid() {
let langfuse_span = LangfuseSpan::from_context(cx.clone());
langfuse_span.set_trace_as_public();
}
}