assistant

package
v0.2.2 Latest Latest
Warning

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

Go to latest
Published: Apr 3, 2026 License: Apache-2.0 Imports: 15 Imported by: 0

Documentation

Overview

Package assistant provides a Go client for interacting with Grafana Assistant via the A2A protocol.

Index

Constants

View Source
const DefaultAgentID = "grafana_assistant_cli"

DefaultAgentID is the default agent to use if not specified.

Variables

This section is empty.

Functions

func CreateMessageStreamRequest

func CreateMessageStreamRequest(prompt, contextID string) ([]byte, error)

CreateMessageStreamRequest creates a JSON-RPC request for message/stream.

func ExtractTextFromParts

func ExtractTextFromParts(parts []A2APart) string

ExtractTextFromParts extracts all text content from A2A parts.

func FormatTimeContext

func FormatTimeContext() string

FormatTimeContext generates time context XML tags for the assistant.

func GetLastContextID

func GetLastContextID() (string, error)

GetLastContextID returns the last context ID from state.

func SaveLastContextID

func SaveLastContextID(contextID string) error

SaveLastContextID saves the last context ID to state.

func SubmitApproval

func SubmitApproval(ctx context.Context, baseURL, token, approvalID, chatID, tenantID, userID string, approved bool) error

SubmitApproval sends an approval response to the dedicated approval endpoint.

Types

type A2AArtifact

type A2AArtifact struct {
	Kind        string          `json:"kind"`
	ArtifactID  string          `json:"artifactId"`
	Name        string          `json:"name,omitempty"`
	Description string          `json:"description,omitempty"`
	Parts       []A2APart       `json:"parts"`
	Index       int             `json:"index,omitempty"`
	LastChunk   bool            `json:"lastChunk,omitempty"`
	Metadata    json.RawMessage `json:"metadata,omitempty"`
}

A2AArtifact represents an artifact in the A2A protocol.

type A2AArtifactUpdate

type A2AArtifactUpdate struct {
	Kind      string      `json:"kind"`
	TaskID    string      `json:"taskId"`
	ContextID string      `json:"contextId"`
	Artifact  A2AArtifact `json:"artifact"`
	Append    bool        `json:"append,omitempty"`
	LastChunk bool        `json:"lastChunk,omitempty"`
}

A2AArtifactUpdate represents an artifact-update event from SSE.

type A2AEndpoints

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

A2AEndpoints holds the A2A API endpoints for a Grafana instance.

func GetA2AEndpoints

func GetA2AEndpoints(baseURL string) *A2AEndpoints

GetA2AEndpoints returns the A2A API endpoints for the given base URL.

func (*A2AEndpoints) AgentEndpoint

func (e *A2AEndpoints) AgentEndpoint(agentID string) string

AgentEndpoint returns the endpoint for a specific agent.

func (*A2AEndpoints) Approval

func (e *A2AEndpoints) Approval(approvalID string) string

Approval returns the endpoint for submitting an approval response.

type A2AFileContent

type A2AFileContent struct {
	Name     string `json:"name,omitempty"`
	MimeType string `json:"mimeType,omitempty"`
	Bytes    string `json:"bytes,omitempty"`
	URI      string `json:"uri,omitempty"`
}

A2AFileContent represents file content in a part.

type A2AMessage

type A2AMessage struct {
	Kind      string         `json:"kind"`
	Role      string         `json:"role"`
	Parts     []A2APart      `json:"parts"`
	MessageID string         `json:"messageId"`
	Metadata  map[string]any `json:"metadata,omitempty"`
}

A2AMessage represents a message in A2A format.

type A2APart

type A2APart struct {
	Kind     string          `json:"kind"`
	Text     string          `json:"text,omitempty"`
	File     *A2AFileContent `json:"file,omitempty"`
	Data     json.RawMessage `json:"data,omitempty"`
	Metadata json.RawMessage `json:"metadata,omitempty"`
}

A2APart represents a content part in a message or artifact.

type A2AStatus

type A2AStatus struct {
	State   string      `json:"state"`
	Message *A2AMessage `json:"message,omitempty"`
}

A2AStatus represents task status.

type A2AStatusUpdate

type A2AStatusUpdate struct {
	Kind      string    `json:"kind"`
	TaskID    string    `json:"taskId"`
	ContextID string    `json:"contextId"`
	Status    A2AStatus `json:"status"`
	Final     bool      `json:"final,omitempty"`
}

A2AStatusUpdate represents a status-update event from SSE.

type A2ATask

