frags

package module
v1.0.0-rc6 Latest Latest
Warning

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

Go to latest
Published: Aug 27, 2026 License: AGPL-3.0 Imports: 33 Imported by: 0

README

Welcome to Frags

Note: The project is still in development, but you can already try it out.

What is Frags?

Frags is an advanced AI/LLM Agent dedicated to executing complex workflows of data retrieval, transformation, extraction and aggregation. It is designed to be highly customizable and extensible, allowing you to integrate it with your own tools and processes. Its main goal is precision and focus, and it's a system dedicated to engineers and specialists rather than a code-free quick fix.

Frags comes as a CLI tool and as a library to be integrated into Golang projects.

Main features
  • Multi LLM: Frags supports multiple LLMs, allowing you to choose the one that best suits your needs.
  • Dedicated almost exclusively to producing structured content: the purpose of Frags is to be integrated in advanced workflows, therefore its output needs to be perfectly predictable and consumable by a machine.
  • Orchestration system: Frags is not an agent to which you ask a question a simple answer back. The whole purpose of Frags is to allow the user to describe complex data retrieval, transformation, extraction and aggregation to produce complex data structures.
  • Advanced support for tools: Frags has a whole standardized system to integrate with internal (as in: provided by the integrator) and external tools (as in: MCP servers).
  • Anti-context-bloating: Frags multi-session system allows you to define and organize what is present in the LLM context, based on the session task, improving focus and reducing the risk of hallucinations
  • Output segmentation: Frags allows you to segment your output into multiple parts, allowing you to overcome output token limitations, and improving answer quality.
  • Advanced pre/post-processing: Frags allows you to define custom pre/post-processing steps, scripts, tools, and transformers, reducing the amount of LLM work where not necessary, reducing cost, improving performance and answer quality.
  • Modularity: Frags is designed to be easily extensible, allowing you to add new features and integrate them with your own tools.
Use cases
  • Research/Paper: when your needs go beyond getting a straight answer, but need a whole structured research on sophisticated topics. The context reduction, focus enhancement, document ingestion combined with internet search allows you to design how your paper should contain in each section, allowing the LLM to focus on each objective and produce data you can process however you want.
  • Data extraction: Frags allows you to define complex data extraction pipelines, allowing you to extract data from documents, making sure the output is structured and predictable. This makes it easy to plug into other systems that expect predefined fields and values.
  • Data transformation/analysis: From data retrieval (via the Internet, databases or any MCP tool available) to analysis or transformation, Frags can guide the process and provide solid data structures, skimming the context and increasing the credibility of the results.
  • Reporting: Connect Frags to data sources and define complex reporting templates that describe the entire status of a system, division or company. Connect the output to a reporting tool to produce quality reports.
  • Notes augmentation: give Frags your notes and design how you want the LLM to expand them into a fully featured document.
  • Chatbot augmentation: improve your chatbot from an "answers machine" to an "explanation engine."
  • Creative writing: Frags can be used to generate creative content, allowing you to design how your writing should look like, and how it should be structured.

Find the full documentation in the Frags Wiki

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type AdditionalHeadersTransport

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

AdditionalHeadersTransport is a wrapper around the default http.RoundTripper that adds default headers to every request

func (*AdditionalHeadersTransport) RoundTrip

func (t *AdditionalHeadersTransport) RoundTrip(req *http.Request) (*http.Response, error)

RoundTrip adds default headers to the request

type Ai

type Ai interface {
	Ask(ctx *util.FragsContext, text string, schema *schema.Schema, tools ToolDefinitions, runner ExportableRunner, resources ...resources.ResourceData) ([]byte, error)
	New() Ai
	SetFunctions(functions ExternalFunctions)
	RunFunction(ctx *util.FragsContext, functionCall FunctionCaller, runner ExportableRunner) (any, error)
	SetSystemPrompt(systemPrompt string)
}

Ai is an interface for AI models.

type CollectionConfig

type CollectionConfig struct {
	ToolType string            `json:"tool_type,omitempty" tui:"label=Tool Type,enum=fs|postgres|http,subtitle"`
	Params   map[string]string `json:"params,omitempty" tui:"label=Params"`
	Disabled bool              `json:"disabled" tui:"label=Disabled,!badge"`
}

