### Install Langfuse JS/TS SDK
Source: https://langfuse-docs-git-add-js-sdk-v4-docs-langfuse.vercel.app/docs/prompts/get-started
Install the @langfuse/client package for JavaScript/TypeScript to interact with Langfuse services. This uses npm and is suitable for Node.js environments. Requires an internet connection and Node.js 14+. No specific inputs or outputs; limitations include package manager setup and network access.
```javascript
npm i @langfuse/client
```
--------------------------------
### Install and Configure Langfuse for LangChain Python SDK
Source: https://langfuse-docs-git-add-js-sdk-v4-docs-langfuse.vercel.app/docs/get-started
Installs necessary Langfuse and LangChain packages for Python and configures Langfuse API credentials via environment variables. It demonstrates initializing the Langfuse callback handler.
```bash
pip install langfuse langchain-openai
```
```dotenv
LANGFUSE_SECRET_KEY = "sk-lf-..."
LANGFUSE_PUBLIC_KEY = "pk-lf-..."
LANGFUSE_HOST = "https://cloud.langfuse.com" # πͺπΊ EU region
# LANGFUSE_HOST = "https://us.cloud.langfuse.com" # πΊπΈ US region
```
```python
from langfuse.langchain import CallbackHandler
langfuse_handler = CallbackHandler()
```
--------------------------------
### Install Dependencies for Langfuse, OpenAI, and Langchain
Source: https://langfuse-docs-git-add-js-sdk-v4-docs-langfuse.vercel.app/guides/cookbook/example_decorator_openai_langchain
Installs the required Python packages for Langfuse, OpenAI, and Langchain. This is a prerequisite for running the subsequent code examples.
```python
%pip install langfuse openai langchain_openai langchain --upgrade
```
--------------------------------
### Install Langfuse and Langchain Libraries (Python)
Source: https://langfuse-docs-git-add-js-sdk-v4-docs-langfuse.vercel.app/guides/cookbook/example_multi_modal_traces
Installs the necessary Langfuse, Langchain, and Langchain-OpenAI Python packages using pip. This is a prerequisite for running the subsequent examples.
```python
%pip install langfuse langchain langchain_openai
```
--------------------------------
### Install Langfuse Python SDK
Source: https://langfuse-docs-git-add-js-sdk-v4-docs-langfuse.vercel.app/docs/get-started
Installs the core Langfuse Python SDK, which can be used to wrap any LLM or Agent for observability. Requires Langfuse credentials to be set as environment variables.
```bash
pip install langfuse
```
```dotenv
LANGFUSE_SECRET_KEY = "sk-lf-..."
LANGFUSE_PUBLIC_KEY = "pk-lf-..."
LANGFUSE_HOST = "https://cloud.langfuse.com" # πͺπΊ EU region
```
--------------------------------
### Install Python SDK and Configure Environment Variables
Source: https://langfuse-docs-git-add-js-sdk-v4-docs-langfuse.vercel.app/docs/prompts
Installs the Langfuse Python SDK and sets up essential environment variables for authentication and host configuration. Requires Python 3.7+.
```shell
pip install langfuse
.env
```
LANGFUSE_SECRET_KEY = "sk-lf-..."
LANGFUSE_PUBLIC_KEY = "pk-lf-..."
LANGFUSE_HOST = "https://cloud.langfuse.com" # πͺπΊ EU region
# LANGFUSE_HOST = "https://us.cloud.langfuse.com" # πΊπΈ US region
```
```
--------------------------------
### Install Langfuse for Python OpenAI SDK
Source: https://langfuse-docs-git-add-js-sdk-v4-docs-langfuse.vercel.app/docs/get-started
Installs the Langfuse Python package and configures environment variables for API credentials. This enables drop-in replacement for the OpenAI Python SDK for observability.
```bash
pip install langfuse
```
```dotenv
LANGFUSE_SECRET_KEY = "sk-lf-..."
LANGFUSE_PUBLIC_KEY = "pk-lf-..."
LANGFUSE_HOST = "https://cloud.langfuse.com" # πͺπΊ EU region
# LANGFUSE_HOST = "https://us.cloud.langfuse.com" # πΊπΈ US region
```
--------------------------------
### Install Langfuse, Langchain, and OpenAI SDKs
Source: https://langfuse-docs-git-add-js-sdk-v4-docs-langfuse.vercel.app/docs/prompts/example-langchain
Installs the necessary Python packages for Langfuse, Langchain, and OpenAI integration. This is a prerequisite for running the example.
```python
%pip install langfuse langchain langchain-openai --upgrade
```
--------------------------------
### Install JS/TS SDK and Configure Environment Variables
Source: https://langfuse-docs-git-add-js-sdk-v4-docs-langfuse.vercel.app/docs/prompts
Installs the Langfuse JavaScript/TypeScript SDK and sets up environment variables for authentication and base URL. Supports both direct and constructor-based configuration.
```shell
npm i @langfuse/client
.env
```
LANGFUSE_SECRET_KEY = "sk-lf-...";
LANGFUSE_PUBLIC_KEY = "pk-lf-...";
LANGFUSE_BASE_URL = "https://cloud.langfuse.com"; πͺπΊ EU region
# LANGFUSE_BASE_URL = "https://us.cloud.langfuse.com"; πΊπΈ US region
```
```
```javascript
import { LangfuseClient } from "@langfuse/client";
const langfuse = new LangfuseClient();
```
```javascript
import { LangfuseClient } from "@langfuse/client";
const langfuse = new LangfuseClient({
secretKey: "sk-lf-...",
publicKey: "pk-lf-...",
baseUrl: "https://cloud.langfuse.com", // πͺπΊ EU region
// baseUrl: "https://us.cloud.langfuse.com", // πΊπΈ US region
});
```
--------------------------------
### Install Langfuse Tracing Packages (Bash)
Source: https://langfuse-docs-git-add-js-sdk-v4-docs-langfuse.vercel.app/docs/observability/sdk/typescript/setup
Installs the necessary packages for Langfuse tracing: `@langfuse/tracing` for core functions, `@langfuse/otel` for exporting traces, and `@opentelemetry/sdk-node` for the OpenTelemetry SDK.
```bash
npm install @langfuse/tracing @langfuse/otel @opentelemetry/sdk-node
```
--------------------------------
### Install Langfuse Client Package (Bash)
Source: https://langfuse-docs-git-add-js-sdk-v4-docs-langfuse.vercel.app/docs/observability/sdk/typescript/setup
Installs the `@langfuse/client` package, which provides the necessary tools to interact with the Langfuse API for features beyond tracing.
```bash
npm install @langfuse/client
```
--------------------------------
### Install Langfuse JS/TS SDK Package
Source: https://langfuse-docs-git-add-js-sdk-v4-docs-langfuse.vercel.app/docs/get-started
Installs the Langfuse JavaScript/TypeScript SDK for tracing LLM and agent applications. Requires NPM or a compatible package manager. This example installs the package with OpenAI integration support.
```bash
npm install @langfuse/openai
```
--------------------------------
### Install and Configure Langfuse for JS/TS OpenAI SDK
Source: https://langfuse-docs-git-add-js-sdk-v4-docs-langfuse.vercel.app/docs/get-started
Installs the Langfuse OpenAI package for Node.js and sets up environment variables for Langfuse credentials. It also includes code for initializing OpenTelemetry with the LangfuseSpanProcessor.
```bash
npm install @langfuse/openai
```
```dotenv
LANGFUSE_SECRET_KEY = "sk-lf-..."
LANGFUSE_PUBLIC_KEY = "pk-lf-..."
LANGFUSE_BASE_URL = "https://cloud.langfuse.com" # πͺπΊ EU region
# LANGFUSE_BASE_URL = "https://us.cloud.langfuse.com" # πΊπΈ US region
```
```typescript
import { NodeSDK } from "@opentelemetry/sdk-node";
import { LangfuseSpanProcessor } from "@langfuse/otel";
const sdk = new NodeSDK({
spanProcessors: [new LangfuseSpanProcessor()],
});
sdk.start();
```
```typescript
import "./instrumentation"; // Must be the first import
```
--------------------------------
### Setup: Disable Warnings and Install Packages (Python)
Source: https://langfuse-docs-git-add-js-sdk-v4-docs-langfuse.vercel.app/guides/cookbook/example_intent_classification_pipeline
Initializes the environment by disabling warnings and installing necessary Python packages for Langfuse and intent classification tasks. Includes Langfuse client, pandas, scikit-learn, sentence-transformers, torch, transformers, chromadb, hdbscan, and openai.
```python
import warnings
warnings.filterwarnings("ignore")
```
```python
# Install Langfuse
%pip install --quiet "langfuse<3.0.0"
# Install dependencies for supervised intent classification
%pip install --quiet pandas scikit-learn sentence-transformers torch transformers
# Install dependencies for unsupervised intent recognition
%pip install --quiet chromadb hdbscan openai
```
--------------------------------
### Install and Configure Langfuse for LangChain JS/TS SDK
Source: https://langfuse-docs-git-add-js-sdk-v4-docs-langfuse.vercel.app/docs/get-started
Installs the Langfuse LangChain package for JavaScript/TypeScript and configures environment variables for Langfuse API credentials. It shows the initialization of the Langfuse callback handler.
```bash
npm i @langfuse/langchain
```
```dotenv
LANGFUSE_SECRET_KEY = "sk-lf-..."
LANGFUSE_PUBLIC_KEY = "pk-lf-..."
LANGFUSE_BASE_URL = "https://cloud.langfuse.com" # πͺπΊ EU region
# LANGFUSE_BASE_URL = "https://us.cloud.langfuse.com" # πΊπΈ US region
```
```typescript
import { CallbackHandler } from "@langfuse/langchain";
const langfuseHandler = new CallbackHandler();
```
--------------------------------
### Create Prompts with Python SDK
Source: https://langfuse-docs-git-add-js-sdk-v4-docs-langfuse.vercel.app/docs/prompt-management/get-started
This snippet shows how to create text and chat prompts using the Langfuse Python SDK. It includes installation instructions and setting environment variables for API credentials. Prompts can be defined with names, types, content, labels, and configurations.
```bash
pip install langfuse
LANGFUSE_SECRET_KEY = "sk-lf-..."
LANGFUSE_PUBLIC_KEY = "pk-lf-..."
LANGFUSE_HOST = "https://cloud.langfuse.com" # πͺπΊ EU region
# LANGFUSE_HOST = "https://us.cloud.langfuse.com" # πΊπΈ US region
```
```python
# Create a text prompt
langfuse.create_prompt(
name="movie-critic",
type="text",
prompt="As a {{criticlevel}} movie critic, do you like {{movie}}?",
labels=["production"], # directly promote to production
config={
"model": "gpt-4o",
"temperature": 0.7,
"supported_languages": ["en", "fr"],
}, # optionally, add configs (e.g. model parameters or model tools) or tags
)
# Create a chat prompt
langfuse.create_prompt(
name="movie-critic-chat",
type="chat",
prompt=[
{ "role": "system", "content": "You are an {{criticlevel}} movie critic" },
{ "role": "user", "content": "Do you like {{movie}}?" },
],
labels=["production"], # directly promote to production
config={
"model": "gpt-4o",
"temperature": 0.7,
"supported_languages": ["en", "fr"],
}, # optionally, add configs (e.g. model parameters or model tools) or tags
)
```
--------------------------------
### Create Prompts with JS/TS SDK
Source: https://langfuse-docs-git-add-js-sdk-v4-docs-langfuse.vercel.app/docs/prompt-management/get-started
This snippet demonstrates creating text and chat prompts using the Langfuse JS/TS SDK. It covers installation and authentication via environment variables or constructor parameters. Similar to the Python SDK, prompts can be configured with various details.
```bash
npm i @langfuse/client
# Environment variables
LANGFUSE_SECRET_KEY = "sk-lf-...";
LANGFUSE_PUBLIC_KEY = "pk-lf-...";
LANGFUSE_BASE_URL = "https://cloud.langfuse.com"; // πͺπΊ EU region
// LANGFUSE_BASE_URL = "https://us.cloud.langfuse.com"; // πΊπΈ US region
```
```typescript
import { LangfuseClient } from "@langfuse/client";
const langfuse = new LangfuseClient();
// Create a text prompt
await langfuse.prompt.create({
name: "movie-critic",
type: "text",
prompt: "As a {{criticlevel}} critic, do you like {{movie}}?",
labels: ["production"], // directly promote to production
config: {
model: "gpt-4o",
temperature: 0.7,
supported_languages: ["en", "fr"],
}, // optionally, add configs (e.g. model parameters or model tools) or tags
});
// Create a chat prompt
await langfuse.prompt.create({
name: "movie-critic-chat",
type: "chat",
prompt: [
{ role: "system", content: "You are an {{criticlevel}} movie critic" },
{ role: "user", content: "Do you like {{movie}}?" },
],
labels: ["production"], // directly promote to production
config: {
model: "gpt-4o",
temperature: 0.7,
supported_languages: ["en", "fr"],
}, // optionally, add configs (e.g. model parameters or model tools) or tags
});
```
--------------------------------
### Install Langfuse and OpenAI Python SDKs
Source: https://langfuse-docs-git-add-js-sdk-v4-docs-langfuse.vercel.app/docs/prompts/example-openai-functions
Install required Python packages for Langfuse and OpenAI integration. This is the initial setup step for using Langfuse prompt management with OpenAI functions.
```bash
%pip install langfuse openai --upgrade
```
--------------------------------
### Install Langfuse via Pip
Source: https://langfuse-docs-git-add-js-sdk-v4-docs-langfuse.vercel.app/docs/api-and-data-platform/features/query-via-sdk
Install the Langfuse Python SDK package using pip. Requires Python environment and internet access to PyPI. This is a one-time setup step before using the SDK.
```bash
pip install langfuse
```
--------------------------------
### Java SDK Setup and Usage
Source: https://langfuse-docs-git-add-js-sdk-v4-docs-langfuse.vercel.app/docs/api-and-data-platform/features/public-api
Details the setup and usage of the Java SDK for Langfuse, including dependency configuration and example usage for fetching prompts.
```xml
com.langfuse
langfuse-java
0.0.1-SNAPSHOT
github
GitHub Package Registry
https://maven.pkg.github.com/langfuse/langfuse-java
```
```java
import com.langfuse.client.LangfuseClient;
import com.langfuse.client.resources.prompts.types.PromptMetaListResponse;
import com.langfuse.client.core.LangfuseClientApiException;
LangfuseClient client = LangfuseClient.builder()
.url("https://cloud.langfuse.com") // πͺπΊ EU data region
// .url("https://us.cloud.langfuse.com") // πΊπΈ US data region
// .url("http://localhost:3000") // Local deployment
.credentials("pk-lf-...", "sk-lf-...")
.build();
try {
PromptMetaListResponse prompts = client.prompts().list();
} catch (LangfuseClientApiException error) {
System.out.println(error.getBody());
System.out.println(error.getStatusCode());
}
```
--------------------------------
### Initialize Langfuse Client in JS/TS
Source: https://langfuse-docs-git-add-js-sdk-v4-docs-langfuse.vercel.app/docs/prompts/get-started
Import and instantiate the LangfuseClient for JavaScript/TypeScript, using environment variables or constructor parameters for credentials. Depends on the @langfuse/client package being installed. Inputs: optional secretKey, publicKey, baseUrl. Outputs: a LangfuseClient instance for API interactions. Limitations: Requires valid keys; environment variables take precedence over constructor params.
```javascript
import { LangfuseClient } from "@langfuse/client";
const langfuse = new LangfuseClient();
```
```javascript
import { LangfuseClient } from "@langfuse/client";
const langfuse = new LangfuseClient({
secretKey: "sk-lf-",
publicKey: "pk-lf-",
baseUrl: "https://cloud.langfuse.com", // πͺπΊ EU region
// baseUrl: "https://us.cloud.langfuse.com", // πΊπΈ US region
});
```
--------------------------------
### Install Libraries for OpenAI-Agents SDK Evaluation
Source: https://langfuse-docs-git-add-js-sdk-v4-docs-langfuse.vercel.app/guides/cookbook/example_evaluating_openai_agents
Installs necessary Python libraries for using the OpenAI Agents SDK, Pydantic-AI with Logfire instrumentation, Langfuse for tracing and evaluation, and the Hugging Face Datasets library. This step ensures all dependencies are met for the subsequent integration.
```python
%pip install openai-agents nest_asyncio "pydantic-ai[logfire]" langfuse datasets
```
--------------------------------
### GET /prompt.get
Source: https://langfuse-docs-git-add-js-sdk-v4-docs-langfuse.vercel.app/docs/prompt-management/get-started
Retrieves a specific prompt by its name. Supports fetching specific versions or labels, and handling both text and chat prompts.
```APIDOC
## GET /prompt.get
### Description
Retrieves a specific prompt by its name. Supports fetching specific versions or labels, and handling both text and chat prompts.
### Method
GET
### Endpoint
`/prompt.get`
### Parameters
#### Query Parameters
- **name** (string) - Required - The name of the prompt to retrieve.
- **options** (object) - Optional - An object for specifying version, type, or label.
- **version** (number) - Optional - The specific version number of the prompt.
- **type** (string) - Optional - The type of prompt ('text' or 'chat'). Defaults to 'text'.
- **label** (string) - Optional - The label associated with the prompt version (e.g., 'staging', 'latest').
### Request Example
```typescript
// Get a text prompt
const langfusePrompt = await langfuse.prompt.get("movie-critic");
// Get a chat prompt
const langfusePrompt = await langfuse.prompt.get("movie-critic-chat", { type: "chat" });
// Get a specific version
const prompt = await langfuse.prompt.get("movie-critic", { version: 1 });
// Get a prompt by label
const prompt = await langfuse.prompt.get("movie-critic", { label: "staging" });
```
### Response
#### Success Response (200)
- **prompt** (object) - The retrieved prompt object.
- **prompt** (string | array) - The raw prompt content. String for text prompts, array of messages for chat prompts.
- **config** (object) - The configuration object for the prompt.
- **getLangchainPrompt** (function) - A method to transform the prompt for Langchain.
#### Response Example
```json
{
"prompt": "Translate the following text to French: {{text}}",
"config": {},
"getLangchainPrompt": () => "Translate the following text to French: {text}"
}
```
```json
{
"prompt": [
{ "role": "user", "content": "Who is {{character_name}}?" },
{ "role": "system", "content": "You are a helpful assistant." }
],
"config": {},
"getLangchainPrompt": () => [
{ "role": "user", "content": "Who is {character_name}?" },
{ "role": "system", "content": "You are a helpful assistant." }
]
}
```
```
--------------------------------
### Start Langfuse Server Locally with Docker Compose
Source: https://langfuse-docs-git-add-js-sdk-v4-docs-langfuse.vercel.app/self-hosting/v2/docker-compose
Clones the Langfuse repository, checks out the v2 branch, and starts the database and Langfuse server using docker compose. Assumes docker and docker compose are installed.
```bash
# Clone the Langfuse repository
git clone https://github.com/langfuse/langfuse.git
cd langfuse
# Checkout V2 branch
git checkout v2
# Start the database and langfuse server
docker compose up
```
--------------------------------
### Initialize Langfuse and Callback Handler
Source: https://langfuse-docs-git-add-js-sdk-v4-docs-langfuse.vercel.app/docs/prompts/get-started
Sets up the Langfuse client and callback handler for tracing. Requires Langfuse SDK and Langchain integration. Used for linking prompts to generations.
```Python
from langfuse.callback import CallbackHandler
from langfuse import Langfuse
langfuse_handler = CallbackHandler(
secret_key="sk-lf-...",
public_key="pk-lf-...",
base_url="https://cloud.langfuse.com", # EU region
# base_url="https://us.cloud.langfuse.com", # US region
)
langfuse = Langfuse()
```
```JavaScript
import { LangfuseClient } from "@langfuse/client";
import { CallbackHandler } from "@langfuse/langchain";
const langfuseHandler = new CallbackHandler({
secretKey: "sk-lf-...",
publicKey: "pk-lf-...",
baseUrl: "https://cloud.langfuse.com", // πͺπΊ EU region
// baseUrl: "https://us.cloud.langfuse.com", // πΊπΈ US region
});
const langfuse = new Langfuse();
```
--------------------------------
### Initialize Agent and Langfuse Client for Evaluation (Python)
Source: https://langfuse-docs-git-add-js-sdk-v4-docs-langfuse.vercel.app/guides/cookbook/example_evaluating_openai_agents
Sets up the Langfuse client and defines an agent with tools and instructions for web search. This prepares the environment for running the agent against a dataset. Requires `langfuse` and custom `agents` modules.
```python
from langfuse import get_client
langfuse = get_client()
dataset_name = "search-dataset_huggingface_openai-agent"
current_run_name = "qna_model_v3_run_05_20" # Identifies this specific evaluation run
agent = Agent(
name="WebSearchAgent",
instructions="You are an agent that can search the web.",
tools=[WebSearchTool(search_context_size= "high")]
)
```
--------------------------------
### Integrate Langfuse with LangChain Python SDK
Source: https://langfuse-docs-git-add-js-sdk-v4-docs-langfuse.vercel.app/docs/observability/get-started
This integration uses Langfuse CallbackHandler for observability in LangChain Python applications. It requires installing langfuse and langchain-openai packages along with environment variable setup for credentials. The handler traces chains and agents automatically; inputs are LangChain workflows, outputs are observed executions; partial setup shown, full usage requires additional LangChain code.
```bash
pip install langfuse langchain-openai
```
```bash
LANGFUSE_SECRET_KEY = "sk-lf-..."
LANGFUSE_PUBLIC_KEY = "pk-lf-..."
LANGFUSE_HOST = "https://cloud.langfuse.com" # πͺπΊ EU region
```
--------------------------------
### MinIO Docker Setup for Local Development
Source: https://langfuse-docs-git-add-js-sdk-v4-docs-langfuse.vercel.app/self-hosting/deployment/infrastructure/blobstorage
Command to start a MinIO container locally with Docker. Includes environment variables for root user and password, and exposes ports for console access.
```bash
docker run --name minio \
-p 9000:9000 \
-p 9001:9001 \
-e MINIO_ROOT_USER=minio \
-e MINIO_ROOT_PASSWORD=miniosecret \
minio/minio server /data --console-address ":9001"
```
--------------------------------
### Install Langfuse CallbackHandler for LangChain (JS/TS)
Source: https://langfuse-docs-git-add-js-sdk-v4-docs-langfuse.vercel.app/docs/observability/get-started
Installs the Langfuse callback handler package for LangChain using npm. This is the first step to integrating Langfuse observability into your JavaScript or TypeScript LangChain applications.
```bash
npm i @langfuse/langchain
```
--------------------------------
### Initialize Langfuse Client in JS and Python
Source: https://langfuse-docs-git-add-js-sdk-v4-docs-langfuse.vercel.app/docs/prompts/get-started
Initializes the Langfuse client for interacting with prompt management features. Requires the respective SDK packages (@langfuse/client for JS, langfuse for Python). No inputs needed beyond optional secret keys; outputs a client instance for further API calls. Limited to SDK-specific configurations.
```JavaScript
import { LangfuseClient } from "@langfuse/client";
// Iniitialize the Langfuse client
const langfuse = new LangfuseClient();
```
```Python
from langfuse import Langfuse
# Initialize Langfuse client
langfuse = Langfuse()
```
--------------------------------
### Initialize Langfuse client and handler (TypeScript)
Source: https://langfuse-docs-git-add-js-sdk-v4-docs-langfuse.vercel.app/docs/prompt-management/get-started
Shows how to set up Langfuse client and callback handler for tracing in TypeScript. Requires @langfuse/client and @langfuse/langchain packages.
```typescript
import { LangfuseClient } from "@langfuse/client";
import { CallbackHandler } from "@langfuse/langchain";
import { PromptTemplate } from "@langchain/core/prompts";
import { ChatOpenAI, OpenAI } from "@langchain/openai";
const langfuseHandler = new CallbackHandler({
secretKey: "sk-lf-...",
publicKey: "pk-lf-...",
baseUrl: "https://cloud.langfuse.com", // πͺπΊ EU region
// baseUrl: "https://us.cloud.langfuse.com", // πΊπΈ US region
});
const langfuse = new Langfuse();
```
--------------------------------
### Create and Use Text Prompt with Langchain
Source: https://langfuse-docs-git-add-js-sdk-v4-docs-langfuse.vercel.app/docs/prompts/get-started
Demonstrates creating a text prompt in Langchain using Langfuse prompt data. Metadata links the prompt to generated outputs for tracing. Assumes prior prompt creation in Langfuse.
```Python
langfuse_text_prompt = langfuse.get_prompt("movie-critic")
langchain_text_prompt = PromptTemplate.from_template(
langfuse_text_prompt.get_langchain_prompt(),
metadata={"langfuse_prompt": langfuse_text_prompt},
)
llm = OpenAI()
completion_chain = langchain_text_prompt | llm
completion_chain.invoke({"movie": "Dune 2", "criticlevel": "expert"}, config={"callbacks": [langfuse_handler]})
```
```JavaScript
const langfuseTextPrompt = await langfuse.prompt.get("movie-critic");
const langchainTextPrompt = PromptTemplate.fromTemplate(
langfuseTextPrompt.getLangchainPrompt()
).withConfig({
metadata: { langfusePrompt: langfuseTextPrompt },
});
const model = new OpenAI();
const chain = langchainTextPrompt.pipe(model);
await chain.invoke({ movie: "Dune 2", criticlevel: "expert" }, { callbacks: [langfuseHandler] });
```
--------------------------------
### Integrate Langfuse with OpenAI JS/TS SDK
Source: https://langfuse-docs-git-add-js-sdk-v4-docs-langfuse.vercel.app/docs/observability/get-started
This setup wraps the OpenAI JS/TS SDK with Langfuse for observability using OpenTelemetry. It involves installing the @langfuse/openai package, configuring environment variables, and initializing OpenTelemetry with LangfuseSpanProcessor. Inputs are standard OpenAI requests, outputs are wrapped responses with traces; limitations include needing dotenv for env vars and early import of instrumentation.
```bash
npm install @langfuse/openai
```
```bash
LANGFUSE_SECRET_KEY = "sk-lf-..."
LANGFUSE_PUBLIC_KEY = "pk-lf-..."
LANGFUSE_BASE_URL = "https://cloud.langfuse.com" # πͺπΊ EU region
# LANGFUSE_BASE_URL = "https://us.cloud.langfuse.com" # πΊπΈ US region
```
```typescript
import { NodeSDK } from "@opentelemetry/sdk-node";
import { LangfuseSpanProcessor } from "@langfuse/otel";
const sdk = new NodeSDK({
spanProcessors: [new LangfuseSpanProcessor()],
});
sdk.start();
```
```typescript
import "./instrumentation"; // Must be the first import
```
```typescript
import OpenAI from "openai";
import { observeOpenAI } from "@langfuse/openai";
const openai = observeOpenAI(new OpenAI());
const res = await openai.chat.completions.create({
messages: [{ role: "system", content: "Tell me a story about a dog." }],
model: "gpt-4o",
max_tokens: 300,
});
```
--------------------------------
### Install RAGAS and Dependencies
Source: https://langfuse-docs-git-add-js-sdk-v4-docs-langfuse.vercel.app/guides/cookbook/example_synthetic_datasets
Installs the RAGAS library and necessary components for document loading and language model interaction. This is the first step in setting up the RAGAS test generation environment.
```python
%pip install ragas langchain-community langchain-openai unstructured
```
--------------------------------
### Use chat prompt in Langchain (TypeScript)
Source: https://langfuse-docs-git-add-js-sdk-v4-docs-langfuse.vercel.app/docs/prompt-management/get-started
Example of fetching a chat prompt from Langfuse and using it in a Langchain ChatPromptTemplate with proper metadata linking. Requires @langchain packages.
```typescript
const langfuseChatPrompt = await langfuse.prompt.get(
"movie-critic-chat",
{
type: "chat",
}
); // type option infers the prompt type as chat (default is 'text')
const langchainChatPrompt = ChatPromptTemplate.fromMessages(
langfuseChatPrompt.getLangchainPrompt().map((m) => [m.role, m.content])
).withConfig({
metadata: { langfusePrompt: langfuseChatPrompt },
});
const chatModel = new ChatOpenAI();
const chatChain = langchainChatPrompt.pipe(chatModel);
await chatChain.invoke({ movie: "Dune 2", criticlevel: "expert" }, { callbacks: [langfuseHandler] });
```
--------------------------------
### Wrap OpenAI Client with Langfuse for JS/TS
Source: https://langfuse-docs-git-add-js-sdk-v4-docs-langfuse.vercel.app/docs/get-started
Shows how to wrap the standard OpenAI client with Langfuse's `observeOpenAI` function for automatic trace ingestion. This example assumes OpenTelemetry and Langfuse are already configured.
```typescript
import OpenAI from "openai";
import { observeOpenAI } from "@langfuse/openai";
const openai = observeOpenAI(new OpenAI());
const res = await openai.chat.completions.create({
messages: [{ role: "system", content: "Tell me a story about a dog." }],
model: "gpt-4o",
max_tokens: 300,
});
```
--------------------------------
### Test Basic Agent Instrumentation with Python
Source: https://langfuse-docs-git-add-js-sdk-v4-docs-langfuse.vercel.app/guides/cookbook/example_evaluating_openai_agents
This Python script demonstrates a simple Q&A agent and runs it to verify that Langfuse instrumentation is working correctly. It sends logs and spans to the observability dashboard upon successful execution. Ensure the 'agents' library and 'asyncio' are installed.
```python
import asyncio
from agents import Agent, Runner
async def main():
agent = Agent(
name="Assistant",
instructions="You are a senior software engineer",
)
result = await Runner.run(agent, "Tell me why it is important to evaluate AI agents.")
print(result.final_output)
loop = asyncio.get_running_loop()
await loop.create_task(main())
langfuse.flush()
```
--------------------------------
### Create a Prompt using Langfuse Public API (curl)
Source: https://langfuse-docs-git-add-js-sdk-v4-docs-langfuse.vercel.app/docs/prompts
Example using curl to create a chat prompt via the Langfuse public API. Requires specifying content type and providing prompt details in JSON format.
```shell
curl https://cloud.langfuse.com/api/public/v2/prompts \
--request POST \
--header 'Content-Type: application/json' \
--data '{
"type": "chat",
"name": "",
"prompt": [
{
"type": "chatmessage",
"role": "",
"content": ""
}
],
"config": null,
"labels": [
""
],
"tags": [
""
],
"commitMessage": null
}'
```
--------------------------------
### Fetch and Compile Chat Prompt in Python
Source: https://langfuse-docs-git-add-js-sdk-v4-docs-langfuse.vercel.app/docs/prompt-management/get-started
Fetches the production version of a chat prompt and compiles it with variables. Outputs a list of chat messages.
```Python
# Get current `production` version of a chat prompt
chat_prompt = langfuse.get_prompt("movie-critic-chat", type="chat") # type arg infers the prompt type (default is 'text')
# Insert variables into chat prompt template
compiled_chat_prompt = chat_prompt.compile(criticlevel="expert", movie="Dune 2")
# -> [{"role": "system", "content": "You are an expert movie critic"}, {"role": "user", "content": "Do you like Dune 2?"}]
```
--------------------------------
### Add Langfuse MCP Server via CLI
Source: https://langfuse-docs-git-add-js-sdk-v4-docs-langfuse.vercel.app/docs/observability/get-started
Command-line instructions for adding Langfuse Docs MCP server to Claude Code using HTTP transport. Includes manual configuration fallback and one-liner JSON import option for quick setup.
```bash
claude mcp add \
--transport http \
langfuse-docs \
https://langfuse.com/api/mcp \
--scope user
```
```bash
claude mcp add-json langfuse-docs \
'{"type":"http","url":"https://langfuse.com/api/mcp"}'
```
--------------------------------
### Create and Fetch Datasets in Python
Source: https://langfuse-docs-git-add-js-sdk-v4-docs-langfuse.vercel.app/docs/observability/sdk/python/evaluation
Demonstrates how to use the Langfuse SDK to fetch existing datasets and their items, as well as programmatically create new datasets and add items to them. It requires the 'langfuse' package to be installed.
```python
from langfuse import get_client
langfuse = get_client()
# Fetch an existing dataset
dataset = langfuse.get_dataset(name="my-eval-dataset")
for item in dataset.items:
print(f"Input: {item.input}, Expected: {item.expected_output}")
# Briefly: Creating a dataset and an item
new_dataset = langfuse.create_dataset(name="new-summarization-tasks")
langfuse.create_dataset_item(
dataset_name="new-summarization-tasks",
input={"text": "Long article..."},
expected_output={"summary": "Short summary."}
)
```
--------------------------------
### Example GET Request for Daily Metrics
Source: https://langfuse-docs-git-add-js-sdk-v4-docs-langfuse.vercel.app/changelog/2024-02-19-metrics-api-endpoint
This example shows how to make a GET request to the /api/public/metrics/daily endpoint to retrieve aggregated daily usage metrics. It demonstrates the use of optional filters like traceName and userId for targeted data retrieval. The endpoint is useful for analyzing application usage patterns over time.
```HTTP
GET /api/public/metrics/daily?traceName=my-copilot&userId=john
```
--------------------------------
### Install and Initialize JS/TS SDK
Source: https://langfuse-docs-git-add-js-sdk-v4-docs-langfuse.vercel.app/docs/query-traces
Installs the Langfuse JS/TS SDK using npm and initializes the Langfuse client with required authentication keys and optional base URL for different regions.
```javascript
npm install langfuse
```
```javascript
import { Langfuse } from "langfuse";
const langfuse = new Langfuse({
secretKey: "sk-lf-...",
```
```javascript
publicKey: "pk-lf-...",
baseUrl: "https://cloud.langfuse.com", // πͺπΊ EU region
//baseUrl: "https://us.cloud.langfuse.com", // πΊπΈ US region
});
```
--------------------------------
### Create and Use Chat Prompt with Langchain
Source: https://langfuse-docs-git-add-js-sdk-v4-docs-langfuse.vercel.app/docs/prompts/get-started
Demonstrates creating a chat prompt in Langchain using Langfuse prompt data. Metadata links the prompt to generated outputs for tracing. Requires specifying prompt type as 'chat'.
```Python
langfuse_chat_prompt = langfuse.get_prompt("movie-critic-chat", type="chat")
langchain_chat_prompt = ChatPromptTemplate.from_messages(
langfuse_chat_prompt.get_langchain_prompt()
)
langchain_chat_prompt.metadata = {"langfuse_prompt": langfuse_chat_prompt}
chat_llm = ChatOpenAI()
chat_chain = langchain_chat_prompt | chat_llm
chat_chain.invoke({"movie": "Dune 2", "criticlevel": "expert"}, config={"callbacks": [langfuse_handler]})
```
```JavaScript
const langfuseChatPrompt = await langfuse.prompt.get(
"movie-critic-chat",
{
type: "chat",
}
);
const langchainChatPrompt = ChatPromptTemplate.fromMessages(
langfuseChatPrompt.getLangchainPrompt().map((m) => [m.role, m.content])
).withConfig({
metadata: { langfusePrompt: langfuseChatPrompt },
});
const chatModel = new ChatOpenAI();
const chatChain = langchainChatPrompt.pipe(chatModel);
await chatChain.invoke({ movie: "Dune 2", criticlevel: "expert" }, { callbacks: [langfuseHandler] });
```
--------------------------------
### Initialize Langfuse Client (Python)
Source: https://langfuse-docs-git-add-js-sdk-v4-docs-langfuse.vercel.app/docs/prompts
Initializes the Langfuse client for use in Python applications. This is the starting point for interacting with Langfuse services in Python.
```python
from langfuse import Langfuse
from langchain_core.prompts import ChatPromptTemplate
# Initialize Langfuse client
langfuse = Langfuse()
```
--------------------------------
### Install Langfuse Helm Chart
Source: https://langfuse-docs-git-add-js-sdk-v4-docs-langfuse.vercel.app/self-hosting/deployment/kubernetes-helm
This command installs the Langfuse Helm chart into the specified Kubernetes namespace ('langfuse'). It deploys the Langfuse application and its dependencies.
```bash
helm install langfuse langfuse/langfuse -n langfuse
```
--------------------------------
### Initialize OpenTelemetry SDK with Langfuse
Source: https://langfuse-docs-git-add-js-sdk-v4-docs-langfuse.vercel.app/docs/get-started
Initializes the OpenTelemetry Node.js SDK and registers the LangfuseSpanProcessor. This file should be imported first in your application to ensure tracing is active from the start.
```typescript
import { NodeSDK } from "@opentelemetry/sdk-node";
import { LangfuseSpanProcessor } from "@langfuse/otel";
const sdk = new NodeSDK({
spanProcessors: [new LangfuseSpanProcessor()],
});
sdk.start();
```
--------------------------------
### Download Test Files (Python)
Source: https://langfuse-docs-git-add-js-sdk-v4-docs-langfuse.vercel.app/guides/cookbook/example_multi_modal_traces
Downloads sample files (image, audio, PDF) from a GitHub repository to a local 'static' directory. Handles potential download and save errors.
```python
import os
from urllib.request import urlretrieve
from urllib.error import URLError
REPO_URL = "https://github.com/langfuse/langfuse-python"
download_path = "static"
os.makedirs(download_path, exist_ok=True)
test_files = ["puton.jpg", "joke_prompt.wav", "bitcoin.pdf"]
raw_url = f"{REPO_URL}/raw/main/{download_path}"
for file in test_files:
try:
urlretrieve(f"{raw_url}/{file}", f"{download_path}/{file}")
print(f"Successfully downloaded: {file}")
except URLError as e:
print(f"Failed to download {file}: {e}")
except OSError as e:
print(f"Failed to save {file}: {e}")
```
--------------------------------
### Environment Setup and Langfuse Client Initialization
Source: https://langfuse-docs-git-add-js-sdk-v4-docs-langfuse.vercel.app/docs/evaluation/features/synthetic-datasets
Install required packages and initialize the Langfuse client with environment variables. This snippet sets up the necessary dependencies and credentials for connecting to Langfuse cloud service. The authentication is verified using auth_check() method to ensure proper connection.
```python
# Install required packages
%pip install openai langfuse
import os
# Get keys for your project from the project settings page: https://cloud.langfuse.com
os.environ["LANGFUSE_PUBLIC_KEY"] = "pk-lf-..."
os.environ["LANGFUSE_SECRET_KEY"] = "sk-lf-..."
os.environ["LANGFUSE_HOST"] = "https://cloud.langfuse.com" # πͺπΊ EU region
# os.environ["LANGFUSE_HOST"] = "https://us.cloud.langfuse.com" # πΊπΈ US region
# Your openai key
os.environ["OPENAI_API_KEY"] = "sk-proj-..."
from langfuse import get_client
langfuse = get_client()
# Verify connection
if langfuse.auth_check():
print("Langfuse client is authenticated and ready!")
else:
print("Authentication failed. Please check your credentials and host.")
```
--------------------------------
### Install and Run Flowise CLI
Source: https://langfuse-docs-git-add-js-sdk-v4-docs-langfuse.vercel.app/docs/flowise
This snippet shows the commands to install the Flowise CLI globally and then start the Flowise application. This is a prerequisite for using the Flowise no-code builder.
```bash
# install
npm install -g flowise
# start
npx flowise start
```
--------------------------------
### Setting Up Environment Variables for Langfuse and OpenAI
Source: https://langfuse-docs-git-add-js-sdk-v4-docs-langfuse.vercel.app/docs/prompts/example-langchain-js
Configures authentication keys and host for Langfuse, along with OpenAI API key using Deno.js syntax. This setup is required before initializing SDKs. It supports US data region by setting LANGFUSE_HOST accordingly; for Node.js, use process.env instead.
```javascript
// Langfuse authentication keys
Deno.env.set("LANGFUSE_PUBLIC_KEY", "pk-lf-***");
Deno.env.set("LANGFUSE_SECRET_KEY", "sk-lf-***");
// Langfuse host configuration
// For US data region, set this to "https://us.cloud.langfuse.com"
Deno.env.set("LANGFUSE_HOST", "https://cloud.langfuse.com")
// Set environment variables using Deno-specific syntax
Deno.env.set("OPENAI_API_KEY", "sk-proj-***");
```
--------------------------------
### Get Specific Prompt Version (Python)
Source: https://langfuse-docs-git-add-js-sdk-v4-docs-langfuse.vercel.app/docs/prompts
Retrieves a prompt by its name and a specific version number. This is useful for ensuring consistency or rolling back to a previous prompt configuration.
```python
# Get specific version
prompt = langfuse.get_prompt("movie-critic", version=1)
```