shared

package
v0.8.0 Latest Latest
Warning

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

Go to latest
Published: Oct 23, 2026 License: GPL-3.0 Imports: 48 Imported by: 0

Documentation

Index

Constants

View Source
const APrefix = "secai"
View Source
const (
	EnvNoDotEnv = "SECAI_NO_DOTENV"
)

Variables

View Source
var (
	FromAssistant = From{"assistant"}
	FromSystem    = From{"system"}
	FromUser      = From{"user"}
	FromNarrator  = From{"narrator"}

	FromEnum = enum.New(FromAssistant, FromSystem, FromUser)
)
View Source
var (
	ValEncJson = ValEnc{"json"}
	ValEncYaml = ValEnc{"yaml"}
	ValEncDump = ValEnc{"dump"}
	ValEncTxt  = ValEnc{"txt"}

	ValEncEnum = enum.New(ValEncJson, ValEncYaml, ValEncDump, ValEncTxt)
	ValEncs    = ValEncEnum
)
View Source
var (
	ValFileEncJson = ValEncJson
	ValFileEncYaml = ValEncYaml
	ValFileEncDump = ValEncDump
	ValFileEncTxt  = ValEncTxt

	ValFileEncEnum = ValEncEnum
	ValFileEncs    = ValEncs
)
View Source
var ErrAI = errors.New("AI error")

ErrAI is for states.AgentBaseStatesDef.ErrAI.

View Source
var ErrDB = errors.New("DB error")

ErrDB is for states.AgentBaseStatesDef.ErrDB.

View Source
var (
	ErrHistNil = errors.New("history is nil")
)

Functions

func AddErrAI added in v0.6.0

func AddErrAI(
	event *am.Event, mach *am.Machine, err error, args ...am.A,
) am.Result

AddErrAI adds ErrAI.

func AddErrDB added in v0.6.0

func AddErrDB(
	event *am.Event, mach *am.Machine, err error, args ...am.A,
) am.Result

AddErrDB adds ErrDB.

func BinaryPath added in v0.5.0

func BinaryPath(absolute bool) string

func GenerateAtomFeed added in v0.6.0

func GenerateAtomFeed(items []FeedItem, title string) string

func GetSQLiteSchema added in v0.5.0

func GetSQLiteSchema(db *sql.DB) (string, error)

TODO format "github.com/maxrichie5/go-sqlfmt/sqlfmt" config := sqlfmt.NewDefaultConfig() formatted := sqlfmt.Format(rawSQL, config)

func GetVersion added in v0.6.0

func GetVersion() string

func IsStory added in v0.8.0

func IsStory(state string) bool

func KdlFormat added in v0.6.0

func KdlFormat(input []byte, cfg any) string

KdlFormat parses a raw KDL string and returns it formatted with proper newlines, inherited indentation, and names resolved from the Config struct.

func MachTelemetry

func MachTelemetry(mach *am.Machine, logArgs am.LogArgsMapperFn)

func Map

func Map[A, B any](vals []A, f func(A) B) []B

Map maps vals through f and returns a list of returned values from f.

func NullString added in v0.8.0

func NullString(s string) sql.NullString

func NumRef added in v0.2.0

func NumRef(text string) int

NumRef returns a number reference from the passed text, or -1 if none found.

func OpenURL added in v0.5.0

func OpenURL(url string) error

OpenURL opens the specified URL in the default browser of the user. https://gist.github.com/sevkin/9798d67b2cb9d07cb05f89f14ba682f8

func OptArgs added in v0.5.0

func OptArgs(args []am.A) am.A

OptArgs will read the first A from an optional list.

func P

func P(txt string, args ...any)

P formats and prints the given string after de-denting and trimming it, and returns the number of bytes written and any error.

func PascalCase added in v0.2.0

func PascalCase(in string) string

PascalCase converts the input string to pascal case, matching the naming convention of state names.

func RemoveStyling added in v0.2.0

func RemoveStyling(str string) string

func RevertPascalCase added in v0.2.0

func RevertPascalCase(in string) string

func Sj

func Sj(parts ...string) string

Sj is a string join and will join passed string args with a space.

func Sl

func Sl(txt string, args ...any) string

Sl is a string line - expands txt with args and ends with a newline.

func SlicesWithout added in v0.2.0

func SlicesWithout[S ~[]E, E comparable](coll S, el E) S

func Sp

func Sp(txt string, args ...any) string

