task

package
v0.0.2 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Mar 20, 2025 License: MIT Imports: 12 Imported by: 0

README

Task Execution Package

The task execution package provides functionality for executing tasks synchronously and asynchronously, including API calls and Temporal workflows.

Features

  • Execute tasks synchronously and asynchronously
  • Built-in retry mechanism with configurable retry policies
  • API client for making HTTP requests
  • Temporal workflow integration
  • Task cancellation and status tracking
  • Task adapter pattern for integrating with agent-specific models

Usage

Basic Task Execution
// Create a task executor
executor := agentsdk.NewTaskExecutor()

// Register a task
executor.RegisterTask("hello", func(ctx context.Context, params interface{}) (interface{}, error) {
    name, ok := params.(string)
    if !ok {
        name = "World"
    }
    return fmt.Sprintf("Hello, %s!", name), nil
})

// Execute the task synchronously
result, err := executor.ExecuteSync(context.Background(), "hello", "John", nil)
if err != nil {
    fmt.Printf("Error: %v\n", err)
} else {
    fmt.Printf("Result: %v\n", result.Data)
}

// Execute the task asynchronously
resultChan, err := executor.ExecuteAsync(context.Background(), "hello", "Jane", nil)
if err != nil {
    fmt.Printf("Error: %v\n", err)
} else {
    result := <-resultChan
    fmt.Printf("Result: %v\n", result.Data)
}
API Task Execution
// Create an API client
apiClient := agentsdk.NewAPIClient("https://api.example.com", 10*time.Second)

// Register an API task
executor.RegisterTask("get_data", agentsdk.APITask(apiClient, task.APIRequest{
    Method: "GET",
    Path:   "/data",
    Query:  map[string]string{"limit": "10"},
}))

// Execute the API task with retry policy
timeout := 5 * time.Second
retryPolicy := &interfaces.RetryPolicy{
    MaxRetries:        3,
    InitialBackoff:    100 * time.Millisecond,
    MaxBackoff:        1 * time.Second,
    BackoffMultiplier: 2.0,
}

result, err := executor.ExecuteSync(context.Background(), "get_data", nil, &interfaces.TaskOptions{
    Timeout:     &timeout,
    RetryPolicy: retryPolicy,
})
Using the Task Adapter Pattern

The task adapter pattern allows you to use your own agent-specific models while still leveraging the SDK's task management functionality. This pattern separates the concerns of the SDK from your agent-specific implementations.

Default Implementation

The SDK provides a default implementation of the task models and adapter that you can use directly:

package main

import (
    "context"
    "fmt"
    "github.com/Ingenimax/agent-sdk-go/pkg/logging"
    "github.com/Ingenimax/agent-sdk-go/pkg/task"
)

func main() {
    ctx := context.Background()
    logger := logging.New()
    
    // Create the SDK task service
    sdkTaskService := task.NewInMemoryTaskService(logger, nil, nil)
    
    // Create the default adapter
    adapter := task.NewDefaultTaskAdapter(logger)
    
    // Create the agent task service with default models
    taskService := task.NewAgentTaskService(
        logger,
        sdkTaskService,
        adapter,
    )
    
    // Create a task using the default models
    newTask, err := taskService.CreateTask(ctx, task.DefaultCreateRequest{
        Description: "Deploy a new service",
        UserID:      "user123",
        Title:       "Service Deployment",
        TaskKind:    "deployment",
    })
    
    if err != nil {
        panic(err)
    }
    
    fmt.Printf("Created task: %s\n", newTask.ID)
}
Custom Implementation

Alternatively, you can create your own models and adapter:

// Define your agent-specific task models
type MyTask struct {
    ID          string
    Name        string
    Status      string
    CreatedAt   time.Time
    CompletedAt *time.Time
}

type MyCreateRequest struct {
    Name   string
    UserID string
}

type MyApprovalRequest struct {
    Approved bool
    Comment  string
}

type MyTaskUpdate struct {
    Type   string
    ID     string
    Status string
}

// Implement the TaskAdapter interface
type MyTaskAdapter struct {
    logger logging.Logger
}

// Create a new adapter
func NewMyTaskAdapter(logger logging.Logger) task.TaskAdapter[MyTask, MyCreateRequest, MyApprovalRequest, MyTaskUpdate] {
    return &MyTaskAdapter{
        logger: logger,
    }
}

// Implement conversion methods
func (a *MyTaskAdapter) ConvertCreateRequest(req MyCreateRequest) task.CreateTaskRequest {
    return task.CreateTaskRequest{
        Description: req.Name,
        UserID:      req.UserID,
        Metadata:    make(map[string]interface{}),
    }
}

func (a *MyTaskAdapter) ConvertApproveRequest(req MyApprovalRequest) task.ApproveTaskPlanRequest {
    return task.ApproveTaskPlanRequest{
        Approved: req.Approved,
        Feedback: req.Comment,
    }
}

