GetTaskStatus()
Get current task status:Copy
package main
import (
"context"
"fmt"
"os"
legnext "github.com/legnext-ai/sdks/sdks/go"
)
func main() {
config := legnext.NewConfiguration()
config.Servers = legnext.ServerConfigurations{
{
URL: "https://api.legnext.ai",
},
}
apiKey := os.Getenv("LEGNEXT_API_KEY")
config.AddDefaultHeader("x-api-key", apiKey)
client := legnext.NewAPIClient(config)
ctx := context.Background()
jobId := "job-123"
task, httpRes, err := client.TaskManagementAPI.GetTaskStatus(ctx, jobId).Execute()
if err != nil {
fmt.Printf("Error: %v\n", err)
return
}
fmt.Printf("Status: %s\n", *task.Status)
fmt.Printf("Progress: %d%%\n", *task.Progress)
if *task.Status == "completed" {
fmt.Printf("Result: %v\n", task.Output)
}
}
Polling for Completion
Wait for task completion with polling:Copy
package main
import (
"context"
"fmt"
"os"
"time"
legnext "github.com/legnext-ai/sdks/sdks/go"
)
func waitForCompletion(
ctx context.Context,
client *legnext.APIClient,
jobId string,
timeoutSeconds int,
pollIntervalSeconds int,
) (*legnext.TaskResponse, error) {
startTime := time.Now()
timeout := time.Duration(timeoutSeconds) * time.Second
for {
task, _, err := client.TaskManagementAPI.GetTaskStatus(ctx, jobId).Execute()
if err != nil {
return nil, err
}
fmt.Printf("Current status: %s\n", *task.Status)
if *task.Status == "completed" {
fmt.Println("Task completed successfully!")
fmt.Printf("Output: %v\n", task.Output)
return task, nil
} else if *task.Status == "failed" {
return nil, fmt.Errorf("task failed: %v", task.Error)
}
// Check timeout
if time.Since(startTime) > timeout {
return nil, fmt.Errorf("task timeout after %d seconds", timeoutSeconds)
}
// Wait before next poll
time.Sleep(time.Duration(pollIntervalSeconds) * time.Second)
}
}
func main() {
config := legnext.NewConfiguration()
config.Servers = legnext.ServerConfigurations{
{
URL: "https://api.legnext.ai",
},
}
apiKey := os.Getenv("LEGNEXT_API_KEY")
config.AddDefaultHeader("x-api-key", apiKey)
client := legnext.NewAPIClient(config)
ctx := context.Background()
jobId := "job-123"
result, err := waitForCompletion(ctx, client, jobId, 300, 3)
if err != nil {
fmt.Printf("Error: %v\n", err)
return
}
fmt.Printf("Final result: %v\n", result)
}
Complete Example with Error Handling
Copy
package main
import (
"context"
"fmt"
"os"
"time"
legnext "github.com/legnext-ai/sdks/sdks/go"
)
func waitForCompletion(
ctx context.Context,
client *legnext.APIClient,
jobId string,
timeoutSeconds int,
pollIntervalSeconds int,
) (*legnext.TaskResponse, error) {
startTime := time.Now()
timeout := time.Duration(timeoutSeconds) * time.Second
for {
task, _, err := client.TaskManagementAPI.GetTaskStatus(ctx, jobId).Execute()
if err != nil {
return nil, err
}
if *task.Status == "completed" {
return task, nil
} else if *task.Status == "failed" {
return nil, fmt.Errorf("task failed: %v", task.Error)
}
if time.Since(startTime) > timeout {
return nil, fmt.Errorf("task timeout after %d seconds", timeoutSeconds)
}
time.Sleep(time.Duration(pollIntervalSeconds) * time.Second)
}
}
func generateImageWithPolling() error {
config := legnext.NewConfiguration()
config.Servers = legnext.ServerConfigurations{
{
URL: "https://api.legnext.ai",
},
}
apiKey := os.Getenv("LEGNEXT_API_KEY")
config.AddDefaultHeader("x-api-key", apiKey)
client := legnext.NewAPIClient(config)
ctx := context.Background()
// Step 1: Start generation
text := "a beautiful sunset over mountains"
request := legnext.DiffusionRequest{
Text: &text,
}
response, _, err := client.ImageGenerationAPI.GenerateImage(ctx).
DiffusionRequest(request).
Execute()
if err != nil {
return fmt.Errorf("error starting generation: %v", err)
}
jobId := *response.JobId
fmt.Printf("Job started: %s\n", jobId)
// Step 2: Poll for completion
result, err := waitForCompletion(ctx, client, jobId, 600, 3)
if err != nil {
return fmt.Errorf("error waiting for completion: %v", err)
}
// Step 3: Get final result
if result.Output != nil && result.Output.ImageUrls != nil {
fmt.Printf("Image URLs: %v\n", result.Output.ImageUrls)
}
return nil
}
func main() {
if err := generateImageWithPolling(); err != nil {
fmt.Printf("Error: %v\n", err)
}
}
Error Handling
HTTP Error Handling:Copy
task, httpRes, err := client.TaskManagementAPI.GetTaskStatus(ctx, jobId).Execute()
if err != nil {
if httpRes != nil {
switch httpRes.StatusCode {
case 400:
fmt.Println("Validation error: Check request parameters")
case 401:
fmt.Println("Authentication error: Invalid API key")
case 404:
fmt.Println("Resource not found: Check job ID exists")
case 429:
fmt.Println("Rate limit exceeded. Please retry later.")
case 500, 502, 503:
fmt.Println("Server error. Please retry with backoff.")
default:
fmt.Printf("API error (%d): %v\n", httpRes.StatusCode, err)
}
} else {
fmt.Printf("Unexpected error: %v\n", err)
}
return
}
| Status Code | Description | Action |
|---|---|---|
| 400 | Invalid request parameters | Check request body format |
| 401 | Invalid API key | Verify API key is correct |
| 404 | Resource not found | Check job ID exists |
| 429 | Rate limit exceeded | Wait and retry with backoff |
| 500/502/503 | Server error | Retry with exponential backoff |
Copy
import (
"math"
"time"
)
func callWithRetry(
ctx context.Context,
client *legnext.APIClient,
request legnext.DiffusionRequest,
maxRetries int,
) (*legnext.TaskResponse, error) {
for i := 0; i < maxRetries; i++ {
response, httpRes, err := client.ImageGenerationAPI.GenerateImage(ctx).
DiffusionRequest(request).
Execute()
if err != nil {
if httpRes != nil {
if httpRes.StatusCode == 429 {
// Rate limited - wait and retry
time.Sleep(5 * time.Second)
continue
} else if httpRes.StatusCode >= 500 {
// Server error - exponential backoff
delay := time.Duration(math.Pow(2, float64(i))) * time.Second
time.Sleep(delay)
if i == maxRetries-1 {
return nil, err
}
continue
} else {
// Other errors - don't retry
return nil, err
}
}
return nil, err
}
return response, nil
}
return nil, fmt.Errorf("max retries exceeded")
}
// Usage
text := "a beautiful landscape"
request := legnext.DiffusionRequest{
Text: &text,
}
response, err := callWithRetry(ctx, client, request, 3)
if err != nil {
fmt.Printf("Failed after retries: %v\n", err)
return
}
Concurrent Operations with Goroutines
For processing multiple tasks concurrently:Copy
package main
import (
"context"
"fmt"
"os"
"sync"
legnext "github.com/legnext-ai/sdks/sdks/go"
)
func generateMultipleImages() error {
config := legnext.NewConfiguration()
config.Servers = legnext.ServerConfigurations{
{
URL: "https://api.legnext.ai",
},
}
apiKey := os.Getenv("LEGNEXT_API_KEY")
config.AddDefaultHeader("x-api-key", apiKey)
client := legnext.NewAPIClient(config)
ctx := context.Background()
prompts := []string{"sunset", "mountains", "ocean"}
var wg sync.WaitGroup
results := make(chan string, len(prompts))
errors := make(chan error, len(prompts))
for _, prompt := range prompts {
wg.Add(1)
go func(p string) {
defer wg.Done()
// Start generation
text := p
request := legnext.DiffusionRequest{
Text: &text,
}
response, _, err := client.ImageGenerationAPI.GenerateImage(ctx).
DiffusionRequest(request).
Execute()
if err != nil {
errors <- err
return
}
jobId := *response.JobId
// Wait for completion
result, err := waitForCompletion(ctx, client, jobId, 600, 3)
if err != nil {
errors <- err
return
}
if result.Output != nil && result.Output.ImageUrls != nil && len(result.Output.ImageUrls) > 0 {
results <- result.Output.ImageUrls[0]
}
}(prompt)
}
// Wait for all goroutines
go func() {
wg.Wait()
close(results)
close(errors)
}()
// Collect results
for {
select {
case url, ok := <-results:
if ok {
fmt.Printf("Image generated: %s\n", url)
}
case err, ok := <-errors:
if ok {
fmt.Printf("Error: %v\n", err)
}
}
if len(results) == 0 && len(errors) == 0 {
break
}
}
return nil
}
func main() {
if err := generateMultipleImages(); err != nil {
fmt.Printf("Error: %v\n", err)
}
}
Progress Callbacks
Copy
type ProgressCallback func(progress int, status string)
func waitForCompletionWithProgress(
ctx context.Context,
client *legnext.APIClient,
jobId string,
onProgress ProgressCallback,
timeoutSeconds int,
pollIntervalSeconds int,
) (*legnext.TaskResponse, error) {
startTime := time.Now()
timeout := time.Duration(timeoutSeconds) * time.Second
for {
task, _, err := client.TaskManagementAPI.GetTaskStatus(ctx, jobId).Execute()
if err != nil {
return nil, err
}
// Call progress callback
if onProgress != nil {
progress := 0
if task.Progress != nil {
progress = int(*task.Progress)
}
status := ""
if task.Status != nil {
status = *task.Status
}
onProgress(progress, status)
}
if *task.Status == "completed" {
return task, nil
} else if *task.Status == "failed" {
return nil, fmt.Errorf("task failed: %v", task.Error)
}
if time.Since(startTime) > timeout {
return nil, fmt.Errorf("task timeout after %d seconds", timeoutSeconds)
}
time.Sleep(time.Duration(pollIntervalSeconds) * time.Second)
}
}
// Usage
result, err := waitForCompletionWithProgress(
ctx,
client,
jobId,
func(progress int, status string) {
fmt.Printf("Progress: %d%% - Status: %s\n", progress, status)
},
600,
3,
)
Context with Timeout
Use Go’s context for better timeout management:Copy
import (
"context"
"time"
)
func main() {
// Create context with timeout
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Minute)
defer cancel()
config := legnext.NewConfiguration()
config.Servers = legnext.ServerConfigurations{
{
URL: "https://api.legnext.ai",
},
}
apiKey := os.Getenv("LEGNEXT_API_KEY")
config.AddDefaultHeader("x-api-key", apiKey)
client := legnext.NewAPIClient(config)
// Start generation
text := "a beautiful landscape"
request := legnext.DiffusionRequest{
Text: &text,
}
response, _, err := client.ImageGenerationAPI.GenerateImage(ctx).
DiffusionRequest(request).
Execute()
if err != nil {
if ctx.Err() == context.DeadlineExceeded {
fmt.Println("Request timeout exceeded")
} else {
fmt.Printf("Error: %v\n", err)
}
return
}
fmt.Printf("Job ID: %s\n", *response.JobId)
}