CopilotKit

Types

The Agent User Interaction Protocol Go SDK is built on a set of core types that represent the fundamental structures used throughout the system. This page documents these types and their properties.

Event Interface

The Event interface is the core abstraction for all AG-UI events. All events in the system implement this interface.


type Event interface {
    // Type returns the event type
    Type() EventType

    // Timestamp returns the event timestamp (Unix milliseconds)
    Timestamp() *int64

    // SetTimestamp sets the event timestamp
    SetTimestamp(timestamp int64)

    // ThreadID returns the thread ID associated with this event
    ThreadID() string

    // RunID returns the run ID associated with this event
    RunID() string

    // Validate validates the event structure and content
    Validate() error

    // ToJSON serializes the event to JSON for cross-SDK compatibility
    ToJSON() ([]byte, error)

    // GetBaseEvent returns the underlying base event
    GetBaseEvent() *BaseEvent
}
MethodReturn TypeDescription
Type()EventTypeReturns the type of the event (e.g., TEXT_MESSAGE_START)
Timestamp()*int64Returns the Unix timestamp in milliseconds when the event occurred
SetTimestamp()-Sets the event timestamp
ThreadID()stringReturns the thread ID this event belongs to
RunID()stringReturns the run ID this event is part of
Validate()errorValidates the event structure and returns error if invalid
ToJSON()[]byte, errorSerializes the event to JSON bytes
GetBaseEvent()*BaseEventReturns the embedded base event struct

Usage Example

// Working with events through the interface
func handleEvent(event events.Event) error {
    // Validate the event
    if err := event.Validate(); err != nil {
        return fmt.Errorf("invalid event: %w", err)
    }

    // Check event type
    switch event.Type() {
    case events.EventTypeTextMessageStart:
        fmt.Printf("Message started at %d\n", *event.Timestamp())
    case events.EventTypeToolCallStart:
        fmt.Printf("Tool call in thread %s\n", event.ThreadID())
    }

    // Serialize to JSON
    jsonData, err := event.ToJSON()
    if err != nil {
        return err
    }

    return nil
}

BaseEvent Struct

The BaseEvent struct provides common fields and functionality that all events inherit through embedding.

type BaseEvent struct {
    EventType   EventType `json:"type"`
    TimestampMs *int64    `json:"timestamp,omitempty"`
    RawEvent    any       `json:"rawEvent,omitempty"`
}
FieldTypeDescription
EventTypeEventTypeThe type of event (required)
TimestampMs*int64Unix timestamp in milliseconds (optional)
RawEventanyRaw event data for custom/external events (optional)

Usage Example

// Creating a base event
baseEvent := events.NewBaseEvent(events.EventTypeTextMessageStart)

// All specific events embed BaseEvent
type TextMessageStartEvent struct {
    *BaseEvent
    MessageID string  `json:"messageId"`
    Role      *string `json:"role,omitempty"`
}

// The BaseEvent provides common functionality
event := &TextMessageStartEvent{
    BaseEvent: baseEvent,
    MessageID: "msg-123",
}

Message Types

Message events represent text messages being streamed from the agent.

TextMessageStartEvent

Indicates the start of a streaming text message.

type TextMessageStartEvent struct {
    *BaseEvent
    MessageID string  `json:"messageId"`
    Role      *string `json:"role,omitempty"`
}
FieldTypeDescription
MessageIDstringUnique identifier for the message (required)
Role*stringRole of the message sender (optional)

TextMessageContentEvent

Contains a piece of streaming text message content.

type TextMessageContentEvent struct {
    *BaseEvent
    MessageID string `json:"messageId"`
    Delta     string `json:"delta"`
}
FieldTypeDescription
MessageIDstringID of the message this content belongs to (required)
DeltastringThe text content chunk (required)

TextMessageEndEvent

Indicates the end of a streaming text message.

type TextMessageEndEvent struct {
    *BaseEvent
    MessageID string `json:"messageId"`
}
FieldTypeDescription
MessageIDstringID of the message that ended (required)

Usage Example

// Creating and streaming a text message
messageID := events.GenerateMessageID()

// Start the message
startEvent := events.NewTextMessageStartEvent(messageID, events.WithRole("assistant"))

// Stream content
contentEvent1 := events.NewTextMessageContentEvent(messageID, "Hello, ")
contentEvent2 := events.NewTextMessageContentEvent(messageID, "how can I help you?")

// End the message
endEvent := events.NewTextMessageEndEvent(messageID)

// Validate and send events
for _, event := range []events.Event{startEvent, contentEvent1, contentEvent2, endEvent} {
    if err := event.Validate(); err != nil {
        log.Printf("Invalid event: %v", err)
        continue
    }
    // Send event to stream...
}