Sp formats a de-dented and trimmed string using the provided arguments, similar to fmt.Sprintf.

func TextCut added in v0.6.0

func TextCut(txt string, maxLen int) string

Types

type ABaseDBSaving added in v0.6.0

type ABaseDBSaving struct {
	Args
	// DBQuery is a function that executes a query on the database.
	DBQuery func(ctx context.Context) error
}

func (ABaseDBSaving) ArgsState added in v0.6.0

func (ABaseDBSaving) ArgsState() string

type ACheckingMenuRefs added in v0.6.0

type ACheckingMenuRefs struct {
	Args
	// RetStr returns dereferenced user prompts based on the list of offer.
	RetOfferRef chan<- *OfferRef
	// Perform additional checks via LLM
	CheckLLM bool `log:"check_llm"`
	// Prompt is a prompt to be checked.
	Prompt string `log:"prompt"`
	// List of choices (optional)
	Choices []string
}

func (ACheckingMenuRefs) ArgsState added in v0.6.0

func (ACheckingMenuRefs) ArgsState() string

type AConfigUpdate added in v0.6.0

type AConfigUpdate struct {
	Args
	ConfigAI *ConfigAI
}

func (AConfigUpdate) ArgsState added in v0.6.0

func (AConfigUpdate) ArgsState() string

type AIClient added in v0.6.0

type AIClient struct {
	OpenAI *OpenAIClient
	Gemini *GeminiClient
}

AIClient is the picked AI client from the pool (from either provider).

func (*AIClient) Cfg added in v0.6.0

func (c *AIClient) Cfg() *ConfigAICommon

func (*AIClient) Model added in v0.8.0

func (c *AIClient) Model() string

func (*AIClient) Provider added in v0.8.0

func (c *AIClient) Provider() string

type AInterrupted added in v0.6.0

type AInterrupted struct {
	Args
	IntByTimeout bool `log:"int_by_timeout"`
}

func (AInterrupted) ArgsState added in v0.6.0

func (AInterrupted) ArgsState() string

type APrompt added in v0.6.0

type APrompt struct {
	Args
	// Prompt is a prompt to be sent to LLM.
	Prompt string `log:"prompt"`
}

func (APrompt) ArgsState added in v0.6.0

func (APrompt) ArgsState() string

type ARequestingAI added in v0.8.0

type ARequestingAI struct {
	Args
	Length string `log:"length"`
	Source string `log:"source"`
}

func (ARequestingAI) State added in v0.8.0

func (ARequestingAI) State() string

type ARequestingTool added in v0.8.0

type ARequestingTool struct {
	Args
	Name   string `log:"name"`
	Source string `log:"source"`
	Target string `log:"target"`
}

func (ARequestingTool) State added in v0.8.0

func (ARequestingTool) State() string

type ASSHConn added in v0.6.0

type ASSHConn struct {
	Args
	SSHSess ssh.Session
	// Done is a buffered channel to be closed by the receiver
	Done chan<- struct{}
}

func (ASSHConn) ArgsState added in v0.6.0

func (ASSHConn) ArgsState() string

type ASSHDisconn added in v0.6.0

type ASSHDisconn struct {
	Args
	Addr string `log:"addr"`
	// Id of the disconnected TUI.
	Id string `log:"id"`
}

func (ASSHDisconn) ArgsState added in v0.6.0

func (ASSHDisconn) ArgsState() string

type ASSHReady added in v0.6.0

type ASSHReady struct {
	Args
	SSHServer *ssh.Server
}

func (ASSHReady) ArgsState added in v0.6.0

func (ASSHReady) ArgsState() string

type AStoryAction added in v0.6.0

type AStoryAction struct {
	Args
	// ID of the action.
	ID string `log:"id"`
}

func (AStoryAction) ArgsState added in v0.6.0

func (AStoryAction) ArgsState() string

type AStoryChanged added in v0.6.0

type AStoryChanged struct {
	Args
	StatesList   []string `log:"states_list"`
	ActivateList []bool   `log:"activate_list"`
}

func (AStoryChanged) ArgsState added in v0.6.0

func (AStoryChanged) ArgsState() string

type AUIMsg added in v0.6.0

type AUIMsg struct {
	Args
	// Msg is a single message with an author and text.
	Msg *Msg `log:"msg"`
}

func (AUIMsg) ArgsState added in v0.6.0

func (AUIMsg) ArgsState() string