type A2ATask struct {
	Kind      string           `json:"kind"`
	ID        string           `json:"id"`
	ContextID string           `json:"contextId"`
	Status    A2AStatus        `json:"status"`
	Artifacts []A2AArtifact    `json:"artifacts,omitempty"`
	History   []A2AMessage     `json:"history,omitempty"`
	Metadata  *A2ATaskMetadata `json:"metadata,omitempty"`
}

A2ATask represents a task returned from the A2A API.

type A2ATaskMetadata

type A2ATaskMetadata struct {
	Error string `json:"error,omitempty"`
}

A2ATaskMetadata contains metadata for a task, including error information.

type ApprovalHandler

type ApprovalHandler interface {
	// HandleApproval is called when an approval request is received.
	// Returns true if approved, false if denied.
	HandleApproval(req ApprovalRequest) bool
}

ApprovalHandler handles approval requests during streaming. If nil, approvals are auto-denied.

type ApprovalRequest

type ApprovalRequest struct {
	ID          string          `json:"id"`
	ChatID      string          `json:"chatId"`
	TenantID    string          `json:"tenantId"`
	UserID      string          `json:"userId"`
	ToolName    string          `json:"toolName"`
	ToolInput   json.RawMessage `json:"toolInput,omitempty"`
	Description string          `json:"description,omitempty"`
}

ApprovalRequest represents an approval request from the backend.

type ApprovalResponse

type ApprovalResponse struct {
	ID       string `json:"id"`
	ChatID   string `json:"chatId"`
	TenantID string `json:"tenantId"`
	UserID   string `json:"userId"`
	Approved bool   `json:"approved"`
}

ApprovalResponse represents the user's response to an approval request.

type Chat

type Chat struct {
	ID       string `json:"id"`
	Name     string `json:"name"`
	Category string `json:"category,omitempty"`
	Source   string `json:"source"`
}

Chat represents a chat conversation.

func FetchChat

func FetchChat(ctx context.Context, baseURL, token, chatID string) (*Chat, error)

FetchChat fetches a single chat by ID from the Chat API.

type ChatEndpoints

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

ChatEndpoints holds the Chat API endpoints for a Grafana instance.

func GetChatEndpoints

func GetChatEndpoints(baseURL string) *ChatEndpoints

GetChatEndpoints returns the Chat API endpoints for the given base URL.

func (*ChatEndpoints) Chat

func (e *ChatEndpoints) Chat(chatID string) string

Chat returns the endpoint for a specific chat.

func (*ChatEndpoints) Chats

func (e *ChatEndpoints) Chats() string

Chats returns the base endpoint for chats.

type ChatMessage

type ChatMessage struct {
	ID        string      `json:"id"`
	Role      string      `json:"role"`
	Content   ContentJSON `json:"content"`
	CreatedAt string      `json:"created"`
	Type      string      `json:"type,omitempty"`
	Hidden    bool        `json:"hidden,omitempty"`
}

ChatMessage represents a message from the Chat REST API.

func FetchChatMessages

func FetchChatMessages(ctx context.Context, baseURL, token, chatID string) ([]ChatMessage, error)

FetchChatMessages fetches messages for a chat from the REST API.

func (*ChatMessage) ExtractText

func (m *ChatMessage) ExtractText() string

ExtractText extracts all text content from a ChatMessage. It strips out <context>...</context> tags that are injected by the system.

type Client

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

Client is a client for interacting with the Grafana Assistant via A2A API.

func New

func New(opts ClientOptions) *Client

New creates a new Client with the given options.

func (*Client) Chat

func (c *Client) Chat(ctx context.Context, prompt string, opts StreamOptions) StreamResult

Chat sends a message and streams the response.

func (*Client) ChatWithApproval

func (c *Client) ChatWithApproval(ctx context.Context, prompt string, opts StreamOptions, approvalHandler ApprovalHandler) StreamResult

ChatWithApproval sends a message and streams the response with approval handling.

func (*Client) GetBaseURL

func (c *Client) GetBaseURL() string

GetBaseURL returns the computed base URL for API requests.

func (*Client) GetChat

func (c *Client) GetChat(ctx context.Context, chatID string) (*Chat, error)

GetChat fetches a single chat by ID.

func (*Client) GetGrafanaURL

func (c *Client) GetGrafanaURL() string

GetGrafanaURL returns the Grafana instance URL.

func (*Client) GetToken

func (c *Client) GetToken() string

GetToken returns the current authentication token.

func (*Client) SetLogger

func (c *Client) SetLogger(logger Logger)

SetLogger sets a custom logger for events.

func (*Client) ValidateCLIContext

