go-client-langfuse is a Go client library for accessing the Langfuse API.
go-client-langfuse is compatible with modern Go releases in module mode, with Go installed:
go get github.com/MyCarrier-DevOps/[email protected]
will resolve and add the package to the current development module, along with its dependencies.
Alternatively the same can be achieved if you use import in a package:
import "github.com/MyCarrier-DevOps/go-client-langfuse/langfuse"
and run go get
without parameters.
import "github.com/MyCarrier-DevOps/go-client-langfuse/langfuse"
The Langfuse API uses HTTP Basic Authentication with your public and secret keys. The library handles this automatically using environment variables.
Set the following environment variables:
export LANGFUSE_SERVER_URL="https://cloud.langfuse.com" # or your self-hosted URL
export LANGFUSE_PUBLIC_KEY="pk-lf-..."
export LANGFUSE_SECRET_KEY="sk-lf-..."
You can create a client in two ways:
Load the configuration from environment variables, then create a client:
package main
import (
"log"
"github.com/MyCarrier-DevOps/go-client-langfuse/langfuse"
)
func main() {
// Load configuration from environment variables
config, err := langfuse.LoadConfigFromEnvVars()
if err != nil {
log.Fatalf("Failed to load config: %v", err)
}
// Create a new client with the loaded configuration
client := langfuse.NewClient(config)
// Use the client...
}
Create a configuration directly without environment variables:
package main
import (
"log"
"github.com/MyCarrier-DevOps/go-client-langfuse/langfuse"
)
func main() {
// Create configuration directly
config, err := langfuse.NewConfig(
"https://cloud.langfuse.com",
"pk-lf-xxx",
"sk-lf-xxx",
)
if err != nil {
log.Fatalf("Failed to create config: %v", err)
}
// Create a new client with the config
client := langfuse.NewClient(config)
// Use the client...
}
The client uses retryable HTTP requests with the following default configuration:
- Max Retries: 3 attempts
- Retry Wait Min: 1 second
- Retry Wait Max: 4 seconds
- Retry Policy: Retries on 5xx errors and network failures
Get information about the project associated with your API keys:
project, err := client.Projects.GetProject()
if err != nil {
log.Fatalf("Error fetching project: %v", err)
}
fmt.Printf("Project ID: %v\n", project["id"])
fmt.Printf("Project Name: %v\n", project["name"])
The library provides comprehensive support for managing prompts in Langfuse.
prompts, err := client.Prompts.GetPrompts()
if err != nil {
log.Fatalf("Error fetching prompts: %v", err)
}
fmt.Printf("Prompts: %+v\n", prompts)
Retrieve a prompt by name with optional label or version:
// Get latest version with no label
prompt, err := client.Prompts.GetPromptByName("my-prompt", "", nil)
if err != nil {
log.Fatalf("Error fetching prompt: %v", err)
}
// Get prompt with specific label
prompt, err := client.Prompts.GetPromptByName("my-prompt", "production", nil)
// Get specific version
version := 3
prompt, err := client.Prompts.GetPromptByName("my-prompt", "", &version)
Create a text prompt:
newPrompt := &langfuse.Prompt{
Name: "simple-text-prompt",
Type: "text",
Prompt: "Translate the following text to French: {{text}}",
Labels: []string{"production"},
Tags: []string{"translation", "french"},
CommitMessage: "Initial version",
}
createdPrompt, err := client.Prompts.CreatePrompt(newPrompt)
if err != nil {
log.Fatalf("Error creating prompt: %v", err)
}
Create a chat prompt:
chatPrompt := &langfuse.Prompt{
Name: "chat-assistant",
Type: "chat",
Prompt: []langfuse.ChatMessage{
{
Type: "chatmessage",
Role: "system",
Content: "You are a helpful assistant that answers questions concisely.",
},
{
Type: "chatmessage",
Role: "user",
Content: "{{user_question}}",
},
},
Labels: []string{"production", "v1"},
Tags: []string{"chat", "assistant"},
CommitMessage: "Initial chat prompt",
}
createdPrompt, err := client.Prompts.CreatePrompt(chatPrompt)
if err != nil {
log.Fatalf("Error creating chat prompt: %v", err)
}
Update the labels for a specific prompt version. Note that labels must be unique across all versions of a prompt, and the latest
label is reserved and managed by Langfuse:
// Update labels for version 1 of "my-prompt"
updatedPrompt, err := client.Prompts.UpdatePromptVersionLabels(
"my-prompt",
1,
[]string{"staging", "beta"},
)
if err != nil {
log.Fatalf("Error updating prompt version labels: %v", err)
}
fmt.Printf("Updated prompt version %d with labels: %v\n",
updatedPrompt.Version,
updatedPrompt.Labels)
Common use cases:
- Promote a version from "staging" to "production"
- Add experiment labels like "beta" or "canary"
- Remove labels by providing a new list that excludes them
- Clear all labels by providing an empty slice
[]string{}
For a complete working example, see example/example.go.
To run the example:
# Set environment variables
export LANGFUSE_SERVER_URL="https://cloud.langfuse.com"
export LANGFUSE_PUBLIC_KEY="your-public-key"
export LANGFUSE_SECRET_KEY="your-secret-key"
# Run the example
go run example/example.go
The library uses Go's standard error handling. All API methods return an error as the last return value:
project, err := client.Projects.GetProject()
if err != nil {
// Handle error
log.Printf("Error: %v", err)
return
}
Errors are wrapped with context to help identify where issues occurred:
error making request:
- HTTP request failed (network issues, timeouts)client error 4xx:
- Client errors (bad request, unauthorized, not found, etc.)server error 5xx:
- Server errors (internal server error, service unavailable)error unmarshalling:
- Failed to parse JSON responseerror fetching project:
- Project-specific operation failederror fetching prompt:
- Prompt-specific operation failed
The library includes comprehensive test coverage. To run tests:
# Run all tests
go test ./langfuse
# Run with verbose output
go test -v ./langfuse
# Run with coverage
go test -cover ./langfuse
# Run specific test
go test -v -run TestClient_Do_Success ./langfuse
Tests use mock HTTP servers to avoid making real API calls.
The library currently supports the following Langfuse API endpoints:
GET /api/public/projects
- Get project information
GET /api/public/v2/prompts
- List all promptsGET /api/public/v2/prompts/{name}
- Get prompt by name (with optional label/version)POST /api/public/v2/prompts
- Create a new prompt or versionPATCH /api/public/v2/prompts/{name}/versions/{version}
- Update prompt version labels
Future enhancements planned:
- Support for Traces API
- Support for Generations API
- Support for Observations API
- Support for Datasets API
- Support for Scores API
- Context-aware request cancellation
- Additional configuration options
- Pagination helpers
Contributions are welcome! Please feel free to submit a Pull Request.
When contributing:
- Fork the repository
- Create your feature branch (
git checkout -b feature/amazing-feature
) - Write tests for your changes
- Ensure all tests pass (
go test ./...
) - Run linting (
golangci-lint run
) - Commit your changes (
git commit -m 'Add some amazing feature'
) - Push to the branch (
git push origin feature/amazing-feature
) - Open a Pull Request
This library follows Semantic Versioning.
For issues, questions, or contributions, please visit the GitHub repository.