func (a *MyTaskAdapter) ConvertTaskUpdates(updates []MyTaskUpdate) []task.TaskUpdate {
    sdkUpdates := make([]task.TaskUpdate, len(updates))
    for i, update := range updates {
        sdkUpdates[i] = task.TaskUpdate{
            Type:   update.Type,
            StepID: update.ID,
            Status: update.Status,
        }
    }
    return sdkUpdates
}

func (a *MyTaskAdapter) ConvertTask(sdkTask *task.Task) MyTask {
    if sdkTask == nil {
        return MyTask{}
    }
    
    return MyTask{
        ID:          sdkTask.ID,
        Name:        sdkTask.Description,
        Status:      string(sdkTask.Status),
        CreatedAt:   sdkTask.CreatedAt,
        CompletedAt: sdkTask.CompletedAt,
    }
}

func (a *MyTaskAdapter) ConvertTasks(sdkTasks []*task.Task) []MyTask {
    tasks := make([]MyTask, len(sdkTasks))
    for i, sdkTask := range sdkTasks {
        tasks[i] = a.ConvertTask(sdkTask)
    }
    return tasks
}

// Use the adapter with a task service
type MyTaskService struct {
    sdkService task.Service
    adapter    task.TaskAdapter[MyTask, MyCreateRequest, MyApprovalRequest, MyTaskUpdate]
}

func NewMyTaskService(sdkService task.Service, adapter task.TaskAdapter[MyTask, MyCreateRequest, MyApprovalRequest, MyTaskUpdate]) *MyTaskService {
    return &MyTaskService{
        sdkService: sdkService,
        adapter:    adapter,
    }
}

// Create a task using your own models
func (s *MyTaskService) CreateTask(ctx context.Context, req MyCreateRequest) (MyTask, error) {
    // Convert to SDK request
    sdkReq := s.adapter.ConvertCreateRequest(req)
    
    // Create task using SDK service
    sdkTask, err := s.sdkService.CreateTask(ctx, sdkReq)
    if err != nil {
        return MyTask{}, err
    }
    
    // Convert back to your model
    return s.adapter.ConvertTask(sdkTask), nil
}
Using the Agent Task Service

The SDK provides an AgentTaskService that you can use to work with your agent-specific models. It wraps the adapter service and provides a simpler interface:

// Create the agent task service
taskService := task.NewAgentTaskService(
    ctx,
    logger,
    sdkTaskService,
    myAdapter,
)

// Use the service with your agent-specific models
myTask, err := taskService.CreateTask(ctx, myCreateRequest)
if err != nil {
    // Handle error
}

// Get a task
myTask, err = taskService.GetTask(ctx, "task-123")
if err != nil {
    // Handle error
}

// List tasks for a user
myTasks, err := taskService.ListTasks(ctx, "user-456")
if err != nil {
    // Handle error
}

// Approve a task plan
myTask, err = taskService.ApproveTaskPlan(ctx, "task-123", myApproveRequest)
if err != nil {
    // Handle error
}

// Update a task
myTask, err = taskService.UpdateTask(ctx, "task-123", "conversation-789", myTaskUpdates)
if err != nil {
    // Handle error
}

// Add a log entry to a task
err = taskService.AddTaskLog(ctx, "task-123", "Starting deployment", "info")
if err != nil {
    // Handle error
}
Temporal Workflow Execution
// Create a Temporal client
temporalClient := agentsdk.NewTemporalClient(task.TemporalConfig{
    HostPort:                 "localhost:7233",
    Namespace:                "default",
    TaskQueue:                "example",
    WorkflowIDPrefix:         "example-",
    WorkflowExecutionTimeout: 10 * time.Minute,
    WorkflowRunTimeout:       5 * time.Minute,
    WorkflowTaskTimeout:      10 * time.Second,
})

// Register a Temporal workflow task
executor.RegisterTask("example_workflow", agentsdk.TemporalWorkflowTask(temporalClient, "ExampleWorkflow"))

// Execute the Temporal workflow task
result, err := executor.ExecuteSync(context.Background(), "example_workflow", map[string]interface{}{
    "input": "example input",
}, nil)

Task Options

You can configure task execution with the following options:

options := &interfaces.TaskOptions{
    // Timeout specifies the maximum duration for task execution
    Timeout: &timeout,
    
    // RetryPolicy specifies the retry policy for the task
    RetryPolicy: &interfaces.RetryPolicy{
        MaxRetries:        3,
        InitialBackoff:    100 * time.Millisecond,
        MaxBackoff:        1 * time.Second,
        BackoffMultiplier: 2.0,
    },
    
    // Metadata contains additional information for the task execution
    Metadata: map[string]interface{}{
        "purpose": "example",
    },
}

Task Result

The task result contains the following information:

type TaskResult struct {
    // Data contains the result data
    Data interface{}
    
    // Error contains any error that occurred during task execution
    Error error
    
    // Metadata contains additional information about the task execution
    Metadata map[string]interface{}
}

Task Package

The task package provides comprehensive task management functionality for agents. It includes models, interfaces, and services for creating, retrieving, and managing tasks.