type AUIRenderClock added in v0.6.0

type AUIRenderClock struct {
	Args
	ClockDiff [][]int
}

func (AUIRenderClock) ArgsState added in v0.6.0

func (AUIRenderClock) ArgsState() string

type AUIRenderStories added in v0.6.0

type AUIRenderStories struct {
	Args
	Actions []ActionInfo `log:"actions"`
	Stories []StoryInfo  `log:"stories"`
}

func (AUIRenderStories) ArgsState added in v0.6.0

func (AUIRenderStories) ArgsState() string

type Action added in v0.5.0

type Action struct {
	// random ID
	ID string

	// Current value.
	Value func() int
	// Maximum value.
	ValueEnd func() int

	Label  string
	Desc   string
	Action func()

	StateAdd    string
	StateRemove string

	VisibleAgent amhelp.Cond
	VisibleMem   amhelp.Cond
	IsDisabled   func() bool
	LabelEnd     string

	Pos         int
	PosInferred bool
}

func (Action) String added in v0.5.0

func (s Action) String() string

type ActionInfo added in v0.5.0

type ActionInfo struct {
	// random ID
	ID string

	// Current value.
	Value int
	// Maximum value.
	ValueEnd int

	Label  string
	Desc   string
	Action bool

	StateAdd    string
	StateRemove string

	VisibleAgent bool
	VisibleMem   bool
	IsDisabled   bool
	LabelEnd     string

	Pos         int
	PosInferred bool
}

ActionInfo is a static model for Action.

type AgentAPI added in v0.5.0

type AgentAPI interface {
	AgentBaseAPI

	Msgs() []*Msg
	Splash() string
	MachSchema() (am.Schema, am.S)
	Actions() []ActionInfo
	Stories() []StoryInfo
	Story(state string) *Story
	DBAgent() *sql.DB
	MachMem() *am.Machine
	// Moves return a list of moves and their descriptions for orienting.
	OrientingMoves() map[string]string
	// HistoryStates returns a list of states to track in the history.
	HistoryStates() am.S
}

AgentAPI is the top-level API to be implemented by the final agent.

type AgentBaseAPI added in v0.5.0

type AgentBaseAPI interface {
	// AgentImpl returns the top-level agent implementation.
	AgentImpl() AgentAPI
	// Output outputs text to the user.
	Output(txt string, from From) am.Result

	Mach() *am.Machine
	DBG() *debugger.Debugger
	Hist() (history.MemoryApi, error)

	SetConfigBase(*Config) error
	ConfigBase() *Config
	AIs() []*AIClient

	Start() am.Result
	Stop(disposeCtx context.Context)
	Log(msg string, args ...any)
	LogTrace(msg string, args ...any)
	LogDebug(msg string, args ...any)
	LogWarn(msg string, err error, args ...any)
	LogErr(msg string, err error, args ...any)

	LogCtx(ctx context.Context, txt string, args ...any)
	LogCtxDebug(ctx context.Context, txt string, args ...any)
	LogCtxTrace(ctx context.Context, txt string, args ...any)
	LogCtxWarn(ctx context.Context, txt string, err error, args ...any)
	LogCtxErr(ctx context.Context, msg string, err error, args ...any)

	LogEv(e *am.Event, txt string, args ...any)
	LogEvDebug(e *am.Event, txt string, args ...any)
	LogEvTrace(e *am.Event, txt string, args ...any)
	LogEvWarn(e *am.Event, txt string, err error, args ...any)
	LogEvErr(e *am.Event, msg string, err error, args ...any)

	Logger() *slog.Logger
	Store() *AgentStore

	QueriesBase() *sqlc.Queries

	DBBase() *sql.DB
	DBHistory() *sql.DB
}

AgentBaseAPI is the base agent API implemented by the framework.

type AgentInit added in v0.5.0

type AgentInit interface {
	Init(
		agentImpl AgentAPI, cfg *Config, logArgs am.LogArgsMapperFn, groups any, states am.States, args []am.ArgsApi,
	) error
}

AgentInit is an init func for embeddable agent structs (non-top level ones).

type AgentQueries added in v0.5.0

type AgentQueries[TQueries any] interface {
	Queries() *TQueries
}

AgentQueries is a generic SQL API.

type AgentStore added in v0.5.0

type AgentStore struct {
	M         map[string]any
	ClockDiff [][]int
	Web       fs.FS
}