func (c *Client) ValidateCLIContext(ctx context.Context, contextID string) error

ValidateCLIContext validates that a context ID belongs to a CLI-created chat.

type ClientOptions

type ClientOptions struct {
	GrafanaURL     string
	Token          string
	APIEndpoint    string
	TokenRefresher TokenRefresher
}

ClientOptions represents options for creating a Client.

type ContentBlock

type ContentBlock struct {
	Type string `json:"type"`
	Text string `json:"text,omitempty"`
}

ContentBlock represents a single content block in a message.

type ContentJSON

type ContentJSON []ContentBlock

ContentJSON is an array of content blocks from the API.

type InteractiveApprovalHandler

type InteractiveApprovalHandler struct {
	Logger Logger
}

InteractiveApprovalHandler prompts the user via stdin for approval.

func (*InteractiveApprovalHandler) HandleApproval

func (h *InteractiveApprovalHandler) HandleApproval(req ApprovalRequest) bool

HandleApproval prompts the user for approval via stdin.

type JSONRPCError

type JSONRPCError struct {
	Code    int    `json:"code"`
	Message string `json:"message"`
	Data    string `json:"data,omitempty"`
}

JSONRPCError represents a JSON-RPC 2.0 error.

type JSONRPCRequest

type JSONRPCRequest struct {
	JSONRPC string          `json:"jsonrpc"`
	ID      string          `json:"id"`
	Method  string          `json:"method"`
	Params  json.RawMessage `json:"params"`
}

JSONRPCRequest represents a JSON-RPC 2.0 request.

type JSONRPCResponse

type JSONRPCResponse struct {
	JSONRPC string          `json:"jsonrpc"`
	ID      string          `json:"id,omitempty"`
	Result  json.RawMessage `json:"result,omitempty"`
	Error   *JSONRPCError   `json:"error,omitempty"`
}

JSONRPCResponse represents a JSON-RPC 2.0 response.

type Logger

type Logger interface {
	Info(message string)
	Debug(message string)
	Warning(message string)
}

Logger interface for events.

type MessageSendParams

type MessageSendParams struct {
	Message   A2AMessage `json:"message"`
	ContextID string     `json:"contextId,omitempty"`
}

MessageSendParams represents parameters for the message/send or message/stream method.

type NopLogger

type NopLogger struct{}

NopLogger is a logger that does nothing.

func (NopLogger) Debug

func (NopLogger) Debug(string)

func (NopLogger) Info

func (NopLogger) Info(string)

func (NopLogger) Warning

func (NopLogger) Warning(string)

type State

type State struct {
	// LastContextID is the context ID of the last chat session.
	LastContextID string `yaml:"last-context-id,omitempty"`
}

State represents runtime state that persists across sessions.

func LoadState

func LoadState() (*State, error)

LoadState loads the state from the state file.

func (*State) Save

func (s *State) Save() error

Save saves the state to the state file.

type StreamEvent

type StreamEvent struct {
	Type      string `json:"type"`
	TaskID    string `json:"taskId,omitempty"`
	ContextID string `json:"contextId,omitempty"`
	State     string `json:"state,omitempty"`
	Final     bool   `json:"final,omitempty"`
	ToolName  string `json:"toolName,omitempty"`
	Text      string `json:"text,omitempty"`
	Error     string `json:"error,omitempty"`
	Timeout   int    `json:"timeout,omitempty"`
}

StreamEvent represents a single event emitted during streaming.

type StreamOptions

type StreamOptions struct {
	Timeout   int
	ContextID string
	OnEvent   func(StreamEvent)
}

StreamOptions represents options for streaming.

type StreamResult

type StreamResult struct {
	TaskID            string
	ContextID         string
	Completed         bool
	TimedOut          bool
	Failed            bool
	Canceled          bool
	ErrorMessage      string
	Response          string
	ErrorEventEmitted bool
}

StreamResult represents the result of a streaming chat.

func StreamChat

func StreamChat(ctx context.Context, baseURL, token, agentID, prompt string, opts StreamOptions, logger Logger) StreamResult

StreamChat sends a message and streams the response via A2A SSE.

func StreamChatWithApproval

func StreamChatWithApproval(ctx context.Context, baseURL, token, agentID, prompt string, opts StreamOptions, logger Logger, approvalHandler ApprovalHandler) StreamResult

StreamChatWithApproval sends a message and streams the response, handling approval requests.

type TokenRefresher

type TokenRefresher func() (string, error)

TokenRefresher is called before each API request to ensure the token is fresh.

Jump to

Keyboard shortcuts

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