### Setup OpenTelemetry Tracing with IConfiguration Source: https://github.com/lukaszzborek/langfuse-dotnet/blob/main/docs/setup.md Register the Langfuse OpenTelemetry exporter and trace service using `IConfiguration` for setup. This method reads configuration from `appsettings.json`. ```csharp using zborek.Langfuse.OpenTelemetry; var builder = WebApplication.CreateBuilder(args); builder.Services.AddOpenTelemetry() .WithTracing(tracing => { tracing.AddLangfuseExporter(builder.Configuration.GetSection("Langfuse")); }); // Register IOtelLangfuseTrace for dependency injection builder.Services.AddLangfuseTracing(); ``` -------------------------------- ### Restore Dependencies and Run .NET Examples Source: https://github.com/lukaszzborek/langfuse-dotnet/blob/main/Examples/Langfuse.Example.OpenTelemetry/README.md Command-line instructions for restoring NuGet packages and executing the OpenTelemetry example application. ```bash dotnet restore dotnet run dotnet run genai ``` -------------------------------- ### Setup API Client Programmatically Source: https://github.com/lukaszzborek/langfuse-dotnet/blob/main/docs/setup.md Configure the Langfuse API client programmatically by providing configuration options directly. This allows for dynamic setup of the client. ```csharp builder.Services.AddLangfuse(config => { config.Url = "https://cloud.langfuse.com"; config.PublicKey = "pk-..."; config.SecretKey = "sk-..."; }); ``` -------------------------------- ### Install Langfuse .NET SDK Source: https://github.com/lukaszzborek/langfuse-dotnet/blob/main/docs/setup.md Use the `dotnet add package` command to install the Langfuse .NET SDK. This command adds the necessary package to your project file. ```bash dotnet add package zborek.LangfuseDotnet ``` -------------------------------- ### GenAiToolDefinition Object Initialization Source: https://github.com/lukaszzborek/langfuse-dotnet/blob/main/docs/tracing.md Example of initializing a GenAiToolDefinition object with name and description. ```csharp new GenAiToolDefinition { Name = "get_weather", Description = "Get weather info" } ``` -------------------------------- ### GenAiResponse Object Initialization Source: https://github.com/lukaszzborek/langfuse-dotnet/blob/main/docs/tracing.md Example of initializing a GenAiResponse object with details like model, token counts, finish reasons, and completion. ```csharp new GenAiResponse { Model = "gpt-4", InputTokens = 50, OutputTokens = 100, FinishReasons = ["stop"], Completion = "result text" } ``` -------------------------------- ### Setup API Client with IConfiguration Source: https://github.com/lukaszzborek/langfuse-dotnet/blob/main/docs/setup.md Register the Langfuse API client service using `IConfiguration`. This method reads configuration from `appsettings.json` for connecting to the Langfuse API. ```csharp using zborek.Langfuse; builder.Services.AddLangfuse(builder.Configuration); ``` -------------------------------- ### Setup OpenTelemetry Tracing Programmatically Source: https://github.com/lukaszzborek/langfuse-dotnet/blob/main/docs/setup.md Configure the Langfuse OpenTelemetry exporter programmatically by providing options directly. This is useful for dynamic configuration or when not using `IConfiguration`. ```csharp builder.Services.AddOpenTelemetry() .WithTracing(tracing => { tracing.AddLangfuseExporter(options => { options.PublicKey = "pk-..."; options.SecretKey = "sk-..."; options.Url = "https://cloud.langfuse.com"; }); }); ``` -------------------------------- ### GenAiMessage Object Initialization Source: https://github.com/lukaszzborek/langfuse-dotnet/blob/main/docs/tracing.md Example of initializing a GenAiMessage object with role and content. ```csharp new GenAiMessage { Role = "user", Content = "Hello!" } ``` -------------------------------- ### Register Langfuse Client Source: https://github.com/lukaszzborek/langfuse-dotnet/blob/main/README.md Configure the ILangfuseClient via dependency injection using either configuration files or programmatic setup. ```csharp using zborek.Langfuse; builder.Services.AddLangfuse(builder.Configuration); ``` ```csharp builder.Services.AddLangfuse(config => { config.Url = "https://cloud.langfuse.com"; config.PublicKey = "pk-..."; config.SecretKey = "sk-..."; }); ``` -------------------------------- ### LLM Provider Configurations for Langfuse .NET Source: https://github.com/lukaszzborek/langfuse-dotnet/blob/main/Examples/Langfuse.Example.OpenTelemetry/GENAI_HELPER_REFERENCE.md Provides configuration examples for various LLM providers compatible with the Langfuse .NET SDK. This includes specifying the provider name and the available models for each service. The examples cover OpenAI, Anthropic (Claude), Azure OpenAI, and AWS Bedrock. ```plaintext Provider = "openai" Model = "gpt-4" | "gpt-3.5-turbo" | "text-embedding-ada-002" ``` ```plaintext Provider = "anthropic" Model = "claude-3-5-sonnet-20241022" | "claude-3-opus-20240229" FinishReasons = new[] { "end_turn" | "max_tokens" | "stop_sequence" } ``` ```plaintext Provider = "azure.ai.openai" Model = "your-deployment-name" ``` ```plaintext Provider = "aws.bedrock" Model = "anthropic.claude-v2" | "amazon.titan-text-express-v1" ``` -------------------------------- ### Development CLI Commands Source: https://github.com/lukaszzborek/langfuse-dotnet/blob/main/CLAUDE.md Common CLI commands for building, testing, and running the Langfuse .NET project. These commands utilize the dotnet CLI to manage the solution and example applications. ```bash dotnet build dotnet test dotnet run --project Examples/Langfuse.Example.Console dotnet pack src/Langfuse/Langfuse.csproj ``` -------------------------------- ### Skip Pattern Source: https://github.com/lukaszzborek/langfuse-dotnet/blob/main/docs/tracing.md Learn how to conditionally skip instrumentation for spans or entire traces, for example, when utilizing a cache. ```APIDOC ## Skip Pattern ### Description Conditionally skip the instrumentation of individual spans or entire traces. This is useful for scenarios like cache hits where you don't want to record redundant operations. ### Method `span.Skip()` or `trace.Skip()` ### Parameters None ### Request Example ```csharp using var span = trace.CreateSpan("llm-processing"); if (cachedResult != null) { // Skip this span - won't be sent to Langfuse span.Skip(); return cachedResult; } // Or skip the entire trace trace.Skip(); ``` ### Response N/A ``` -------------------------------- ### Dependency Injection Registration Source: https://github.com/lukaszzborek/langfuse-dotnet/blob/main/CLAUDE.md Registers the Langfuse client and services into the .NET dependency injection container. This setup configures HTTP clients, authentication handlers, and background services. ```csharp services.AddLangfuse(configuration); ``` -------------------------------- ### OtelLangfuseTrace constructors and factory Source: https://github.com/lukaszzborek/langfuse-dotnet/blob/main/docs/tracing.md Initialization options for direct trace instantiation. ```text OtelLangfuseTrace() — default, lazy trace initialization OtelLangfuseTrace(ActivitySource) — with custom ActivitySource OtelLangfuseTrace(name, userId?, sessionId?, environment?, release?, tags?, input?, isPublic?) — immediate trace creation OtelLangfuseTrace(ActivitySource, name, userId?, sessionId?, environment?, release?, tags?, input?, isPublic?) — with ActivitySource and immediate creation ``` ```csharp // Create independent trace for parallel operations (not linked to current Activity context) var detached = OtelLangfuseTrace.CreateDetachedTrace("parallel-task", userId: "user-123", sessionId: "session-456"); ``` -------------------------------- ### Trace operations using direct instantiation Source: https://github.com/lukaszzborek/langfuse-dotnet/blob/main/README.md Use OtelLangfuseTrace directly for manual trace management without dependency injection. ```csharp using var trace = new OtelLangfuseTrace("customer-support", userId: "user-123", sessionId: "session-456", tags: ["support", "billing"], input: new { source = "web-chat" }); // Create a span for a logical operation using (var span = trace.CreateSpan("document-retrieval", type: "retrieval", description: "Retrieve relevant documents")) { // Nested embedding using var embedding = trace.CreateEmbedding("query-embedding", model: "text-embedding-3-small", provider: "openai", input: query); await Task.Delay(50); embedding.SetResponse(new GenAiResponse { InputTokens = 15 }); span.SetOutput(new { documents = new[] { "doc1.pdf", "doc2.pdf" } }); } // Create a generation using (var generation = trace.CreateGeneration("generate-response", model: "gpt-4", provider: "openai", configure: g => { g.SetTemperature(0.7); g.SetInputMessages(new List { new() { Role = "user", Content = "Hello!" } }); })) { var response = await CallLLMAsync(); generation.SetResponse(new GenAiResponse { Model = "gpt-4", InputTokens = 10, OutputTokens = 25, FinishReasons = ["stop"], Completion = response }); } ``` -------------------------------- ### Instrumenting Chat Completions with GenAiActivityHelper Source: https://github.com/lukaszzborek/langfuse-dotnet/blob/main/Examples/Langfuse.Example.OpenTelemetry/GENAI_HELPER_REFERENCE.md Demonstrates how to initialize a chat completion activity using configuration parameters and record the resulting response metadata. This pattern ensures that token usage and model information are captured according to semantic standards. ```csharp using Langfuse.Example.OpenTelemetry; var activitySource = new ActivitySource("MyApp"); var config = new GenAiChatCompletionConfig { Provider = "openai", Model = "gpt-4", Temperature = 0.7, MaxTokens = 1000 }; using var activity = GenAiActivityHelper.CreateChatCompletionActivity(activitySource, "chat", config); // ... make your LLM API call ... GenAiActivityHelper.RecordResponse(activity, new GenAiResponse { ResponseId = "chatcmpl-123", Model = "gpt-4-0613", InputTokens = 25, OutputTokens = 150, FinishReasons = new[] { "stop" } }); ``` -------------------------------- ### OtelLangfuseTrace (Direct) Source: https://github.com/lukaszzborek/langfuse-dotnet/blob/main/docs/tracing.md Direct instantiation of tracing objects for scenarios where dependency injection is not available or for parallel tasks. ```APIDOC ## OtelLangfuseTrace ### Description Allows manual creation of traces and detached traces for parallel operations. ### Constructors - **OtelLangfuseTrace()** - Default constructor. - **OtelLangfuseTrace(name, userId?, sessionId?, environment?, release?, tags?, input?, isPublic?)** - Immediate trace creation. ### Static Factory - **CreateDetachedTrace**(name, userId?, sessionId?) - Creates an independent trace not linked to the current Activity context. ``` -------------------------------- ### SCIM User Provisioning Source: https://github.com/lukaszzborek/langfuse-dotnet/blob/main/docs/api-client.md Endpoints for SCIM-based user provisioning and configuration. ```APIDOC ## GET /scim/ServiceProviderConfig ### Description Retrieves SCIM service provider configuration. ### Method GET ### Endpoint /scim/ServiceProviderConfig ## GET /scim/Schemas ### Description Retrieves SCIM schemas. ### Method GET ### Endpoint /scim/Schemas ## GET /scim/ResourceTypes ### Description Retrieves SCIM resource types. ### Method GET ### Endpoint /scim/ResourceTypes ## GET /scim/Users ### Description Retrieves a paginated list of SCIM users. ### Method GET ### Endpoint /scim/Users ## POST /scim/Users ### Description Creates a new SCIM user. ### Method POST ### Endpoint /scim/Users ### Request Body - **CreateScimUserRequest** (object) - Required - Request body for creating a SCIM user ``` -------------------------------- ### Register Langfuse with Dependency Injection Source: https://github.com/lukaszzborek/langfuse-dotnet/blob/main/README.md Configure OpenTelemetry and register the tracing service in your application startup. ```csharp using zborek.Langfuse.OpenTelemetry; var builder = WebApplication.CreateBuilder(args); // Configure OpenTelemetry with Langfuse exporter builder.Services.AddOpenTelemetry() .WithTracing(tracing => { tracing.AddLangfuseExporter(builder.Configuration.GetSection("Langfuse")); }); // Register IOtelLangfuseTrace for dependency injection builder.Services.AddLangfuseTracing(); ``` ```csharp builder.Services.AddOpenTelemetry() .WithTracing(tracing => { tracing.AddLangfuseExporter(options => { options.PublicKey = "pk-..."; options.SecretKey = "sk-..."; options.Url = "https://cloud.langfuse.com"; }); }); ``` -------------------------------- ### Trace Agent Workflows with OtelAgent Source: https://github.com/lukaszzborek/langfuse-dotnet/blob/main/docs/tracing.md Use OtelAgent to trace agent workflows. Provide a name, agent ID, description, and input. Set the agent's final output. ```csharp using var agent = trace.CreateAgent("research-assistant", agentId: "agent-001", description: "An agent that researches topics", input: query); // Agent performs multiple steps with nested observations... agent.SetOutput(synthesizedResult); ``` -------------------------------- ### Define Prompt Request Structures Source: https://github.com/lukaszzborek/langfuse-dotnet/blob/main/docs/api-types.md Request models for creating prompts and listing existing prompts with filters. ```text CreatePromptRequest (abstract) Type: PromptType? // Text or Chat Name: string // Prompt name (required) Config: object? // Configuration Labels: List // Labels Tags: List // Tags CommitMessage: string? // Commit message PromptListRequest Page: int? Limit: int? Name: string? // Filter by name Tag: string? // Filter by tag Label: string? // Filter by label ``` -------------------------------- ### Trace directly without dependency injection Source: https://github.com/lukaszzborek/langfuse-dotnet/blob/main/docs/tracing.md Instantiate OtelLangfuseTrace directly for scenarios where dependency injection is not used. ```csharp using var trace = new OtelLangfuseTrace("customer-support", userId: "user-123", sessionId: "session-456", tags: ["support", "billing"], input: new { source = "web-chat" }); using (var span = trace.CreateSpan("document-retrieval", type: "retrieval", description: "Retrieve relevant documents")) { using var embedding = trace.CreateEmbedding("query-embedding", model: "text-embedding-3-small", provider: "openai", input: query); embedding.SetResponse(new GenAiResponse { InputTokens = 15 }); span.SetOutput(new { documents = new[] { "doc1.pdf", "doc2.pdf" } }); } ``` -------------------------------- ### Manage observation lifecycle and properties Source: https://github.com/lukaszzborek/langfuse-dotnet/blob/main/docs/tracing.md Methods and properties for managing individual observations. ```text SetInput(object) SetOutput(object) SetMetadata(string key, object value) SetLevel(LangfuseObservationLevel) // DEBUG, INFO, WARNING, ERROR SetTag(string key, object? value) SetStatusMessage(string) Skip() // don't export this observation EndObservation() // explicitly end Dispose() // ends the observation ``` ```text Activity → Activity? // underlying OTel Activity HasActivity → bool // check if activity exists IsSkipped → bool // check if skipped ``` -------------------------------- ### Trace Discrete Events with OtelEvent Source: https://github.com/lukaszzborek/langfuse-dotnet/blob/main/docs/tracing.md Use OtelEvent to trace discrete point-in-time events. Provide a name and optional input/output details. ```csharp using var evt = trace.CreateEvent("user-feedback", input: new { rating = 5 }, output: new { action = "logged" }); ``` -------------------------------- ### Create and Record Chat Completion Activities in .NET Source: https://github.com/lukaszzborek/langfuse-dotnet/blob/main/Examples/Langfuse.Example.OpenTelemetry/README.md Demonstrates how to initialize a GenAiChatCompletionConfig, create an activity using GenAiActivityHelper, and record the LLM response metadata. This is essential for tracking token usage and model performance. ```csharp var config = new GenAiChatCompletionConfig { Provider = "openai", Model = "gpt-4", Temperature = 0.7, MaxTokens = 1000, TopP = 1.0, ConversationId = "conv-123" }; using var activity = GenAiActivityHelper.CreateChatCompletionActivity( activitySource, "chat-completion", config); // ... perform your LLM API call ... // Record the response var response = new GenAiResponse { ResponseId = "chatcmpl-123456", Model = "gpt-4-0613", InputTokens = 25, OutputTokens = 150, FinishReasons = new[] { "stop" } }; GenAiActivityHelper.RecordResponse(activity, response); ``` -------------------------------- ### Create observations Source: https://github.com/lukaszzborek/langfuse-dotnet/blob/main/docs/tracing.md Methods for creating various observation types within a trace. ```text CreateSpan(name, type?, description?, input?, configure?) → OtelSpan CreateGeneration(name, model, provider, input?, configure?) → OtelGeneration CreateEmbedding(name, model, provider, input?, configure?) → OtelEmbedding CreateToolCall(name, toolName, toolDescription?, provider, input?, configure?) → OtelToolCall CreateAgent(name, agentId, description?, input?, configure?) → OtelAgent CreateEvent(name, input?, output?) → OtelEvent ``` -------------------------------- ### Create an Agent Observation Source: https://github.com/lukaszzborek/langfuse-dotnet/blob/main/README.md Use CreateAgent to track iterations within an agent loop. ```csharp using var agent = trace.CreateAgent("research-assistant", agentId: "agent-001", description: "An agent that researches topics", input: query); // Agent performs multiple steps... agent.SetOutput(synthesizedResult); ``` -------------------------------- ### C# Function Calling with Langfuse Helper Source: https://github.com/lukaszzborek/langfuse-dotnet/blob/main/Examples/Langfuse.Example.OpenTelemetry/GENAI_HELPER_REFERENCE.md Demonstrates how to use the GenAiActivityHelper in C# to track chat completions, tool calls, and responses. It shows the creation of chat and tool call activities, recording response details, and executing tool calls as child spans. This approach ensures OpenTelemetry compliance for AI operations. ```csharp // Main chat request using var chatActivity = GenAiActivityHelper.CreateChatCompletionActivity( activitySource, "chat", config); var chatResult = await CallOpenAiAsync(); GenAiActivityHelper.RecordResponse(chatActivity, new GenAiResponse { ResponseId = chatResult.Id, FinishReasons = new[] { "tool_calls" } }); // Execute tool call as child span using (var toolActivity = GenAiActivityHelper.CreateToolCallActivity( activitySource, "execute-function", "get_weather", "function", "call_123")) { toolActivity?.SetTag("gen_ai.tool.call.arguments", "{\"location\":\"SF\"}"); var result = await ExecuteToolAsync(); toolActivity?.SetTag("gen_ai.tool.call.result", result); } // Send result back to model var finalResult = await CallOpenAiAsync(); GenAiActivityHelper.RecordResponse(chatActivity, ...); ``` -------------------------------- ### Trace LLM Generation Calls with OtelGeneration Source: https://github.com/lukaszzborek/langfuse-dotnet/blob/main/docs/tracing.md Use OtelGeneration to trace LLM calls, including model, provider, input, and configuration like temperature and max tokens. Set the response details after receiving it. ```csharp using var gen = trace.CreateGeneration("chat", model: "gpt-4", provider: "openai", input: new { prompt }, configure: g => { g.SetTemperature(0.7); g.SetMaxTokens(500); g.SetInputMessages(new List { new() { Role = "user", Content = "Hello!" } }); }); gen.SetResponse(new GenAiResponse { Model = "gpt-4", InputTokens = 50, OutputTokens = 100, FinishReasons = ["stop"], Completion = result }); ``` -------------------------------- ### Trace LLM operations using Dependency Injection Source: https://github.com/lukaszzborek/langfuse-dotnet/blob/main/README.md Inject IOtelLangfuseTrace to manage traces and generations within a scoped service. ```csharp public class MyService { private readonly IOtelLangfuseTrace _trace; public MyService(IOtelLangfuseTrace trace) { _trace = trace; } public async Task ProcessAsync(string prompt) { // Start a trace (call once per request) _trace.StartTrace("my-workflow", userId: "user-123", sessionId: "session-456"); // Create a generation for LLM call using var generation = _trace.CreateGeneration("openai-chat", model: "gpt-4", provider: "openai", input: new { prompt }, configure: g => { g.SetTemperature(0.7); g.SetMaxTokens(500); }); var result = await CallLLMAsync(prompt); generation.SetResponse(new GenAiResponse { Model = "gpt-4", InputTokens = 50, OutputTokens = 100, FinishReasons = ["stop"], Completion = result }); _trace.SetOutput(new { result }); return result; } } ``` -------------------------------- ### Trace properties and lifecycle methods Source: https://github.com/lukaszzborek/langfuse-dotnet/blob/main/docs/tracing.md Reference for trace properties and methods available on the tracing interface. ```text TraceActivity → Activity? // underlying OTel Activity HasActiveTrace → bool // whether trace is active ``` ```text StartTrace(name, traceId?, userId?, sessionId?, environment?, tags?, input?, isPublic?) → IOtelLangfuseTrace SetTraceName(string) SetInput(object) SetOutput(object) SetTraceId(string) SetUserId(string) SetSessionId(string) SetEnvironment(string) SetRelease(string) SetVersion(string) SetPublic(bool) SetMetadata(string key, object value) SetTags(IEnumerable) Skip() // don't export this trace ``` -------------------------------- ### Trace workflow using IOtelLangfuseTrace with DI Source: https://github.com/lukaszzborek/langfuse-dotnet/blob/main/docs/tracing.md Inject IOtelLangfuseTrace into a service to manage trace lifecycles and record generations within a scoped request. ```csharp public class MyService { private readonly IOtelLangfuseTrace _trace; public MyService(IOtelLangfuseTrace trace) { _trace = trace; } public async Task ProcessAsync(string prompt) { _trace.StartTrace("my-workflow", userId: "user-123", sessionId: "session-456"); using var generation = _trace.CreateGeneration("openai-chat", model: "gpt-4", provider: "openai", input: new { prompt }, configure: g => { g.SetTemperature(0.7); g.SetMaxTokens(500); }); var result = await CallLLMAsync(prompt); generation.SetResponse(new GenAiResponse { Model = "gpt-4", InputTokens = 50, OutputTokens = 100, FinishReasons = ["stop"], Completion = result }); _trace.SetOutput(new { result }); return result; } } ``` -------------------------------- ### Trace Vector Embeddings with OtelEmbedding Source: https://github.com/lukaszzborek/langfuse-dotnet/blob/main/docs/tracing.md Use OtelEmbedding to trace vector embedding generation. Specify the model, provider, and input query. Set response details like input tokens. ```csharp using var emb = trace.CreateEmbedding("query-embedding", model: "text-embedding-3-small", provider: "openai", input: query); emb.SetResponse(new GenAiResponse { InputTokens = 15 }); ``` -------------------------------- ### Creating Specialized Gen AI Activities Source: https://github.com/lukaszzborek/langfuse-dotnet/blob/main/Examples/Langfuse.Example.OpenTelemetry/GENAI_HELPER_REFERENCE.md Provides the API signatures for creating activities for text completions, embeddings, and tool calls. These methods allow developers to track specific Gen AI operations with appropriate context. ```csharp // Text Completion GenAiActivityHelper.CreateTextCompletionActivity(activitySource, "operationName", config); // Embeddings var activity = GenAiActivityHelper.CreateEmbeddingsActivity(activitySource, "op", "openai", "text-embedding-3"); activity?.SetTag("gen_ai.embeddings.dimension.count", 1536); // Tool Calls var toolActivity = GenAiActivityHelper.CreateToolCallActivity(activitySource, "op", "my_tool"); toolActivity?.SetTag("gen_ai.tool.call.arguments", jsonArguments); ``` -------------------------------- ### Project Management Source: https://github.com/lukaszzborek/langfuse-dotnet/blob/main/docs/api-client.md Endpoints for managing project lifecycle and configuration. ```APIDOC ## GET /projects ### Description Retrieves project details. ### Method GET ### Endpoint /projects ## GET /projects/list ### Description Retrieves a paginated list of projects. ### Method GET ### Endpoint /projects/list ## POST /projects ### Description Creates a new project. ### Method POST ### Endpoint /projects ### Request Body - **CreateProjectRequest** (object) - Required - Request body for creating a project ## PUT /projects/{id} ### Description Updates an existing project. ### Method PUT ### Endpoint /projects/{id} ### Parameters #### Path Parameters - **id** (string) - Required - The ID of the project ### Request Body - **UpdateProjectRequest** (object) - Required - Request body for updating a project ## DELETE /projects/{id} ### Description Deletes a project. ### Method DELETE ### Endpoint /projects/{id} ### Parameters #### Path Parameters - **id** (string) - Required - The ID of the project ``` -------------------------------- ### Create a score Source: https://github.com/lukaszzborek/langfuse-dotnet/blob/main/docs/api-client.md Submits a new score for a specific trace. ```csharp await _langfuseClient.CreateScoreAsync(new ScoreCreateRequest { TraceId = "trace-123", Name = "accuracy", Value = 0.95 }); ``` -------------------------------- ### OtelAgent — agent workflows Source: https://github.com/lukaszzborek/langfuse-dotnet/blob/main/docs/tracing.md Instrumenting agent workflows. This allows tracking the agent's ID, description, input, and the final output or result of the agent's execution. ```APIDOC ## OtelAgent — agent workflows ### Description Instrument agent workflows to track the agent's execution, including its ID, description, input, and the synthesized output. ### Method `trace.CreateAgent(string name, ...)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None (Parameters are passed to the constructor and methods) ### Request Example ```csharp using var agent = trace.CreateAgent("research-assistant", agentId: "agent-001", description: "An agent that researches topics", input: query); // Agent performs multiple steps with nested observations... agent.SetOutput(synthesizedResult); ``` ### Response #### Success Response (200) N/A #### Response Example N/A ### Available Methods for OtelAgent: - `SetDataSource(string)` ``` -------------------------------- ### OtelGeneration — LLM calls Source: https://github.com/lukaszzborek/langfuse-dotnet/blob/main/docs/tracing.md Instrumenting Large Language Model (LLM) calls using the `CreateGeneration` method. This allows for detailed logging of prompts, model parameters, and responses. ```APIDOC ## OtelGeneration — LLM calls ### Description Instrument LLM calls to capture model, provider, input, and configuration details. You can also set the response, including token counts and finish reasons. ### Method `trace.CreateGeneration(string name, ...)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None (Configuration is done via method parameters and fluent API) ### Request Example ```csharp using var gen = trace.CreateGeneration("chat", model: "gpt-4", provider: "openai", input: new { prompt }, configure: g => { g.SetTemperature(0.7); g.SetMaxTokens(500); g.SetInputMessages(new List { new() { Role = "user", Content = "Hello!" } }); }); gen.SetResponse(new GenAiResponse { Model = "gpt-4", InputTokens = 50, OutputTokens = 100, FinishReasons = ["stop"], Completion = result }); ``` ### Response #### Success Response (200) N/A (This is for instrumentation, not an API endpoint response) #### Response Example N/A ### Available Methods for OtelGeneration: - `SetInputMessages(IEnumerable)` - `SetPrompt(string)` - `SetResponse(GenAiResponse)` - `SetCompletion(string)` - `SetPromptReference(name, version?)` - `RecordCompletionStartTime(DateTimeOffset?)` // Time to First Token - `SetTemperature(double)` - `SetMaxTokens(int)` - `SetTopP(double)` - `SetTopK(int)` - `SetFrequencyPenalty(double)` - `SetPresencePenalty(double)` - `SetRequestModel(string)` - `SetProvider(string)` - `SetChoiceCount(int)` - `SetSeed(int)` - `SetStopSequences(string[])` - `SetOutputType(string)` // "text", "json" - `SetConversationId(string)` - `SetSystemInstructions(string)` - `SetToolDefinitions(List)` - `SetToolDefinitions(string)` // from JSON - `SetServerAddress(string)` - `SetServerPort(int)` - `SetUsageDetails(Dictionary)` - `SetCostDetails(Dictionary)` - `SetCacheReadInputTokens(int)` - `SetCacheCreationInputTokens(int)` ``` -------------------------------- ### Retrieve a prompt Source: https://github.com/lukaszzborek/langfuse-dotnet/blob/main/docs/api-client.md Fetches a specific prompt version from the Langfuse API. ```csharp var prompt = await _langfuseClient.GetPromptAsync("my-prompt", label: "production"); ``` -------------------------------- ### Trace Function/Tool Invocations with OtelToolCall Source: https://github.com/lukaszzborek/langfuse-dotnet/blob/main/docs/tracing.md Use OtelToolCall to trace function or tool invocations. Provide the tool name, description, provider, and input. Set the result after the tool execution. ```csharp using var tool = trace.CreateToolCall("lookup-account", toolName: "get_account_info", toolDescription: "Retrieves customer account information", provider: "internal", input: new { customer_id = "cust-789" }); var accountInfo = await GetAccountAsync("cust-789"); tool.SetResult(accountInfo); ``` -------------------------------- ### Define Prompt Data Models Source: https://github.com/lukaszzborek/langfuse-dotnet/blob/main/docs/api-types.md Polymorphic structures for text and chat prompts, including metadata and message types. ```text Prompt (abstract, polymorphic on Type: "text" or "chat") Name: string // Prompt name Version: int // Version number Config: object? // Configuration object Labels: List // Categorization labels Tags: List // Metadata tags CommitMessage: string? // Version description TextPrompt : Prompt Type: "text" PromptText: string // Text content of prompt ChatPrompt : Prompt Type: "chat" PromptMessages: List // Chat messages ChatMessage : ChatMessageWithPlaceholders Role: string // system, user, assistant, etc. Content: string // Message content PlaceholderMessage : ChatMessageWithPlaceholders Name: string // Placeholder variable name PromptMeta Name: string // Prompt name Type: PromptType // Text or Chat Versions: List // Available version numbers Tags: List Labels: List LastUpdatedAt: DateTime LastConfig: object? PromptType (enum): Text, Chat ``` -------------------------------- ### Dataset Management Requests Source: https://github.com/lukaszzborek/langfuse-dotnet/blob/main/docs/api-types.md Definitions for creating and listing datasets, items, and runs. ```APIDOC ## POST /datasets ### Description Creates a new dataset. ### Request Body - **Name** (string) - Required - Dataset name - **Description** (string) - Optional - Dataset description - **Metadata** (object) - Optional - Metadata - **InputSchema** (object) - Optional - JSON schema for inputs - **ExpectedOutputSchema** (object) - Optional - JSON schema for outputs ## POST /dataset-items ### Description Creates a new item within a dataset. ### Request Body - **DatasetName** (string) - Required - Target dataset - **Input** (object) - Optional - Input data - **ExpectedOutput** (object) - Optional - Expected output - **Metadata** (object) - Optional - Metadata - **SourceTraceId** (string) - Optional - Source trace ID - **SourceObservationId** (string) - Optional - Source observation ID - **Id** (string) - Optional - Custom item ID - **Status** (DatasetStatus) - Optional - Active or Archived ``` -------------------------------- ### Instrument Tool and Function Calls in .NET Source: https://github.com/lukaszzborek/langfuse-dotnet/blob/main/Examples/Langfuse.Example.OpenTelemetry/README.md Shows how to track tool execution within an LLM workflow using GenAiActivityHelper. It includes setting custom tags for arguments and results to provide visibility into function calling capabilities. ```csharp using var toolActivity = GenAiActivityHelper.CreateToolCallActivity( activitySource, "execute-weather-function", "get_weather", "function", "call_abc123"); toolActivity?.SetTag("gen_ai.tool.call.arguments", "{\"location\":\"San Francisco\"}"); // ... execute the tool ... toolActivity?.SetTag("gen_ai.tool.call.result", "{\"temperature\":18}"); ``` -------------------------------- ### Blob Storage Integration Models Source: https://github.com/lukaszzborek/langfuse-dotnet/blob/main/docs/api-types.md Defines the structure for Blob Storage integration responses and the request object for creating new integrations. ```APIDOC ## Blob Storage Integration Models ### BlobStorageIntegrationResponse - **Id** (string) - Integration ID - **ProjectId** (string) - **Type** (BlobStorageIntegrationType) - S3, GCS, Azure, etc. - **BucketName** (string) - **Endpoint** (string?) - Custom endpoint - **Region** (string) - **Prefix** (string) - File prefix - **ExportFrequency** (BlobStorageExportFrequency) - **Enabled** (bool) - **FileType** (BlobStorageIntegrationFileType) - JSONL, Parquet, etc. - **ExportMode** (BlobStorageExportMode) - **ExportStartDate** (DateTime?) - **NextSyncAt** (DateTime?) - **LastSyncAt** (DateTime?) - **CreatedAt** (DateTime) - **UpdatedAt** (DateTime) ### CreateBlobStorageIntegrationRequest - **ProjectId** (string) - Required - **Type** (BlobStorageIntegrationType) - Required - **BucketName** (string) - Required - **Region** (string) - Required - **AccessKeyId** (string?) - Optional - **SecretAccessKey** (string?) - Optional - **Endpoint** (string?) - Optional - **Prefix** (string?) - Optional - **ExportFrequency** (BlobStorageExportFrequency) - Required - **Enabled** (bool) - Required - **FileType** (BlobStorageIntegrationFileType) - Required - **ExportMode** (BlobStorageExportMode) - Required - **ExportStartDate** (DateTime?) - Optional ``` -------------------------------- ### Define Trace Request Structures Source: https://github.com/lukaszzborek/langfuse-dotnet/blob/main/docs/api-types.md Request models for querying trace lists and performing bulk deletion. ```text TraceListRequest Page: int? Limit: int? UserId: string? // Filter by user Name: string? // Filter by name SessionId: string? // Filter by session FromTimestamp: DateTime? // Min timestamp ToTimestamp: DateTime? // Max timestamp OrderBy: string? // Sort field and direction Tags: string[]? // Filter by tags Version: string? // Filter by version Release: string? // Filter by release Environment: string? // Filter by environment DeleteTraceManyRequest TraceIds: string[] // Trace IDs to delete ``` -------------------------------- ### Langfuse Exporter Configuration in appsettings.json Source: https://github.com/lukaszzborek/langfuse-dotnet/blob/main/docs/setup.md Configure Langfuse OpenTelemetry exporter settings, including API keys and URL, within the `appsettings.json` file. Ensure sensitive keys are managed securely. ```json { "Langfuse": { "PublicKey": "YOUR_PUBLIC_KEY", "SecretKey": "YOUR_SECRET_KEY", "Url": "https://cloud.langfuse.com" } } ``` -------------------------------- ### OtelEmbedding — vector embeddings Source: https://github.com/lukaszzborek/langfuse-dotnet/blob/main/docs/tracing.md Instrumenting the creation of vector embeddings. Captures the model used, provider, input data, and response details like token counts. ```APIDOC ## OtelEmbedding — vector embeddings ### Description Instrument the process of generating vector embeddings. This allows tracking the model, provider, input, and response details such as token usage. ### Method `trace.CreateEmbedding(string name, ...)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None (Parameters are passed to the constructor and methods) ### Request Example ```csharp using var emb = trace.CreateEmbedding("query-embedding", model: "text-embedding-3-small", provider: "openai", input: query); emb.SetResponse(new GenAiResponse { InputTokens = 15 }); ``` ### Response #### Success Response (200) N/A #### Response Example N/A ### Available Methods for OtelEmbedding: - `SetText(string)` - `SetResponse(GenAiResponse)` - `SetDimensions(int)` - `SetUsageDetails(Dictionary)` - `SetCostDetails(Dictionary)` ``` -------------------------------- ### Create a Tool Call Observation Source: https://github.com/lukaszzborek/langfuse-dotnet/blob/main/README.md Use CreateToolCall to track function or tool invocations within a trace. ```csharp using var toolCall = trace.CreateToolCall("lookup-account", toolName: "get_account_info", toolDescription: "Retrieves customer account information", input: new { customer_id = "cust-789" }); var accountInfo = await GetAccountAsync("cust-789"); toolCall.SetResult(accountInfo); ``` -------------------------------- ### Handling Errors and Multi-Turn Conversations Source: https://github.com/lukaszzborek/langfuse-dotnet/blob/main/Examples/Langfuse.Example.OpenTelemetry/GENAI_HELPER_REFERENCE.md Demonstrates robust error handling using RecordError and managing multi-turn conversations by passing a unique ConversationId through the configuration. ```csharp // Error Handling try { // ... operation ... } catch (Exception ex) { GenAiActivityHelper.RecordError(activity, ex); } // Multi-Turn var config = new GenAiChatCompletionConfig { ConversationId = "conv-123" }; using var activity = GenAiActivityHelper.CreateChatCompletionActivity(activitySource, "turn-1", config); ``` -------------------------------- ### Prompts API Source: https://github.com/lukaszzborek/langfuse-dotnet/blob/main/docs/api-client.md Endpoints for managing prompt templates and versions. ```APIDOC ## Prompts API ### Methods - **GetPromptListAsync**(PromptListRequest?) → PromptMetaListResponse - **GetPromptAsync**(name, version?) → Prompt - **CreatePromptAsync**(CreatePromptRequest) → Prompt - **UpdatePromptAsync**(name, CreatePromptRequest) → Prompt - **DeletePromptAsync**(name) - **DeletePromptVersionAsync**(name, version) ``` -------------------------------- ### Key Types Source: https://github.com/lukaszzborek/langfuse-dotnet/blob/main/docs/tracing.md Reference for key data structures used in Langfuse instrumentation, including GenAiResponse, GenAiMessage, GenAiToolDefinition, and LangfuseObservationLevel. ```APIDOC ## Key Types ### GenAiResponse Represents the response from a Generative AI model. ```csharp new GenAiResponse { Model = "gpt-4", InputTokens = 50, OutputTokens = 100, FinishReasons = ["stop"], Completion = "result text" } ``` ### GenAiMessage Represents a message in a conversation, typically used for LLM input. ```csharp new GenAiMessage { Role = "user", Content = "Hello!" } ``` ### GenAiToolDefinition Defines a tool or function that can be called. ```csharp new GenAiToolDefinition { Name = "get_weather", Description = "Get weather info" } ``` ### LangfuseObservationLevel Enum for observation logging levels. ``` DEBUG, INFO, WARNING, ERROR ``` ``` -------------------------------- ### OtelToolCall — function/tool invocations Source: https://github.com/lukaszzborek/langfuse-dotnet/blob/main/docs/tracing.md Instrumenting function or tool calls made by an LLM or application. Captures the tool name, description, input, and the result of the invocation. ```APIDOC ## OtelToolCall — function/tool invocations ### Description Instrument function or tool calls to capture the tool's name, description, input arguments, and the result returned by the tool. ### Method `trace.CreateToolCall(string name, ...)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None (Parameters are passed to the constructor and methods) ### Request Example ```csharp using var tool = trace.CreateToolCall("lookup-account", toolName: "get_account_info", toolDescription: "Retrieves customer account information", provider: "internal", input: new { customer_id = "cust-789" }); var accountInfo = await GetAccountAsync("cust-789"); tool.SetResult(accountInfo); ``` ### Response #### Success Response (200) N/A #### Response Example N/A ### Available Methods for OtelToolCall: - `SetArguments(object)` - `SetResult(object)` ``` -------------------------------- ### Prompt Types Source: https://github.com/lukaszzborek/langfuse-dotnet/blob/main/docs/api-types.md Defines the structures for prompts, including text and chat prompts, and their associated metadata. ```APIDOC ## Prompt Types ### Description Structures for representing prompts, including abstract `Prompt`, concrete `TextPrompt` and `ChatPrompt`, and related metadata. ### Prompt Structure ``` Prompt (abstract, polymorphic on Type: "text" or "chat") Name: string // Prompt name Version: int // Version number Config: object? // Configuration object Labels: List // Categorization labels Tags: List // Metadata tags CommitMessage: string? // Version description TextPrompt : Prompt Type: "text" PromptText: string // Text content of prompt ChatPrompt : Prompt Type: "chat" PromptMessages: List // Chat messages ChatMessage : ChatMessageWithPlaceholders Role: string // system, user, assistant, etc. Content: string // Message content PlaceholderMessage : ChatMessageWithPlaceholders Name: string // Placeholder variable name ``` ### Prompt Metadata Structure ``` PromptMeta Name: string // Prompt name Type: PromptType // Text or Chat Versions: List // Available version numbers Tags: List Labels: List LastUpdatedAt: DateTime LastConfig: object? PromptType (enum): Text, Chat ``` ### Prompt Request Types #### Create Prompt Request ``` CreatePromptRequest (abstract) Type: PromptType? // Text or Chat Name: string // Prompt name (required) Config: object? // Configuration Labels: List // Labels Tags: List // Tags CommitMessage: string? // Commit message ``` #### Prompt List Request ``` PromptListRequest Page: int? Limit: int? Name: string? // Filter by name Tag: string? // Filter by tag Label: string? // Filter by label ``` ``` -------------------------------- ### Define Pagination Response Structures Source: https://github.com/lukaszzborek/langfuse-dotnet/blob/main/docs/api-types.md Base structures for handling paginated API responses and metadata. ```text PaginatedResponse Data: T[] // Items in this page Meta: ApiMetadata // Pagination info ApiMetadata Page: int // Current page (1-based) Limit: int // Items per page TotalItems: int // Total across all pages TotalPages: int // Total pages ``` -------------------------------- ### OtelEvent — discrete point-in-time events Source: https://github.com/lukaszzborek/langfuse-dotnet/blob/main/docs/tracing.md Instrumenting discrete, point-in-time events. Useful for logging specific occurrences within an application flow that are not spans or traces. ```APIDOC ## OtelEvent — discrete point-in-time events ### Description Instrument discrete, point-in-time events. These are useful for logging specific occurrences or actions within your application that don't fit the model of a span or trace. ### Method `trace.CreateEvent(string name, ...)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None (Parameters are passed to the constructor) ### Request Example ```csharp using var evt = trace.CreateEvent("user-feedback", input: new { rating = 5 }, output: new { action = "logged" }); ``` ### Response #### Success Response (200) N/A #### Response Example N/A ``` -------------------------------- ### Configure Langfuse Exporter in .NET Source: https://github.com/lukaszzborek/langfuse-dotnet/blob/main/Examples/Langfuse.Example.OpenTelemetry/README.md Methods for registering the Langfuse OpenTelemetry exporter using either configuration files or programmatic options. ```csharp // Using Configuration File services.AddOpenTelemetry() .WithTracing(tracing => { tracing.AddLangfuseExporter(configuration.GetSection("Langfuse")); }); // Using Programmatic Configuration services.AddOpenTelemetry() .WithTracing(tracing => { tracing.AddLangfuseExporter(options => { options.Url = "https://cloud.langfuse.com"; options.PublicKey = "your-public-key"; options.SecretKey = "your-secret-key"; options.TimeoutMilliseconds = 10000; options.Headers.Add("X-Custom-Header", "value"); }); }); ``` -------------------------------- ### Organization Management Source: https://github.com/lukaszzborek/langfuse-dotnet/blob/main/docs/api-client.md Endpoints for managing organization details, API keys, and memberships. ```APIDOC ## GET /organizations ### Description Retrieves organization details. ### Method GET ### Endpoint /organizations ## GET /organizations/projects ### Description Retrieves a list of projects within the organization. ### Method GET ### Endpoint /organizations/projects ## GET /organizations/api-keys ### Description Retrieves API keys for the organization. ### Method GET ### Endpoint /organizations/api-keys ## POST /organizations/api-keys ### Description Creates a new API key. ### Method POST ### Endpoint /organizations/api-keys ### Request Body - **CreateApiKeyRequest** (object) - Required - Request body for creating an API key ## DELETE /organizations/api-keys/{id} ### Description Deletes an API key by ID. ### Method DELETE ### Endpoint /organizations/api-keys/{id} ### Parameters #### Path Parameters - **id** (string) - Required - The ID of the API key to delete ## GET /organizations/memberships ### Description Retrieves organization memberships. ### Method GET ### Endpoint /organizations/memberships ## POST /organizations/memberships ### Description Creates a new membership. ### Method POST ### Endpoint /organizations/memberships ### Request Body - **CreateMembershipRequest** (object) - Required - Request body for creating a membership ## DELETE /organizations/memberships/{userId} ### Description Deletes a membership for a specific user. ### Method DELETE ### Endpoint /organizations/memberships/{userId} ### Parameters #### Path Parameters - **userId** (string) - Required - The ID of the user ### Request Body - **DeleteMembershipRequest** (object) - Required - Request body for deleting a membership ``` -------------------------------- ### Use ILangfuseClient for API Operations Source: https://github.com/lukaszzborek/langfuse-dotnet/blob/main/README.md Inject ILangfuseClient to perform operations like fetching prompts, datasets, or creating scores. ```csharp public class MyService { private readonly ILangfuseClient _langfuseClient; public MyService(ILangfuseClient langfuseClient) { _langfuseClient = langfuseClient; } public async Task RunEvaluationAsync() { // Get a prompt var prompt = await _langfuseClient.GetPromptAsync("my-prompt", label: "production"); // Get dataset items var dataset = await _langfuseClient.GetDatasetAsync("my-dataset"); // Create a score await _langfuseClient.CreateScoreAsync(new ScoreCreateRequest { TraceId = "trace-123", Name = "accuracy", Value = 0.95 }); } } ```