type Args added in v0.6.0

type Args struct {
	am.ArgsBase
}

func (Args) ArgsPrefix added in v0.6.0

func (Args) ArgsPrefix() string

type Config added in v0.4.0

type Config struct {
	AI    ConfigAI
	Agent ConfigAgent
	Web   ConfigWeb
	TUI   ConfigTUI
	Tools ConfigTools
	Debug ConfigDebug

	// File is the path to the loaded config file.
	File      string `kdl:"-"`
	ProdBuild bool   `kdl:"-"`
	// ServerMode doesnt autorun the GUI and listens on 0.0.0.0
	ServerMode bool `kdl:"-"`
	DockerMode bool `kdl:"-"`
	// random instance ID
	SessionID string `kdl:"-"`
}

func ConfigDefault added in v0.4.0

func ConfigDefault() Config

ConfigDefault produces a default config with ports in the range 12800-12900.

func (Config) Clone added in v0.8.0

func (c Config) Clone() Config

func (Config) DotEnv added in v0.5.0

func (c Config) DotEnv() string

type ConfigAI added in v0.4.0

type ConfigAI struct {
	OpenAI []ConfigAIOpenAI `kdl:"OpenAI,multiple"`
	Gemini []ConfigAIGemini `kdl:"Gemini,multiple"`
	// Max LLM requests per session.
	ReqLimit int
}

type ConfigAICommon added in v0.6.0

type ConfigAICommon struct {
	Model    string
	Key      string
	Disabled bool

	Name string `kdl:",omitempty"`
	// Def: 3
	Retries  int      `kdl:",omitempty"`
	Tags     []string `kdl:",omitempty"`
	Priority int      `kdl:",omitempty"`
	// For how long blacklist this provider on error (def 1h).
	FallbackTimeout time.Duration `kdl:",omitempty"`
	// Number of concurrent req for this provider TODO
	Concurrency int    `kdl:",omitempty"`
	URL         string `kdl:",omitempty"`

	// temporarily disabled (eg offline)
	DisabledUntil time.Time `kdl:"-"`
	// provider name
	API string `kdl:"-"`
	// num of times this backend was called without errs
	Calls int `kdl:"-"`
}

ConfigAICommon are shared fields across all AI providers.

func (*ConfigAICommon) IsEnabled added in v0.6.0

func (c *ConfigAICommon) IsEnabled() bool

type ConfigAIGemini added in v0.4.0

type ConfigAIGemini struct {
	ConfigAICommon

	// NoEnforceSchema skips `instr.WithMode(instr.ModeJSONSchema)` for local models
	NoEnforceSchema bool
}

func ConfigDefaultAIGemini added in v0.6.0

func ConfigDefaultAIGemini() ConfigAIGemini

type ConfigAIOpenAI added in v0.4.0

type ConfigAIOpenAI struct {
	ConfigAICommon

	// NoEnforceSchema skips `instr.WithMode(instr.ModeJSONSchema)` for local models
	NoEnforceSchema bool
}

func ConfigDefaultAIOpenAI added in v0.6.0

func ConfigDefaultAIOpenAI() ConfigAIOpenAI

type ConfigAgent added in v0.4.0

type ConfigAgent struct {
	// bot ID
	ID    string
	Label string
	// // dir for tmp files, defaults to CWD
	Dir       string
	Intro     string
	IntroDash string
	Footer    string
	Log       ConfigAgentLog
	History   ConfigAgentHistory
}

func (*ConfigAgent) DirPath added in v0.6.0

func (c *ConfigAgent) DirPath() string

DirPath returns an absolute path to the agent's data directory.

func (*ConfigAgent) LogPath added in v0.6.0

func (c *ConfigAgent) LogPath(absolute bool) string

type ConfigAgentHistory added in v0.4.0

type ConfigAgentHistory struct {
	Backend string
	// TODO BackendParsed enum
	Max int
}

type ConfigAgentLog added in v0.4.0

type ConfigAgentLog struct {
	// path to the log file
	File string
	// log prompts as log level debug
	Prompts bool
	// mark log errs as ErrLog multi state
	FwdErrState bool
	// mark log warning as WarnLog multi state
	FwdWarnState bool
	// mach log level 0-5
	MachLevel am.LogLevel
	// print machine log
	MachPrint bool
	// agent log level
	Level slog.Level
	// enable instructor-go logging for AI requests
	AI bool
}