CollectionConfig defines the configuration for a collection

type Components

type Components struct {
	Prompts map[string]string        `yaml:"prompts" json:"prompts,omitempty"`
	Schemas map[string]schema.Schema `yaml:"schemas" json:"schemas,omitempty"`
}

Components holds the reusable components of the sessions and schema

type ContextConfig

type ContextConfig struct {
	Bool   *bool
	String *string
}

func (*ContextConfig) HasTemplate

func (c *ContextConfig) HasTemplate() bool

func (*ContextConfig) IsTrue

func (c *ContextConfig) IsTrue() bool

func (*ContextConfig) MarshalJSON

func (c *ContextConfig) MarshalJSON() ([]byte, error)

func (*ContextConfig) MarshalYAML

func (c *ContextConfig) MarshalYAML() (interface{}, error)

func (*ContextConfig) RenderTemplate

func (c *ContextConfig) RenderTemplate(scope evaluators.EvalScope) (string, error)

func (*ContextConfig) UnmarshalJSON

func (c *ContextConfig) UnmarshalJSON(data []byte) error

func (*ContextConfig) UnmarshalYAML

func (c *ContextConfig) UnmarshalYAML(value *yaml.Node) error

type Dependencies

type Dependencies []Dependency

Dependencies is a list of Dependencies

type Dependency

type Dependency struct {
	Session    *string `json:"session" yaml:"session"`
	Expression *string `json:"expression" yaml:"expression"`
}

Dependency defines whether this session can run or should: * wait on another Session to complete * run at all, based on an Expression

type DependencyCheckResult

type DependencyCheckResult string

DependencyCheckResult is the result of a dependency check.

const (
	DependencyCheckPassed     DependencyCheckResult = "passed"
	DependencyCheckFailed     DependencyCheckResult = "failed"
	DependencyCheckUnsolvable DependencyCheckResult = "unsolvable"
)

type DummyAi

type DummyAi struct {
	History []dummyHistoryItem
}

DummyAi is a dummy AI model for testing purposes.

func NewDummyAi

func NewDummyAi() *DummyAi

NewDummyAi returns a new DummyAi instance.

func (*DummyAi) Ask

func (d *DummyAi) Ask(_ *util.FragsContext, text string, schema *schema.Schema, _ ToolDefinitions, _ ExportableRunner, resources ...resources.ResourceData) ([]byte, error)

Ask returns a dummy response for testing purposes.

func (*DummyAi) New

func (d *DummyAi) New() Ai

func (*DummyAi) RunFunction

func (d *DummyAi) RunFunction(_ *util.FragsContext, _ FunctionCaller, _ ExportableRunner) (any, error)

func (*DummyAi) SetFunctions

func (d *DummyAi) SetFunctions(_ ExternalFunctions)

func (*DummyAi) SetSystemPrompt

func (d *DummyAi) SetSystemPrompt(_ string)

type DummyScriptEngine

type DummyScriptEngine struct{}

func (*DummyScriptEngine) RunCode

type ExportableRunner

type ExportableRunner interface {
	Transformers() *Transformers
	RunFunction(ctx *util.FragsContext, name string, args map[string]any) (any, error)
	ScriptEngine() ScriptEngine
	Logger() *log.StreamerLogger
}

type ExternalFunction

type ExternalFunction struct {
	Func         func(ctx *util.FragsContext, data map[string]any) (any, error) `yaml:"-"`
	Name         string                                                         `yaml:"name"`
	Collection   string                                                         `yaml:"collection"`
	Description  string                                                         `yaml:"description"`
	Schema       *schema.Schema                                                 `yaml:"schema"`
	OutputSchema *schema.Schema                                                 `yaml:"outputSchema"`
}

ExternalFunction represents a function that can be called by the AI model. Name is the function name. ToolsCollection is the MCP server or collection that contains the function. Description is the function description Schema is the input schema for the function.

func (ExternalFunction) Run

func (f ExternalFunction) Run(ctx *util.FragsContext, args map[string]any, runner ExportableRunner) (any, error)

Run runs the function, applying any transformers defined in the runner.

func (ExternalFunction) String

func (f ExternalFunction) String() string

type ExternalFunctions

