### Copy Environment Example Source: https://github.com/langfuse/langfuse-java/blob/main/README.md Copy the .env.example file to .env and fill in your API keys for integration tests. ```bash cp .env.example .env ``` -------------------------------- ### Initialize LangfuseClient with Multiple Options Source: https://github.com/langfuse/langfuse-java/blob/main/_autodocs/client-initialization.md Example demonstrating the initialization of LangfuseClient with several configuration options chained together. ```java LangfuseClient client = LangfuseClient.builder() .url("https://cloud.langfuse.com") .credentials("pk-lf-...", "sk-lf-...") .timeout(120) .maxRetries(3) .build(); ``` -------------------------------- ### TextPrompt Example Source: https://github.com/langfuse/langfuse-java/blob/main/_autodocs/types.md Creates a TextPrompt object with a name and a template string containing placeholders. ```java TextPrompt prompt = TextPrompt.builder() .name("greeting") .prompt("Hello {{name}}, welcome to {{place}}!") .build(); ``` -------------------------------- ### Async Batch Processing Example Source: https://github.com/langfuse/langfuse-java/blob/main/_autodocs/api-async-and-v2.md Illustrates how to fetch multiple prompts concurrently using `CompletableFuture.allOf` for efficient batch processing. ```APIDOC ## Async Batch Processing Example ### Description Processes multiple prompts concurrently by initiating individual asynchronous requests and waiting for all of them to complete. ### Method `client.prompts().get(String promptId)` used in a loop with `CompletableFuture.allOf`. ### Usage ```java import com.langfuse.client.AsyncLangfuseClient; import com.langfuse.client.prompts.AsyncPromptsClient; import com.langfuse.client.prompts.types.Prompt; import java.util.ArrayList; import java.util.List; import java.util.concurrent.CompletableFuture; AsyncLangfuseClient client = ...; // Assume client is already built AsyncPromptsClient prompts = client.prompts(); List promptNames = List.of("prompt1", "prompt2", "prompt3"); List> futures = new ArrayList<>(); for (String name : promptNames) { futures.add(prompts.get(name)); } CompletableFuture.allOf(futures.toArray(new CompletableFuture[0])) .thenAccept(v -> { futures.forEach(f -> { try { Prompt prompt = f.get(); System.out.println("Loaded: " + prompt); } catch (Exception e) { System.err.println("Error: " + e); } }); }) .get(); // Blocking wait for all futures to complete ``` ### Parameters - `promptId` (String) - The ID of the prompt to retrieve for each item in the batch. ``` -------------------------------- ### Initialize LangfuseClient with Credentials and URL Source: https://github.com/langfuse/langfuse-java/blob/main/_autodocs/client-initialization.md Example of initializing the LangfuseClient with basic authentication credentials and a custom API endpoint URL. ```java LangfuseClient client = LangfuseClient.builder() .credentials("pk-lf-1234567890", "sk-lf-abcdefghij") .url("https://cloud.langfuse.com") .build(); ``` -------------------------------- ### Async Prompts Example Source: https://github.com/langfuse/langfuse-java/blob/main/_autodocs/api-async-and-v2.md Shows how to fetch a single prompt asynchronously and handle the response or errors using CompletableFuture. ```APIDOC ## Async Prompts Example ### Description Fetches a single prompt asynchronously and processes the result or handles errors using `CompletableFuture`. ### Method `client.prompts().get(String promptId)` ### Usage ```java import com.langfuse.client.AsyncLangfuseClient; import com.langfuse.client.prompts.AsyncPromptsClient; import com.langfuse.client.prompts.types.Prompt; import java.util.concurrent.CompletableFuture; AsyncLangfuseClient client = ...; // Assume client is already built AsyncPromptsClient prompts = client.prompts(); CompletableFuture future = prompts.get("my-prompt"); future.thenAccept(prompt -> { System.out.println("Got prompt: " + prompt); }).exceptionally(ex -> { System.err.println("Error: " + ex.getMessage()); return null; }); // Optional: Blocking wait for completion // Prompt prompt = future.get(); // Blocking wait // Prompt prompt = future.join(); // Alternative blocking wait ``` ### Parameters - `promptId` (String) - The ID of the prompt to retrieve. ``` -------------------------------- ### ChatPrompt Example Source: https://github.com/langfuse/langfuse-java/blob/main/_autodocs/types.md Constructs a ChatPrompt object with system and user messages, including placeholders and version labels. ```java List messages = Arrays.asList( ChatMessageWithPlaceholders.of( ChatMessage.builder() .role("system") .content("You are a helpful assistant.") .build() ), ChatMessageWithPlaceholders.of( ChatMessage.builder() .role("user") .content("Answer this question: {{question}}") .build() ) ); ChatPrompt prompt = ChatPrompt.builder() .name("qa") .prompt(messages) .labels(Arrays.asList("production", "v2")) .build(); ``` -------------------------------- ### TraceWithFullDetails Example Source: https://github.com/langfuse/langfuse-java/blob/main/_autodocs/types.md Retrieves a TraceWithFullDetails object from the client and prints its name, input, latency, and observation count. ```java TraceWithFullDetails trace = client.trace().get("trace-123"); System.out.println("Name: " + trace.getName().orElse("unnamed")); System.out.println("Input: " + trace.getInput().orElse(null)); System.out.println("Latency: " + trace.getLatency().orElse(0.0) + "ms"); System.out.println("Observations: " + trace.getObservations().size()); ``` -------------------------------- ### Paginated Traces Example Source: https://github.com/langfuse/langfuse-java/blob/main/_autodocs/types.md Demonstrates how to retrieve paginated traces and access total count. Use this when fetching lists of traces where you need to know the total number of records available. ```java public class Traces { List getData() // Actual data Integer getTotalCount() // Total matching records } ``` ```java Traces result = client.trace().list( GetTracesRequest.builder() .page(0) .limit(50) .build() ); System.out.println("Loaded: " + result.getData().size()); System.out.println("Total: " + result.getTotalCount()); int pages = (result.getTotalCount() + 49) / 50; System.out.println("Pages: " + pages); ``` -------------------------------- ### Provide Custom OkHttpClient for Advanced Configuration Source: https://github.com/langfuse/langfuse-java/blob/main/_autodocs/configuration.md Integrates a pre-configured OkHttpClient instance for advanced customization, such as setting connection timeouts, interceptors, or proxy configurations. The example shows setting connect, read, and write timeouts, adding an interceptor, and configuring a proxy. ```java OkHttpClient customClient = new OkHttpClient.Builder() .connectTimeout(30, TimeUnit.SECONDS) .readTimeout(30, TimeUnit.SECONDS) .writeTimeout(30, TimeUnit.SECONDS) .addInterceptor(new LoggingInterceptor()) .proxy(new Proxy(Proxy.Type.HTTP, new InetSocketAddress("proxy.example.com", 8080))) .build(); LangfuseClient client = LangfuseClient.builder() .httpClient(customClient) .url("https://cloud.langfuse.com") .credentials("pk-ப்படாத", "sk-ப்படாத") .build(); ``` -------------------------------- ### Async Error Handling Example Source: https://github.com/langfuse/langfuse-java/blob/main/_autodocs/api-async-and-v2.md Demonstrates how to catch and handle specific API exceptions, such as a 404 Not Found error, during asynchronous operations. ```APIDOC ## Async Error Handling Example ### Description Provides an example of how to handle specific API errors, like a 404 status code, when performing asynchronous operations. ### Method `client.trace().get(String traceId)` with `.exceptionally()` block. ### Usage ```java import com.langfuse.client.AsyncLangfuseClient; import com.langfuse.client.LangfuseClientApiException; import com.langfuse.client.traces.types.Trace; import java.util.concurrent.CompletableFuture; AsyncLangfuseClient client = ...; // Assume client is already built client.trace().get("trace-123") .thenAccept(trace -> { System.out.println("Trace: " + trace.getId()); }) .exceptionally(ex -> { if (ex.getCause() instanceof LangfuseClientApiException) { LangfuseClientApiException apiEx = (LangfuseClientApiException) ex.getCause(); if (apiEx.statusCode() == 404) { System.out.println("Trace not found"); } } return null; }); ``` ### Parameters - `traceId` (String) - The ID of the trace to retrieve. ``` -------------------------------- ### Get HTTP Client from ClientOptions Source: https://github.com/langfuse/langfuse-java/blob/main/_autodocs/core-infrastructure.md Retrieve the OkHttpClient instance used by the Langfuse client. ```java import com.langfuse.client.core.ClientOptions; import okhttp3.OkHttpClient; // Assuming 'options' is an instance of ClientOptions // OkHttpClient httpClient = options.httpClient(); ``` -------------------------------- ### List Datasets Source: https://github.com/langfuse/langfuse-java/blob/main/_autodocs/api-scores-ingestion-datasets.md Retrieves a paginated list of all datasets. Useful for getting an overview of available datasets and their properties. ```java import com.langfuse.client.LangfuseClient; import com.langfuse.client.resources.commons.types.Dataset; import com.langfuse.client.resources.datasets.types.PaginatedDatasets; // Assuming 'client' is an initialized LangfuseClient instance // LangfuseClient client = LangfuseClientBuilder.newInstance().setHost("http://localhost:3000").setPublicKey("pk_...").setSecretKey("sk_...").build(); PaginatedDatasets result = client.datasets().list(); for (Dataset dataset : result.getData()) { System.out.println("Dataset: " + dataset.getName()); } ``` -------------------------------- ### Example Usage of LangfuseClientException Source: https://github.com/langfuse/langfuse-java/blob/main/_autodocs/errors.md Catch and handle LangfuseClientException for general SDK errors like network issues or configuration problems. ```java try { Prompt prompt = client.prompts().get("my-prompt"); } catch (LangfuseClientException e) { System.err.println("Client error: " + e.getMessage()); if (e.getCause() != null) { e.getCause().printStackTrace(); } } ``` -------------------------------- ### Asynchronous API Call Example Source: https://github.com/langfuse/langfuse-java/blob/main/_autodocs/README.md Demonstrates an asynchronous API call using CompletableFuture for non-blocking operations. The result can be retrieved later using .get(). ```java CompletableFuture future = client.prompts().get("my-prompt"); Prompt prompt = future.get(); // Can wait or handle async ``` -------------------------------- ### Retrieve a Specific Prompt by Name Source: https://github.com/langfuse/langfuse-java/blob/main/_autodocs/api-prompts.md Use the get method to fetch a prompt by its name. You can optionally specify a version or a label to retrieve a particular prompt version. ```java // Get the latest version of a prompt Prompt prompt = client.prompts().get("my-prompt"); // Get a specific version Prompt prompt = client.prompts().get("my-prompt", GetPromptRequest.builder() .version(3) .build()); // Get by label (e.g., "production") Prompt prompt = client.prompts().get("my-prompt", GetPromptRequest.builder() .label("production") .build()); ``` -------------------------------- ### get(String sessionId) Source: https://github.com/langfuse/langfuse-java/blob/main/_autodocs/api-traces-observations-sessions.md Retrieves a specific session with its associated traces. Use this method to get detailed information about a single session. ```APIDOC ## get(String sessionId) ### Description Retrieves a specific session with its associated traces. Use this method to get detailed information about a single session. ### Method GET ### Endpoint /api/public/sessions/{sessionId} ### Parameters #### Path Parameters - **sessionId** (String) - Required - Session identifier ### Request Example ```java SessionWithTraces session = client.sessions().get("session-123"); ``` ### Response #### Success Response (200) - **id** (String) - Session ID - **createdAt** (OffsetDateTime) - Creation timestamp - **userId** (Optional) - User ID - **traces** (List) - Traces in session (unpaginated) #### Response Example ```json { "id": "session-123", "createdAt": "2023-10-27T10:00:00Z", "userId": "user-456", "traces": [ { "id": "trace-abc", "createdAt": "2023-10-27T10:01:00Z" } ] } ``` ### Note The `traces` array is NOT paginated. For large sessions, use `GET /api/public/traces?sessionId=` instead. ``` -------------------------------- ### Get Prompt Asynchronously Source: https://github.com/langfuse/langfuse-java/blob/main/_autodocs/MANIFEST.md Retrieve a prompt using an asynchronous operation. The result is returned as a CompletableFuture, which can be blocked to get the final Prompt object. ```java CompletableFuture future = client.prompts().get("my-prompt"); Prompt prompt = future.get(); // Blocking wait ``` -------------------------------- ### ObservationsV2Client get(String observationId) Source: https://github.com/langfuse/langfuse-java/blob/main/_autodocs/api-async-and-v2.md Retrieves a single observation using its ID from the V2 API. This method is identical in functionality to the V1 `get` method. ```APIDOC ## ObservationsV2Client get(String observationId) ### Description Retrieves a single observation by its ID. This method functions identically to the `get` method in the V1 API. ### Method `client.observationsV2().get(String observationId)` ### Endpoint N/A (SDK method) ### Parameters #### Path Parameters - **observationId** (String) - Required - The unique identifier for the observation to retrieve. #### Request Body None ### Response #### Success Response - `CompletableFuture`: A CompletableFuture that will resolve to an `ObservationV2` object upon successful retrieval. ### Example ```java import com.langfuse.client.AsyncLangfuseClient; import com.langfuse.client.resources.observationsv2.AsyncObservationsV2Client; import com.langfuse.client.resources.observationsv2.types.ObservationV2; import java.util.concurrent.CompletableFuture; AsyncLangfuseClient client = ...; // Assume client is already built AsyncObservationsV2Client observationsV2 = client.observationsV2(); CompletableFuture future = observationsV2.get("obs-123"); future.thenAccept(observation -> { System.out.println("Observation: " + observation.getId()); }).exceptionally(ex -> { System.err.println("Error retrieving observation: " + ex.getMessage()); return null; }); ``` ``` -------------------------------- ### Get Response Headers Source: https://github.com/langfuse/langfuse-java/blob/main/_autodocs/core-infrastructure.md Retrieve the headers from the HTTP response. ```java Map> headers() ``` -------------------------------- ### Initialize Langfuse Client and Fetch Prompts Source: https://github.com/langfuse/langfuse-java/blob/main/_autodocs/README.md Demonstrates how to initialize the LangfuseClient with your API keys and URL, and then fetch a list of prompts. It also shows how to retrieve a specific prompt and determine its type (chat or text). ```java import com.langfuse.client.LangfuseClient; import com.langfuse.client.resources.prompts.types.PromptMetaListResponse; // Initialize client LangfuseClient client = LangfuseClient.builder() .url("https://cloud.langfuse.com") .credentials("pk-lf-your-public-key", "sk-lf-your-secret-key") .build(); // Fetch prompts PromptMetaListResponse prompts = client.prompts().list(); System.out.println("Found " + prompts.getPrompts().size() + " prompts"); // Get a specific prompt Prompt prompt = client.prompts().get("my-prompt"); System.out.println("Prompt type: " + prompt.visit( new Prompt.Visitor() { public String visitChat(ChatPrompt p) { return "chat"; } public String visitText(TextPrompt p) { return "text"; } public String _visitUnknown(Object o) { return "unknown"; } } )); ``` -------------------------------- ### Get Response Body Source: https://github.com/langfuse/langfuse-java/blob/main/_autodocs/core-infrastructure.md Retrieve the body of the HTTP response. ```java T body() ``` -------------------------------- ### LangfuseClient Initialization Source: https://github.com/langfuse/langfuse-java/blob/main/_autodocs/client-initialization.md Demonstrates how to build and configure a `LangfuseClient` instance using various builder methods for authentication, endpoint URL, timeouts, and retries. ```APIDOC ## LangfuseClient Initialization ### Description Initializes the Langfuse Java client with specified configuration options using a builder pattern. ### Builder Methods #### `credentials(String username, String password)` Sets Basic authentication credentials for API requests. - **username** (String) - Required - Public API key (e.g., `pk-lf-...`) - **password** (String) - Required - Secret API key (e.g., `sk-lf-...`) #### `url(String url)` Sets the Langfuse API endpoint URL. - **url** (String) - Required - Full API endpoint URL #### `timeout(int timeout)` Sets the HTTP request timeout in seconds. - **timeout** (int) - Optional - Timeout in seconds (Default: 60) #### `maxRetries(int maxRetries)` Sets the maximum number of retry attempts for failed requests. - **maxRetries** (int) - Optional - Maximum number of retries (Default: 2) #### `httpClient(OkHttpClient httpClient)` Provides a custom OkHttpClient instance for advanced HTTP configuration. - **httpClient** (OkHttpClient) - Optional - Custom OkHttp client #### `addHeader(String name, String value)` Adds a custom HTTP header to all requests. - **name** (String) - Required - Header name - **value** (String) - Required - Header value #### `xLangfuseSdkName(String xLangfuseSdkName)` Sets the SDK name header for tracking SDK usage. - **xLangfuseSdkName** (String) - Optional - SDK name identifier #### `xLangfuseSdkVersion(String xLangfuseSdkVersion)` Sets the SDK version header for tracking SDK usage. - **xLangfuseSdkVersion** (String) - Optional - SDK version #### `xLangfusePublicKey(String xLangfusePublicKey)` Sets a public key header for advanced configuration. - **xLangfusePublicKey** (String) - Optional - Public key value ### Build Method #### `build()` Constructs the LangfuseClient with configured options. ### Request Example ```java LangfuseClient client = LangfuseClient.builder() .url("https://cloud.langfuse.com") .credentials("pk-lf-1234567890", "sk-lf-abcdefghij") .timeout(120) .maxRetries(3) .build(); ``` ``` -------------------------------- ### Get HTTP Status Code Source: https://github.com/langfuse/langfuse-java/blob/main/_autodocs/core-infrastructure.md Retrieve the HTTP status code from the response. ```java int statusCode() ``` -------------------------------- ### Get Request Headers Source: https://github.com/langfuse/langfuse-java/blob/main/_autodocs/core-infrastructure.md Retrieve custom headers associated with a RequestOptions object. ```java import com.langfuse.client.core.RequestOptions; import java.util.Map; // Assuming 'options' is an instance of RequestOptions Map headers = options.getHeaders(); ``` -------------------------------- ### Prepare Release Version Source: https://github.com/langfuse/langfuse-java/blob/main/README.md Prepare a release by running the release:prepare command with the desired version. Ensure to push changes including the tag afterwards. ```bash ./mvnw release:prepare -DreleaseVersion= ``` -------------------------------- ### get() - Organization Source: https://github.com/langfuse/langfuse-java/blob/main/_autodocs/api-additional-resources.md Retrieves information about the current organization. This is a simple synchronous call. ```APIDOC ## get() - Organization ### Description Retrieves the current organization's information. This method can optionally accept request options. ### Method GET (implied) ### Endpoint /organizations/current (implied) ### Parameters #### Query Parameters - **requestOptions** (RequestOptions) - Optional - Request-specific options. ### Response #### Success Response (200) - **id** (String) - Organization ID - **name** (String) - Organization name - **createdAt** (OffsetDateTime) - Creation timestamp ### Request Example ```java Organization org = client.organizations().get(); System.out.println("Organization: " + org.getName()); ``` ``` -------------------------------- ### Using Prompt Visitor Pattern Source: https://github.com/langfuse/langfuse-java/blob/main/_autodocs/types.md Demonstrates how to use the visitor pattern to process different prompt types (chat or text) retrieved from the client. ```java Prompt prompt = client.prompts().get("my-prompt"); String result = prompt.visit(new Prompt.Visitor() { @Override public String visitChat(ChatPrompt chat) { return "Chat prompt with " + chat.getPrompt().size() + " messages"; } @Override public String visitText(TextPrompt text) { return "Text prompt: " + text.getPrompt(); } @Override public String _visitUnknown(Object unknown) { return "Unknown prompt type"; } }); ``` -------------------------------- ### Get Max Retries from ClientOptions Source: https://github.com/langfuse/langfuse-java/blob/main/_autodocs/core-infrastructure.md Retrieve the maximum number of retries configured for the client. ```java import com.langfuse.client.core.ClientOptions; // Assuming 'options' is an instance of ClientOptions // int maxRetries = options.maxRetries(); ``` -------------------------------- ### Get Environment URL Source: https://github.com/langfuse/langfuse-java/blob/main/_autodocs/core-infrastructure.md Retrieve the API endpoint URL configured for an Environment instance. ```java import com.langfuse.client.core.Environment; // Assuming 'environment' is an instance of Environment String url = environment.getUrl(); ``` -------------------------------- ### Get Dataset by Name Source: https://github.com/langfuse/langfuse-java/blob/main/_autodocs/api-scores-ingestion-datasets.md Retrieves a specific dataset by its name. This method is part of the DatasetsClient. ```APIDOC ## get(String datasetName) ### Description Retrieves a specific dataset by name. ### Method GET (implied) ### Endpoint /datasets/{datasetName} (implied) ### Parameters #### Path Parameters - **datasetName** (String) - Required - Dataset name #### Request Options - **requestOptions** (RequestOptions) - Optional - Request-specific options ### Return Type `Dataset` ### Dataset Fields - **id** (String) - Dataset ID - **name** (String) - Dataset name - **projectId** (String) - Project ID - **description** (Optional) - Description - **createdAt** (OffsetDateTime) - Creation timestamp - **updatedAt** (OffsetDateTime) - Last update timestamp - **itemCount** (Integer) - Number of items in dataset - **runs** (Integer) - Number of dataset runs ### Example ```java Dataset dataset = client.datasets().get("evals-2024"); System.out.println("Items: " + dataset.getItemCount()); System.out.println("Runs: " + dataset.getRuns()); ``` ``` -------------------------------- ### Configure Custom HTTP Client Source: https://github.com/langfuse/langfuse-java/blob/main/_autodocs/README.md Build a custom OkHttpClient with specific timeouts, interceptors, and proxies, then use it to configure the Langfuse client. This allows for fine-grained control over network requests. ```java OkHttpClient httpClient = new OkHttpClient.Builder() .connectTimeout(30, TimeUnit.SECONDS) .addInterceptor(new CustomInterceptor()) .proxy(proxy) .build(); LangfuseClient client = LangfuseClient.builder() .httpClient(httpClient) .url("https://cloud.langfuse.com") .credentials("pk-...", "sk-...") .build(); ``` -------------------------------- ### Get Timeout Time Unit Source: https://github.com/langfuse/langfuse-java/blob/main/_autodocs/core-infrastructure.md Retrieve the time unit for the timeout, which is always SECONDS for this SDK. ```java import com.langfuse.client.core.RequestOptions; import java.util.concurrent.TimeUnit; // Assuming 'options' is an instance of RequestOptions TimeUnit unit = options.getTimeoutTimeUnit(); ``` -------------------------------- ### Get Effective Timeout from ClientOptions Source: https://github.com/langfuse/langfuse-java/blob/main/_autodocs/core-infrastructure.md Calculate the effective request timeout by considering both client-level and request-level settings. ```java import com.langfuse.client.core.ClientOptions; import com.langfuse.client.core.RequestOptions; // Assuming 'options' is an instance of ClientOptions and 'requestOptions' is an instance of RequestOptions // int timeoutSeconds = options.timeout(requestOptions); ``` -------------------------------- ### Build Langfuse Client with Custom Configuration Source: https://github.com/langfuse/langfuse-java/blob/main/_autodocs/MANIFEST.md Demonstrates how to build a Langfuse client instance using the builder pattern, specifying the API URL, credentials, and request timeout. ```java LangfuseClient client = LangfuseClient.builder() .url("https://cloud.langfuse.com") .credentials("pk-...", "sk-...") .timeout(120) .build(); ``` -------------------------------- ### Get Request Timeout Source: https://github.com/langfuse/langfuse-java/blob/main/_autodocs/core-infrastructure.md Retrieve the timeout value configured for a RequestOptions object. Returns an Optional Integer. ```java import com.langfuse.client.core.RequestOptions; import java.util.Optional; // Assuming 'options' is an instance of RequestOptions Optional timeout = options.getTimeout(); if (timeout.isPresent()) { System.out.println("Timeout: " + timeout.get() + "s"); } ``` -------------------------------- ### Handle Missing Resources by Creating Defaults Source: https://github.com/langfuse/langfuse-java/blob/main/_autodocs/errors.md Catch a 404 error when trying to retrieve a resource and create a default version if it doesn't exist. This pattern is useful for ensuring resources are available before use. ```java try { Prompt prompt = client.prompts().get(promptName); return prompt; } catch (LangfuseClientApiException e) { if (e.statusCode() == 404) { // Create default prompt return client.prompts().create( CreatePromptRequest.of( CreateTextPromptRequest.builder() .name(promptName) .prompt("Default prompt") .build() ) ); } throw e; } ``` -------------------------------- ### Get Current Organization Source: https://github.com/langfuse/langfuse-java/blob/main/_autodocs/api-additional-resources.md Retrieves details about the currently authenticated organization. Use this to access organization-specific information. ```java Organization org = client.organizations().get(); System.out.println("Organization: " + org.getName()); ``` -------------------------------- ### Accessing Resource Clients Source: https://github.com/langfuse/langfuse-java/blob/main/_autodocs/client-initialization.md Shows how to obtain client instances for interacting with specific Langfuse API resources such as prompts, traces, and observations. ```APIDOC ## Accessing Resource Clients ### Description Both `LangfuseClient` and `AsyncLangfuseClient` provide methods to access specialized clients for different Langfuse API resources. These resource clients offer methods to perform operations related to their specific domain. ### Methods and Resources - **Prompts:** - `client.prompts()`: Returns a `PromptsClient`. - **Traces:** - `client.trace()`: Returns a `TraceClient`. - **Sessions:** - `client.sessions()`: Returns a `SessionsClient`. - **Observations:** - `client.observations()`: Returns an `ObservationsClient` for standard pagination. - `client.observationsV2()`: Returns an `ObservationsV2Client` for cursor-based pagination. - **Scores:** - `client.score()`: Returns a `ScoreClient`. - `client.scoreV2()`: Returns a `ScoreV2Client`. - `client.scoreConfigs()`: Returns a `ScoreConfigsClient`. - **Datasets:** - `client.datasets()`: Returns a `DatasetsClient`. - `client.datasetItems()`: Returns a `DatasetItemsClient`. - `client.datasetRunItems()`: Returns a `DatasetRunItemsClient`. - **Other Resources:** - `client.annotationQueues()`: Returns an `AnnotationQueuesClient`. - `client.blobStorageIntegrations()`: Returns a `BlobStorageIntegrationsClient`. - `client.comments()`: Returns a `CommentsClient`. - `client.health()`: Returns a `HealthClient`. - `client.ingestion()`: Returns an `IngestionClient`. - `client.llmConnections()`: Returns an `LlmConnectionsClient`. - `client.media()`: Returns a `MediaClient`. - `client.metrics()`: Returns a `MetricsClient`. - `client.metricsV2()`: Returns a `MetricsV2Client`. - `client.models()`: Returns a `ModelsClient`. - `client.opentelemetry()`: Returns an `OpentelemetryClient`. - `client.organizations()`: Returns an `OrganizationsClient`. - `client.projects()`: Returns a `ProjectsClient`. - `client.promptVersion()`: Returns a `PromptVersionClient`. - `client.scim()`: Returns a `ScimClient`. ### Example Usage ```java // Assuming 'client' is an initialized LangfuseClient or AsyncLangfuseClient PromptsClient promptsClient = client.prompts(); TraceClient traceClient = client.trace(); ``` ``` -------------------------------- ### Run Unit Tests Source: https://github.com/langfuse/langfuse-java/blob/main/README.md Run unit tests, which include deserialization and query string mapping, without requiring any credentials. ```bash mvn test ``` -------------------------------- ### Handle Union Types with Visitor Pattern Source: https://github.com/langfuse/langfuse-java/blob/main/_autodocs/MANIFEST.md Illustrates how to use the visitor pattern to handle different types of prompts (e.g., ChatPrompt, TextPrompt) exhaustively. ```java prompt.visit(new Prompt.Visitor() { public String visitChat(ChatPrompt p) { ... } public String visitText(TextPrompt p) { ... } public String _visitUnknown(Object o) { ... } }); ``` -------------------------------- ### AsyncLangfuseClient Initialization Source: https://github.com/langfuse/langfuse-java/blob/main/_autodocs/client-initialization.md Demonstrates how to build an asynchronous Langfuse client with a custom URL and credentials. This client uses CompletableFuture for non-blocking operations. ```APIDOC ## AsyncLangfuseClient Initialization ### Description Initializes the asynchronous Langfuse client, which returns `CompletableFuture` for non-blocking API calls. This builder pattern allows for easy configuration of the client's endpoint and authentication credentials. ### Method `AsyncLangfuseClient.builder()` ### Endpoint N/A (Client-side configuration) ### Parameters #### Builder Methods - `url(String url)`: Sets the API endpoint URL. Defaults to `https://cloud.langfuse.com`. - `credentials(String publicKey, String secretKey)`: Sets the API keys for authentication. #### Build Method - `build()`: Constructs and returns the `AsyncLangfuseClient` instance. ### Request Example ```java import com.langfuse.client.AsyncLangfuseClient; AsyncLangfuseClient client = AsyncLangfuseClient.builder() .url("https://cloud.langfuse.com") .credentials("pk-lf-your-public-key", "sk-lf-your-secret-key") .build(); ``` ### Response - `AsyncLangfuseClient`: The initialized asynchronous client instance. ``` -------------------------------- ### Get Specific Dataset Source: https://github.com/langfuse/langfuse-java/blob/main/_autodocs/api-scores-ingestion-datasets.md Retrieves a specific dataset by its name. Provides details such as item count and number of runs. ```java import com.langfuse.client.LangfuseClient; import com.langfuse.client.resources.commons.types.Dataset; // Assuming 'client' is an initialized LangfuseClient instance // LangfuseClient client = LangfuseClientBuilder.newInstance().setHost("http://localhost:3000").setPublicKey("pk_...").setSecretKey("sk_...").build(); Dataset dataset = client.datasets().get("evals-2024"); System.out.println("Items: " + dataset.getItemCount()); System.out.println("Runs: " + dataset.getRuns()); ``` -------------------------------- ### Configure Langfuse Client with Environment Variables Source: https://github.com/langfuse/langfuse-java/blob/main/_autodocs/configuration.md Initialize the Langfuse client using environment variables for public key, secret key, and URL. Provides a fallback to default URL if the environment variable is not set. ```java String publicKey = System.getenv("LANGFUSE_PUBLIC_KEY"); String secretKey = System.getenv("LANGFUSE_SECRET_KEY"); String url = System.getenv("LANGFUSE_URL"); LangfuseClient client = LangfuseClient.builder() .url(url != null ? url : "https://cloud.langfuse.com") .credentials(publicKey, secretKey) .build(); ``` -------------------------------- ### Async Client Builder Source: https://github.com/langfuse/langfuse-java/blob/main/_autodocs/api-async-and-v2.md Configure and build an asynchronous Langfuse client. Set the API URL, credentials, timeout, and retry settings. ```java import com.langfuse.client.AsyncLangfuseClient; import java.util.concurrent.CompletableFuture; AsyncLangfuseClient client = AsyncLangfuseClient.builder() .url("https://cloud.langfuse.com") .credentials("pk-lf-...", "sk-lf-...") .timeout(120) .maxRetries(3) .build(); ``` -------------------------------- ### AsyncLangfuseClient Builder Source: https://github.com/langfuse/langfuse-java/blob/main/_autodocs/api-async-and-v2.md Demonstrates how to build an asynchronous Langfuse client with custom configurations like URL, credentials, timeout, and retries. ```APIDOC ## AsyncLangfuseClient Builder ### Description Builds an asynchronous HTTP client for non-blocking API calls using CompletableFuture. ### Usage ```java import com.langfuse.client.AsyncLangfuseClient; AsyncLangfuseClient client = AsyncLangfuseClient.builder() .url("https://cloud.langfuse.com") .credentials("pk-lf-...", "sk-lf-...") .timeout(120) .maxRetries(3) .build(); ``` ### Builder Methods - `url(String url)`: Sets the API endpoint URL. - `credentials(String publicKey, String secretKey)`: Sets the API credentials. - `timeout(int timeoutSeconds)`: Sets the request timeout in seconds. - `maxRetries(int maxRetries)`: Sets the maximum number of retries for failed requests. ``` -------------------------------- ### Configure Langfuse Client for Production Source: https://github.com/langfuse/langfuse-java/blob/main/_autodocs/README.md Set up the Langfuse client with production-specific settings, including a timeout, retry count, and custom headers for environment identification. ```java LangfuseClient client = LangfuseClient.builder() .url("https://cloud.langfuse.com") .credentials(publicKey, secretKey) .timeout(120) // 2 minute timeout .maxRetries(5) // Aggressive retries for reliability .addHeader("X-Environment", "production") .build(); ``` -------------------------------- ### get Source: https://github.com/langfuse/langfuse-java/blob/main/_autodocs/api-traces-observations-sessions.md Retrieves a specific observation by its ID. This is useful for inspecting the details of a single span, event, or generation within a trace. ```APIDOC ## get(String observationId) ### Description Retrieves a specific observation. ### Method GET ### Endpoint /api/v1/observations/{observationId} ### Parameters #### Path Parameters - **observationId** (String) - Required - Observation identifier ### Response #### Success Response (200) - **ObservationsView** (object) - Details of the requested observation - **id** (String) - Observation ID - **traceId** (String) - Parent trace ID - **parentObservationId** (Optional) - Parent observation (if nested) - **type** (String) - Type: "GENERATION", "SPAN", "EVENT" - **name** (String) - Observation name - **startTime** (OffsetDateTime) - Start timestamp - **endTime** (Optional) - End timestamp - **duration** (Optional) - Duration in seconds - **input** (Optional) - Input data - **output** (Optional) - Output data - **metadata** (Optional) - Custom metadata - **level** (Optional) - Log level - **statusMessage** (Optional) - Status/error message - **model** (Optional) - Model name (for generations) - **modelParameters** (Optional) - Model parameters - **inputTokens** (Optional) - LLM input tokens - **outputTokens** (Optional) - LLM output tokens - **totalTokens** (Optional) - Total tokens - **cost** (Optional) - Estimated cost ### Request Example ```java ObservationsView obs = client.observations().get("obs-123"); System.out.println("Type: " + obs.getType()); System.out.println("Duration: " + obs.getDuration() + "s"); if (obs.getInputTokens().isPresent()) { System.out.println("Input tokens: " + obs.getInputTokens().get()); } ``` ``` -------------------------------- ### Run All Tests Source: https://github.com/langfuse/langfuse-java/blob/main/README.md Run all tests, including unit and integration tests, by executing the mvn verify command. ```bash mvn verify ``` -------------------------------- ### Import LangfuseClient and ClientOptions Source: https://github.com/langfuse/langfuse-java/blob/main/_autodocs/client-initialization.md Import the necessary classes for using the Langfuse Java client. ```java import com.langfuse.client.LangfuseClient; import com.langfuse.client.core.ClientOptions; ``` -------------------------------- ### Set HTTP Request Timeout Source: https://github.com/langfuse/langfuse-java/blob/main/_autodocs/configuration.md Configures the timeout for HTTP requests in seconds. A value of 120 seconds is shown as an example. ```java .timeout(120) // 2 minute timeout ``` -------------------------------- ### Async Trace Retrieval with Project Reactor Source: https://github.com/langfuse/langfuse-java/blob/main/_autodocs/api-async-and-v2.md Demonstrates fetching multiple traces asynchronously using Project Reactor's Flux and Mono. Useful for high-throughput applications and reactive frameworks. ```java AsyncLangfuseClient client = AsyncLangfuseClient.builder() .url("https://cloud.langfuse.com") .credentials("pk-...", "sk-...") .build(); Flux traces = Flux.fromIterable(traceIds) .flatMapSequential(id -> Mono.fromCompletionStage(() -> client.trace().get(id)) ); traces .doOnNext(trace -> System.out.println("Processing: " + trace.getId())) .doOnError(ex -> System.err.println("Error: " + ex)) .subscribe(); ``` -------------------------------- ### Get a Specific Trace Source: https://github.com/langfuse/langfuse-java/blob/main/_autodocs/api-traces-observations-sessions.md Retrieve a trace by its ID, including all its observations and scores. This method is useful for detailed inspection of a single trace. ```java TraceWithFullDetails trace = client.trace().get("trace-123"); System.out.println("Trace name: " + trace.getName()); System.out.println("Observations: " + trace.getObservations().size()); System.out.println("Total cost: " + trace.getTotalCost()); ``` -------------------------------- ### List Available Models Source: https://github.com/langfuse/langfuse-java/blob/main/_autodocs/api-additional-resources.md Retrieve a list of available models in your project using the list() method. This includes model names and pricing information. ```java import com.langfuse.client.resources.models.ModelsClient; import com.langfuse.client.resources.models.types.Model; // ... inside a method or class ModelList models = client.models().list(); for (Model model : models.getData()) { System.out.println(model.getModelName()); if (model.getInputPrice().isPresent()) { System.out.println(" Input: $" + model.getInputPrice().get()); } if (model.getOutputPrice().isPresent()) { System.out.println(" Output: $" + model.getOutputPrice().get()); } } ``` -------------------------------- ### Lazy Initialization with Memoization Source: https://github.com/langfuse/langfuse-java/blob/main/_autodocs/core-infrastructure.md Shows how to use Suppliers.memoize to create a lazily initialized, thread-safe singleton instance. ```java Supplier promptsClient = Suppliers.memoize( () -> new PromptsClient(clientOptions) ); // First call creates instance PromptsClient client1 = promptsClient.get(); // Subsequent calls return same instance PromptsClient client2 = promptsClient.get(); assert client1 == client2; // True ``` -------------------------------- ### Synchronous API Call Example Source: https://github.com/langfuse/langfuse-java/blob/main/_autodocs/README.md Illustrates a synchronous API call where the method returns a concrete type and blocks until the response is received. ```java Prompt prompt = client.prompts().get("my-prompt"); // Blocks ``` -------------------------------- ### Import PromptsClient and Types Source: https://github.com/langfuse/langfuse-java/blob/main/_autodocs/api-prompts.md Import necessary classes for using the Prompts API, including the client itself and types for prompts and requests. ```java import com.langfuse.client.resources.prompts.PromptsClient; import com.langfuse.client.resources.prompts.types.Prompt; import com.langfuse.client.resources.prompts.types.CreatePromptRequest; import com.langfuse.client.resources.prompts.types.PromptMetaListResponse; ``` -------------------------------- ### Add langfuse-java Dependency Source: https://github.com/langfuse/langfuse-java/blob/main/README.md Install the langfuse-java API client using Maven Central by adding this dependency to your project's pom.xml. ```xml com.langfuse langfuse-java 0.2.0 ``` -------------------------------- ### Async Pattern: With Virtual Threads (Java 19+) Source: https://github.com/langfuse/langfuse-java/blob/main/_autodocs/api-async-and-v2.md Demonstrates how to use the asynchronous client with virtual threads for high concurrency, processing multiple trace details in parallel. ```APIDOC ## Async Operations with Virtual Threads ### Description This example shows how to leverage the asynchronous Langfuse client with Java 19+ virtual threads to concurrently fetch and process multiple traces. ### Usage ```java AsyncLangfuseClient client = AsyncLangfuseClient.builder() .url("https://cloud.langfuse.com") .credentials("pk-...", "sk-...") .build(); // Use virtual threads for high concurrency List traceIds = getTraceIds(); List> futures = traceIds.stream() .map(id -> client.trace().get(id)) .collect(Collectors.toList()); CompletableFuture.allOf(futures.toArray(new CompletableFuture[0])) .thenAccept(v -> { futures.forEach(f -> { try { TraceWithFullDetails trace = f.get(); processTrace(trace); } catch (Exception e) { logger.error("Error processing trace", e); } }); }) .exceptionally(ex -> { logger.error("Batch processing failed", ex); return null; }) .join(); ``` ``` -------------------------------- ### List Traces with Filtering Source: https://github.com/langfuse/langfuse-java/blob/main/_autodocs/api-traces-observations-sessions.md Retrieve a paginated list of traces, with options to filter by tags, environment, user ID, session ID, and more. Useful for analyzing multiple traces. ```java // Get first page of traces Traces result = client.trace().list(); // Get traces with filters Traces result = client.trace().list( GetTracesRequest.builder() .userId("user-123") .tags(Arrays.asList("production")) .limit(100) .page(0) .build() ); for (TraceWithFullDetails trace : result.getData()) { System.out.println(trace.getId() + ": " + trace.getName()); } ``` -------------------------------- ### get(String traceId) Source: https://github.com/langfuse/langfuse-java/blob/main/_autodocs/api-traces-observations-sessions.md Retrieves a specific trace with all its details, including observations and scores. It can optionally accept request options for fine-grained control. ```APIDOC ## get(String traceId) ### Description Retrieves a specific trace with all its details (observations and scores). ### Method GET (Implied) ### Endpoint /traces/{traceId} ### Parameters #### Path Parameters - **traceId** (String) - Yes - Unique trace identifier #### Query Parameters - **requestOptions** (RequestOptions) - No - Request-specific options ### Response #### Success Response (200) - **TraceWithFullDetails** (TraceWithFullDetails) - Details of the trace, including observations and scores. ### Response Example ```json { "id": "trace-123", "timestamp": "2023-10-27T10:00:00Z", "name": "Example Trace", "input": {"query": "What is Langfuse?"}, "output": {"answer": "Langfuse is an open-source observability platform..."}, "sessionId": "session-abc", "userId": "user-xyz", "metadata": {"source": "web"}, "tags": ["api", "example"], "release": "v1.0.0", "version": "1.0", "public_": true, "environment": "production", "htmlPath": "/traces/trace-123", "latency": 150.5, "totalCost": 0.05, "observations": [], "scores": [] } ``` ### Throws `LangfuseClientApiException` on API errors ``` -------------------------------- ### PromptsClient.create Source: https://github.com/langfuse/langfuse-java/blob/main/_autodocs/api-prompts.md Creates a new version for a prompt or creates the prompt if it does not exist. Supports both text and chat prompt types. ```APIDOC ## POST /prompts ### Description Creates a new version for a prompt. If the prompt does not exist, it will be created. This endpoint supports both text and chat prompt formats. ### Method POST ### Endpoint /prompts ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **request** (CreatePromptRequest) - Required - The details for creating the prompt. This can be either a `CreateTextPromptRequest` or a `CreateChatPromptRequest`. - **CreateTextPromptRequest fields:** - `name` (String) - Required - Prompt name. - `prompt` (String) - Required - The text template for the prompt. - `config` (Object) - Optional - Provider-specific configuration. - `labels` (List) - Optional - Labels for versioning (e.g., "production"). - **CreateChatPromptRequest fields:** - `name` (String) - Required - Prompt name. - `prompt` (List) - Required - List of chat messages defining the prompt. - `config` (Object) - Optional - Provider-specific configuration. - `labels` (List) - Optional - Labels for versioning. ### Response #### Success Response (200) - **Prompt** (Object) - The newly created or updated prompt object. ### Request Example ```java // Create a text prompt Prompt textPrompt = client.prompts().create( CreatePromptRequest.of( CreateTextPromptRequest.builder() .name("greeting") .prompt("Hello {{name}}, welcome to {{place}}!") .labels(Arrays.asList("production", "v1")) .build() ) ); // Create a chat prompt List messages = new ArrayList<>(); messages.add( ChatMessageWithPlaceholders.of( ChatMessage.builder() .role("user") .content("Say hello to {{name}}") .build() ) ); Prompt chatPrompt = client.prompts().create( CreatePromptRequest.of( CreateChatPromptRequest.builder() .name("chat-greeting") .prompt(messages) .build() ) ); ``` ``` -------------------------------- ### Get Annotation Queue Items Source: https://github.com/langfuse/langfuse-java/blob/main/_autodocs/api-additional-resources.md Retrieves a paginated list of items within a specific annotation queue. Useful for processing or reviewing items associated with a queue. ```java PaginatedAnnotationQueueItems items = client.annotationQueues().getItems("queue-123"); for (AnnotationQueueItem item : items.getData()) { System.out.println("Item: " + item.getObjectId() + " (" + item.getObjectType() + ")"); } ``` -------------------------------- ### Import ScoreConfigsClient and Types Source: https://github.com/langfuse/langfuse-java/blob/main/_autodocs/api-additional-resources.md Imports necessary classes for working with score configurations. ```java import com.langfuse.client.resources.scoreconfigs.ScoreConfigsClient; import com.langfuse.client.resources.scoreconfigs.types.ScoreConfig; import com.langfuse.client.resources.scoreconfigs.types.CreateScoreConfigRequest; ``` -------------------------------- ### PromptTemplate.compile(String template, Map variables) Source: https://github.com/langfuse/langfuse-java/blob/main/_autodocs/api-prompts.md Compiles a single template string. ```APIDOC ## compile(String template, Map variables) ### Description Compiles a single template string. ### Signature ```java static String compile(String template, Map variables) ``` ### Parameters #### Path Parameters - **template** (String) - Required - The template string to compile - **variables** (Map) - Required - A map of variable names to their values ### Example ```java String template = "The answer is {{answer}}."; Map vars = Collections.singletonMap("answer", 42); String result = PromptTemplate.compile(template, vars); // Result: "The answer is 42." ``` ``` -------------------------------- ### Get Prompt with Raw HTTP Response Source: https://github.com/langfuse/langfuse-java/blob/main/_autodocs/api-prompts.md Retrieve a prompt along with its HTTP metadata such as status code and headers. Useful for debugging or advanced response handling. ```java LangfuseClientHttpResponse response = client.prompts().withRawResponse().get("my-prompt"); Prompt prompt = response.body(); int statusCode = response.statusCode(); Map> headers = response.headers(); ``` -------------------------------- ### Create a Text Prompt using Builder Pattern Source: https://github.com/langfuse/langfuse-java/blob/main/_autodocs/README.md Create a new text prompt using the builder pattern for request construction. Sets the prompt name, content, and labels. ```java Prompt prompt = client.prompts().create( CreatePromptRequest.of( CreateTextPromptRequest.builder() .name("greeting") .prompt("Hello {{name}}") .labels(List.of("production")) .build() ) ); ``` -------------------------------- ### Get and Print Dataset Information Source: https://github.com/langfuse/langfuse-java/blob/main/_autodocs/types.md Retrieves a dataset by its ID and prints the total item count and number of runs. Assumes the client and dataset ID are available. ```java Dataset dataset = client.datasets().get("test-dataset"); System.out.println("Items: " + dataset.getItemCount()); System.out.println("Runs: " + dataset.getRuns()); ```