type ConfigDebug added in v0.4.0

type ConfigDebug struct {
	Root *Config `kdl:"-" json:"-"`

	// Display extra info about these stories in the machine log
	Story []string
	// Run the mock scenario
	Mock bool
	// Start pprof on addr
	ProfilerAddr string
	// Enable misc debugging modes (am-relay, browser RPC, TRACE logs)
	Verbose bool
	// Enable SQL query logging
	VerboseSQL bool
	// Create value files for inspection
	ValFiles bool
	// Enable REPL for agent, mem, and tools
	REPL bool
	// Connect and send dbg info to am-dbg
	DBGAddr string

	// Start an embedded debugger on localhost:{DBGAddr}
	DBGEmbed bool
	// Expose the embedded debugger on http://localhost:{DBGEmbedWeb}
	DBGEmbedWeb int
	// Start a web REPL on http://localhost:{REPLWeb}
	REPLWeb int
}

func (*ConfigDebug) DbgAddrListen added in v0.8.0

func (c *ConfigDebug) DbgAddrListen() (dbgAddr string, err error)

func (*ConfigDebug) DbgAddrs added in v0.6.0

func (c *ConfigDebug) DbgAddrs() (dbgAddr, httpAddr, sshAddr string, err error)

TODO keep in sync with debugger.Params

type ConfigSearXNG added in v0.4.0

type ConfigSearXNG struct {
	// Port to start a local instance on
	Port string
	// URL of an existing instance (disables Port).
	URL string
}

type ConfigTUI added in v0.4.0

type ConfigTUI struct {
	Root *Config `kdl:"-" json:"-"`

	// TODO Addr
	// TODO WebAddr
	// SSH host
	Host string
	// SSH port
	PortSSH int
	// Web host
	WebHost string
	// Web port
	PortWeb int
	// Number of transitions to show on the clock
	ClockRange int
}

type ConfigTools added in v0.4.0

type ConfigTools struct {
	SearXNG ConfigSearXNG
}

type ConfigWeb added in v0.5.0

type ConfigWeb struct {
	Root *Config `kdl:"-" json:"-"`

	// Base address for HTTP services:
	// - main HTTP server
	// - +1 WebSocket addr of the agent's RPC server (dashboard)
	// - +2 WebSocket addr of the agent's RPC server (agent UI)
	Addr string
	// Start a DBPort web UI on http://localhost:{DBPort[0-2]}
	DBPort int
	// Start a log web UI on http://localhost:{LogPort}
	LogPort int
}

func (*ConfigWeb) AddrAgent added in v0.6.0

func (c *ConfigWeb) AddrAgent() string

func (*ConfigWeb) AddrListen added in v0.8.0

func (c *ConfigWeb) AddrListen() string

func (*ConfigWeb) AgentURL added in v0.5.0

func (c *ConfigWeb) AgentURL() string

func (*ConfigWeb) ConfigWebLogAddr added in v0.6.0

func (c *ConfigWeb) ConfigWebLogAddr() string

func (*ConfigWeb) DBAddrs added in v0.6.0

func (c *ConfigWeb) DBAddrs() (base, agent, mach string)

func (*ConfigWeb) DBAddrsListen added in v0.8.0

func (c *ConfigWeb) DBAddrsListen() (base, agent, mach string)

func (*ConfigWeb) DashURL added in v0.5.0

func (c *ConfigWeb) DashURL() string

func (*ConfigWeb) REPLAddrAgentUI added in v0.5.0

func (c *ConfigWeb) REPLAddrAgentUI() string

func (*ConfigWeb) REPLAddrDash added in v0.5.0

func (c *ConfigWeb) REPLAddrDash() string

type Document added in v0.6.0

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

func NewDocument added in v0.6.0

func NewDocument(title string, content ...string) *Document

func (*Document) AddPart added in v0.6.0

func (d *Document) AddPart(parts ...string) *Document

func (*Document) AddToPrompts added in v0.6.0

func (d *Document) AddToPrompts(prompts ...PromptApi)

func (*Document) Clear added in v0.6.0

func (d *Document) Clear() *Document

func (*Document) Clone added in v0.6.0

func (d *Document) Clone() Document

func (*Document) Parts added in v0.6.0

func (d *Document) Parts() []string

func (*Document) Title added in v0.6.0

func (d *Document) Title() string

type FeedItem added in v0.6.0