type ExternalFunctions map[string]ExternalFunction

ExternalFunctions is a map of functions, indexed by name.

func (ExternalFunctions) Get

Get returns a function by name.

func (ExternalFunctions) ListByCollection

func (f ExternalFunctions) ListByCollection(collection string) ExternalFunctions

ListByCollection returns a subset of functions, filtered by MCP server or collection

func (ExternalFunctions) String

func (f ExternalFunctions) String() string

func (ExternalFunctions) WithFunctions

func (f ExternalFunctions) WithFunctions(functions ExternalFunctions) ExternalFunctions

type FunctionCallDestination

type FunctionCallDestination string
const (
	AiFunctionCallDestination      FunctionCallDestination = "ai"
	VarsFunctionCallDestination    FunctionCallDestination = "vars"
	ContextFunctionCallDestination FunctionCallDestination = "context"
	DbFunctionCallDestination      FunctionCallDestination = "db"
)

type FunctionCaller

type FunctionCaller struct {
	Name        string                     `yaml:"name" json:"name"`
	Code        *string                    `yaml:"code" json:"code"`
	Args        map[string]any             `yaml:"args" json:"args"`
	Description *string                    `yaml:"description" json:"description"`
	In          *FunctionCallDestination   `yaml:"in" json:"in" validate:"omitempty,oneof=ai vars context"`
	Var         *string                    `yaml:"var" json:"var"`
	Func        FunctionCallerCallbackFunc `yaml:"-" json:"-"`
}

FunctionCaller Represents a function invocation. NOTE: description is meant to explain to LLM what the output data is about when the function is called by an entity that's not the LLM itself. IMPORTANT: if Code is not nil, this will trigger the execution of the scripting engine. If the engine is nil, nothing will happen.

type FunctionCallerCallbackFunc

type FunctionCallerCallbackFunc func(ctx *util.FragsContext, data map[string]any) (any, error)

type FunctionCallers

type FunctionCallers []FunctionCaller

type McpServerConfig

type McpServerConfig struct {
	Command          string            `json:"command,omitempty" tui:"label=Command,subtitle"`
	Args             []string          `json:"args,omitempty" tui:"label=Args"`
	Env              map[string]string `json:"env,omitempty" tui:"label=Env"`
	Cwd              string            `json:"cwd,omitempty" tui:"label=Cwd"`
	Transport        string            `json:"transport,omitempty" tui:"label=Transport"`
	Url              string            `json:"url,omitempty" tui:"label=URL,subtitle"`
	Headers          map[string]string `json:"headers,omitempty" tui:"label=Headers"`
	Disabled         bool              `json:"disabled" tui:"label=Disabled,!badge"`
	ClientID         *string           `json:"client_id,omitempty" tui:"label=Client ID"`
	ClientSecret     *string           `json:"client_secret,omitempty" tui:"label=Client Secret"`
	AuthorizationURL *string           `json:"authorization_url,omitempty" tui:"label=Authorization URL"`
	TokenURL         *string           `json:"token_url,omitempty" tui:"label=Token URL"`
	Token            *string           `json:"token,omitempty" tui:"label=Token"`
	// Placeholders for future functionalities and integrations
	PreAuthorizedOauth  *mcpauth.TokenResult `json:"pre_authorized_oauth,omitempty" tui:"label=Pre-Authorized OAuth"`
	AuthorizationMethod *string              `json:"authorization_method,omitempty" tui:"label=Authorization Method"`
}

McpServerConfig defines the configuration to connect to a MCP server

func (*McpServerConfig) HttpHeaders

func (m *McpServerConfig) HttpHeaders() http.Header

type McpServerConfigs

type McpServerConfigs map[string]McpServerConfig

McpServerConfigs is a map of MCP servers

func (McpServerConfigs) AsToolDefinitions

func (m McpServerConfigs) AsToolDefinitions() ToolDefinitions

AsToolDefinitions returns the MCP server configs as tool definitions

func (McpServerConfigs) McpTools

func (m McpServerConfigs) McpTools() McpTools

McpTools returns McpTool instances for each server configuration

type McpTool

type McpTool struct {
	Name string
	// contains filtered or unexported fields
}

McpTool is a wrapper around the MCP client

func NewMcpTool

