agent

package
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Aug 21, 2026 License: Apache-2.0 Imports: 10 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

View Source
var ErrApprovalUnavailable = errors.New("tool approval is unavailable")

Functions

func ContextSize added in v0.0.5

func ContextSize(protocol string, usage Usage) int64

ContextSize estimates how many context-window tokens a step occupied, from that step's usage. Fantasy normalizes OpenAI and Anthropic usage so InputTokens excludes cached tokens (cache reads/creations are reported separately), while Google's prompt token count already includes cached content.

func GenerateText

func GenerateText(ctx context.Context, config ModelConfig, systemPrompt, prompt string) (string, error)

func RequireApproval added in v0.0.7

func RequireApproval(ctx context.Context, request ApprovalRequest) (bool, error)

RequireApproval pauses the current tool call until the run's approval handler returns a decision or the run context is cancelled.

func WithAutoApprove added in v0.0.7

func WithAutoApprove(ctx context.Context) context.Context

WithAutoApprove makes RequireApproval succeed without user interaction. It is meant for surfaces such as API-key access where the key's scope is the pre-authorization; never use it for interactive chat runs.

Types

type ApprovalDetail added in v0.0.7

type ApprovalDetail struct {
	Label  string `json:"label,omitempty"`
	Value  string `json:"value"`
	Format string `json:"format,omitempty"`
	Tone   string `json:"tone,omitempty"`
}

ApprovalDetail is one trusted, server-resolved fact shown in an approval card. Format and Tone are deliberately small enums interpreted by the UI.

type ApprovalHandler added in v0.0.7

type ApprovalHandler func(context.Context, ApprovalRequest) (bool, error)

type ApprovalPresentation added in v0.0.7

type ApprovalPresentation struct {
	ConfirmLabel   string `json:"confirmLabel,omitempty"`
	ConfirmVariant string `json:"confirmVariant,omitempty"`
	PendingMessage string `json:"pendingMessage,omitempty"`
	SuccessMessage string `json:"successMessage,omitempty"`
	DeniedMessage  string `json:"deniedMessage,omitempty"`
	FailureMessage string `json:"failureMessage,omitempty"`
}

ApprovalPresentation lets a tool describe its approval action without the frontend knowing the tool name. Empty fields fall back to generic labels.

type ApprovalRequest added in v0.0.7

type ApprovalRequest struct {
	ToolCallID   string
	ToolName     string
	Title        string
	Summary      string
	Target       map[string]any
	Details      []ApprovalDetail
	Presentation ApprovalPresentation
}

ApprovalRequest describes a tool action that must be approved before the tool may execute it. Target is presentation-only metadata resolved by the server; it must never be used as the source of truth for the mutation.

type EmitFunc

type EmitFunc func(context.Context, StreamChunk) error

type FantasyRunner

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

func NewFantasyRunner

func NewFantasyRunner(toolFactory FantasyToolFactory) *FantasyRunner

func (*FantasyRunner) Stream

func (r *FantasyRunner) Stream(ctx context.Context, request Request, emit EmitFunc) (Result, error)

type FantasyToolFactory

type FantasyToolFactory func(scope ToolScope) []fantasy.AgentTool

FantasyRunner adapts Fantasy to the application's AI SDK UI compatible stream protocol. PocketBase and application-domain services stay outside this package and are supplied through an actor-scoped tool factory.

type Message

type Message struct {
	ID       string         `json:"id"`
	Role     string         `json:"role"`
	Metadata map[string]any `json:"metadata,omitempty"`
	Parts    []Part         `json:"parts"`
}

Message is the provider-neutral, AI SDK UI compatible message shape used by the chat package and persisted by the application.

type ModelConfig

type ModelConfig struct {
	ID               string
	Name             string
	ModelID          string
	BaseURL          string
	APIKey           string
	Protocol         string
	MaxOutputTokens  int
	MaxContextTokens int
}

type Part

type Part map[string]any

