NAME

Langertha::Knarr::Tracing - Automatic Langfuse tracing per proxy request

VERSION

version 0.004

SYNOPSIS

use Langertha::Knarr::Tracing;

my $tracing = Langertha::Knarr::Tracing->new(config => $config);

my $trace_id = $tracing->start_trace(
  model    => 'gpt-4o',
  engine   => 'Langertha::Engine::OpenAI',
  messages => \@messages,
  params   => \%params,
  format   => 'openai',
);

# ... handle request ...

$tracing->end_trace($trace_id,
  output => $response_text,
  model  => 'gpt-4o',
  usage  => { input => 100, output => 50, total => 150 },
);

DESCRIPTION

Records every proxy request as a Langfuse trace with a nested generation. When tracing is not configured (no public and secret key), all methods are no-ops.

Langfuse credentials are read from the config file's langfuse: section or from the LANGFUSE_PUBLIC_KEY, LANGFUSE_SECRET_KEY, and LANGFUSE_URL environment variables. The module strips surrounding quotes from environment variable values, which Docker --env-file sometimes adds literally.

config

The Langertha::Knarr::Config object. Required. Provides Langfuse credentials and trace_name.

trace_name

The Langfuse trace name applied to all traces. Resolved in priority order from: langfuse.trace_name in config, LANGFUSE_TRACE_NAME env var, KNARR_TRACE_NAME env var, or the default knarr-proxy.

start_trace

my $trace_info = $tracing->start_trace(
  model    => $model_name,
  engine   => $engine_class,
  messages => \@messages,
  params   => \%params,
  format   => 'openai',
);

Creates a new Langfuse trace and generation. Returns a $trace_info hashref that must be passed to "end_trace". Returns undef when tracing is disabled.

end_trace

$tracing->end_trace($trace_info,
  output => $response_text,
  model  => $model,
  usage  => { input => 100, output => 50, total => 150 },
);

# On error:
$tracing->end_trace($trace_info, error => "Something went wrong");

Closes the generation and trace started by "start_trace", then flushes the batch to Langfuse. Pass error to record a failed generation at level ERROR. Does nothing when $trace_info is undef (tracing was disabled at start).

flush

$tracing->flush;

Sends all pending trace events to the Langfuse ingestion API as a batch and clears the internal buffer. Called automatically by "end_trace". Does nothing when tracing is disabled or the batch is empty.

SEE ALSO

SUPPORT

Issues

Please report bugs and feature requests on GitHub at https://github.com/Getty/langertha-knarr/issues.

CONTRIBUTING

Contributions are welcome! Please fork the repository and submit a pull request.

AUTHOR

Torsten Raudssus <torsten@raudssus.de> https://raudssus.de/

COPYRIGHT AND LICENSE

This software is copyright (c) 2026 by Torsten Raudssus.

This is free software; you can redistribute it and/or modify it under the same terms as the Perl 5 programming language system itself.