func NewMcpTool(name string, serverConfig McpServerConfig) *McpTool

NewMcpTool creates a new MCP client wrapper

func (*McpTool) AsFunctions

func (c *McpTool) AsFunctions(ctx context.Context) (ExternalFunctions, error)

AsFunctions returns the tools as functions

func (*McpTool) Close

func (c *McpTool) Close() error

Close closes the connection to the server

func (*McpTool) Connect

func (c *McpTool) Connect(ctx context.Context, logger *log.StreamerLogger) error

Connect connects to the MCP server

func (*McpTool) ConnectSSE

func (c *McpTool) ConnectSSE(ctx context.Context, logger *log.StreamerLogger) error

ConnectSSE connects to the MCP server using an SSE transport

func (*McpTool) ConnectStd

func (c *McpTool) ConnectStd(ctx context.Context, _ *log.StreamerLogger) error

ConnectStd connects to the MCP server using a std/stdout transport

func (*McpTool) ConnectStreamableHttp

func (c *McpTool) ConnectStreamableHttp(ctx context.Context, logger *log.StreamerLogger) error

ConnectStreamableHttp connects to the MCP server using a Streamable HTTP transport, which is now the default. In case of failure, it falls back to SSE transport

func (*McpTool) ListTools

func (c *McpTool) ListTools(ctx context.Context) (ToolDefinitions, error)

ListTools lists the tools available on the server

func (*McpTool) Run

func (c *McpTool) Run(ctx *util.FragsContext, name string, arguments any) (any, error)

Run runs a tool on the server

func (*McpTool) WithOAuthProvider

func (c *McpTool) WithOAuthProvider(oauthProvider mcpauth.GenericOauthProvider) *McpTool

type McpTools

type McpTools []*McpTool

func (McpTools) AsFunctions

func (m McpTools) AsFunctions(ctx context.Context) (ExternalFunctions, error)

AsFunctions returns all the tools as functions

func (McpTools) Close

func (m McpTools) Close() error

Close closes all the connections

func (McpTools) Connect

func (m McpTools) Connect(ctx context.Context, logger *log.StreamerLogger) error

Connect connects to all the servers

func (McpTools) WithOAuthProvider

func (m McpTools) WithOAuthProvider(oauthProvider mcpauth.GenericOauthProvider) McpTools

type Parameter

type Parameter struct {
	Name   string         `yaml:"name" json:"name"`
	Schema *schema.Schema `yaml:"schema" json:"schema"`
}

type Parameters

type Parameters []Parameter

type ParametersConfig

type ParametersConfig struct {
	Parameters
	LooseType bool
}

ParametersConfig holds a list of Parameters and a flag to allow loose type checking. We're using this to allow less accurate input mechanisms (like a CLI) to input everything as strings, and still validate it against the schema.

func (*ParametersConfig) MarshalJSON

func (p *ParametersConfig) MarshalJSON() ([]byte, error)

func (*ParametersConfig) MarshalYAML

func (p *ParametersConfig) MarshalYAML() (interface{}, error)

func (*ParametersConfig) SetLooseType

func (p *ParametersConfig) SetLooseType(looseType bool)

SetLooseType sets the type check to "loose". It means that whenever the validator finds a string in a parameter, it will investigate whether the string represents the expected type

func (*ParametersConfig) UnmarshalJSON

func (p *ParametersConfig) UnmarshalJSON(data []byte) error

UnmarshalJSON allows unmarshaling a Parameters slice directly into ParametersConfig

func (*ParametersConfig) UnmarshalYAML

func (p *ParametersConfig) UnmarshalYAML(node *yaml.Node) error

func (*ParametersConfig) Validate

func (p *ParametersConfig) Validate(data any) error

type Parser

type Parser string
const (
	JsonParser Parser = "json"
	CsvParser  Parser = "csv"
)

type PrePrompt

type PrePrompt []string

func (*PrePrompt) UnmarshalYAML

func (p *PrePrompt) UnmarshalYAML(unmarshal func(interface{}) error) error

type RequiredTool

type RequiredTool struct {
	Name string   `json:"name" yaml:"name" validate:"required,min=1"`
	Type ToolType `json:"type" yaml:"type" validate:"required,min=1"`
}