Concepts

A task represents a unit of work that an agent needs to perform. Tasks have a lifecycle, starting from creation, through planning, execution, and finally completion. Each task can have multiple steps, which are executed sequentially.

Core Components

Task Model

The Task struct represents a task in the system:

type Task struct {
	ID             string                 // Unique identifier
	Description    string                 // Task description
	Status         Status                 // Current status (pending, planning, awaiting_approval, executing, completed, failed)
	Title          string                 // Task title
	TaskKind       string                 // Type of task
	ConversationID string                 // Associated conversation ID
	Plan           *Plan                  // Execution plan
	Steps          []Step                 // Task steps
	CreatedAt      time.Time              // Creation timestamp
	UpdatedAt      time.Time              // Last update timestamp
	StartedAt      *time.Time             // When execution started
	CompletedAt    *time.Time             // When execution completed
	UserID         string                 // Owner user ID
	Logs           []LogEntry             // Activity logs
	Requirements   interface{}            // Task requirements
	Feedback       string                 // User feedback
	Metadata       map[string]interface{} // Additional metadata
}
Task Service

The Service interface defines methods for interacting with tasks:

type Service interface {
	CreateTask(ctx context.Context, req CreateTaskRequest) (*Task, error)
	GetTask(ctx context.Context, taskID string) (*Task, error)
	ListTasks(ctx context.Context, filter TaskFilter) ([]*Task, error)
	ApproveTaskPlan(ctx context.Context, taskID string, req ApproveTaskPlanRequest) (*Task, error)
	UpdateTask(ctx context.Context, taskID string, updates []TaskUpdate) (*Task, error)
	AddTaskLog(ctx context.Context, taskID string, message string, level string) error
}

Task Adapter Pattern

The task package supports the adapter pattern to allow agents to work with their own domain-specific task models while leveraging the SDK's task management capabilities.

File Organization

The package is organized into the following key files:

  • models.go: Contains all the data structures used in the task package
  • service.go: Defines the core Service interface and provides both InMemoryTaskService and AgentTaskService implementations
  • adapter.go: Implements the TaskAdapter interface and AdapterService for working with agent-specific models, including the default implementation

This compact organization helps keep related functionality together while still maintaining clean separation of concerns.

TaskAdapter Interface

The TaskAdapter is a generic interface that allows you to define custom conversion methods between SDK and agent-specific models:

type TaskAdapter[AgentTask any, AgentCreateRequest any, AgentApprovalRequest any, AgentTaskUpdate any] interface {
	// ToSDK conversions (Agent -> SDK)
	ConvertCreateRequest(req AgentCreateRequest) CreateTaskRequest
	ConvertApproveRequest(req AgentApprovalRequest) ApproveTaskPlanRequest
	ConvertTaskUpdates(updates []AgentTaskUpdate) []TaskUpdate

	// FromSDK conversions (SDK -> Agent)
	ConvertTask(sdkTask *Task) AgentTask
	ConvertTasks(sdkTasks []*Task) []AgentTask
}

Documentation

Overview

Package task provides task management functionality.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type APIClient

type APIClient struct {
	// contains filtered or unexported fields
}

APIClient is a client for making API calls

func NewAPIClient

func NewAPIClient(baseURL string, timeout time.Duration) *APIClient

NewAPIClient creates a new API client

func (*APIClient) Delete

func (c *APIClient) Delete(ctx context.Context, path string, headers map[string]string) (*APIResponse, error)

Delete makes a DELETE request

func (*APIClient) Get

func (c *APIClient) Get(ctx context.Context, path string, query map[string]string, headers map[string]string) (*APIResponse, error)

Get makes a GET request

func (*APIClient) Post

func (c *APIClient) Post(ctx context.Context, path string, body interface{}, headers map[string]string) (*APIResponse, error)

Post makes a POST request

func (*APIClient) Put

func (c *APIClient) Put(ctx context.Context, path string, body interface{}, headers map[string]string) (*APIResponse, error)

Put makes a PUT request

func (*APIClient) Request

func (c *APIClient) Request(ctx context.Context, req APIRequest) (*APIResponse, error)

Request makes an API request

func (*APIClient) SetHeader

func (c *APIClient) SetHeader(key, value string)

SetHeader sets a header for all requests

func (*APIClient) SetHeaders

func (c *APIClient) SetHeaders(headers map[string]string)

SetHeaders sets multiple headers for all requests

type APIRequest

type APIRequest struct {
	Method  string
	Path    string
	Body    interface{}
	Headers map[string]string
	Query   map[string]string
}

APIRequest represents an API request

type APIResponse

type APIResponse struct {
	StatusCode int
	Body       []byte
	Headers    http.Header
}

APIResponse represents an API response

type AdapterOption

type AdapterOption func(*AdapterOptions)

AdapterOption is a function that configures AdapterOptions

func WithDefaultUserID

func WithDefaultUserID(userID string) AdapterOption

WithDefaultUserID sets a default user ID for task creation