Tool Types

Tool events represent tool/function calls made by the agent.

ToolCallStartEvent

Indicates the start of a tool call.

type ToolCallStartEvent struct {
    *BaseEvent
    ToolCallID string `json:"toolCallId"`
    ToolName   string `json:"toolName"`
}
FieldTypeDescription
ToolCallIDstringUnique identifier for the tool call (required)
ToolNamestringName of the tool being called (required)

ToolCallArgsEvent

Contains streaming arguments for a tool call.

type ToolCallArgsEvent struct {
    *BaseEvent
    ToolCallID string `json:"toolCallId"`
    Args       string `json:"args"`
}
FieldTypeDescription
ToolCallIDstringID of the tool call (required)
ArgsstringJSON string of arguments chunk (required)

ToolCallEndEvent

Indicates the end of a tool call.

type ToolCallEndEvent struct {
    *BaseEvent
    ToolCallID string `json:"toolCallId"`
}
FieldTypeDescription
ToolCallIDstringID of the tool call that ended (required)

ToolCallResultEvent

Contains the result of a tool call execution.

type ToolCallResultEvent struct {
    *BaseEvent
    ToolCallID string  `json:"toolCallId"`
    Result     any     `json:"result"`
    Error      *string `json:"error,omitempty"`
}
FieldTypeDescription
ToolCallIDstringID of the tool call (required)
ResultanyResult data from the tool execution (required)
Error*stringError message if the tool call failed (optional)

State Types

State events manage the agent's state during execution.

StateSnapshotEvent

Represents the complete state at a point in time.

type StateSnapshotEvent struct {
    *BaseEvent
    State any `json:"state"`
}
FieldTypeDescription
StateanyComplete state object (required)

StateDeltaEvent

Represents incremental changes to the state.

type StateDeltaEvent struct {
    *BaseEvent
    Delta     any     `json:"delta"`
    Operation *string `json:"operation,omitempty"`
}
FieldTypeDescription
DeltaanyState changes to apply (required)
Operation*stringType of operation (merge, replace, etc.) (optional)

Usage Example

// Creating state events
type AgentState struct {
    Counter int    `json:"counter"`
    Status  string `json:"status"`
}

// Snapshot event with complete state
state := &AgentState{Counter: 5, Status: "processing"}
snapshotEvent := events.NewStateSnapshotEvent(state)

// Delta event with incremental update
delta := map[string]interface{}{
    "counter": 6,
}
deltaEvent := events.NewStateDeltaEvent(delta, events.WithOperation("merge"))

ID Generation

The SDK provides utility functions for generating unique IDs for various entities.

ID Generation Functions

// Generate a unique thread ID (format: "thread-{uuid}")
threadID := events.GenerateThreadID()

// Generate a unique run ID (format: "run-{uuid}")
runID := events.GenerateRunID()

// Generate a unique message ID (format: "msg-{uuid}")
messageID := events.GenerateMessageID()

// Generate a unique tool call ID (format: "tool-{uuid}")
toolCallID := events.GenerateToolCallID()

// Generate a unique step ID (format: "step-{uuid}")
stepID := events.GenerateStepID()

Custom ID Generators

You can also implement custom ID generation strategies:

// Use timestamp-based IDs
generator := events.NewTimestampIDGenerator("myapp")
events.SetDefaultIDGenerator(generator)

// Now all ID generation will use timestamp format
// Format: "myapp-{type}-{timestamp}-{shortUUID}"
messageID := events.GenerateMessageID() // "myapp-msg-1709123456789-a1b2c3d4"

// Or implement your own IDGenerator interface
type CustomIDGenerator struct{}

func (g *CustomIDGenerator) GenerateMessageID() string {
    return fmt.Sprintf("custom-msg-%d", time.Now().Unix())
}
// ... implement other methods

events.SetDefaultIDGenerator(&CustomIDGenerator{})

Event Type Composition

Events in the Go SDK compose through struct embedding, allowing for clean type hierarchies:

// Example showing how events compose
type TextMessageStartEvent struct {
    *BaseEvent                    // Embeds base event fields and methods
    MessageID string  `json:"messageId"`
    Role      *string `json:"role,omitempty"`
}

// The event automatically inherits all BaseEvent methods
event := &TextMessageStartEvent{
    BaseEvent: events.NewBaseEvent(events.EventTypeTextMessageStart),
    MessageID: "msg-123",
}

// Can call both BaseEvent and specific methods
event.SetTimestamp(time.Now().UnixMilli()) // From BaseEvent
err := event.Validate()                     // TextMessageStartEvent override

This composition pattern allows the SDK to maintain a clean separation between common functionality and event-specific behavior while providing a consistent interface through the Event type.