type FeedItem struct {
	Title  string
	Author string
	Link   string
	Date   string
	Desc   string
}

type From

type From enum.Member[string]

type GeminiClient added in v0.5.0

type GeminiClient struct {
	Cfg *ConfigAIGemini
	C   *instructor.InstructorGoogle
}

type HasPromptUsage added in v0.8.0

type HasPromptUsage interface {
	GetPromptUsage() *PromptUsage
}

type MCPCallToolParams added in v0.8.0

type MCPCallToolParams struct {
	Name      string          `json:"name" jsonschema:"description=The name of the target MCP tool"`
	Arguments json.RawMessage `json:"arguments" jsonschema:"description=JSON object of arguments matching the tool schema"`
}

MCPCallToolParams represents the inner parameters of a tools/call request

type MCPCallToolRequest added in v0.8.0

type MCPCallToolRequest struct {
	JSONRPC string            `json:"jsonrpc" jsonschema:"const=2.0"`
	ID      int               `json:"id" jsonschema:"description=Request identifier"`
	Method  string            `json:"method" jsonschema:"const=tools/call"`
	Params  MCPCallToolParams `json:"params"`
}

MCPCallToolRequest enforces the exact JSON-RPC 2.0 MCP request structure

type Msg added in v0.2.0

type Msg struct {
	From      From
	Text      string
	CreatedAt time.Time
}

func NewMsg added in v0.2.0

func NewMsg(text string, from From) *Msg

func (*Msg) String added in v0.2.0

func (m *Msg) String() string

type OfferRef added in v0.2.0

type OfferRef struct {
	// Index from 0
	Index int
	Text  string
}

type OpenAIClient added in v0.5.0

type OpenAIClient struct {
	Cfg *ConfigAIOpenAI
	C   *instructor.InstructorOpenAI
}

type Prompt added in v0.6.0

type Prompt[P any, R any] struct {
	Conditions string
	Steps      string
	Result     string
	State      string
	A          AgentBaseAPI
	// number of previous messages to include (excluding system msg)
	HistoryMsgLen int
	// Msg holds msgs for this prompt and is used to build the Conversation instance (on-demand)
	Msgs      []*PromptMsg
	Thread    string
	Reasoning string
	LastModel string
	Godoc     map[string]string
	// contains filtered or unexported fields
}

func NewPrompt added in v0.6.0

func NewPrompt[P any, R any](agent AgentBaseAPI, state, condition, steps, results string) *Prompt[P, R]

func (*Prompt[P, R]) AddDoc added in v0.6.0

func (p *Prompt[P, R]) AddDoc(doc *Document)

AddDoc adds a document into the system prompt.

func (*Prompt[P, R]) AddGodoc added in v0.8.0

func (p *Prompt[P, R]) AddGodoc(godoc map[string]string) *Prompt[P, R]

AddGodoc adds entries to the godoc comment map for the prompt schema.

func (*Prompt[P, R]) AddTool added in v0.6.0

func (p *Prompt[P, R]) AddTool(tool ToolApi)

AddTool registers a SECAI TOOL which then exports it's documents into the system prompt. This is different from an AI tool.

func (*Prompt[P, R]) Concurrency added in v0.6.0

func (p *Prompt[P, R]) Concurrency() int

Concurrency returns the number of concurrent requests possible for this prompt, based on configured providers.

func (*Prompt[P, R]) Conversation added in v0.6.0

func (p *Prompt[P, R]) Conversation() (*core.Conversation, string)

Conversation will create a conversation with history and system prompt, return sys prompt on the side.

func (*Prompt[P, R]) Exec added in v0.6.0

func (p *Prompt[P, R]) Exec(e *am.Event, params P, cachedParams []*P, opts ...PromptOpts) (res *R, usage *PromptUsage, err error)

Exec sends the AI prompt to the AI provider and returns unmarshalled output. [cachedParams] are useful for caching common data between similar prompts. Unlike historical messages, cache prompts never triggered an AI response.

func (*Prompt[P, R]) ExecMulti added in v0.6.0

func (p *Prompt[P, R]) ExecMulti(
	e *am.Event, times int, params P, cachedParams []*P, opts ...PromptOpts,
) ([]*R, []*PromptUsage, error)

ExecMulti executes Prompt.Exec multiple times and returns all the results. Useful for scoring content.

func (*Prompt[P, R]) GenSysPrompt added in v0.6.0