func WithMetadata

func WithMetadata(include bool) AdapterOption

WithMetadata configures the adapter to include SDK metadata in conversions

type AdapterOptions

type AdapterOptions struct {
	// Additional options can be added here as needed
	IncludeMetadata bool
	DefaultUserID   string
}

AdapterOptions contains optional parameters for creating a task adapter

type AdapterService

type AdapterService[AgentTask any, AgentCreateRequest any, AgentApprovalRequest any, AgentTaskUpdate any] struct {
	// contains filtered or unexported fields
}

AdapterService provides a generic service for adapting between SDK tasks and agent-specific tasks. It wraps the SDK's task service and provides methods for working with agent-specific task models.

func NewAdapterService

func NewAdapterService[AgentTask any, AgentCreateRequest any, AgentApprovalRequest any, AgentTaskUpdate any](
	logger logging.Logger,
	sdkService Service,
	adapter TaskAdapter[AgentTask, AgentCreateRequest, AgentApprovalRequest, AgentTaskUpdate],
) *AdapterService[AgentTask, AgentCreateRequest, AgentApprovalRequest, AgentTaskUpdate]

NewAdapterService creates a new adapter service for adapting between SDK and agent-specific task models. It provides a simple way for agents to work with their own task models while leveraging the SDK's task service.

func (*AdapterService[AgentTask, AgentCreateRequest, AgentApprovalRequest, AgentTaskUpdate]) AddTaskLog

func (s *AdapterService[AgentTask, AgentCreateRequest, AgentApprovalRequest, AgentTaskUpdate]) AddTaskLog(
	ctx context.Context,
	taskID string,
	message string,
	level string,
) error

AddTaskLog adds a log entry to a task.

func (*AdapterService[AgentTask, AgentCreateRequest, AgentApprovalRequest, AgentTaskUpdate]) ApproveTaskPlan

func (s *AdapterService[AgentTask, AgentCreateRequest, AgentApprovalRequest, AgentTaskUpdate]) ApproveTaskPlan(
	ctx context.Context,
	taskID string,
	req AgentApprovalRequest,
) (AgentTask, error)

ApproveTaskPlan approves or rejects a task plan using the agent-specific approval model.

func (*AdapterService[AgentTask, AgentCreateRequest, AgentApprovalRequest, AgentTaskUpdate]) CreateTask

func (s *AdapterService[AgentTask, AgentCreateRequest, AgentApprovalRequest, AgentTaskUpdate]) CreateTask(
	ctx context.Context,
	req AgentCreateRequest,
) (AgentTask, error)

CreateTask creates a new task using the agent-specific task model.

func (*AdapterService[AgentTask, AgentCreateRequest, AgentApprovalRequest, AgentTaskUpdate]) GetTask

func (s *AdapterService[AgentTask, AgentCreateRequest, AgentApprovalRequest, AgentTaskUpdate]) GetTask(
	ctx context.Context,
	taskID string,
) (AgentTask, error)

GetTask retrieves a task by ID and returns it in the agent-specific format.

func (*AdapterService[AgentTask, AgentCreateRequest, AgentApprovalRequest, AgentTaskUpdate]) ListTasks

func (s *AdapterService[AgentTask, AgentCreateRequest, AgentApprovalRequest, AgentTaskUpdate]) ListTasks(
	ctx context.Context,
	userID string,
) ([]AgentTask, error)

ListTasks returns all tasks for a user in the agent-specific format.

func (*AdapterService[AgentTask, AgentCreateRequest, AgentApprovalRequest, AgentTaskUpdate]) UpdateTask

func (s *AdapterService[AgentTask, AgentCreateRequest, AgentApprovalRequest, AgentTaskUpdate]) UpdateTask(
	ctx context.Context,
	taskID string,
	conversationID string,
	updates []AgentTaskUpdate,
) (AgentTask, error)

UpdateTask updates an existing task using agent-specific task updates.

type AgentTaskService

type AgentTaskService[AgentTask any, AgentCreateRequest any, AgentApproveRequest any, AgentTaskUpdate any] struct {
	// contains filtered or unexported fields
}

AgentTaskService provides a complete implementation of AgentTaskServiceInterface Agents can use this directly without writing their own wrapper around AdapterService

func NewAgentTaskService

func NewAgentTaskService[AgentTask any, AgentCreateRequest any, AgentApproveRequest any, AgentTaskUpdate any](
	logger logging.Logger,
	sdkService Service,
	adapter TaskAdapter[AgentTask, AgentCreateRequest, AgentApproveRequest, AgentTaskUpdate],
) *AgentTaskService[AgentTask, AgentCreateRequest, AgentApproveRequest, AgentTaskUpdate]

NewAgentTaskService creates a new service that agents can use with their own models

func (*AgentTaskService[AgentTask, AgentCreateRequest, AgentApproveRequest, AgentTaskUpdate]) AddTaskLog