RequiredTool allows the plan writer to define what tools are certainly required, and allow for the runner to check requirements and possibly fail if the requirements are not met

type RequiredTools

type RequiredTools []RequiredTool

RequiredTools is a collection of RequiredTool

func (RequiredTools) Check

func (r RequiredTools) Check(toolDefinitions ToolDefinitions) error

Check verifies whether the RequiredTools are present in the toolDefinitions. An error will be returned if a tool is missing. However, if toolDefinitions is nil, this function will pass and return no error.

type Resource

type Resource struct {
	Identifier  string                         `json:"identifier" yaml:"identifier" validate:"required,min=1"`
	Description string                         `json:"description" yaml:"description"`
	Params      map[string]string              `json:"params" yaml:"params"`
	In          *resources.ResourceDestination `json:"in" yaml:"in" validate:"omitempty,oneof=ai vars prePrompt prompt"`
	Var         *string                        `json:"var" yaml:"var"`
}

Resource defines a resource to load, with an identifier and a map of parameters

type Runner

type Runner struct {
	ExternalFunctions ExternalFunctions
	ToolsDefinitions  ToolDefinitions
	// contains filtered or unexported fields
}

Runner is a struct that runs a session manager.

func NewRunner

func NewRunner(sessionManager SessionManager, resourceLoader resources.ResourceLoader, ai Ai, options ...RunnerOption) Runner

NewRunner creates a new runner.

func (*Runner) CheckDependencies

func (r *Runner) CheckDependencies(dependencies Dependencies) (DependencyCheckResult, error)

CheckDependencies checks whether a session can start, cannot start yet, or will never start

func (*Runner) DB

func (r *Runner) DB() *zealql.Database

func (*Runner) IsCompleted

func (r *Runner) IsCompleted() bool

IsCompleted returns true if all sessions are completed

func (*Runner) ListFailedSessions

func (r *Runner) ListFailedSessions() []string

func (*Runner) ListQueued

func (r *Runner) ListQueued() Sessions

ListQueued returns a list of queued sessions

func (*Runner) Logger

func (r *Runner) Logger() *log.StreamerLogger

func (*Runner) Run

func (r *Runner) Run(ctx *util.FragsContext, params any) (util.ProgMap, error)

Run runs the runner against an optional collection fo parameters

func (*Runner) RunAllFunctionCallers

func (r *Runner) RunAllFunctionCallers(ctx *util.FragsContext, fc FunctionCallers, inputScope evaluators.EvalScope, outputVars evaluators.Vars) (*scoper.KnowledgeNode, error)

RunAllFunctionCallers runs all the function calls in the given collection.

func (*Runner) RunFunction

func (r *Runner) RunFunction(ctx *util.FragsContext, name string, args map[string]any) (any, error)

func (*Runner) ScriptEngine

func (r *Runner) ScriptEngine() ScriptEngine

func (*Runner) SetStatus

func (r *Runner) SetStatus(sessionID string, status SessionStatus)

SetStatus sets the status of a session (thread-safe)

func (*Runner) Transformers

func (r *Runner) Transformers() *Transformers

type RunnerOption

type RunnerOption func(*RunnerOptions)

RunnerOption is an option for the runner.

func WithExternalFunctions

func WithExternalFunctions(externalFunctions ExternalFunctions) RunnerOption

func WithInternalDatabase

func WithInternalDatabase(db *zealql.Database) RunnerOption

func WithLogger

func WithLogger(logger *log.StreamerLogger) RunnerOption

WithLogger sets the logger for the runner.

func WithScriptEngine

func WithScriptEngine(scriptEngine ScriptEngine) RunnerOption

func WithSessionWorkers

func WithSessionWorkers(sessionWorkers int) RunnerOption

WithSessionWorkers sets the number of workers for the runner.

func WithToolsDefinitions

func WithToolsDefinitions(toolsDefinitions ToolDefinitions) RunnerOption

type RunnerOptions

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

RunnerOptions are options for the runner.

type SafeMap

type SafeMap[K comparable, V any] struct {
	// contains filtered or unexported fields
}

func NewSafeMap

func NewSafeMap[K comparable, V any]() *SafeMap[K, V]

func (*SafeMap[K, V]) Iter

func (sm *SafeMap[K, V]) Iter() map[K]V

