### Minimal Server Setup with Go SDK Source: https://github.com/dibbla-agents/sdk-go/blob/main/cmd/worker/SDK_SUMMARY.md Shows the basic setup required to start a server using the Go SDK. This includes initializing the server, registering functions, and starting the server process, which handles registration, activation, and lifecycle management automatically. ```go import ( "github.com/dibbla-agents/sdk" "path/to/your/myFunction" ) func main() { server, _ := sdk.New() server.RegisterFunction(myFunction.NewSDKFunction()) server.Start() // Handles everything: registration, activation } ``` -------------------------------- ### Basic Server Setup in Go Source: https://github.com/dibbla-agents/sdk-go/blob/main/sdk/README.md Demonstrates the fundamental steps to initialize and start a Go Tool Server using the SDK. It includes creating a new server instance, registering a function, and starting the server, which blocks indefinitely. ```go package main import ( "go-toolserver/sdk" "log" ) func main() { // Create server with default configuration server, err := sdk.New() if err != nil { log.Fatal("Failed to create server:", err) } // Register your functions server.RegisterFunction(NewMyFunction()) // Start server (blocks forever) if err := server.Start(); err != nil { log.Fatal("Server failed:", err) } } ``` -------------------------------- ### Create and Start a New Function with Go SDK Source: https://github.com/dibbla-agents/sdk-go/blob/main/cmd/worker/SDK_SUMMARY.md This snippet demonstrates how to import the SDK, define a new function using `FunctionBuilder`, and start the server. It's essential for initializing new projects with the SDK. ```go // 1. Import the SDK import "go-toolserver/sdk" // 2. Create your function func NewMyFunction() sdk.FunctionBuilder { return sdk.NewSimpleFunction[Input, Output](...).WithHandler(myHandler) } // 3. Start your server func main() { server, _ := sdk.New() server.RegisterFunction(NewMyFunction()) server.Start() } ``` -------------------------------- ### Install Dibbla Go SDK Source: https://github.com/dibbla-agents/sdk-go/blob/main/README.md Command to install the Dibbla SDK for Go using the go get command. Ensures the latest version is available in your Go project. ```bash go get github.com/dibbla-agents/sdk-go@latest ``` -------------------------------- ### Go Tool Server Configuration (Programmatic) Source: https://github.com/dibbla-agents/sdk-go/blob/main/sdk/README.md Demonstrates programmatic configuration of the Go Tool Server SDK. It provides an example of passing configuration options, such as `WithServerName`, during server initialization. ```go server, err := sdk.New( sdk.WithServerName("my-custom-service"), ) ``` -------------------------------- ### Go Worker Example with Simple Function Registration Source: https://github.com/dibbla-agents/sdk-go/blob/main/README.md Demonstrates creating a new Dibbla SDK server, defining input/output structures for a function, registering a simple function with a handler, and starting the server. This is a minimal example for a workflow worker. ```go package main import ( "fmt" "log" "github.com/dibbla-agents/sdk-go" ) type GreetingInput struct { Name string `json:"name"` } type GreetingOutput struct { Message string `json:"message"` } func main() { // Create server with minimal configuration // (defaults to grpc.dibbla.com:443 with TLS enabled) server, err := sdk.New( sdk.WithServerName("my-custom-worker"), sdk.WithServerApiToken("your-api-token"), ) if err != nil { log.Fatal("Failed to create server:", err) } // Register a simple function greetingFn := sdk.NewSimpleFunction[GreetingInput, GreetingOutput]( "greeting", "1.0.0", "Generate a greeting message", ).WithHandler(func(input GreetingInput) (GreetingOutput, error) { return GreetingOutput{ Message: fmt.Sprintf("Hello, %s!", input.Name), }, nil }).WithTags("utility", "greeting") server.RegisterFunction(greetingFn) // Start server (blocks forever) log.Println("Starting worker...") if err := server.Start(); err != nil { log.Fatal("Server failed:", err) } } ``` -------------------------------- ### Initialize Dibbla SDK Server with Options Source: https://context7.com/dibbla-agents/sdk-go/llms.txt Initializes a new Dibbla SDK server instance using various configuration options. Supports minimal configuration, local development setup, and custom settings including server address, API token, and TLS control. Dependencies include the core 'sdk-go' package. ```go package main import ( "log" "github.com/dibbla-agents/sdk-go" ) func main() { // Minimal configuration - uses grpc.dibbla.com:443 with TLS server, err := sdk.New( sdk.WithServerName("my-custom-worker"), sdk.WithServerApiToken("your-api-token"), ) if err != nil { log.Fatal("Failed to create server:", err) } // Local development configuration server, err = sdk.New( sdk.WithServerName("local-worker"), sdk.WithGrpcServerAddress("localhost:50051"), ) // Custom configuration with explicit TLS control server, err = sdk.New( sdk.WithServerName("custom-worker"), sdk.WithGrpcServerAddress("custom.example.com:443"), sdk.WithServerApiToken("token-123"), sdk.WithGrpcTLS(true), sdk.WithPingInterval(60), // 60 seconds ) if err != nil { log.Fatal("Failed to create server:", err) } } ``` -------------------------------- ### Docker Build and Run Commands for Dibbla Go Worker Source: https://github.com/dibbla-agents/sdk-go/blob/main/README.md Provides Docker commands for building a worker image and running it. It shows examples with minimal configuration and custom server addresses, using environment variables for configuration. ```bash # Build Docker image docker build -t my-worker . # Run with minimal configuration (uses grpc.dibbla.com:443 by default) docker run -e SERVER_NAME=my-worker \ -e SERVER_API_TOKEN=your-token \ my-worker # Or with custom server address docker run -e SERVER_NAME=my-worker \ -e GRPC_SERVER_ADDRESS=custom.example.com:443 \ -e SERVER_API_TOKEN=your-token \ my-worker ``` -------------------------------- ### Automatic TLS Detection in Go SDK Source: https://github.com/dibbla-agents/sdk-go/blob/main/MIGRATION.md Demonstrates how the SDK automatically enables TLS for production addresses and disables it for localhost addresses when creating a new server instance. ```go // Automatically uses TLS for production addresses server, _ := dibbla.New( dibbla.WithGrpcServerAddress("api.example.com:443"), ) // Automatically disables TLS for localhost server, _ := dibbla.New( dibbla.WithGrpcServerAddress("localhost:9090"), ) ``` -------------------------------- ### Migration: SDK Function Registration (After SDK) in Go Source: https://github.com/dibbla-agents/sdk-go/blob/main/sdk/README.md Presents the 'after' state of function registration using the Go Tool Server SDK. This simplified `main.go` example demonstrates registering a function via the SDK's `RegisterFunction` method. ```go // main.go func main() { server, err := sdk.New() if err != nil { log.Fatal(err) } server.RegisterFunction(input_function.NewSDKFunction()) if err := server.Start(); err != nil { log.Fatal(err) } } ``` -------------------------------- ### Explicit TLS Control in Go SDK Source: https://github.com/dibbla-agents/sdk-go/blob/main/MIGRATION.md Shows how to explicitly enable or disable TLS when creating a new server instance, overriding the automatic detection behavior. ```go // Override auto-detection if needed server, _ := dibbla.New( dibbla.WithGrpcServerAddress("localhost:9090"), dibbla.WithGrpcTLS(true), // Force TLS on ) ``` -------------------------------- ### Update Go Module Dependencies Source: https://github.com/dibbla-agents/sdk-go/blob/main/MIGRATION.md Update the Go module to the latest version of the Dibbla Agents SDK and tidy up dependencies. This is the first step in migrating to the new SDK version. ```bash go get github.com/dibbla-agents/sdk-go@latest go mod tidy ``` -------------------------------- ### Rollback to Previous SDK Version Source: https://github.com/dibbla-agents/sdk-go/blob/main/MIGRATION.md Instructions to revert to the previous version (v0.0.0) of the SDK if necessary. This involves updating the dependency to the specific old version and tidying the Go modules. ```bash go get github.com/FatsharkStudiosAB/codex/workflows/workers/go/sdk@v0.0.0 go mod tidy ``` -------------------------------- ### Update SDK Function Call Prefixes Source: https://github.com/dibbla-agents/sdk-go/blob/main/MIGRATION.md Change all occurrences of the `sdk.` prefix to `dibbla.` when calling SDK functions. This reflects the new package name after the module restructuring. ```go // Old server, err := sdk.New( sdk.WithServerName("my-worker"), sdk.WithGrpcServerAddress("localhost:9090"), ) // New server, err := dibbla.New( dibbla.WithServerName("my-worker"), dibbla.WithGrpcServerAddress("localhost:9090"), ) ``` -------------------------------- ### Advanced Function with State Access in Go Source: https://github.com/dibbla-agents/sdk-go/blob/main/sdk/README.md Details the creation of an advanced function that requires access to event messages and global state. This example shows using the generic `NewFunction` and provides a handler signature that accepts `types.EventMessage` and `state.GlobalState`. ```go // Create function with access to event state and global state func NewAdvancedFunction() sdk.FunctionBuilder { return sdk.NewFunction[MyInput, MyOutput]( "advanced", "1.0.0", "Advanced function with state access", ).WithHandler(advancedHandler).WithTags("advanced") } // Advanced handler with full access func advancedHandler(input MyInput, event *types.EventMessage, gs *state.GlobalState) (MyOutput, error) { // Access workflow information log.Printf("Processing in workflow: %s", event.Workflow) // Access RPC client through global state // gs.RpcClient return MyOutput{...}, nil } ``` -------------------------------- ### Advanced Usage: Accessing Global State in Go Source: https://github.com/dibbla-agents/sdk-go/blob/main/sdk/README.md Explains how to access and utilize the `GlobalState` object within an advanced function handler. It shows examples of calling other services via `gs.RpcClient` and accessing caching mechanisms. ```go func advancedHandler(input MyInput, event *types.EventMessage, gs *state.GlobalState) (MyOutput, error) { // Access RPC client for calling other services response, err := gs.RpcClient.Call(...) _ = response // Access function cache via grpccache if configured on the workflow side return MyOutput{...}, nil } ``` -------------------------------- ### Update Go Import Path and Package Alias Source: https://github.com/dibbla-agents/sdk-go/blob/main/MIGRATION.md Replace the old import path with the new one and update the package alias from `sdk` to `dibbla`. This ensures the code correctly references the restructured SDK module. ```go // Old import sdk "github.com/FatsharkStudiosAB/codex/workflows/workers/go/sdk" // New import "github.com/dibbla-agents/sdk-go" ``` -------------------------------- ### Implement Error Handling in Go Handlers Source: https://github.com/dibbla-agents/sdk-go/blob/main/sdk/README.md Shows how to return meaningful errors from Go function handlers. The example checks for invalid input values and missing required fields, returning specific error messages. The SDK automatically serializes and transmits these errors to the workflow engine. ```go func myHandler(input MyInput) (MyOutput, error) { if input.Value < 0 { return MyOutput{}, fmt.Errorf("value must be non-negative, got: %d", input.Value) } if input.Name == "" { return MyOutput{}, fmt.Errorf("name is required") } // ... business logic return output, nil } ``` -------------------------------- ### Configure Function Caching with TTL in Go Source: https://context7.com/dibbla-agents/sdk-go/llms.txt Demonstrates how to configure caching for a Go function using the Dibbla Agents SDK. Caching improves performance by storing results for a specified Time-To-Live (TTL), reducing redundant computations. This example sets a 5-minute TTL for an 'expensive_computation' function. ```go package main import ( "crypto/sha256" "fmt" "time" "github.com/dibbla-agents/sdk-go" "github.com/dibbla-agents/sdk-go/internal/state" "github.com/dibbla-agents/sdk-go/internal/types" ) type ExpensiveInput struct { Query string `json:"query"` } type ExpensiveOutput struct { Result string `json:"result"` Cached bool `json:"cached"` } func main() { server, _ := sdk.New( sdk.WithServerName("cache-worker"), sdk.WithServerApiToken("your-token"), ) expensiveFunc := sdk.NewFunction[ExpensiveInput, ExpensiveOutput]( "expensive_computation", "1.0.0", "Expensive function with 5-minute cache TTL", ).WithHandler(func( input ExpensiveInput, event *types.EventMessage, gs *state.GlobalState, ) (ExpensiveOutput, error) { // Simulate expensive computation hash := sha256.Sum256([]byte(input.Query)) result := fmt.Sprintf("Result: %x", hash) return ExpensiveOutput{ Result: result, Cached: false, }, nil }).WithCacheTTL(5 * time.Minute).WithTags("expensive", "cached") server.RegisterFunction(expensiveFunc) server.Start() } ``` -------------------------------- ### Configure TLS via Environment Variables (Bash) Source: https://github.com/dibbla-agents/sdk-go/blob/main/MIGRATION.md Configure TLS for the SDK using environment variables. `GRPC_SERVER_ADDRESS` can be set to a production address to automatically enable TLS, or `GRPC_USE_TLS` can be explicitly set to `true` or `false` to override auto-detection. ```bash # Let SDK auto-detect (recommended) export GRPC_SERVER_ADDRESS="api.example.com:443" # TLS will be automatically enabled # Or explicitly enable export GRPC_USE_TLS=true # Localhost automatically disables TLS export GRPC_SERVER_ADDRESS="localhost:9090" # Force TLS off export GRPC_USE_TLS=false ``` -------------------------------- ### Use gRPC Store for Persistent Data in Go Source: https://context7.com/dibbla-agents/sdk-go/llms.txt Illustrates how to use the built-in gRPC store client in the Dibbla Agents SDK for persistent key-value storage within workflows. This example implements a chat function that appends messages to a per-workflow history stored in the gRPC store. ```go package main import ( "context" "encoding/json" "fmt" "strings" "time" "github.com/dibbla-agents/sdk-go" "github.com/dibbla-agents/sdk-go/internal/state" "github.com/dibbla-agents/sdk-go/internal/types" ) type StoreChatInput struct { Text string `json:"text"` } type StoreChatOutput struct { History string `json:"history"` } func main() { server, _ := sdk.New( sdk.WithServerName("storage-worker"), sdk.WithServerApiToken("your-token"), ) storeChatFunc := sdk.NewFunction[StoreChatInput, StoreChatOutput]( "store_chat_history", "1.0.0", "Append input text to per-workflow chat history using gRPC store", ).WithCacheTTL(0).WithHandler(func( input StoreChatInput, event *types.EventMessage, gs *state.GlobalState, ) (StoreChatOutput, error) { if gs == nil || gs.GrpcStore == nil { return StoreChatOutput{}, fmt.Errorf("grpc store client not available") } workflowID := event.Workflow if workflowID == "" { workflowID = "__global__" } const historyKey = "chat_history" // Handle clear command if input.Text == "clear" { if err := gs.GrpcStore.Set(context.Background(), workflowID, historyKey, []byte("")); err != nil { return StoreChatOutput{}, fmt.Errorf("failed to clear history: %w", err) } return StoreChatOutput{History: "cleared"}, nil } // Retrieve existing history var history []string ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) defer cancel() if data, err := gs.GrpcStore.Get(ctx, workflowID, historyKey); err == nil && len(data) > 0 { json.Unmarshal(data, &history) } // Append new text and save history = append(history, input.Text) bytes, err := json.Marshal(history) if err != nil { return StoreChatOutput{}, fmt.Errorf("failed to marshal history: %w", err) } if err := gs.GrpcStore.Set(context.Background(), workflowID, historyKey, bytes); err != nil { return StoreChatOutput{}, fmt.Errorf("failed to persist history: %w", err) } return StoreChatOutput{History: strings.Join(history, "\n")}, nil }).WithTags("storage", "chat", "persistence") server.RegisterFunction(storeChatFunc) server.Start() } ``` -------------------------------- ### Register Multiple Functions in One Worker (Go) Source: https://context7.com/dibbla-agents/sdk-go/llms.txt This Go code demonstrates how to register multiple distinct functions (uppercase, lowercase, reverse, word count) within a single worker process using the Dibbla Agents SDK. It includes defining input/output structures and handlers for each function, then registering them with the SDK server. The server is then started to handle requests for these functions. ```go package main import ( "fmt" "log" "strings" "github.com/dibbla-agents/sdk-go" ) type TextInput struct { Text string `json:"text"` } type TextOutput struct { Result string `json:"result"` } func main() { server, err := sdk.New( sdk.WithServerName("text-processing-worker"), sdk.WithServerApiToken("your-token"), ) if err != nil { log.Fatal(err) } // Uppercase function uppercaseFunc := sdk.NewSimpleFunction[TextInput, TextOutput]( "text_uppercase", "1.0.0", "Convert text to uppercase", ).WithHandler(func(input TextInput) (TextOutput, error) { return TextOutput{Result: strings.ToUpper(input.Text)}, }).WithTags("text", "transform") // Lowercase function lowercaseFunc := sdk.NewSimpleFunction[TextInput, TextOutput]( "text_lowercase", "1.0.0", "Convert text to lowercase", ).WithHandler(func(input TextInput) (TextOutput, error) { return TextOutput{Result: strings.ToLower(input.Text)}, }).WithTags("text", "transform") // Reverse function reverseFunc := sdk.NewSimpleFunction[TextInput, TextOutput]( "text_reverse", "1.0.0", "Reverse text", ).WithHandler(func(input TextInput) (TextOutput, error) { runes := []rune(input.Text) for i, j := 0, len(runes)-1; i < j; i, j = i+1, j-1 { runes[i], runes[j] = runes[j], runes[i] } return TextOutput{Result: string(runes)}, }).WithTags("text", "transform") // Word count function wordCountFunc := sdk.NewSimpleFunction[TextInput, TextOutput]( "text_word_count", "1.0.0", "Count words in text", ).WithHandler(func(input TextInput) (TextOutput, error) { words := strings.Fields(input.Text) result := fmt.Sprintf("Word count: %d", len(words)) return TextOutput{Result: result}, }).WithTags("text", "analysis") // Register all functions server.RegisterFunction(uppercaseFunc) server.RegisterFunction(lowercaseFunc) server.RegisterFunction(reverseFunc) server.RegisterFunction(wordCountFunc) log.Println("Starting text processing worker with 4 functions...") if err := server.Start(); err != nil { log.Fatal(err) } } ``` -------------------------------- ### Simple Function Creation in Go Source: https://github.com/dibbla-agents/sdk-go/blob/main/sdk/README.md Illustrates how to define and create a simple function using the SDK, suitable for input-output transformations. It shows defining input/output structs, creating the function builder with a handler, and assigning tags. ```go // Define input/output types type GreetingInput struct { Name string `json:"name"` } type GreetingOutput struct { Message string `json:"message"` } // Create function using simple interface func NewGreetingFunction() sdk.FunctionBuilder { return sdk.NewSimpleFunction[GreetingInput, GreetingOutput]( "greeting", "1.0.0", "Generates a personalized greeting", ).WithHandler(greetingHandler).WithTags("utility", "greeting") } // Simple handler - just input -> output func greetingHandler(input GreetingInput) (GreetingOutput, error) { if input.Name == "" { return GreetingOutput{}, fmt.Errorf("name cannot be empty") } return GreetingOutput{ Message: fmt.Sprintf("Hello, %s!", input.Name), }, nil } ``` -------------------------------- ### Go SDK Server Initialization with Different TLS Configurations Source: https://github.com/dibbla-agents/sdk-go/blob/main/README.md Illustrates various ways to initialize the Dibbla SDK server in Go, focusing on server address and TLS settings. Covers default TLS, disabling TLS for local development, and explicitly forcing TLS. ```go // Minimal configuration - uses grpc.dibbla.com:443 with TLS (recommended) server, _ := sdk.New( sdk.WithServerName("my-worker"), sdk.WithServerApiToken("your-token"), ) ``` ```go // Local development - uses localhost without TLS server, _ := sdk.New( sdk.WithServerName("my-worker"), sdk.WithGrpcServerAddress("localhost:50051"), ) ``` ```go // Force TLS on for localhost (advanced) server, _ := sdk.New( sdk.WithServerName("my-worker"), sdk.WithGrpcServerAddress("localhost:9090"), sdk.WithGrpcTLS(true), ) ``` -------------------------------- ### Migrate Go SDK Server Initialization Source: https://github.com/dibbla-agents/sdk-go/blob/main/README.md Shows the API change for server initialization during migration. While the import path changes, the method for creating a new server instance (`sdk.New()`) remains the same, simplifying the migration process for this specific part of the code. ```go // Old (from FatsharkStudiosAB/codex) import sdk "github.com/FatsharkStudiosAB/codex/workflows/workers/go/sdk" server := sdk.New() // New (dibbla-agents/sdk-go) import "github.com/dibbla-agents/sdk-go" server := sdk.New() // package name is still "sdk" ``` -------------------------------- ### Fluent Configuration API for Go SDK Server Source: https://github.com/dibbla-agents/sdk-go/blob/main/cmd/worker/SDK_SUMMARY.md Illustrates the fluent configuration API provided by the Go SDK for initializing and customizing the server. This pattern allows for chaining configuration options programmatically, enhancing readability and maintainability. ```go import ( "github.com/dibbla-agents/sdk" ) server, err := sdk.New( sdk.WithServerName("my-service"), ) ``` -------------------------------- ### Simple Function Creation Syntax in Go Source: https://github.com/dibbla-agents/sdk-go/blob/main/sdk/README.md Presents the syntax for creating simple functions using `NewSimpleFunction`. It outlines the required parameters (name, version, description) and the methods for attaching a handler and tags. ```go sdk.NewSimpleFunction[Input, Output](name, version, description) .WithHandler(func(Input) (Output, error)) .WithTags("tag1", "tag2") ``` -------------------------------- ### Full Function Creation Syntax in Go Source: https://github.com/dibbla-agents/sdk-go/blob/main/sdk/README.md Outlines the syntax for creating full-featured functions using `NewFunction`, which allows access to event and global state. It details the parameters and methods for handler attachment and tagging. ```go sdk.NewFunction[Input, Output](name, version, description) .WithHandler(func(Input, *types.EventMessage, *state.GlobalState) (Output, error)) .WithTags("tag1", "tag2") ``` -------------------------------- ### Go Tool Server Configuration (Environment Variables) Source: https://github.com/dibbla-agents/sdk-go/blob/main/sdk/README.md Shows how the Go Tool Server SDK can be configured using environment variables. It lists common variables like `SERVER_NAME` and `GRPC_SERVER_ADDRESS` that control server behavior and connectivity. ```bash SERVER_NAME=my-service GRPC_SERVER_ADDRESS=localhost:9090 ``` -------------------------------- ### Migration: Manual Function Registration (Before SDK) in Go Source: https://github.com/dibbla-agents/sdk-go/blob/main/sdk/README.md Shows the 'before' state of function registration, illustrating manual registration and publishing of functions within a global state. This is contrasted with the SDK's simplified approach. ```go // init_functions.go func RegisterAndPublishFunctions(gs *state.GlobalState) { functionMap := map[string]basefunction.FunctionInterface{} registerFunction(gs, functionMap, input_function.NewFunction(gs)) publishFunctions(gs, functionMap) for key, function := range functionMap { gs.Functions.Store(key, function) } } // main.go func main() { globalState := state.NewGlobalState() RegisterAndPublishFunctions(globalState) handlers.Activate(globalState) select {} } ``` -------------------------------- ### Dockerize and Deploy Dibbla SDK Worker Source: https://context7.com/dibbla-agents/sdk-go/llms.txt Builds and deploys the Dibbla SDK worker as a containerized service using Docker. The Dockerfile defines a multi-stage build to create a lean production image. It includes instructions for building the image and running it with different environment configurations for production and local development, along with a command to view logs. ```dockerfile FROM golang:1.23.1-alpine AS builder WORKDIR /app COPY go.mod go.sum ./ RUN go mod download COPY . . RUN go build -o worker ./cmd/worker FROM alpine:latest RUN apk --no-cache add ca-certificates WORKDIR /root/ COPY --from=builder /app/worker . CMD ["./worker"] ``` ```bash # Build the Docker image docker build -t my-dibbla-worker . # Run with production configuration docker run -d \ --name worker-prod \ -e SERVER_NAME=prod-worker-1 \ -e GRPC_SERVER_ADDRESS=grpc.dibbla.com:443 \ -e SERVER_API_TOKEN=your-production-token \ -e GRPC_USE_TLS=true \ my-dibbla-worker # Run with local server docker run -d \ --name worker-local \ --network host \ -e SERVER_NAME=local-worker \ -e GRPC_SERVER_ADDRESS=localhost:50051 \ -e GRPC_USE_TLS=false \ my-dibbla-worker # View logs docker logs -f worker-prod ``` -------------------------------- ### Configure Dibbla SDK via Environment Variables in Go Source: https://context7.com/dibbla-agents/sdk-go/llms.txt Configures the Dibbla SDK using environment variables, enabling deployment flexibility without code changes. This is useful for managing different environments like production and local development. It uses the `godotenv` package to load a `.env` file if present, then initializes the SDK which automatically picks up the configuration. ```go package main import ( "log" "github.com/dibbla-agents/sdk-go" "github.com/joho/godotenv" ) func main() { // Load .env file if present if err := godotenv.Load(); err != nil { log.Println("No .env file found, using environment variables") } // Create server - automatically reads from environment server, err := sdk.New() if err != nil { log.Fatal("Failed to create server:", err) } // Register your functions here // server.RegisterFunction(...) log.Println("Starting worker...") if err := server.Start(); err != nil { log.Fatal("Server failed:", err) } } ``` ```bash # Production configuration export SERVER_NAME=production-worker export GRPC_SERVER_ADDRESS=grpc.dibbla.com:443 export SERVER_API_TOKEN=prod-token-xyz export GRPC_USE_TLS=true # Local development export SERVER_NAME=dev-worker export GRPC_SERVER_ADDRESS=localhost:50051 export GRPC_USE_TLS=false # Run the worker go run main.go ``` -------------------------------- ### Create Simple Go Function with Handler and Tags Source: https://github.com/dibbla-agents/sdk-go/blob/main/README.md Defines a simple function for basic input-output transformations. It requires generic input and output types, a name, version, and description. The handler contains the core logic, and tags can be added for categorization. Dependencies include the core SDK package. ```go fn := sdk.NewSimpleFunction[Input, Output](name, version, description) .WithHandler(func(input Input) (Output, error) { // Your logic here return output, nil }) .WithTags("tag1", "tag2") ``` -------------------------------- ### Enable TLS for Production Source: https://github.com/dibbla-agents/sdk-go/blob/main/README.md Demonstrates how to enable TLS for secure connections to the workflow server in a production environment using an environment variable. ```bash export GRPC_USE_TLS=true ``` -------------------------------- ### Set Server API Token Source: https://github.com/dibbla-agents/sdk-go/blob/main/README.md Details how to provide an API token for server authentication if required, using the `SERVER_API_TOKEN` environment variable. ```bash export SERVER_API_TOKEN=your-valid-token ``` -------------------------------- ### Migrate Go SDK Import Path Source: https://github.com/dibbla-agents/sdk-go/blob/main/README.md Illustrates the change in import paths when migrating from the older `github.com/FatsharkStudiosAB/codex/workflows/workers/go/sdk` to the new `github.com/dibbla-agents/sdk-go`. This change simplifies the import statement for cleaner code. ```go // Old import import sdk "github.com/FatsharkStudiosAB/codex/workflows/workers/go/sdk" // New import - clean and simple! import "github.com/dibbla-agents/sdk-go" ``` -------------------------------- ### Update Go Module Dependencies for SDK Migration Source: https://github.com/dibbla-agents/sdk-go/blob/main/README.md Provides the command-line instructions to update the Go module dependencies when migrating to the new SDK. This involves adding the new SDK package and tidying up the go.mod file to reflect the changes. ```bash # Update go.mod go get github.com/dibbla-agents/sdk-go@latest go mod tidy ``` -------------------------------- ### Define and Use Custom Configuration in Go Functions Source: https://github.com/dibbla-agents/sdk-go/blob/main/sdk/README.md Demonstrates how to define a custom configuration struct and pass it to a function builder. The handler can then access these configuration values for database connections or API clients. This is useful for externalizing settings like database URLs and API keys. ```go type MyConfig struct { DatabaseURL string APIKey string } func NewMyFunction(config MyConfig) sdk.FunctionBuilder { return sdk.NewFunction[Input, Output](...).WithHandler( func(input Input, event *types.EventMessage, gs *state.GlobalState) (Output, error) { // Use your custom config db := connectTo(config.DatabaseURL) api := newClient(config.APIKey) // ... }, ) } ``` -------------------------------- ### Create and Register a Simple Function Source: https://context7.com/dibbla-agents/sdk-go/llms.txt Defines and registers a simple function using the Dibbla SDK for Go, suitable for basic input-to-output transformations. It requires input and output struct definitions and handles them without needing workflow context. Dependencies include 'sdk-go' and 'fmt'. ```go package main import ( "fmt" "github.com/dibbla-agents/sdk-go" ) type GreetingInput struct { Name string `json:"name"` } type GreetingOutput struct { Message string `json:"message"` } func main() { server, _ := sdk.New( sdk.WithServerName("greeting-worker"), sdk.WithServerApiToken("your-token"), ) // Create and register a simple function greetingFn := sdk.NewSimpleFunction[GreetingInput, GreetingOutput]( "greeting", "1.0.0", "Generate a greeting message", ).WithHandler(func(input GreetingInput) (GreetingOutput, error) { if input.Name == "" { return GreetingOutput{}, fmt.Errorf("name cannot be empty") } return GreetingOutput{ Message: fmt.Sprintf("Hello, %s!", input.Name), }, nil }).WithTags("utility", "greeting", "demo") server.RegisterFunction(greetingFn) if err := server.Start(); err != nil { panic(err) } } ``` -------------------------------- ### Enable Debug Logging Source: https://github.com/dibbla-agents/sdk-go/blob/main/README.md Shows how to enable verbose logging for debugging purposes by setting the `CODEX_DEBUG` environment variable before running the worker executable. ```bash export CODEX_DEBUG=true ./your-worker ``` -------------------------------- ### Set Local Development Server Address Source: https://github.com/dibbla-agents/sdk-go/blob/main/README.md Explains how to configure the SDK to connect to a local workflow server during development by setting the `GRPC_SERVER_ADDRESS` environment variable. ```bash export GRPC_SERVER_ADDRESS=localhost:50051 ``` -------------------------------- ### Type-Safe Function Creation with Go SDK Source: https://github.com/dibbla-agents/sdk-go/blob/main/cmd/worker/SDK_SUMMARY.md Demonstrates creating both simple and advanced type-safe functions using the Go SDK. Simple functions handle basic input-output transformations, while advanced functions allow access to event state and global state. This utilizes Go generics for compile-time safety. ```go import ( "github.com/dibbla-agents/sdk" "github.com/dibbla-agents/sdk/types" "github.com/dibbla-agents/sdk/state" ) // Simple functions for basic input->output transformations sdk.NewSimpleFunction[Input, Output](name, version, description) .WithHandler(func(Input) (Output, error)) // Advanced functions with access to event state and global state sdk.NewFunction[Input, Output](name, version, description) .WithHandler(func(Input, *types.EventMessage, *state.GlobalState) (Output, error)) ``` -------------------------------- ### Create Advanced Go Function with Context and Caching Source: https://github.com/dibbla-agents/sdk-go/blob/main/README.md Defines an advanced function that has access to workflow context (event message and global state) and supports cache Time-To-Live (TTL) configuration. It requires generic input and output types, a name, version, and description. The handler can utilize workflow information and RPC client. Dependencies include core SDK, types, and state packages. ```go import ( "github.com/dibbla-agents/sdk-go" "github.com/dibbla-agents/sdk-go/internal/types" "github.com/dibbla-agents/sdk-go/internal/state" ) fn := sdk.NewFunction[Input, Output](name, version, description) .WithHandler(func(input Input, event *types.EventMessage, gs *state.GlobalState) (Output, error) { // Access workflow info: event.Workflow, event.Node, etc. // Use RPC client: gs.RpcClient // Use caching: gs.GrpcCache return output, nil }) .WithCacheTTL(5 * time.Minute) ``` -------------------------------- ### Accessing gRPC Cache Directly in Go Source: https://context7.com/dibbla-agents/sdk-go/llms.txt Demonstrates how to interact with the distributed gRPC cache directly within a Go function. This allows for custom caching strategies beyond the SDK's automatic caching. It requires the `sdk-go` and its internal state and types packages. The function takes input, marshals a value to JSON, stores it in the cache with a TTL, and then retrieves it. ```go package main import ( "context" "encoding/json" "fmt" "strconv" "time" "github.com/dibbla-agents/sdk-go" "github.com/dibbla-agents/sdk-go/internal/state" "github.com/dibbla-agents/sdk-go/internal/types" ) type CacheInput struct { Key string `json:"key"` Value string `json:"value"` } type CacheOutput struct { Status string `json:"status"` Value string `json:"value,omitempty"` } func main() { server, _ := sdk.New( sdk.WithServerName("cache-worker"), sdk.WithServerApiToken("your-token"), ) cacheFunc := sdk.NewFunction[CacheInput, CacheOutput]( "custom_cache", "1.0.0", "Demonstrate direct cache access", ).WithHandler(func( input CacheInput, event *types.EventMessage, gs *state.GlobalState, ) (CacheOutput, error) { if gs.GrpcCache == nil { return CacheOutput{}, fmt.Errorf("cache client not available") } ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) defer cancel() // Store data in cache with 10-minute TTL cacheKey := fmt.Sprintf("custom:%s", input.Key) payload, _ := json.Marshal(input.Value) err := gs.GrpcCache.SetByString(ctx, cacheKey, payload, 600) // 10 minutes if err != nil { return CacheOutput{}, fmt.Errorf("failed to set cache: %w", err) } // Retrieve from cache data, err := gs.GrpcCache.GetByString(ctx, cacheKey) if err != nil { return CacheOutput{Status: "stored", Value: ""}, nil } var cachedValue string json.Unmarshal(data, &cachedValue) return CacheOutput{ Status: "retrieved", Value: cachedValue, }, nil }).WithTags("cache", "custom") server.RegisterFunction(cacheFunc) server.Start() } ``` -------------------------------- ### Create and Register an Advanced Function with Context Source: https://context7.com/dibbla-agents/sdk-go/llms.txt Defines and registers an advanced function using the Dibbla SDK for Go, providing access to workflow context, event metadata, and global state. This is suitable for complex operations requiring detailed information about the workflow execution. Dependencies include 'sdk-go', 'log', 'fmt', and internal types/state packages. ```go package main import ( "fmt" "log" "github.com/dibbla-agents/sdk-go" "github.com/dibbla-agents/sdk-go/internal/state" "github.com/dibbla-agents/sdk-go/internal/types" ) type ProcessInput struct { Data string `json:"data"` UserID string `json:"user_id"` } type ProcessOutput struct { Result string `json:"result"` Timestamp string `json:"timestamp"` NodeID string `json:"node_id"` } func main() { server, _ := sdk.New( sdk.WithServerName("advanced-worker"), sdk.WithServerApiToken("your-token"), ) processFunc := sdk.NewFunction[ProcessInput, ProcessOutput]( "process_data", "2.0.0", "Process data with full workflow context access", ).WithHandler(func( input ProcessInput, event *types.EventMessage, gs *state.GlobalState, ) (ProcessOutput, error) { // Access workflow metadata workflowID := event.Workflow nodeID := event.Node log.Printf("Processing data for workflow: %s, node: %s", workflowID, nodeID) // Process the input result := fmt.Sprintf("Processed: %s for user %s", input.Data, input.UserID) return ProcessOutput{ Result: result, Timestamp: event.Timestamp, NodeID: nodeID, }, nil }).WithTags("processing", "advanced") server.RegisterFunction(processFunc) server.Start() } ``` -------------------------------- ### Set GRPC_USE_TLS Environment Variable for Go SDK Source: https://github.com/dibbla-agents/sdk-go/blob/main/README.md Bash commands to set the GRPC_USE_TLS environment variable. This variable overrides the default TLS auto-detection behavior for the Dibbla Go SDK, allowing explicit control over TLS encryption. ```bash # Force TLS on (overrides auto-detection) export GRPC_USE_TLS=true # Force TLS off export GRPC_USE_TLS=false # Let SDK auto-detect (default) # Don't set GRPC_USE_TLS or leave it empty ``` -------------------------------- ### Implement Error Handling and Validation (Go) Source: https://context7.com/dibbla-agents/sdk-go/llms.txt This Go code illustrates how to implement error handling and input validation within a Dibbla Agents SDK workflow function. It defines an email validation function that checks for required fields, email format using regex, and minimum name length, returning a structured output indicating validity and a message. The function is registered with the SDK server. ```go package main import ( "fmt" "regexp" "github.com/dibbla-agents/sdk-go" ) type EmailInput struct { Email string `json:"email"` Name string `json:"name"` } type EmailOutput struct { Valid bool `json:"valid"` Message string `json:"message"` } func main() { server, _ := sdk.New( sdk.WithServerName("validation-worker"), sdk.WithServerApiToken("your-token"), ) validateEmailFunc := sdk.NewSimpleFunction[EmailInput, EmailOutput]( "validate_email", "1.0.0", "Validate email address with comprehensive checks", ).WithHandler(func(input EmailInput) (EmailOutput, error) { // Input validation if input.Email == "" { return EmailOutput{}, fmt.Errorf("email field is required") } if input.Name == "" { return EmailOutput{}, fmt.Errorf("name field is required") } // Email format validation emailRegex := regexp.MustCompile(`^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$`) if !emailRegex.MatchString(input.Email) { return EmailOutput{ Valid: false, Message: fmt.Sprintf("Invalid email format: %s", input.Email), }, nil } // Business logic validation if len(input.Name) < 2 { return EmailOutput{ Valid: false, Message: "Name must be at least 2 characters", }, nil } // Validation passed return EmailOutput{ Valid: true, Message: fmt.Sprintf("Valid email for %s: %s", input.Name, input.Email), }, nil }).WithTags("validation", "email") server.RegisterFunction(validateEmailFunc) server.Start() } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.