func (p *Prompt[P, R]) GenSysPrompt() string

GenSysPrompt generates a system prompt.

func (*Prompt[P, R]) HistClean added in v0.6.0

func (p *Prompt[P, R]) HistClean()

func (*Prompt[P, R]) QueryProviders added in v0.8.0

func (p *Prompt[P, R]) QueryProviders(opts ...PromptOpts) []*AIClient

func (*Prompt[P, R]) SetGodoc added in v0.8.0

func (p *Prompt[P, R]) SetGodoc(godoc map[string]string) *Prompt[P, R]

SetGodoc sets the godoc comment map for the prompt schema.

type PromptApi added in v0.6.0

type PromptApi interface {
	AddTool(tool ToolApi)
	AddDoc(doc *Document)

	GenSysPrompt() string
	Conversation() (*core.Conversation, string)
	HistClean()
}

TODO incomplete?

type PromptConfig added in v0.8.0

type PromptConfig struct {
	ModelTag     string
	ModelSortTag string
	Reasoning    string
	MaxTries     int
	Concurrency  int
}

type PromptMsg added in v0.6.0

type PromptMsg struct {
	From    core.Role
	Content string
}

type PromptOpts added in v0.6.0

type PromptOpts struct {

	// required provider tags
	RequiredTags []string
	// disallowed provider tags
	NoTags []string
	// skip checking if state is active
	SkipState bool
	Reasoning string
}

type PromptRaw added in v0.8.0

type PromptRaw struct {
	Conditions string
	Steps      string
	Result     string
	// TODO use better schema pkg
	ResultSchema *oaischema.Definition
	State        string
	A            AgentBaseAPI
	// number of previous messages to include
	HistoryMsgLen int
	Msgs          []*PromptRawMsg
	// contains filtered or unexported fields
}

PromptRaw is a prompt that uses stock clients (openai.Client, genai.Client) instead of instructor-go for structured output parsing. Params are a raw string (typically JSON), and ResultSchema defines the expected JSON Schema for structured output enforcement. The raw JSON response is returned via Exec / ExecInto.

func NewPromptRaw added in v0.8.0

func NewPromptRaw(agent AgentBaseAPI, state, condition, steps, result string, resultEmpty any) (*PromptRaw, error)

func (*PromptRaw) AddDoc added in v0.8.0

func (p *PromptRaw) AddDoc(doc *Document)

AddDoc adds a document into the system prompt.

func (*PromptRaw) AddTool added in v0.8.0

func (p *PromptRaw) AddTool(tool ToolApi)

AddTool registers a SECAI TOOL which then exports its documents into the system prompt.

func (*PromptRaw) Concurrency added in v0.8.0

func (p *PromptRaw) Concurrency() int

Concurrency returns the number of concurrent requests possible for this prompt.

func (*PromptRaw) Conversation added in v0.8.0

func (p *PromptRaw) Conversation() (*core.Conversation, string)

Conversation will create a conversation with history and system prompt, return sys prompt on the side.

func (*PromptRaw) Exec added in v0.8.0

func (p *PromptRaw) Exec(e *am.Event, params string, opts ...PromptOpts) (res []byte, usage *PromptUsage, err error)

Exec sends params as a user message and returns the raw JSON response bytes.

func (*PromptRaw) ExecInto added in v0.8.0

func (p *PromptRaw) ExecInto(e *am.Event, params string, result any, opts ...PromptOpts) (*PromptUsage, error)

ExecInto calls Exec and unmarshals the raw JSON response into result.

func (*PromptRaw) ExecMulti added in v0.8.0

func (p *PromptRaw) ExecMulti(e *am.Event, times int, params string) ([][]byte, []*PromptUsage, error)

ExecMulti calls Exec multiple times and collects results as JSON byte slices.

func (*PromptRaw) GenSysPrompt added in v0.8.0

func (p *PromptRaw) GenSysPrompt() string

GenSysPrompt generates a system prompt.

func (*PromptRaw) HistClean added in v0.8.0

func (p *PromptRaw) HistClean()

HistClean clears the message history.

type PromptRawMsg added in v0.8.0

type PromptRawMsg struct {
	Role    PromptRawRole
	Content string
}

PromptRawMsg is a message in a PromptRaw conversation.

type PromptRawRole added in v0.8.0

type PromptRawRole string

PromptRawRole is a simple role type, replacing core.Role from instructor-go.