func (*SafeMap[K, V]) Load

func (sm *SafeMap[K, V]) Load(key K) (V, bool)

func (*SafeMap[K, V]) Store

func (sm *SafeMap[K, V]) Store(key K, value V)

Store is strongly typed: K and V are enforced at compile time.

type ScriptEngine

type ScriptEngine interface {
	RunCode(ctx *util.FragsContext, code string, params any, runner ExportableRunner) (any, error)
}

ScriptEngine is the interface that wraps the RunCode method. Frags provides NO script engines, it's the program that includes Frags that provides one, if necessary. Beware though, most script engines pose a security risk.

type Session

type Session struct {
	PreCalls  FunctionCallers `json:"preCalls,omitempty" yaml:"preCalls" validate:"omitempty,dive"`
	PrePrompt PrePrompt       `json:"prePrompt,omitempty" yaml:"prePrompt,omitempty"`
	Prompt    string          `json:"prompt,omitempty" yaml:"prompt,omitempty" validate:"omitempty,min=3"`
	Resources []Resource      `json:"resources,omitempty" yaml:"resources,omitempty" validate:"dive"`
	Timeout   *string         `json:"timeout,omitempty" yaml:"timeout,omitempty"`
	DependsOn Dependencies    `json:"dependsOn,omitempty" yaml:"dependsOn,omitempty"`
	Context   *ContextConfig  `json:"context" yaml:"context"`
	Attempts  int             `json:"attempts,omitempty" yaml:"attempts,omitempty"`
	Tools     ToolDefinitions `json:"tools,omitempty" yaml:"tools,omitempty"`
	IterateOn *string         `json:"iterateOn,omitempty" yaml:"iterateOn,omitempty"`
	Vars      map[string]any  `json:"vars,omitempty" yaml:"vars,omitempty"`
}

Session defines an LLM session, with its own context. Each session has a Prompt, and a list of resources to load. Each session may also have a PrePrompt, that is an LLM interaction that happens before the main one, produces no structured data, and has the sole purpose to enrich the context and get it ready. This is mostly useful for situations in which we need to use an extraction functionality that poorly harmonizes with a structured output. PreCalls defines a list of functions to call before the main interaction. PrePrompt is the prompt that will be called before the main interaction. This is mainly for context enrichment Prompt defines the main interaction. Resources configure resource loaders to load files for the session. Timeout defines the maximum time the session can run for. DependsOn defines a list of sessions that must be completed before this session can start, and expressions defining code evaluations against the already extracted data, to determine whether the session can start. Context defines whether the partially extracted data should be passed to the session. Attempts defines the number of times each phase should be retried if it fails. ToolDefinitions defines the tools that can be used in this session. IterateOn describes a variable (typically a list) over which we will iterate the session. The session will run len(IterateOn) times. Use an github.com/expr-lang/expr expression. Vars defines variables that are local to the session.

func (*Session) HasPrePrompt

func (s *Session) HasPrePrompt() bool

func (*Session) HasPrompt

func (s *Session) HasPrompt() bool

func (*Session) RenderPrePrompts

func (s *Session) RenderPrePrompts(scope evaluators.EvalScope) (PrePrompt, error)

RenderPrePrompts renders the pre-prompt (which may contain Go templates), with the given scope

func (*Session) RenderPrompt

func (s *Session) RenderPrompt(scope evaluators.EvalScope) (string, error)

RenderPrompt renders the prompt (which may contain Go templates), with the given scope

type SessionManager

type SessionManager struct {
	Parameters    *ParametersConfig `yaml:"parameters,omitempty" json:"parameters,omitempty"`
	RequiredTools RequiredTools     `yaml:"requiredTools,omitempty" json:"requiredTools,omitempty"`
	Transformers  *Transformers     `yaml:"transformers,omitempty" json:"transformers,omitempty"`
	SystemPrompt  *string           `yaml:"systemPrompt,omitempty" json:"systemPrompt,omitempty"`
	Components    Components        `yaml:"components,omitempty" json:"components,omitempty"`
	Sessions      Sessions          `yaml:"sessions" json:"sessions" validate:"required"`
	Schema        *schema.Schema    `yaml:"schema,omitempty" json:"schema,omitempty"`
	Vars          map[string]any    `yaml:"vars,omitempty" json:"vars,omitempty"`
	PreCalls      FunctionCallers   `yaml:"preCalls,omitempty" json:"preCalls,omitempty"`
}