func (s *AgentTaskService[AgentTask, AgentCreateRequest, AgentApproveRequest, AgentTaskUpdate]) AddTaskLog(
	ctx context.Context,
	taskID string,
	message string,
	level string,
) error

AddTaskLog adds a log entry to a task

func (*AgentTaskService[AgentTask, AgentCreateRequest, AgentApproveRequest, AgentTaskUpdate]) ApproveTaskPlan

func (s *AgentTaskService[AgentTask, AgentCreateRequest, AgentApproveRequest, AgentTaskUpdate]) ApproveTaskPlan(
	ctx context.Context,
	taskID string,
	req AgentApproveRequest,
) (AgentTask, error)

ApproveTaskPlan approves or rejects a task plan

func (*AgentTaskService[AgentTask, AgentCreateRequest, AgentApproveRequest, AgentTaskUpdate]) CreateTask

func (s *AgentTaskService[AgentTask, AgentCreateRequest, AgentApproveRequest, AgentTaskUpdate]) CreateTask(
	ctx context.Context,
	req AgentCreateRequest,
) (AgentTask, error)

CreateTask creates a new task

func (*AgentTaskService[AgentTask, AgentCreateRequest, AgentApproveRequest, AgentTaskUpdate]) GetTask

func (s *AgentTaskService[AgentTask, AgentCreateRequest, AgentApproveRequest, AgentTaskUpdate]) GetTask(
	ctx context.Context,
	taskID string,
) (AgentTask, error)

GetTask retrieves a task by ID

func (*AgentTaskService[AgentTask, AgentCreateRequest, AgentApproveRequest, AgentTaskUpdate]) ListTasks

func (s *AgentTaskService[AgentTask, AgentCreateRequest, AgentApproveRequest, AgentTaskUpdate]) ListTasks(
	ctx context.Context,
	userID string,
) ([]AgentTask, error)

ListTasks returns all tasks for a user

func (*AgentTaskService[AgentTask, AgentCreateRequest, AgentApproveRequest, AgentTaskUpdate]) UpdateTask

func (s *AgentTaskService[AgentTask, AgentCreateRequest, AgentApproveRequest, AgentTaskUpdate]) UpdateTask(
	ctx context.Context,
	taskID string,
	conversationID string,
	updates []AgentTaskUpdate,
) (AgentTask, error)

UpdateTask updates an existing task

type AgentTaskServiceInterface

type AgentTaskServiceInterface[AgentTask any, AgentCreateRequest any, AgentApproveRequest any, AgentTaskUpdate any] interface {
	// CreateTask creates a new task
	CreateTask(ctx context.Context, req AgentCreateRequest) (AgentTask, error)

	// GetTask gets a task by ID
	GetTask(ctx context.Context, taskID string) (AgentTask, error)

	// ListTasks returns all tasks for a user
	ListTasks(ctx context.Context, userID string) ([]AgentTask, error)

	// ApproveTaskPlan approves or rejects a task plan
	ApproveTaskPlan(ctx context.Context, taskID string, req AgentApproveRequest) (AgentTask, error)

	// UpdateTask updates an existing task with new steps or modifications
	UpdateTask(ctx context.Context, taskID string, conversationID string, updates []AgentTaskUpdate) (AgentTask, error)

	// AddTaskLog adds a log entry to a task
	AddTaskLog(ctx context.Context, taskID string, message string, level string) error
}

AgentTaskServiceInterface defines a standard interface that agents can implement This provides a clear pattern for agents to follow and ensures consistency

type ApproveTaskPlanRequest

type ApproveTaskPlanRequest struct {
	Approved bool   `json:"approved"`
	Feedback string `json:"feedback,omitempty"`
}

ApproveTaskPlanRequest represents the request to approve a task plan

type CreateTaskRequest

type CreateTaskRequest struct {
	Description string                 `json:"description"`
	UserID      string                 `json:"user_id"`
	Title       string                 `json:"title,omitempty"`
	TaskKind    string                 `json:"task_kind,omitempty"`
	Metadata    map[string]interface{} `json:"metadata,omitempty"`
}

CreateTaskRequest represents the request to create a new task

type DefaultApproveRequest

type DefaultApproveRequest struct {
	Approved bool   `json:"approved"`
	Feedback string `json:"feedback,omitempty"`
}

DefaultApproveRequest provides a standard approve request model

type DefaultCreateRequest

type DefaultCreateRequest struct {
	Description string `json:"description"`
	UserID      string `json:"user_id"`
	Title       string `json:"title,omitempty"`
	TaskKind    string `json:"task_kind,omitempty"`
}

DefaultCreateRequest provides a standard create request model

type DefaultStep

type DefaultStep struct {
	ID          string     `json:"id"`
	Description string     `json:"description"`
	Status      string     `json:"status"`
	StartTime   *time.Time `json:"start_time,omitempty"`
	EndTime     *time.Time `json:"end_time,omitempty"`
	Error       string     `json:"error,omitempty"`
	Output      string     `json:"output,omitempty"`
}

DefaultStep represents a task step in the default model

type DefaultTask