const (
	PromptRawRoleSystem    PromptRawRole = "system"
	PromptRawRoleUser      PromptRawRole = "user"
	PromptRawRoleAssistant PromptRawRole = "assistant"
)

type PromptSchemaless added in v0.6.0

type PromptSchemaless = Prompt[any, any]

type PromptUsage added in v0.8.0

type PromptUsage struct {
	Model              string
	API                string
	URL                string
	PromptTokens       int
	PromptTokensCached int
	CompletionTokens   int
	TotalTokens        int
	PromptChars        int
	HistoryChars       int
	Provider           string
}

func (*PromptUsage) Compute added in v0.8.0

func (p *PromptUsage) Compute()

type RawAIClient added in v0.8.0

type RawAIClient struct {
	OpenAI *RawOpenAIClient
	Gemini *RawGeminiClient
}

RawAIClient is the picked AI client from the pool for PromptRaw (stock clients).

func (*RawAIClient) Cfg added in v0.8.0

func (c *RawAIClient) Cfg() *ConfigAICommon

type RawGeminiClient added in v0.8.0

type RawGeminiClient struct {
	Cfg *ConfigAIGemini
	C   *genai.Client
}

RawGeminiClient wraps the stock Google GenAI client.

type RawOpenAIClient added in v0.8.0

type RawOpenAIClient struct {
	Cfg *ConfigAIOpenAI
	C   *openai.Client
}

RawOpenAIClient wraps the stock OpenAI client.

type SlogWriter added in v0.6.0

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

SlogWriter adapts an slog.Logger to the io.Writer interface.

func NewSlogWriter added in v0.6.0

func NewSlogWriter(logger *slog.Logger, level slog.Level) *SlogWriter

NewSlogWriter creates a new io.Writer that writes to the provided slog.Logger at the specified log level.

func (*SlogWriter) Write added in v0.6.0

func (w *SlogWriter) Write(p []byte) (n int, err error)

Write implements the io.Writer interface.

type Story added in v0.2.0

type Story struct {
	StoryInfo

	Agent  StoryActor
	Memory StoryActor

	// If is an optional function used to confirm that this story can activate. It has access to the whole story struct,
	// so all the involved state machines and their historical snapshots (relative to activation and deactivation of
	// this story).
	CanActivate func(instance *Story) bool
	Actions     []Action
}

Story is the basis for all stories.

func (*Story) Check added in v0.2.0

func (s *Story) Check() bool

func (*Story) New added in v0.5.0

func (s *Story) New(actions []Action) *Story

New returns a copy of the story with the actions bound. Used to create new instances.

func (*Story) String added in v0.2.0

func (s *Story) String() string

type StoryActionsByIdx added in v0.4.0

type StoryActionsByIdx []Action

func (StoryActionsByIdx) Len added in v0.4.0

func (s StoryActionsByIdx) Len() int

func (StoryActionsByIdx) Less added in v0.4.0

func (s StoryActionsByIdx) Less(i, j int) bool

func (StoryActionsByIdx) Swap added in v0.4.0

func (s StoryActionsByIdx) Swap(i, j int)

type StoryActor added in v0.2.0

type StoryActor struct {
	Mach *am.Machine

	// actor's time when the story activated
	TimeActivated   am.Time
	TimeDeactivated am.Time

	// When these conditions are met, the story will activate itself.
	Trigger amhelp.Cond
}

StoryActor is a binding between a Story and an actor (state machine).

type StoryInfo added in v0.2.0

type StoryInfo struct {
	// Name of the bound state (eg StoryFoo).
	State string
	// Tick is the current tick of the bound state.
	Tick uint64
	// Epoch is the sum of all previous memories, before a replacement.
	Epoch uint64

	// Title of this story.
	Title string
	// Description of this story.
	Desc string

	// The story was last deactivated at this human time.
	DeactivatedAt time.Time
	// The story was last active for this many ticks of the AgentLLM machine.
	LastActiveTicks uint64
}

StoryInfo is a static model for Story.

func (StoryInfo) String added in v0.2.0

func (s StoryInfo) String() string

type ToolApi added in v0.6.0

type ToolApi interface {
	Mach() *am.Machine
	SetMach(*am.Machine)
	Document() *Document
}

type ValEnc added in v0.8.0

type ValEnc enum.Member[string]

type ValFileEnc added in v0.8.0

type ValFileEnc = ValEnc

Jump to

Keyboard shortcuts

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