SessionManager manages the LLM sessions and the schema. Sessions split the contribution on the schema

func NewSessionManager

func NewSessionManager() SessionManager

NewSessionManager creates a new SessionManager.

func (*SessionManager) AppendToSystemPrompt

func (s *SessionManager) AppendToSystemPrompt(prompt string)

func (*SessionManager) ComputeRequiredResources

func (s *SessionManager) ComputeRequiredResources() []Resource

func (*SessionManager) FromYAML

func (s *SessionManager) FromYAML(data []byte) error

FromYAML unmarshals a YAML document into the SessionManager.

func (*SessionManager) SetSchema

func (s *SessionManager) SetSchema(schema schema.Schema)

SetSchema sets the schema in the SessionManager.

func (*SessionManager) SetSession

func (s *SessionManager) SetSession(sessionID string, session Session)

SetSession sets a session in the SessionManager.

type SessionStatus

type SessionStatus string

SessionStatus is the status of a session.

type Sessions

type Sessions struct {
	Data  map[string]Session `validate:"required"`
	Order []string
}

Sessions is an ordered map of session IDs to sessions.

func NewSessions

func NewSessions() Sessions

func (Sessions) Get

func (s Sessions) Get(key string) Session

func (Sessions) Iter

func (s Sessions) Iter() iter.Seq2[string, Session]

func (Sessions) MarshalJSON

func (s Sessions) MarshalJSON() ([]byte, error)

MarshalJSON serializes the map as a flat JSON object, keeping s.Order sequence.

func (Sessions) MarshalYAML

func (s Sessions) MarshalYAML() (any, error)

MarshalYAML converts the ordered map into a yaml.Node mapping sequence.

func (*Sessions) Set

func (s *Sessions) Set(key string, value Session)

func (*Sessions) UnmarshalJSON

func (s *Sessions) UnmarshalJSON(data []byte) error

UnmarshalJSON uses a token decoder to capture the exact order keys appear in the JSON object.

func (*Sessions) UnmarshalYAML

func (s *Sessions) UnmarshalYAML(value *yaml.Node) error

UnmarshalYAML processes the raw AST node sequence to preserve structural order.

type ToolCollections

type ToolCollections []ToolsCollection

type ToolDefinition

type ToolDefinition struct {
	Name         string         `json:"name" yaml:"name"`
	Collection   string         `json:"-" yaml:"-"`
	Description  string         `json:"description,omitempty" yaml:"description,omitempty"`
	Type         ToolType       `json:"type" yaml:"type" validate:"required"`
	InputSchema  *schema.Schema `json:"inputSchema,omitempty" yaml:"inputSchema,omitempty"`
	OutputSchema *schema.Schema `json:"outputSchema,omitempty" yaml:"outputSchema,omitempty"`
	Allowlist    *[]string      `json:"allowlist,omitempty" yaml:"allowlist,omitempty"`
}

ToolDefinition defines a tool that can be used in a session. A tool can define a function, an MCP server or a collection. Name is either the tool name of the function name Collection gets populated during mcp/collection tool breakdown into single functions Description is the tool description. Optional, as the tool should already have a description, fill if you wish to override the default Type is either internet_search, function, mcp or collection InputSchema defines the input schema for the tool. mcp and collection tools don't have an input schema. Allowlist is a list of allowed functions when the tool is MCP or collection. If nil, all functions are allowed.

func (ToolDefinition) String

func (t ToolDefinition) String() string

type ToolDefinitions

type ToolDefinitions []ToolDefinition

ToolDefinitions is a list of tools

func (*ToolDefinitions) Contains

func (t *ToolDefinitions) Contains(name string, toolType ToolType) bool

Contains checks whether a certain combination of tool name and tool type appears in tools definitions

func (*ToolDefinitions) HasType

func (t *ToolDefinitions) HasType(tt ToolType) bool

HasType returns true if the tool list contains a tool of the given type. This is useful for "special" tools like internet_search, in which the type is all it needs.

func (*ToolDefinitions) WithDefinitions

