Documentation
¶
Overview ¶
Package flowengine provides an agent-style LLM orchestration framework.
Overview ¶
FlowEngine is a zero-external-dependency framework for building composable LLM workflows with RPC-style action definitions and type-safe response handling. It is designed for orchestrating relatively stable flows within a single context.
Core Features ¶
- Agent-style Step definitions with Context, Guide, Task, Input
- RPC-style action registration with automatic JSON Schema generation
- Session management with context chaining
- Configurable retry with validation and hint injection
- Type-safe parameter extraction using generics
- Composable flows: Chain, Decide, Parallel, Iterate
- Function Call output mode for structured responses
- Caching adapter decorator
- Zero external dependencies
Three-Layer Prompt Model ¶
The engine enforces a strict "Three-Layer" structure for prompts:
- Layer 1: Context (System) - Inject "Just-in-Time" data using <context> tag
- Layer 2: Guide (System) - Define "How to operate" using <guide> tag
- Layer 3: Task (User) - Define "What to do" using <task> tag
Quick Start ¶
// 1. Define a step with actions
step := flowengine.NewStep("intent").
Context("You are an intent classifier").
Task("Classify user query intent").
Input("Query: {{.query}}").
Action("search", SearchParams{}).
Action("chat", ChatParams{}).
Build()
// 2. Create engine with adapter
engine := flowengine.New(yourAdapter)
// 3. Run with metadata
fc, resp, err := engine.Run(ctx, step, flowengine.Metadata{"query": "red dress"})
// 4. Type-safe parameter extraction
if params, ok := flowengine.ParamsAs[SearchParams](resp, "search"); ok {
// Use params.Keywords, params.MaxCount
}
Session Support ¶
Session management enables conversation context chaining:
// Run within a session (context is preserved across calls) fc1, resp1, _ := engine.RunWithSession(ctx, "session-id", step1, metadata) fc2, resp2, _ := engine.RunWithSession(ctx, "session-id", step2, metadata) // Delete session when done engine.DeleteSession(ctx, "session-id")
Composable Flows ¶
// Sequential execution
flow := flowengine.Chain(step1, step2, step3)
// Conditional branching
flow := flowengine.Decide(
flowengine.When("search", searchHandler),
flowengine.When("chat", chatHandler),
flowengine.Otherwise(defaultHandler),
)
// Parallel execution
flow := flowengine.Parallel(step1, step2)
// Iteration until condition
flow := flowengine.Iterate(step, func(r *Response) bool {
return r.Is("done")
})
Adapter Interfaces ¶
Implement the Adapter interface to integrate with any LLM provider:
type Adapter interface {
Call(ctx context.Context, system, user string) (string, error)
Stream(ctx context.Context, system, user string) (<-chan string, error)
}
// Session-aware adapter
type SessionAdapter interface {
Adapter
CallWithSession(ctx context.Context, system, user, previousResponseID string) (resp, responseID string, error)
DeleteSession(ctx context.Context, responseID string) error
}
// Function Call adapter
type ToolAdapter interface {
Adapter
CallWithTools(ctx context.Context, system, user string, tools []ToolDef) (*ToolCall, error)
}
Index ¶
- Constants
- func ParamsAs[T any](r *Response, action string) (T, bool)
- type Action
- type ActionRegistry
- func (r *ActionRegistry) Actions() []Action
- func (r *ActionRegistry) IsEmpty() bool
- func (r *ActionRegistry) Names() []string
- func (r *ActionRegistry) Register(name string, prototype any) *ActionRegistry
- func (r *ActionRegistry) RegisterWithDesc(name, description string, prototype any) *ActionRegistry
- func (r *ActionRegistry) ToToolDefs() []ToolDef
- func (r *ActionRegistry) ValidateAction(name string) bool
- type Adapter
- type Cache
- type CachingAdapter
- func (c *CachingAdapter) Call(ctx context.Context, system, user string) (string, error)
- func (c *CachingAdapter) CallWithSession(ctx context.Context, system, user, previousResponseID string) (string, string, error)
- func (c *CachingAdapter) CallWithTools(ctx context.Context, system, user string, tools []ToolDef) (*ToolCall, error)
- func (c *CachingAdapter) CallWithToolsAndSession(ctx context.Context, system, user, previousResponseID string, tools []ToolDef) (*ToolCall, string, error)
- func (c *CachingAdapter) DeleteSession(ctx context.Context, responseID string) error
- func (c *CachingAdapter) IsEnabled() bool
- func (c *CachingAdapter) SetEnabled(enabled bool)
- func (c *CachingAdapter) Stream(ctx context.Context, system, user string) (<-chan string, error)
- type CallHook
- type ContextBuilder
- func (b *ContextBuilder) Add(name, content string) *ContextBuilder
- func (b *ContextBuilder) AddIf(condition bool, name, content string) *ContextBuilder
- func (b *ContextBuilder) AddTemplate(name, template string) *ContextBuilder
- func (b *ContextBuilder) Build() string
- func (b *ContextBuilder) String() string
- type DecideCase
- type Engine
- func (e *Engine) Adapter() Adapter
- func (e *Engine) Close()
- func (e *Engine) DeleteSession(ctx context.Context, sessionID string) error
- func (e *Engine) Run(ctx context.Context, r Runnable, metadata Metadata) (*FlowContext, *Response, error)
- func (e *Engine) RunWithSession(ctx context.Context, sessionID string, r Runnable, metadata Metadata) (*FlowContext, *Response, error)
- func (e *Engine) Sessions() *SessionManager
- func (e *Engine) Stream(ctx context.Context, step *Step, metadata Metadata) (<-chan string, error)
- type EngineOption
- type FlowContext
- func (fc *FlowContext) Engine() *Engine
- func (fc *FlowContext) GetNodeData(name string) (NodeData, bool)
- func (fc *FlowContext) GetNodes() []NodeData
- func (fc *FlowContext) Metadata() Metadata
- func (fc *FlowContext) MetadataSnapshot() Metadata
- func (fc *FlowContext) PrevAction() string
- func (fc *FlowContext) PrevParams() map[string]any
- func (fc *FlowContext) PrevResponse() *Response
- func (fc *FlowContext) RecordNode(name, action string, params map[string]any)
- func (fc *FlowContext) Session() *Session
- func (fc *FlowContext) WithSession(sess *Session) *FlowContext
- type Guide
- type Logger
- type MemoryCache
- type Message
- type Metadata
- type MetricsCollector
- type Middleware
- type MockAdapter
- func (m *MockAdapter) Call(ctx context.Context, system, user string) (string, error)
- func (m *MockAdapter) CallCount() int
- func (m *MockAdapter) CallWithSession(ctx context.Context, system, user, previousResponseID string) (string, string, error)
- func (m *MockAdapter) CallWithTools(ctx context.Context, system, user string, tools []ToolDef) (*ToolCall, error)
- func (m *MockAdapter) CallWithToolsAndSession(ctx context.Context, system, user, previousResponseID string, tools []ToolDef) (*ToolCall, string, error)
- func (m *MockAdapter) DeleteSession(ctx context.Context, responseID string) error
- func (m *MockAdapter) Reset()
- func (m *MockAdapter) Stream(ctx context.Context, system, user string) (<-chan string, error)
- type NamedRunnable
- type NodeData
- type ParallelError
- type Response
- type ResponseType
- type Runnable
- func Chain(steps ...Runnable) Runnable
- func Decide(cases ...DecideCase) Runnable
- func Guard(condition func(*FlowContext) bool, then Runnable) Runnable
- func Iterate(step Runnable, until func(*Response) bool) Runnable
- func IterateMax(step Runnable, until func(*Response) bool, max int) Runnable
- func Parallel(steps ...Runnable) Runnable
- func Transform(fn func(*Response) *Response) Runnable
- type RunnableFunc
- type Session
- func (s *Session) AppendMessage(role, content string)
- func (s *Session) Chain() []string
- func (s *Session) Clear()
- func (s *Session) GetResponseID(stepName string) (string, bool)
- func (s *Session) ID() string
- func (s *Session) LastAccessed() time.Time
- func (s *Session) LastResponseID() string
- func (s *Session) Messages() []Message
- func (s *Session) RecordNode(stepName, responseID string)
- func (s *Session) RootResponseID() string
- func (s *Session) SetRootResponseID(id string)
- type SessionAdapter
- type SessionManager
- func (m *SessionManager) Clear()
- func (m *SessionManager) Count() int
- func (m *SessionManager) Delete(id string)
- func (m *SessionManager) Exists(id string) bool
- func (m *SessionManager) Get(id string) *Session
- func (m *SessionManager) GetIfExists(id string) *Session
- func (m *SessionManager) MaxSize() int
- func (m *SessionManager) Stop()
- func (m *SessionManager) TTL() time.Duration
- type SessionManagerOption
- type Step
- func (s *Step) ActionNames() []string
- func (s *Step) BuildSystemPrompt(fc *FlowContext) (string, error)
- func (s *Step) BuildUserPrompt(fc *FlowContext, hint string) (string, error)
- func (s *Step) GetName() string
- func (s *Step) Run(fc *FlowContext) (*Response, error)
- func (s *Step) ToolDefs() []ToolDef
- func (s *Step) ValidateAction(name string) bool
- type StepBuilder
- func (b *StepBuilder) Action(name string, prototype any) *StepBuilder
- func (b *StepBuilder) ActionWithDesc(name, description string, prototype any) *StepBuilder
- func (b *StepBuilder) Build() *Step
- func (b *StepBuilder) Context(template string) *StepBuilder
- func (b *StepBuilder) Guide(constraints ...string) *StepBuilder
- func (b *StepBuilder) Input(template string) *StepBuilder
- func (b *StepBuilder) Role(r string) *StepBuilder
- func (b *StepBuilder) Task(description string) *StepBuilder
- func (b *StepBuilder) WithRetries(n int) *StepBuilder
- func (b *StepBuilder) WithValidator(v Validator) *StepBuilder
- type ToolAdapter
- type ToolCall
- type ToolDef
- type ValidationError
- type Validator
Constants ¶
const DefaultMaxSessions = 1000
DefaultMaxSessions is the default maximum session count.
const DefaultSessionTTL = 30 * time.Minute
DefaultSessionTTL is the default session TTL (30 minutes).
Variables ¶
This section is empty.
Functions ¶
Types ¶
type Action ¶
type Action struct {
// Name is the action identifier (function name).
Name string
// Description explains what this action does.
Description string
// Schema is the JSON Schema for action parameters.
Schema map[string]any
// Example shows sample parameters for this action (for debugging).
Example string
}
Action defines a Function Call action.
type ActionRegistry ¶
type ActionRegistry struct {
// contains filtered or unexported fields
}
ActionRegistry manages action definitions for a step.
func NewActionRegistry ¶
func NewActionRegistry() *ActionRegistry
NewActionRegistry creates a new action registry.
func (*ActionRegistry) Actions ¶
func (r *ActionRegistry) Actions() []Action
Actions returns all registered actions.
func (*ActionRegistry) IsEmpty ¶
func (r *ActionRegistry) IsEmpty() bool
IsEmpty returns true if no actions are registered.
func (*ActionRegistry) Names ¶
func (r *ActionRegistry) Names() []string
Names returns all action names.
func (*ActionRegistry) Register ¶
func (r *ActionRegistry) Register(name string, prototype any) *ActionRegistry
Register adds an action from a struct prototype. Struct fields become JSON Schema properties. Use `desc` tag to add field descriptions.
func (*ActionRegistry) RegisterWithDesc ¶
func (r *ActionRegistry) RegisterWithDesc(name, description string, prototype any) *ActionRegistry
RegisterWithDesc adds an action with description.
func (*ActionRegistry) ToToolDefs ¶
func (r *ActionRegistry) ToToolDefs() []ToolDef
ToToolDefs converts actions to ToolDef slice for Function Call.
func (*ActionRegistry) ValidateAction ¶
func (r *ActionRegistry) ValidateAction(name string) bool
ValidateAction checks if an action name is registered.
type Adapter ¶
type Adapter interface {
// Call makes a synchronous LLM call and returns the response.
Call(ctx context.Context, system, user string) (string, error)
// Stream makes a streaming LLM call and returns a channel of response chunks.
Stream(ctx context.Context, system, user string) (<-chan string, error)
}
Adapter is the interface for LLM providers.
type Cache ¶
type Cache interface {
Get(key string) (string, bool)
Set(key string, value string)
Delete(key string)
}
Cache is the interface for response caching.
type CachingAdapter ¶
type CachingAdapter struct {
// contains filtered or unexported fields
}
CachingAdapter adds caching support to an Adapter.
func WithCache ¶
func WithCache(inner Adapter, cache Cache, enabled bool) *CachingAdapter
WithCache creates a caching adapter.
func (*CachingAdapter) CallWithSession ¶
func (*CachingAdapter) CallWithTools ¶
func (*CachingAdapter) CallWithToolsAndSession ¶
func (*CachingAdapter) DeleteSession ¶
func (c *CachingAdapter) DeleteSession(ctx context.Context, responseID string) error
func (*CachingAdapter) IsEnabled ¶
func (c *CachingAdapter) IsEnabled() bool
IsEnabled returns whether caching is enabled.
func (*CachingAdapter) SetEnabled ¶
func (c *CachingAdapter) SetEnabled(enabled bool)
SetEnabled toggles caching.
type CallHook ¶
type CallHook struct {
// OnStart is called before the LLM call.
OnStart func(ctx context.Context, system, user string)
// OnEnd is called after the LLM call completes.
OnEnd func(ctx context.Context, system, user, response string, err error)
}
CallHook is called before and after each LLM call.
type ContextBuilder ¶
type ContextBuilder struct {
// contains filtered or unexported fields
}
ContextBuilder dynamically builds step context.
func NewContextBuilder ¶
func NewContextBuilder() *ContextBuilder
NewContextBuilder creates a new context builder.
func (*ContextBuilder) Add ¶
func (b *ContextBuilder) Add(name, content string) *ContextBuilder
Add adds a named data block.
func (*ContextBuilder) AddIf ¶
func (b *ContextBuilder) AddIf(condition bool, name, content string) *ContextBuilder
AddIf conditionally adds a data block.
func (*ContextBuilder) AddTemplate ¶
func (b *ContextBuilder) AddTemplate(name, template string) *ContextBuilder
AddTemplate adds a template data block.
func (*ContextBuilder) Build ¶
func (b *ContextBuilder) Build() string
Build generates the final context string.
func (*ContextBuilder) String ¶
func (b *ContextBuilder) String() string
String implements Stringer.
type DecideCase ¶
type DecideCase struct {
// contains filtered or unexported fields
}
DecideCase represents a branch condition for Decide.
func Otherwise ¶
func Otherwise(r Runnable) DecideCase
Otherwise creates the default decision branch.
func When ¶
func When(action string, r Runnable) DecideCase
When creates a decision branch for a specific action.
type Engine ¶
type Engine struct {
// contains filtered or unexported fields
}
Engine is the flowengine execution engine.
func New ¶
func New(adapter Adapter, opts ...EngineOption) *Engine
New creates a new Engine with the given adapter.
func (*Engine) DeleteSession ¶
DeleteSession deletes a session.
func (*Engine) Run ¶
func (e *Engine) Run(ctx context.Context, r Runnable, metadata Metadata) (*FlowContext, *Response, error)
Run executes a Runnable.
func (*Engine) RunWithSession ¶
func (e *Engine) RunWithSession(ctx context.Context, sessionID string, r Runnable, metadata Metadata) (*FlowContext, *Response, error)
RunWithSession executes a Runnable within a session context.
func (*Engine) Sessions ¶
func (e *Engine) Sessions() *SessionManager
Sessions returns the session manager.
type EngineOption ¶
type EngineOption func(*Engine)
EngineOption configures Engine.
func WithDefaultRetries ¶
func WithDefaultRetries(n int) EngineOption
WithDefaultRetries sets the default retry count.
type FlowContext ¶
FlowContext embeds context.Context and manages all state for a single flow execution.
func NewFlowContext ¶
func NewFlowContext(ctx context.Context, engine *Engine, metadata Metadata) *FlowContext
NewFlowContext creates a new FlowContext.
func (*FlowContext) Engine ¶
func (fc *FlowContext) Engine() *Engine
Engine returns the associated engine.
func (*FlowContext) GetNodeData ¶
func (fc *FlowContext) GetNodeData(name string) (NodeData, bool)
GetNodeData returns node data by name.
func (*FlowContext) GetNodes ¶
func (fc *FlowContext) GetNodes() []NodeData
GetNodes returns all node data.
func (*FlowContext) Metadata ¶
func (fc *FlowContext) Metadata() Metadata
Metadata returns the business metadata.
func (*FlowContext) MetadataSnapshot ¶
func (fc *FlowContext) MetadataSnapshot() Metadata
MetadataSnapshot 返回 metadata 的浅拷贝,用于并发读取。
func (*FlowContext) PrevAction ¶
func (fc *FlowContext) PrevAction() string
PrevAction returns the previous step's action name.
func (*FlowContext) PrevParams ¶
func (fc *FlowContext) PrevParams() map[string]any
PrevParams returns the previous step's parameters.
func (*FlowContext) PrevResponse ¶
func (fc *FlowContext) PrevResponse() *Response
PrevResponse returns the previous step's response.
func (*FlowContext) RecordNode ¶
func (fc *FlowContext) RecordNode(name, action string, params map[string]any)
RecordNode records a node's execution result.
func (*FlowContext) Session ¶
func (fc *FlowContext) Session() *Session
Session returns the current session.
func (*FlowContext) WithSession ¶
func (fc *FlowContext) WithSession(sess *Session) *FlowContext
WithSession attaches a session to the context.
type Logger ¶
type Logger interface {
Debug(msg string, args ...any)
Info(msg string, args ...any)
Error(msg string, args ...any)
}
Logger is the logging interface.
type MemoryCache ¶
type MemoryCache struct {
// contains filtered or unexported fields
}
MemoryCache is a simple in-memory cache.
func (*MemoryCache) Delete ¶
func (c *MemoryCache) Delete(key string)
func (*MemoryCache) Set ¶
func (c *MemoryCache) Set(key string, value string)
type Message ¶
type Message struct {
Role string `json:"role"` // system, user, assistant
Content string `json:"content"`
}
Message represents a session message.
type Metadata ¶
Metadata represents business data for template rendering and data passing.
type MetricsCollector ¶
type MetricsCollector interface {
IncrementCalls()
IncrementErrors()
RecordLatency(milliseconds int64)
}
MetricsCollector is the metrics collection interface.
type Middleware ¶
Middleware wraps an Adapter to add behavior.
func ChainMiddleware ¶
func ChainMiddleware(middlewares ...Middleware) Middleware
ChainMiddleware applies multiple middlewares from left to right.
func WithLogging ¶
func WithLogging(logger Logger) Middleware
WithLogging creates middleware that logs LLM calls.
func WithMetrics ¶
func WithMetrics(collector MetricsCollector) Middleware
WithMetrics creates middleware that collects LLM call metrics.
type MockAdapter ¶
type MockAdapter struct {
// contains filtered or unexported fields
}
MockAdapter is a mock adapter for testing.
func NewMockAdapter ¶
func NewMockAdapter(response string) *MockAdapter
NewMockAdapter creates a mock adapter returning a fixed response.
func NewMockAdapterSequence ¶
func NewMockAdapterSequence(responses ...string) *MockAdapter
NewMockAdapterSequence creates a mock adapter returning sequential responses.
func NewMockAdapterWithToolCall ¶
func NewMockAdapterWithToolCall(name string, args map[string]any) *MockAdapter
NewMockAdapterWithToolCall creates a mock adapter returning a tool call.
func (*MockAdapter) CallCount ¶
func (m *MockAdapter) CallCount() int
CallCount returns the number of times Call was invoked.
func (*MockAdapter) CallWithSession ¶
func (*MockAdapter) CallWithTools ¶
func (*MockAdapter) CallWithToolsAndSession ¶
func (*MockAdapter) DeleteSession ¶
func (m *MockAdapter) DeleteSession(ctx context.Context, responseID string) error
type NamedRunnable ¶
type NamedRunnable interface {
GetName() string
}
NamedRunnable is an optional interface for getting a runnable's name.
type NodeData ¶
type NodeData struct {
Name string `json:"name"`
Action string `json:"action"`
Params map[string]any `json:"params"`
Metadata Metadata `json:"metadata"` // Shared reference with Metadata[Name]
}
NodeData records a single node's execution.
type ParallelError ¶
ParallelError aggregates errors from parallel execution.
func (*ParallelError) Error ¶
func (e *ParallelError) Error() string
func (*ParallelError) FailedIndexes ¶
func (e *ParallelError) FailedIndexes() []int
FailedIndexes returns the indexes of failed steps.
func (*ParallelError) Unwrap ¶
func (e *ParallelError) Unwrap() []error
Unwrap returns all non-nil errors.
type Response ¶
type Response struct {
Type ResponseType `json:"type"`
Action string `json:"action,omitempty"`
Params map[string]any `json:"params,omitempty"`
Message string `json:"message,omitempty"`
Raw string `json:"-"`
}
Response represents a structured LLM output.
func (*Response) ParseParams ¶
ParseParams parses Params into a typed struct.
type ResponseType ¶
type ResponseType string
ResponseType defines the type of LLM response.
const ( ResponseMethod ResponseType = "method" ResponseMessage ResponseType = "message" )
type Runnable ¶
type Runnable interface {
Run(fc *FlowContext) (*Response, error)
}
Runnable is the interface for an executable unit.
func Decide ¶
func Decide(cases ...DecideCase) Runnable
Decide creates a branching flow based on the previous response action.
func Guard ¶
func Guard(condition func(*FlowContext) bool, then Runnable) Runnable
Guard creates a runnable that only executes when the condition is true.
func IterateMax ¶
IterateMax creates a loop with a custom maximum iteration count.
type RunnableFunc ¶
type RunnableFunc func(fc *FlowContext) (*Response, error)
RunnableFunc adapts a function to the Runnable interface.
func (RunnableFunc) Run ¶
func (f RunnableFunc) Run(fc *FlowContext) (*Response, error)
Run implements Runnable.
type Session ¶
type Session struct {
// contains filtered or unexported fields
}
Session represents a session with context chaining.
func NewSession ¶
NewSession creates a new session with the given ID.
func (*Session) AppendMessage ¶
AppendMessage adds a message to session history.
func (*Session) GetResponseID ¶
GetResponseID returns the LLM response ID for a step.
func (*Session) LastAccessed ¶
LastAccessed returns the session's last access time.
func (*Session) LastResponseID ¶
LastResponseID returns the most recent LLM response ID.
func (*Session) RecordNode ¶
RecordNode records step execution with its LLM response ID.
func (*Session) RootResponseID ¶
RootResponseID returns the root LLM response ID.
func (*Session) SetRootResponseID ¶
SetRootResponseID sets the root LLM response ID.
type SessionAdapter ¶
type SessionAdapter interface {
Adapter
// CallWithSession makes a call with session context.
// previousResponseID is the ID from the previous call for context chaining.
CallWithSession(ctx context.Context, system, user, previousResponseID string) (resp string, responseID string, err error)
// DeleteSession deletes a session and all derived contexts.
DeleteSession(ctx context.Context, responseID string) error
}
SessionAdapter extends Adapter with session-based context management.
type SessionManager ¶
type SessionManager struct {
// contains filtered or unexported fields
}
SessionManager manages sessions.
func NewSessionManager ¶
func NewSessionManager(opts ...SessionManagerOption) *SessionManager
NewSessionManager creates a new session manager.
func (*SessionManager) Count ¶
func (m *SessionManager) Count() int
Count returns the number of active sessions.
func (*SessionManager) Delete ¶
func (m *SessionManager) Delete(id string)
Delete removes a session and all its contexts.
func (*SessionManager) Exists ¶
func (m *SessionManager) Exists(id string) bool
Exists checks if a session exists.
func (*SessionManager) Get ¶
func (m *SessionManager) Get(id string) *Session
Get returns or creates a session.
func (*SessionManager) GetIfExists ¶
func (m *SessionManager) GetIfExists(id string) *Session
GetIfExists returns a session if it exists, nil otherwise.
func (*SessionManager) MaxSize ¶
func (m *SessionManager) MaxSize() int
MaxSize returns the current max size setting.
func (*SessionManager) TTL ¶
func (m *SessionManager) TTL() time.Duration
TTL returns the current TTL setting.
type SessionManagerOption ¶
type SessionManagerOption func(*SessionManager)
SessionManagerOption configures SessionManager.
func WithMaxSessions ¶
func WithMaxSessions(max int) SessionManagerOption
WithMaxSessions sets the maximum session count.
type Step ¶
type Step struct {
Name string
Context string
Guide *Guide
Task string
Input string
Actions *ActionRegistry
MaxRetries int
Validator Validator
}
Step represents a single LLM call in an agent workflow.
func SimpleStep ¶
SimpleStep creates a simple message output step.
func (*Step) ActionNames ¶
ActionNames returns registered action names.
func (*Step) BuildSystemPrompt ¶
func (s *Step) BuildSystemPrompt(fc *FlowContext) (string, error)
BuildSystemPrompt builds the system prompt.
func (*Step) BuildUserPrompt ¶
func (s *Step) BuildUserPrompt(fc *FlowContext, hint string) (string, error)
BuildUserPrompt builds the user prompt.
func (*Step) ValidateAction ¶
ValidateAction checks if an action name is valid.
type StepBuilder ¶
type StepBuilder struct {
// contains filtered or unexported fields
}
StepBuilder provides a fluent API for building Steps.
func NewStep ¶
func NewStep(name string) *StepBuilder
NewStep creates a new StepBuilder with the given name.
func (*StepBuilder) Action ¶
func (b *StepBuilder) Action(name string, prototype any) *StepBuilder
Action registers an action.
func (*StepBuilder) ActionWithDesc ¶
func (b *StepBuilder) ActionWithDesc(name, description string, prototype any) *StepBuilder
ActionWithDesc registers an action with description.
func (*StepBuilder) Context ¶
func (b *StepBuilder) Context(template string) *StepBuilder
Context sets the data context.
func (*StepBuilder) Guide ¶
func (b *StepBuilder) Guide(constraints ...string) *StepBuilder
Guide sets the constraints.
func (*StepBuilder) Input ¶
func (b *StepBuilder) Input(template string) *StepBuilder
Input sets the user input template.
func (*StepBuilder) Role ¶
func (b *StepBuilder) Role(r string) *StepBuilder
Role sets the role context (syntactic sugar).
func (*StepBuilder) Task ¶
func (b *StepBuilder) Task(description string) *StepBuilder
Task sets the task description.
func (*StepBuilder) WithRetries ¶
func (b *StepBuilder) WithRetries(n int) *StepBuilder
WithRetries sets the maximum retry count.
func (*StepBuilder) WithValidator ¶
func (b *StepBuilder) WithValidator(v Validator) *StepBuilder
WithValidator sets the validator.
type ToolAdapter ¶
type ToolAdapter interface {
Adapter
// CallWithTools makes a call with tool definitions.
// Returns a tool call if the LLM chooses to call a function.
CallWithTools(ctx context.Context, system, user string, tools []ToolDef) (*ToolCall, error)
// CallWithToolsAndSession combines session and tool support.
CallWithToolsAndSession(ctx context.Context, system, user, previousResponseID string, tools []ToolDef) (call *ToolCall, responseID string, err error)
}
ToolAdapter extends Adapter with Function Call support.
type ToolCall ¶
type ToolCall struct {
// Name is the function to call.
Name string `json:"name"`
// Arguments contains the function arguments.
Arguments map[string]any `json:"arguments"`
}
ToolCall represents an LLM's function call.
type ToolDef ¶
type ToolDef struct {
// Name is the function name.
Name string `json:"name"`
// Description describes what this function does.
Description string `json:"description"`
// Parameters is the JSON Schema for function parameters.
Parameters map[string]any `json:"parameters"`
}
ToolDef defines an LLM-callable function/tool.
type ValidationError ¶
ValidationError indicates a response validation failure.
func (*ValidationError) Error ¶
func (e *ValidationError) Error() string
func (*ValidationError) Unwrap ¶
func (e *ValidationError) Unwrap() error