Using Lamatic SDK with Go
This guide demonstrates how to integrate the Lamatic Go SDK with your Go applications to execute flows.
This is a community-built Go SDK for the Lamatic AI platform. The SDK is maintained under the Lamatic organization on GitHub.
Installation
Install the Lamatic Go SDK using Go modules:
go get github.com/Lamatic/lamatic-sdk-go@latestIf your code imports github.com/AasheeshLikePanner/lamatic-sdk-go, change the import to github.com/Lamatic/lamatic-sdk-go. The module was renamed in v0.1.1.
Getting Started
To use the Lamatic Go SDK, youβll need:
- An API key or access token
- Your project ID
- The Lamatic API endpoint
Basic Setup
Import the SDK in your Go code:
import (
"context"
lamatic "github.com/Lamatic/lamatic-sdk-go/pkg/lamatic"
)Authentication
The SDK supports two authentication methods:
package main
import (
"context"
lamatic "github.com/Lamatic/lamatic-sdk-go/pkg/lamatic"
)
func main() {
apiKey := "your-api-key"
client, err := lamatic.NewClient(lamatic.Config{
Endpoint: "your-endpoint",
ProjectID: "your-project-id",
APIKey: &apiKey,
})
if err != nil {
panic(err)
}
// Use client...
}Executing Flows
Execute a workflow using the ExecuteFlow method:
package main
import (
"context"
"fmt"
"log"
lamatic "github.com/Lamatic/lamatic-sdk-go/pkg/lamatic"
)
func main() {
ctx := context.Background()
apiKey := "your-api-key"
client, err := lamatic.NewClient(lamatic.Config{
Endpoint: "your-endpoint",
ProjectID: "your-project-id",
APIKey: &apiKey,
})
if err != nil {
log.Fatalf("Failed to create client: %v", err)
}
flowId := "your-flow-id"
payload := map[string]interface{}{
"prompt": "Hello, AI!",
}
resp, err := client.ExecuteFlow(ctx, flowId, payload)
if err != nil {
log.Fatalf("Error executing flow: %v", err)
}
if resp.Status == lamatic.StatusSuccess {
fmt.Printf("Result: %v\n", resp.Result)
} else {
fmt.Printf("Failed: %s\n", resp.Message)
}
}Streaming Responses
Use ExecuteFlowTokenStream to show LLM output as it is generated, instead of waiting for the whole flow to finish. It returns a channel that delivers one event at a time. Streaming requires v0.1.1 or later.
ctx := context.Background()
events, err := client.ExecuteFlowTokenStream(ctx, "your-flow-id", map[string]interface{}{
"prompt": "Write a short story",
}, nil)
if err != nil {
log.Fatalf("Could not start the stream: %v", err) // the request could not be sent
}
for event := range events {
switch event.Type {
case lamatic.EventToken:
fmt.Print(event.Token) // one piece of text
case lamatic.EventFinal:
fmt.Println("\nFull text:", event.Text)
case lamatic.EventError:
fmt.Println("\nStream failed:", event.Message)
}
}Events
Type | Fields | When |
|---|---|---|
EventToken | Token, NodeID, Raw | An LLM or RAG node produced the next piece of text |
EventNode | NodeID, Output, Raw | A node finished; Output is its full output |
EventFinal | Result, Text, TextByNode, Raw | The flow finished. This is always the last event of a successful stream |
EventError | Message, NodeID, Raw | Something failed. The stream ends if the failure was fatal |
Texton the final event is every token joined together. Use it instead of readinggeneratedResponsefrom a nodeβs output, because the flowβsResultonly holds what its response node returns.TextByNodesplits the text by node, for flows with more than one LLM or RAG node.Rawis the original server frame. On theEventNodeof an LLM node,Raw.Data["_meta"]holds token counts and cost.
Only LLM and RAG nodes stream token by token. Every other node reports once, as a single EventNode when it finishes.
Stopping a stream
Cancel the context to stop generation, for example from a βStopβ button. Keep reading the channel: it closes on its own once the stream has stopped, without an EventError or EventFinal.
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
events, _ := client.ExecuteFlowTokenStream(ctx, "your-flow-id", payload, nil)
for event := range events {
if event.Type == lamatic.EventToken {
fmt.Print(event.Token)
}
if userPressedStop() {
cancel()
}
}Always either read the channel until it closes or cancel the context. Abandoning the channel otherwise keeps the connection open.
Handling stream errors
ExecuteFlowTokenStream only returns an error if the request could not be sent. Everything after that, such as invalid credentials, a failing node or a dropped connection, arrives as an EventError on the channel.
Async Flows
A flow whose API trigger is set to run asynchronously answers at once with only a request ID (Result is {"requestId": ...}) and keeps running in the background. The SDK can wait for the result for you.
This section needs v0.2.0 or later. In earlier versions CheckStatus returned an empty Result, and it took its interval and timeout as bare ints.
Run a flow and wait for the result
ExecuteFlowPoll runs a flow and, if it was queued, polls until it finishes. A realtime flowβs response comes back unchanged, so it is safe to use for any flow. ExecuteFlowPollAsync reports the result on a channel instead.
resp, err := client.ExecuteFlowPoll(ctx, "your-flow-id", payload, &lamatic.PollOptions{
Interval: 5 * time.Second, // default 15s
Timeout: 5 * time.Minute, // default 15m
})
if err != nil {
log.Fatalf("Error executing flow: %v", err)
}
if resp.Status == lamatic.StatusSuccess {
fmt.Printf("Result: %+v\n", resp.Result)
} else {
fmt.Printf("%s: %s\n", resp.Status, resp.Message)
}Poll a request ID you already have
// nil options use the defaults: check every 15 seconds, give up after 15 minutes.
resp, err := client.CheckStatus(ctx, requestId, nil)CheckStatusAsync reports the result on a channel instead.
What polling returns
Status | StatusCode | Meaning |
|---|---|---|
StatusSuccess | 200 | The flow finished. Result is its output, the same shape a realtime run returns. |
StatusFailed | 200 | A node failed. Message is the error, and Result["failedNode"] names the node. |
StatusError | 404 | The request ID was still unknown after 60 seconds of polling. |
StatusError | 408 | The run had not finished when Timeout ran out. |
A 408 means only that polling gave up: the run may still finish in the background. Call CheckStatus again later with the same request ID.
Updating Access Token
If youβre using access token authentication and need to update the token:
// Update the access token
client.UpdateAccessToken("new-access-token")Response Structure
ExecuteFlow, ExecuteFlowPoll and CheckStatus return a response with the following structure:
type Response struct {
Status Status // StatusSuccess, StatusError or StatusFailed
Result map[string]interface{} // The result data from the workflow (if successful)
Message string // Error message (if the status is not StatusSuccess)
StatusCode int // HTTP status code
}StatusFailed means the flow ran and a node failed. StatusError means the request itself failed. Use resp.Decode(&yourStruct) to unmarshal Result into your own type.
Error Handling
Always handle errors properly:
resp, err := client.ExecuteFlow(ctx, flowId, payload)
if err != nil {
// Handle network errors, configuration errors, etc.
log.Fatalf("Error: %v", err)
}
// Check response status
if resp.Status == lamatic.StatusSuccess {
// Handle success
fmt.Printf("Success: %v\n", resp.Result)
} else if resp.Status == lamatic.StatusError || resp.Status == lamatic.StatusFailed {
// Handle execution errors
fmt.Printf("Execution failed: %s\n", resp.Message)
}Environment Variables
For better security, use environment variables:
package main
import (
"context"
"log"
"os"
lamatic "github.com/Lamatic/lamatic-sdk-go/pkg/lamatic"
)
func main() {
apiKey := os.Getenv("LAMATIC_API_KEY")
projectID := os.Getenv("LAMATIC_PROJECT_ID")
endpoint := os.Getenv("LAMATIC_ENDPOINT")
client, err := lamatic.NewClient(lamatic.Config{
Endpoint: endpoint,
ProjectID: projectID,
APIKey: &apiKey,
})
if err != nil {
log.Fatalf("Failed to create client: %v", err)
}
// Use client...
}Complete Example
Hereβs a complete example that demonstrates executing a flow with proper error handling:
package main
import (
"context"
"fmt"
"log"
"os"
lamatic "github.com/Lamatic/lamatic-sdk-go/pkg/lamatic"
)
func main() {
ctx := context.Background()
// Get credentials from environment variables
apiKey := os.Getenv("LAMATIC_API_KEY")
if apiKey == "" {
log.Fatal("LAMATIC_API_KEY environment variable is not set")
}
projectID := os.Getenv("LAMATIC_PROJECT_ID")
if projectID == "" {
log.Fatal("LAMATIC_PROJECT_ID environment variable is not set")
}
endpoint := os.Getenv("LAMATIC_ENDPOINT")
if endpoint == "" {
log.Fatal("LAMATIC_ENDPOINT environment variable is not set")
}
// Create client
client, err := lamatic.NewClient(lamatic.Config{
Endpoint: endpoint,
ProjectID: projectID,
APIKey: &apiKey,
})
if err != nil {
log.Fatalf("Failed to create client: %v", err)
}
// Execute flow
flowId := os.Getenv("LAMATIC_FLOW_ID")
payload := map[string]interface{}{
"prompt": "Generate a creative story about AI",
}
resp, err := client.ExecuteFlow(ctx, flowId, payload)
if err != nil {
log.Fatalf("Error executing flow: %v", err)
}
// Handle response
if resp.Status == lamatic.StatusSuccess {
fmt.Printf("Flow executed successfully!\n")
fmt.Printf("Result: %+v\n", resp.Result)
} else {
fmt.Printf("Flow execution failed: %s\n", resp.Message)
}
}Project Structure
The Go SDK follows standard Go project structure:
lamatic-sdk-go/
βββ go.mod
βββ README.md
βββ LICENSE
βββ internal/
β βββ client/
β βββ client.go # Internal HTTP client
βββ pkg/
β βββ lamatic/
β βββ lamatic.go # Public SDK API
β βββ lamatic_test.go # Unit tests
βββ examples/
βββ api_key/
β βββ main.go # Example: API Key auth
βββ access_token/
β βββ main.go # Example: Access Token auth
βββ access_token_expiry/
β βββ main.go # Example: Handling token expiry
βββ token_generation/
βββ main.go # Example: Server-side JWT generationFeatures
The Go SDK provides the following features:
- β Execute Workflows (Flows)
- β
Run a flow and wait for an async result with
ExecuteFlowPoll - β
Job Polling with
CheckStatus - β
Token streaming with
ExecuteFlowTokenStream - β Support for API Key and Access Token (JWT) authentication
- β Proper internal/pkg separation for Go best practices
- β Context support for cancellation and timeouts
Resources
- GitHub Repository: github.com/Lamatic/lamatic-sdk-go
- Documentation: Check the repository README for the latest updates
- Examples: See the
examples/directory in the repository for more usage examples
Support
For help and support with the Go SDK:
- Open an issue on GitHub
- Contact [email protected]