type DefaultTask struct {
	ID             string                 `json:"id"`
	Description    string                 `json:"description"`
	Status         string                 `json:"status"`
	Title          string                 `json:"title,omitempty"`
	TaskKind       string                 `json:"task_kind,omitempty"`
	ConversationID string                 `json:"conversation_id,omitempty"`
	CreatedAt      time.Time              `json:"created_at"`
	UpdatedAt      time.Time              `json:"updated_at"`
	StartedAt      *time.Time             `json:"started_at,omitempty"`
	CompletedAt    *time.Time             `json:"completed_at,omitempty"`
	UserID         string                 `json:"user_id"`
	Steps          []DefaultStep          `json:"steps,omitempty"`
	Requirements   interface{}            `json:"requirements,omitempty"`
	Feedback       string                 `json:"feedback,omitempty"`
	Metadata       map[string]interface{} `json:"metadata,omitempty"`
}

DefaultTask provides a standard agent task model that can be embedded or used directly

type DefaultTaskAdapter

type DefaultTaskAdapter struct {
	// contains filtered or unexported fields
}

DefaultTaskAdapter provides a standard implementation of TaskAdapter Agents can use this directly or embed it in their own adapter

func (*DefaultTaskAdapter) ConvertApproveRequest

func (a *DefaultTaskAdapter) ConvertApproveRequest(req DefaultApproveRequest) ApproveTaskPlanRequest

ConvertApproveRequest converts a default approve request to an SDK approve request

func (*DefaultTaskAdapter) ConvertCreateRequest

func (a *DefaultTaskAdapter) ConvertCreateRequest(req DefaultCreateRequest) CreateTaskRequest

ConvertCreateRequest converts a default create request to an SDK create request

func (*DefaultTaskAdapter) ConvertTask

func (a *DefaultTaskAdapter) ConvertTask(sdkTask *Task) *DefaultTask

ConvertTask converts an SDK task to a default task

func (*DefaultTaskAdapter) ConvertTaskUpdates

func (a *DefaultTaskAdapter) ConvertTaskUpdates(updates []DefaultTaskUpdate) []TaskUpdate

ConvertTaskUpdates converts default task updates to SDK task updates

func (*DefaultTaskAdapter) ConvertTasks

func (a *DefaultTaskAdapter) ConvertTasks(sdkTasks []*Task) []*DefaultTask

ConvertTasks converts a slice of SDK tasks to a slice of default tasks

type DefaultTaskUpdate

type DefaultTaskUpdate struct {
	Type        string `json:"type"`
	StepID      string `json:"step_id,omitempty"`
	Description string `json:"description,omitempty"`
	Status      string `json:"status,omitempty"`
}

DefaultTaskUpdate provides a standard task update model

type Executor

type Executor struct {
	// contains filtered or unexported fields
}

Executor implements the TaskExecutor interface

func NewExecutor

func NewExecutor() *Executor

NewExecutor creates a new task executor

func (*Executor) CancelTask

func (e *Executor) CancelTask(ctx context.Context, taskID string) error

CancelTask cancels a running task

func (*Executor) ExecuteAsync

func (e *Executor) ExecuteAsync(ctx context.Context, taskName string, params interface{}, opts *interfaces.TaskOptions) (<-chan *interfaces.TaskResult, error)

ExecuteAsync executes a task asynchronously

func (*Executor) ExecuteSync

func (e *Executor) ExecuteSync(ctx context.Context, taskName string, params interface{}, opts *interfaces.TaskOptions) (*interfaces.TaskResult, error)

ExecuteSync executes a task synchronously

func (*Executor) ExecuteWorkflow

func (e *Executor) ExecuteWorkflow(ctx context.Context, workflowName string, params interface{}, opts *interfaces.TaskOptions) (*interfaces.TaskResult, error)

ExecuteWorkflow initiates a temporal workflow

func (*Executor) ExecuteWorkflowAsync

func (e *Executor) ExecuteWorkflowAsync(ctx context.Context, workflowName string, params interface{}, opts *interfaces.TaskOptions) (<-chan *interfaces.TaskResult, error)

ExecuteWorkflowAsync initiates a temporal workflow asynchronously

func (*Executor) GetTaskStatus

func (e *Executor) GetTaskStatus(ctx context.Context, taskID string) (string, error)

GetTaskStatus gets the status of a task

func (*Executor) RegisterTask

func (e *Executor) RegisterTask(name string, taskFunc TaskFunc)

RegisterTask registers a task function with the executor

type InMemoryTaskService

type InMemoryTaskService struct {
	// contains filtered or unexported fields
}

InMemoryTaskService implements the Service interface with an in-memory storage

func NewInMemoryTaskService

func NewInMemoryTaskService(logger logging.Logger, planner TaskPlanner, executor TaskExecutor) *InMemoryTaskService

NewInMemoryTaskService creates a new in-memory task service

func (*InMemoryTaskService) AddTaskLog

func (s *InMemoryTaskService) AddTaskLog(ctx context.Context, taskID string, message string, level string) error