Part is a finalized UI message part. Keeping this as a JSON object lets the Go backend preserve AI SDK additions without coupling persistence to a provider-specific block model.

type Request

type Request struct {
	SystemPrompt   string
	Messages       []Message
	Model          ModelConfig
	ActorID        string
	ConversationID string
	UserMessageID  string
	Approval       ApprovalHandler
}

type Result

type Result struct {
	Usage        Usage
	FinishReason string
	StepCount    int
	// LastStepUsage is the usage of the final step only. Unlike Usage (which
	// sums input tokens across every step of a multi-step tool run), the last
	// step saw the complete prompt exactly once, so it reflects the current
	// context-window occupancy.
	LastStepUsage Usage
}

type Runner

type Runner interface {
	Stream(context.Context, Request, EmitFunc) (Result, error)
}

type StreamChunk

type StreamChunk struct {
	Type string `json:"type"`

	ID        string `json:"id,omitempty"`
	Delta     string `json:"delta,omitempty"`
	MessageID string `json:"messageId,omitempty"`

	ToolCallID       string `json:"toolCallId,omitempty"`
	ToolName         string `json:"toolName,omitempty"`
	ApprovalID       string `json:"approvalId,omitempty"`
	Approved         *bool  `json:"approved,omitempty"`
	InputTextDelta   string `json:"inputTextDelta,omitempty"`
	Input            any    `json:"input,omitempty"`
	Output           any    `json:"output,omitempty"`
	ErrorText        string `json:"errorText,omitempty"`
	Reason           string `json:"reason,omitempty"`
	Dynamic          bool   `json:"dynamic,omitempty"`
	ProviderExecuted bool   `json:"providerExecuted,omitempty"`

	SourceID  string `json:"sourceId,omitempty"`
	URL       string `json:"url,omitempty"`
	Title     string `json:"title,omitempty"`
	MediaType string `json:"mediaType,omitempty"`
	Filename  string `json:"filename,omitempty"`

	FinishReason     string         `json:"finishReason,omitempty"`
	MessageMetadata  map[string]any `json:"messageMetadata,omitempty"`
	ProviderMetadata map[string]any `json:"providerMetadata,omitempty"`

	Data any `json:"data,omitempty"`
}

StreamChunk mirrors the AI SDK UI Message Stream v1 JSON protocol. Only fields relevant to the current chat implementation are represented.

func (StreamChunk) MarshalJSON

func (c StreamChunk) MarshalJSON() ([]byte, error)

MarshalJSON guarantees that nil metadata is omitted while arbitrary input and output values remain regular JSON values.

func (StreamChunk) ValidForWire

func (c StreamChunk) ValidForWire() bool

ValidForWire reports whether the chunk satisfies the AI SDK UI Message Stream v1 required-field contract for its type. The AI SDK frontend parses the SSE stream with a strict Zod discriminated union: a single part missing a required field (e.g. a "reasoning-delta" without "delta") aborts the whole stream. Source libraries may emit empty/no-op deltas that, combined with the omitempty tags above, serialize to such invalid parts. This check is the single chokepoint that guarantees no structurally-invalid part ever reaches the browser, regardless of what the upstream library or callbacks produce.

Note: the persisted message (built by the reducer) is unaffected — the reducer sees every chunk and tolerates empty deltas — so dropping a chunk here only suppresses its (invalid) wire representation, never the saved state.

type ToolScope added in v0.0.8

type ToolScope struct {
	ActorID        string
	ConversationID string
	UserMessageID  string
}

type Usage

type Usage struct {
	InputTokens         int64 `json:"inputTokens"`
	OutputTokens        int64 `json:"outputTokens"`
	TotalTokens         int64 `json:"totalTokens"`
	ReasoningTokens     int64 `json:"reasoningTokens"`
	CacheCreationTokens int64 `json:"cacheCreationTokens"`
	CacheReadTokens     int64 `json:"cacheReadTokens"`
}

Jump to

Keyboard shortcuts

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