func (t *ToolDefinitions) WithDefinitions(definitions ToolDefinitions) ToolDefinitions

type ToolType

type ToolType string
const (
	ToolTypeInternetSearch ToolType = "internet_search"
	ToolTypeFunction       ToolType = "function"
	ToolTypeMCP            ToolType = "mcp"
	ToolTypeCollection     ToolType = "collection"
)

type ToolsCollection

type ToolsCollection interface {
	Name() string
	Description() string
	AsFunctions() ExternalFunctions
}

ToolsCollection is a collection of functions. This is an integration commodity that standardizes how collections are defined so that multiple integrations can easily integrate one with the other.

type ToolsCollectionConfigs

type ToolsCollectionConfigs map[string]CollectionConfig

ToolsCollectionConfigs is a map of collection names to collection configurations

func (ToolsCollectionConfigs) AsToolDefinitions

func (t ToolsCollectionConfigs) AsToolDefinitions() ToolDefinitions

AsToolDefinitions returns the collection configs as tool definitions

func (*ToolsCollectionConfigs) UnmarshalJSON

func (t *ToolsCollectionConfigs) UnmarshalJSON(data []byte) error

type ToolsConfig

type ToolsConfig struct {
	McpServers  McpServerConfigs       `json:"mcpServers,omitempty"`
	Collections ToolsCollectionConfigs `json:"collections,omitempty"`
}

ToolsConfig defines the configuration for the MCP clients and collections. This serves no specific purpose within Frags itself, but it can be used by integrating applications to standardize the configuration format.

func (ToolsConfig) AsToolDefinitions

func (t ToolsConfig) AsToolDefinitions() ToolDefinitions

AsToolDefinitions returns the tools config as tool definitions

type Transformer

type Transformer struct {
	Name             string                  `yaml:"name" json:"name"`
	OnFunctionInput  *string                 `yaml:"onFunctionInput,omitempty" json:"onFunctionInput,omitempty"`
	OnFunctionOutput *string                 `yaml:"onFunctionOutput,omitempty" json:"onFunctionOutput,omitempty"`
	OnResource       *string                 `yaml:"onResource,omitempty" json:"onResource,omitempty"`
	Jsonata          *string                 `yaml:"jsonata" json:"jsonata"`
	JmesPath         *string                 `yaml:"jmesPath" json:"jmesPath"`
	Expr             *string                 `yaml:"expr" json:"expr"`
	Parser           *Parser                 `yaml:"parser" json:"parser"`
	Code             *string                 `yaml:"code" json:"code"`
	Func             TransformerCallbackFunc `yaml:"-" json:"-"`
}

Transformer is a functionality that given a certain input, transforms it into another output using either a Jsonata expression or a custom script (if the scripting engine is available). The transformer will run on specific triggers. We currently support only OnFunctionOutput.

func (Transformer) Transform

func (t Transformer) Transform(ctx *util.FragsContext, data any, runner ExportableRunner) (any, error)

Transform applies the transformation to the given data

type TransformerCallbackFunc

type TransformerCallbackFunc func(ctx *util.FragsContext, data any, runner ExportableRunner) (any, error)

type Transformers

type Transformers []Transformer

func (Transformers) FilterOnFunctionInput

func (t Transformers) FilterOnFunctionInput(name string) Transformers

func (Transformers) FilterOnFunctionOutput

func (t Transformers) FilterOnFunctionOutput(name string) Transformers

FilterOnFunctionOutput filters the transformers based on the OnFunctionOutput trigger

func (Transformers) FilterOnResource

func (t Transformers) FilterOnResource(name string) Transformers

func (Transformers) Transform

func (t Transformers) Transform(ctx *util.FragsContext, data any, runner ExportableRunner) (any, error)

Transform applies all the transformations to the given data

Directories

Path Synopsis
anthropic module
chatgpt module
gemini module
Package mcpauth provides authentication mechanisms for Model Context Protocol (MCP) servers.
Package mcpauth provides authentication mechanisms for Model Context Protocol (MCP) servers.
ollama module
* Copyright (C) 2026 Simone Pezzano * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version.
* Copyright (C) 2026 Simone Pezzano * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version.

Jump to

Keyboard shortcuts

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