AddTaskLog adds a log entry to a task

func (*InMemoryTaskService) ApproveTaskPlan

func (s *InMemoryTaskService) ApproveTaskPlan(ctx context.Context, taskID string, req ApproveTaskPlanRequest) (*Task, error)

ApproveTaskPlan approves or rejects a task plan

func (*InMemoryTaskService) CreateTask

func (s *InMemoryTaskService) CreateTask(ctx context.Context, req CreateTaskRequest) (*Task, error)

CreateTask creates a new task

func (*InMemoryTaskService) GetTask

func (s *InMemoryTaskService) GetTask(ctx context.Context, taskID string) (*Task, error)

GetTask gets a task by ID

func (*InMemoryTaskService) ListTasks

func (s *InMemoryTaskService) ListTasks(ctx context.Context, filter TaskFilter) ([]*Task, error)

ListTasks returns tasks filtered by the provided criteria

func (*InMemoryTaskService) UpdateTask

func (s *InMemoryTaskService) UpdateTask(ctx context.Context, taskID string, updates []TaskUpdate) (*Task, error)

UpdateTask updates an existing task with new steps or modifications

type LogEntry

type LogEntry struct {
	ID        string    `json:"id"`
	TaskID    string    `json:"task_id"`
	StepID    string    `json:"step_id,omitempty"` // Optional reference to a specific step
	Message   string    `json:"message"`
	Level     string    `json:"level"` // info, warning, error
	Timestamp time.Time `json:"timestamp"`
}

LogEntry represents a log entry for a task

type Plan

type Plan struct {
	ID         string     `json:"id"`
	TaskID     string     `json:"task_id"`
	Steps      []Step     `json:"steps"`
	CreatedAt  time.Time  `json:"created_at"`
	ApprovedAt *time.Time `json:"approved_at,omitempty"`
	IsApproved bool       `json:"is_approved"`
}

Plan represents the execution plan for a task

type Service

type Service interface {
	// CreateTask creates a new task
	CreateTask(ctx context.Context, req CreateTaskRequest) (*Task, error)
	// GetTask gets a task by ID
	GetTask(ctx context.Context, taskID string) (*Task, error)
	// ListTasks returns tasks filtered by the provided criteria
	ListTasks(ctx context.Context, filter TaskFilter) ([]*Task, error)
	// ApproveTaskPlan approves or rejects a task plan
	ApproveTaskPlan(ctx context.Context, taskID string, req ApproveTaskPlanRequest) (*Task, error)
	// UpdateTask updates an existing task with new steps or modifications
	UpdateTask(ctx context.Context, taskID string, updates []TaskUpdate) (*Task, error)
	// AddTaskLog adds a log entry to a task
	AddTaskLog(ctx context.Context, taskID string, message string, level string) error
}

Service defines the interface for task management

type Status

type Status string

Status represents the current status of a task or step

const (
	StatusPending   Status = "pending"
	StatusPlanning  Status = "planning"
	StatusApproval  Status = "awaiting_approval"
	StatusExecuting Status = "executing"
	StatusCompleted Status = "completed"
	StatusFailed    Status = "failed"
)

Task statuses

const (
	StepStatusPending   Status = "pending"
	StepStatusExecuting Status = "executing"
	StepStatusCompleted Status = "completed"
	StepStatusFailed    Status = "failed"
)

Step statuses

type Step

type Step struct {
	ID          string                 `json:"id"`
	PlanID      string                 `json:"plan_id"`
	Description string                 `json:"description"`
	Status      Status                 `json:"status"`
	Order       int                    `json:"order"`
	StartedAt   *time.Time             `json:"started_at,omitempty"`
	CompletedAt *time.Time             `json:"completed_at,omitempty"`
	Error       string                 `json:"error,omitempty"`
	Output      string                 `json:"output,omitempty"`
	Metadata    map[string]interface{} `json:"metadata,omitempty"`
}

Step represents a single step in an execution plan

type Task

type Task struct {
	ID             string                 `json:"id"`
	Description    string                 `json:"description"`
	Status         Status                 `json:"status"`
	Title          string                 `json:"title,omitempty"`
	TaskKind       string                 `json:"task_kind,omitempty"`
	ConversationID string                 `json:"conversation_id,omitempty"`
	Plan           *Plan                  `json:"plan,omitempty"`
	Steps          []Step                 `json:"steps,omitempty"` // Direct access to steps
	CreatedAt      time.Time              `json:"created_at"`
	UpdatedAt      time.Time              `json:"updated_at"`
	StartedAt      *time.Time             `json:"started_at,omitempty"`
	CompletedAt    *time.Time             `json:"completed_at,omitempty"`
	UserID         string                 `json:"user_id"`
	Logs           []LogEntry             `json:"logs,omitempty"`
	Requirements   interface{}            `json:"requirements,omitempty"` // JSON of TaskRequirements
	Feedback       string                 `json:"feedback,omitempty"`
	Metadata       map[string]interface{} `json:"metadata,omitempty"` // For extensibility
}

Task represents an infrastructure task to be executed

type TaskAdapter

type TaskAdapter[AgentTask any, AgentCreateRequest any, AgentApprovalRequest any, AgentTaskUpdate any] interface {

	// ConvertCreateRequest converts an agent-specific create request to an SDK create request
	ConvertCreateRequest(req AgentCreateRequest) CreateTaskRequest

	// ConvertApproveRequest converts an agent-specific approve request to an SDK approve request
	ConvertApproveRequest(req AgentApprovalRequest) ApproveTaskPlanRequest

	// ConvertTaskUpdates converts agent-specific task updates to SDK task updates
	ConvertTaskUpdates(updates []AgentTaskUpdate) []TaskUpdate

	// ConvertTask converts an SDK task to an agent-specific task
	ConvertTask(sdkTask *Task) AgentTask

	// ConvertTasks converts a slice of SDK tasks to a slice of agent-specific tasks
	ConvertTasks(sdkTasks []*Task) []AgentTask
}

TaskAdapter defines a generic interface for adapting SDK task models to agent-specific models and vice versa. This pattern helps separate the concerns of the SDK from agent-specific implementations.

Implementing this interface allows agents to use their own domain models while still leveraging the SDK's task management capabilities.

func NewDefaultTaskAdapter

NewDefaultTaskAdapter creates a new default task adapter

type TaskExecutor

type TaskExecutor interface {
	// ExecuteStep executes a single step in a task's plan
	ExecuteStep(ctx context.Context, task *Task, step *Step) error
	// ExecuteTask executes all steps in a task's plan
	ExecuteTask(ctx context.Context, task *Task) error
}

TaskExecutor defines the interface for executing a task's plan

type TaskFilter

type TaskFilter struct {
	UserID         string     `json:"user_id,omitempty"`
	ConversationID string     `json:"conversation_id,omitempty"`
	Status         []Status   `json:"status,omitempty"`
	TaskKind       string     `json:"task_kind,omitempty"`
	CreatedAfter   *time.Time `json:"created_after,omitempty"`
	CreatedBefore  *time.Time `json:"created_before,omitempty"`
}

TaskFilter represents filters for querying tasks

type TaskFunc

type TaskFunc func(ctx context.Context, params interface{}) (interface{}, error)

TaskFunc is a function that executes a task

func APITask

func APITask(client *APIClient, req APIRequest) TaskFunc

APITask creates a task function for making an API request

func TemporalWorkflowAsyncTask

func TemporalWorkflowAsyncTask(client *TemporalClient, workflowName string) TaskFunc

TemporalWorkflowAsyncTask creates a task function for executing a Temporal workflow asynchronously

func TemporalWorkflowTask

func TemporalWorkflowTask(client *TemporalClient, workflowName string) TaskFunc

TemporalWorkflowTask creates a task function for executing a Temporal workflow

type TaskPlanner

type TaskPlanner interface {
	// CreatePlan creates a plan for a task
	CreatePlan(ctx context.Context, task *Task) (string, error)
}

TaskPlanner defines the interface for planning a task

type TaskUpdate

type TaskUpdate struct {
	Type        string `json:"type"` // add_step, modify_step, remove_step, add_comment, update_status
	StepID      string `json:"step_id,omitempty"`
	Description string `json:"description,omitempty"`
	Status      string `json:"status,omitempty"`
}

TaskUpdate represents an update to a task

type TemporalClient

type TemporalClient struct {
	// contains filtered or unexported fields
}

TemporalClient is a client for Temporal

func NewTemporalClient

func NewTemporalClient(config TemporalConfig) *TemporalClient

NewTemporalClient creates a new Temporal client

func (*TemporalClient) ExecuteWorkflow

func (c *TemporalClient) ExecuteWorkflow(ctx context.Context, workflowName string, params interface{}) (*interfaces.TaskResult, error)

ExecuteWorkflow executes a Temporal workflow

func (*TemporalClient) ExecuteWorkflowAsync

func (c *TemporalClient) ExecuteWorkflowAsync(ctx context.Context, workflowName string, params interface{}) (<-chan *interfaces.TaskResult, error)

ExecuteWorkflowAsync executes a Temporal workflow asynchronously

type TemporalConfig

type TemporalConfig struct {
	// HostPort is the host:port of the Temporal server
	HostPort string
	// Namespace is the Temporal namespace
	Namespace string
	// TaskQueue is the Temporal task queue
	TaskQueue string
	// WorkflowIDPrefix is the prefix for workflow IDs
	WorkflowIDPrefix string
	// WorkflowExecutionTimeout is the timeout for workflow execution
	WorkflowExecutionTimeout time.Duration
	// WorkflowRunTimeout is the timeout for workflow run
	WorkflowRunTimeout time.Duration
	// WorkflowTaskTimeout is the timeout for workflow task
	WorkflowTaskTimeout time.Duration
}

TemporalConfig represents configuration for Temporal

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL