aicommon

package
v1.4.4-alpha1202-loadi... Latest Latest
Warning

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

Go to latest
Published: Dec 2, 2025 License: AGPL-3.0 Imports: 44 Imported by: 0

Documentation

Index

Constants

View Source
const (
	SYNC_TYPE_PLAN           string = "plan"
	SYNC_TYPE_CONSUMPTION    string = "consumption"
	SYNC_TYPE_PING           string = "ping"
	SYNC_TYPE_UPDATE_CONFIG  string = "set_config"
	SYNC_TYPE_PROCESS_EVENT  string = "sync_process_event"
	SYNC_TYPE_TIMELINE              = "timeline"
	SYNC_TYPE_MEMORY_CONTEXT        = "memory_sync"

	ProcessID           string = "process_id"
	SyncProcessEeventID        = "sync_process_event_id"
)
View Source
const (
	TypeLogTool            = "log/tool"
	TypeLogToolErrorOutput = "log/tool-error-output"
	TypeTextPlain          = "text/plain"
	TypeTextMarkdown       = "text/markdown"
	TypeCodeYaklang        = "code/yaklang"
	TypeCodeHTTPRequest    = "code/http-request"
)
View Source
const (
	ToolCallAction_Enough_Cancel = "enough-cancel"
	ToolCallAction_Finish        = "finish"
)

Variables

View Source
var (
	HotPatchType_AllowRequireForUserInteract = "AllowRequireForUserInteract"
	HotPatchType_AgreePolicy                 = "AgreePolicy"
	HotPatchType_AIService                   = "AIService"
	HotPatchType_RiskControlScore            = "RiskControlScore"
)
View Source
var AIRuntimeInvokerGetter = func(ctx context.Context, options ...ConfigOption) (AITaskInvokeRuntime, error) {
	return nil, utils.Errorf("not registered default AI runtime invoker")
}
View Source
var ActionMagicKey = "@action"
View Source
var ToolCallWatcher = []map[string]any{
	{
		"value":          "enough-cancel",
		"prompt":         "跳过",
		"prompt_english": "Tool output is sufficient, can cancel tool execution and continue with the next task",
	},
}
View Source
var ToolUseReviewSuggestions = []*ToolUseReviewSuggestion{
	{
		Value:            "wrong_tool",
		Prompt:           "工具选择不当",
		PromptEnglish:    "Wrong tool used, need to change to a more appropriate tool",
		AllowExtraPrompt: true,
	},
	{
		Value:                   "wrong_params",
		Prompt:                  "参数不合理",
		PromptEnglish:           "Tool parameters are not used properly, need to adjust parameters",
		AllowExtraPrompt:        true,
		AllowParamsModification: true,
	},
	{
		Value:                   "direct_answer",
		Prompt:                  "要求AI直接回答",
		PromptEnglish:           "Tool parameters are not used properly, need to adjust parameters",
		AllowExtraPrompt:        true,
		AllowParamsModification: true,
	},
	{
		Value:         "continue",
		Prompt:        "同意工具使用",
		PromptEnglish: "Tool usage is correct, continue execution",
	},
}

ToolUseReviewSuggestions 是工具使用审查时的建议(内置一些常见选项)

Functions

func CallAITransaction

func CallAITransaction(
	c AICallerConfigIf,
	prompt string,
	callAi func(*AIRequest) (*AIResponse, error),
	postHandler func(rsp *AIResponse) error,
	requestOpts ...AIRequestOption,
) error

func CreateConsumptionReader

func CreateConsumptionReader(r io.Reader, callback func(current int)) io.Reader

CreateConsumptionReader 创建一个新的 Reader,每秒回调当前的 token 数量

func GenerateAIReviewPrompt

func GenerateAIReviewPrompt(config *Config, userQuery, toolOrTitle, params string) (string, error)

func MarshalTimeline

func MarshalTimeline(i *Timeline) (string, error)

MarshalTimeline serializes a Timeline into a string. not include function and ai/config fields.

func NewGuardianEmitter

func NewGuardianEmitter(coordinatorId string, emitter func(*schema.AiOutputEvent)) *guardianEmitter

func RegisterDefaultAIRuntimeInvoker

func RegisterDefaultAIRuntimeInvoker(getter func(ctx context.Context, options ...ConfigOption) (AITaskInvokeRuntime, error))

func SummaryRank

func SummaryRank(task AITask, callResult *aitool.ToolResult) string

func TypeWriterCopy

func TypeWriterCopy(dst io.Writer, src io.Reader, bytesPerSeconds int) (written int64, err error)

TypeWriterCopy 实现打字机模式的 Copy,以约 200 byte/sec 的速率随机延迟打印 模拟 AI 快速输出效果,提升用户体验

func TypeWriterWrite

func TypeWriterWrite(dst io.Writer, src string, bps int) (written int64, err error)

Types

type AICallbackType

type AICallbackType func(i AICallerConfigIf, req *AIRequest) (*AIResponse, error)

func AIChatToAICallbackType

func AIChatToAICallbackType(cb func(prompt string, opts ...aispec.AIConfigOption) (string, error)) AICallbackType

func LoadAIService

func LoadAIService(typeName string, opts ...aispec.AIConfigOption) (AICallbackType, error)

type AICaller

type AICaller interface {
	CallAI(request *AIRequest) (*AIResponse, error)
}

type AICallerConfigIf

type AICallerConfigIf interface {
	AICaller
	KeyValueConfigIf

	// Interactivable
	Interactivable

	// Checkpointable
	CheckpointableStorage

	AcquireId() int64
	GetRuntimeId() string
	IsCtxDone() bool
	GetContext() context.Context
	CallAIResponseConsumptionCallback(int)
	GetAITransactionAutoRetryCount() int64
	GetTimelineContentSizeLimit() int64
	GetUserInteractiveLimitedTimes() int64
	GetMaxIterationCount() int64
	GetAllowUserInteraction() bool
	RetryPromptBuilder(string, error) string
	GetEmitter() *Emitter
	NewAIResponse() *AIResponse
	CallAIResponseOutputFinishedCallback(string)
}

type AIForgeFactory

type AIForgeFactory interface {
	Query(ctx context.Context, opts ...ForgeQueryOption) ([]*schema.AIForge, error)
	GetAIForge(name string) (*schema.AIForge, error)
	GenerateAIForgeListForPrompt(forges []*schema.AIForge) (string, error)
	GenerateAIJSONSchemaFromSchemaAIForge(forge *schema.AIForge) (string, error)
}

type AIInputEventProcessor

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

func NewAIInputEventProcessor

func NewAIInputEventProcessor() *AIInputEventProcessor

func (*AIInputEventProcessor) CallMirrorOfAIInputEvent

func (p *AIInputEventProcessor) CallMirrorOfAIInputEvent(event *ypb.AIInputEvent)

func (*AIInputEventProcessor) IsFreeInputCallbackSet

func (p *AIInputEventProcessor) IsFreeInputCallbackSet() bool

func (*AIInputEventProcessor) RegisterMirrorOfAIInputEvent

func (p *AIInputEventProcessor) RegisterMirrorOfAIInputEvent(id string, f func(*ypb.AIInputEvent))

func (*AIInputEventProcessor) RegisterSyncCallback

func (p *AIInputEventProcessor) RegisterSyncCallback(syncType string, callback func(event *ypb.AIInputEvent) error)

func (*AIInputEventProcessor) SetFreeInputCallback

func (p *AIInputEventProcessor) SetFreeInputCallback(callback func(event *ypb.AIInputEvent) error)

func (*AIInputEventProcessor) UnRegisterFreeInputCallback

func (p *AIInputEventProcessor) UnRegisterFreeInputCallback(inputType string)

func (*AIInputEventProcessor) UnRegisterSyncCallback

func (p *AIInputEventProcessor) UnRegisterSyncCallback(syncType string)

func (*AIInputEventProcessor) UnregisterMirrorOfAIInputEvent

func (p *AIInputEventProcessor) UnregisterMirrorOfAIInputEvent(id string)

type AIInvokeRuntime

type AIInvokeRuntime interface {
	GetBasicPromptInfo(tools []*aitool.Tool) (string, map[string]any, error)

	ExecuteToolRequiredAndCall(ctx context.Context, name string) (*aitool.ToolResult, bool, error)
	ExecuteToolRequiredAndCallWithoutRequired(ctx context.Context, toolName string, params aitool.InvokeParams) (*aitool.ToolResult, bool, error)
	AskForClarification(ctx context.Context, question string, payloads []string) string
	DirectlyAnswer(ctx context.Context, query string, tools []*aitool.Tool) (string, error)
	EnhanceKnowledgeAnswer(context.Context, string) (string, error)
	EnhanceKnowledgeGetter(ctx context.Context, userQuery string) (string, error)
	VerifyUserSatisfaction(ctx context.Context, query string, isToolCall bool, payload string) (bool, string, error)
	RequireAIForgeAndAsyncExecute(ctx context.Context, forgeName string, onFinish func(error))
	AsyncPlanAndExecute(ctx context.Context, planPayload string, onFinish func(error))
	InvokeLiteForge(ctx context.Context, actionName string, prompt string, outputs []aitool.ToolOption, opts ...GeneralKVConfigOption) (*Action, error)

	// timeline operator
	AddToTimeline(entry, content string)

	GetConfig() AICallerConfigIf
	EmitFileArtifactWithExt(name, ext string, data any) string
	EmitResultAfterStream(any)
	EmitResult(any)
}

type AIRequest

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

func NewAIRequest

func NewAIRequest(prompt string, opt ...AIRequestOption) *AIRequest

func (*AIRequest) CallOnAcquireSeq

func (r *AIRequest) CallOnAcquireSeq(seq int64)

func (*AIRequest) CallSaveCheckpointCallback

func (a *AIRequest) CallSaveCheckpointCallback(handler CheckpointCommitHandler)

func (*AIRequest) GetImageList

func (a *AIRequest) GetImageList() []*ImageData

func (*AIRequest) GetPrompt

func (r *AIRequest) GetPrompt() string

func (*AIRequest) GetSeqId

func (a *AIRequest) GetSeqId() int64

func (*AIRequest) GetStartTime

func (a *AIRequest) GetStartTime() time.Time

func (*AIRequest) GetTaskIndex

func (a *AIRequest) GetTaskIndex() string

func (*AIRequest) HaveSaveCheckpointCallback

func (a *AIRequest) HaveSaveCheckpointCallback() bool

func (*AIRequest) IsDetachedCheckpoint

func (ai *AIRequest) IsDetachedCheckpoint() bool

func (*AIRequest) SetDetachCheckpoint

func (ai *AIRequest) SetDetachCheckpoint(b bool)

func (*AIRequest) SetPrompt

func (r *AIRequest) SetPrompt(prompt string)

func (*AIRequest) SetStartTime

func (a *AIRequest) SetStartTime(t time.Time)

func (*AIRequest) SetTaskIndex

func (a *AIRequest) SetTaskIndex(taskIndex string)

type AIRequestOption

type AIRequestOption func(req *AIRequest)

func WithAIRequest_ImageData

func WithAIRequest_ImageData(data *ImageData) AIRequestOption

func WithAIRequest_OnAcquireSeq

func WithAIRequest_OnAcquireSeq(callback func(int64)) AIRequestOption

func WithAIRequest_SaveCheckpointCallback

func WithAIRequest_SaveCheckpointCallback(callback func(CheckpointCommitHandler)) AIRequestOption

func WithAIRequest_SeqId

func WithAIRequest_SeqId(i int64) AIRequestOption

type AIResponse

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

func NewAIResponse

func NewAIResponse(caller AICallerConfigIf) *AIResponse

func NewUnboundAIResponse

func NewUnboundAIResponse() *AIResponse

func TeeAIResponse

func TeeAIResponse(
	aiCaller AICallerConfigIf,
	src *AIResponse,
	onFirstByte func(teeResp *AIResponse),
	onClose func(),
) *AIResponse

func (*AIResponse) Close

func (r *AIResponse) Close()

func (*AIResponse) Debug

func (a *AIResponse) Debug(i ...bool)

func (*AIResponse) EmitOutputStream

func (r *AIResponse) EmitOutputStream(reader io.Reader)

func (*AIResponse) EmitOutputStreamWithoutConsumption

func (r *AIResponse) EmitOutputStreamWithoutConsumption(reader io.Reader)

func (*AIResponse) EmitReasonStream

func (r *AIResponse) EmitReasonStream(reader io.Reader)

func (*AIResponse) EmitReasonStreamWithoutConsumption

func (r *AIResponse) EmitReasonStreamWithoutConsumption(reader io.Reader)

func (*AIResponse) GetOutputStreamReader

func (a *AIResponse) GetOutputStreamReader(nodeId string, system bool, emitter *Emitter) io.Reader

func (*AIResponse) GetRequestStartTime

func (a *AIResponse) GetRequestStartTime() time.Time

func (*AIResponse) GetResponseStartTime

func (a *AIResponse) GetResponseStartTime() time.Time

func (*AIResponse) GetTaskIndex

func (a *AIResponse) GetTaskIndex() string

func (*AIResponse) GetUnboundStreamReader

func (a *AIResponse) GetUnboundStreamReader(haveReason bool) io.Reader

func (*AIResponse) GetUnboundStreamReaderEx

func (a *AIResponse) GetUnboundStreamReaderEx(onFirstByte func(), onClose func(), onError func()) (io.Reader, io.Reader)

func (*AIResponse) SetRequestStartTime

func (a *AIResponse) SetRequestStartTime(t time.Time)

func (*AIResponse) SetResponseStartTime

func (a *AIResponse) SetResponseStartTime(t time.Time)

func (*AIResponse) SetTaskIndex

func (a *AIResponse) SetTaskIndex(taskIndex string)

type AIResponseOutputStream

type AIResponseOutputStream struct {
	NodeType string
	IsReason bool
	// contains filtered or unexported fields
}

type AIResponseSimple

type AIResponseSimple struct {
	Reason string `json:"reason"`
	Output string `json:"output"`
}

type AIReviewPromptData

type AIReviewPromptData struct {
	CurrentTime        string
	OSArch             string
	WorkingDir         string
	WorkingDirGlance   string
	ConversationMemory string
	Timeline           string
	Nonce              string
	UserQuery          string
	Title              string
	Details            string
	Language           string
}

AIReviewPromptData contains data for AI tool call review prompt

type AIStatefulTask

type AIStatefulTask interface {
	AITask

	GetId() string
	SetResult(string)
	GetResult() string
	GetContext() context.Context
	Cancel()
	IsFinished() bool
	GetUserInput() string
	SetUserInput(string)
	GetStatus() AITaskState
	SetStatus(state AITaskState)
	AppendErrorToResult(i error)
	GetCreatedAt() time.Time
	Finish(i error)
	SetAsyncMode(async bool)
	IsAsyncMode() bool
	GetEmitter() *Emitter
	SetEmitter(emitter *Emitter)
	SetReActLoop(loop ReActLoopIF)
	GetReActLoop() ReActLoopIF

	SetDB(db *gorm.DB)
	GetRisks() []*schema.Risk
	GetUUID() string
}

type AIStatefulTaskBase

type AIStatefulTaskBase struct {
	*Emitter
	// contains filtered or unexported fields
}

func NewStatefulTaskBase

func NewStatefulTaskBase(
	taskId string,
	userInput string,
	ctx context.Context,
	Emitter *Emitter,
	skipEvent ...bool,
) *AIStatefulTaskBase

func (*AIStatefulTaskBase) AppendErrorToResult

func (s *AIStatefulTaskBase) AppendErrorToResult(i error)

func (*AIStatefulTaskBase) Cancel

func (s *AIStatefulTaskBase) Cancel()

func (*AIStatefulTaskBase) Finish

func (s *AIStatefulTaskBase) Finish(i error)

func (*AIStatefulTaskBase) GetAllToolCallResults

func (s *AIStatefulTaskBase) GetAllToolCallResults() []*aitool.ToolResult

func (*AIStatefulTaskBase) GetContext

func (s *AIStatefulTaskBase) GetContext() context.Context

func (*AIStatefulTaskBase) GetCreatedAt

func (s *AIStatefulTaskBase) GetCreatedAt() time.Time

func (*AIStatefulTaskBase) GetDB

func (s *AIStatefulTaskBase) GetDB() *gorm.DB

func (*AIStatefulTaskBase) GetEmitter

func (s *AIStatefulTaskBase) GetEmitter() *Emitter

func (*AIStatefulTaskBase) GetId

func (s *AIStatefulTaskBase) GetId() string

func (*AIStatefulTaskBase) GetIndex

func (s *AIStatefulTaskBase) GetIndex() string

func (*AIStatefulTaskBase) GetName

func (s *AIStatefulTaskBase) GetName() string

func (*AIStatefulTaskBase) GetReActLoop

func (s *AIStatefulTaskBase) GetReActLoop() ReActLoopIF

func (*AIStatefulTaskBase) GetResult

func (s *AIStatefulTaskBase) GetResult() string

func (*AIStatefulTaskBase) GetRisks

func (r *AIStatefulTaskBase) GetRisks() []*schema.Risk

func (*AIStatefulTaskBase) GetStatus

func (s *AIStatefulTaskBase) GetStatus() AITaskState

func (*AIStatefulTaskBase) GetSummary

func (s *AIStatefulTaskBase) GetSummary() string

func (*AIStatefulTaskBase) GetUUID

func (s *AIStatefulTaskBase) GetUUID() string

func (*AIStatefulTaskBase) GetUserInput

func (s *AIStatefulTaskBase) GetUserInput() string

func (*AIStatefulTaskBase) IsAsyncMode

func (s *AIStatefulTaskBase) IsAsyncMode() bool

func (*AIStatefulTaskBase) IsFinished

func (s *AIStatefulTaskBase) IsFinished() bool

func (*AIStatefulTaskBase) PushToolCallResult

func (s *AIStatefulTaskBase) PushToolCallResult(result *aitool.ToolResult)

func (*AIStatefulTaskBase) SetAsyncMode

func (s *AIStatefulTaskBase) SetAsyncMode(async bool)

func (*AIStatefulTaskBase) SetDB

func (s *AIStatefulTaskBase) SetDB(db *gorm.DB)

func (*AIStatefulTaskBase) SetEmitter

func (s *AIStatefulTaskBase) SetEmitter(emitter *Emitter)

func (*AIStatefulTaskBase) SetID

func (s *AIStatefulTaskBase) SetID(id string)

func (*AIStatefulTaskBase) SetName

func (s *AIStatefulTaskBase) SetName(name string)

func (*AIStatefulTaskBase) SetReActLoop

func (s *AIStatefulTaskBase) SetReActLoop(loop ReActLoopIF)

func (*AIStatefulTaskBase) SetResult

func (s *AIStatefulTaskBase) SetResult(s2 string)

func (*AIStatefulTaskBase) SetStatus

func (s *AIStatefulTaskBase) SetStatus(status AITaskState)

func (*AIStatefulTaskBase) SetSummary

func (s *AIStatefulTaskBase) SetSummary(summary string)

func (*AIStatefulTaskBase) SetUserInput

func (s *AIStatefulTaskBase) SetUserInput(s2 string)

func (*AIStatefulTaskBase) ToolCallResultsID

func (s *AIStatefulTaskBase) ToolCallResultsID() []int64

type AITask

type AITask interface {
	GetIndex() string
	GetName() string
	PushToolCallResult(result *aitool.ToolResult)
	GetAllToolCallResults() []*aitool.ToolResult
	GetSummary() string
	SetSummary(summary string)
}

type AITaskInvokeRuntime

type AITaskInvokeRuntime interface {
	AIInvokeRuntime
	SetCurrentTask(task AIStatefulTask)
	GetCurrentTask() AIStatefulTask
}

type AITaskState

type AITaskState string
const (
	AITaskState_Created    AITaskState = "created"
	AITaskState_Queueing   AITaskState = "queueing"
	AITaskState_Processing AITaskState = "processing"
	AITaskState_Completed  AITaskState = "completed"
	AITaskState_Aborted    AITaskState = "aborted"
)

type Action

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

func DefaultAIAssistantRiskControl

func DefaultAIAssistantRiskControl(ctx context.Context, config *Config, ep *Endpoint) (*Action, error)

func ExtractAction

func ExtractAction(i string, actionName string, alias ...string) (*Action, error)

ExtractAction 从字符串中提取指定的 Action 对象,支持别名,这里隐含一个强校验行为,即会等待处理完毕之后检查是否有可用的Action

func ExtractActionFromStream

func ExtractActionFromStream(ctx context.Context, reader io.Reader, actionName string, opts ...ActionMakerOption) (*Action, error)

func ExtractAllAction

func ExtractAllAction(i string) []*Action

func ExtractValidActionFromStream

func ExtractValidActionFromStream(ctx context.Context, reader io.Reader, actionName string, opts ...ActionMakerOption) (*Action, error)

func NewSimpleAction

func NewSimpleAction(name string, params aitool.InvokeParams) *Action

func (*Action) ActionType

func (a *Action) ActionType() string

func (*Action) ForceSet

func (a *Action) ForceSet(key string, value interface{})

func (*Action) GetAnyToString

func (a *Action) GetAnyToString(key string, defaults ...string) string

func (*Action) GetBool

func (a *Action) GetBool(key string, defaults ...bool) bool

func (*Action) GetFloat

func (a *Action) GetFloat(key string, defaults ...float64) float64

func (*Action) GetInt

func (a *Action) GetInt(key string, defaults ...int) int

func (*Action) GetInvokeParams

func (a *Action) GetInvokeParams(key string) aitool.InvokeParams

func (*Action) GetInvokeParamsArray

func (a *Action) GetInvokeParamsArray(key string) []aitool.InvokeParams

func (*Action) GetParams

func (a *Action) GetParams() aitool.InvokeParams

func (*Action) GetString

func (a *Action) GetString(key string, defaults ...string) string

func (*Action) GetStringSlice

func (a *Action) GetStringSlice(key string, defaults ...[]string) []string

func (*Action) Name

func (a *Action) Name() string

func (*Action) Set

func (a *Action) Set(key string, value interface{})

func (*Action) SetName

func (a *Action) SetName(i string)

func (*Action) ValidCheck

func (a *Action) ValidCheck(expectName ...string) bool

ValidCheck 检查 检查当前 Action是否有效,主要检查是否有合法的 @action 字段 即 action type

func (*Action) WaitParse

func (a *Action) WaitParse(ctx context.Context)

func (*Action) WaitStream

func (a *Action) WaitStream(ctx context.Context)

type ActionMaker

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

func NewActionMaker

func NewActionMaker(actionName string, opts ...ActionMakerOption) *ActionMaker

func (*ActionMaker) ReadFromReader

func (m *ActionMaker) ReadFromReader(ctx context.Context, reader io.Reader) *Action

type ActionMakerOption

type ActionMakerOption func(maker *ActionMaker)

func WithActionAlias

func WithActionAlias(alias ...string) ActionMakerOption

func WithActionFieldStreamHandler

func WithActionFieldStreamHandler(fieldNames []string, handler func(key string, r io.Reader)) ActionMakerOption

func WithActionJSONCallback

func WithActionJSONCallback(opts ...jsonextractor.CallbackOption) ActionMakerOption

func WithActionNonce

func WithActionNonce(nonce string) ActionMakerOption

func WithActionOnReaderFinished

func WithActionOnReaderFinished(f ...func()) ActionMakerOption

func WithActionTagToKey

func WithActionTagToKey(tagName string, key string) ActionMakerOption

type AgreePolicyType

type AgreePolicyType string
const (
	AgreePolicyYOLO AgreePolicyType = "yolo"
	// auto: auto agree, should with interval at least 10 seconds
	AgreePolicyAuto AgreePolicyType = "auto"
	// manual: block until user agree
	AgreePolicyManual AgreePolicyType = "manual"
	// ai: use ai to agree, is ai is not agree, will use manual
	AgreePolicyAI AgreePolicyType = "ai"
	// ai-auto: use ai to agree, if ai is not agree, will use auto in auto interval
	AgreePolicyAIAuto AgreePolicyType = "ai-auto"
)

type AsyncGuardian

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

func NewAsyncGuardian

func NewAsyncGuardian(ctx context.Context, coordinatorId string) *AsyncGuardian

func (*AsyncGuardian) Feed

func (a *AsyncGuardian) Feed(event *schema.AiOutputEvent)

func (*AsyncGuardian) GetContext

func (a *AsyncGuardian) GetContext() context.Context

func (*AsyncGuardian) GetEventTriggerCallback

func (a *AsyncGuardian) GetEventTriggerCallback() map[schema.EventType][]GuardianEventTrigger

func (*AsyncGuardian) GetMirrorCallback

func (a *AsyncGuardian) GetMirrorCallback() map[string]*mirrorEventStream

func (*AsyncGuardian) GetRWMutex

func (a *AsyncGuardian) GetRWMutex() *sync.RWMutex

func (*AsyncGuardian) GetUnlimitedInput

func (a *AsyncGuardian) GetUnlimitedInput() *chanx.UnlimitedChan[*schema.AiOutputEvent]

func (*AsyncGuardian) RegisterEventTrigger

func (a *AsyncGuardian) RegisterEventTrigger(eventType schema.EventType, trigger GuardianEventTrigger) error

func (*AsyncGuardian) RegisterMirrorStreamTrigger

func (a *AsyncGuardian) RegisterMirrorStreamTrigger(mirror string, trigger GuardianMirrorStreamTrigger) error

func (*AsyncGuardian) SetAICaller

func (a *AsyncGuardian) SetAICaller(caller AICaller)

func (*AsyncGuardian) SetOutputEmitter

func (a *AsyncGuardian) SetOutputEmitter(coordinatorId string, emitter func(event *schema.AiOutputEvent))

type BaseCheckpointableStorage

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

BaseCheckpointableStorage 基础检查点存储实现

func NewBaseCheckpointableStorage

func NewBaseCheckpointableStorage() *BaseCheckpointableStorage

NewBaseCheckpointableStorage 创建新的基础检查点存储

func NewCheckpointableStorageWithDB

func NewCheckpointableStorageWithDB(runtimeUuid string, db *gorm.DB) *BaseCheckpointableStorage

NewCheckpointableStorageWithDB 使用指定数据库创建检查点存储

func (*BaseCheckpointableStorage) CreateAIInteractiveCheckpoint

func (s *BaseCheckpointableStorage) CreateAIInteractiveCheckpoint(id int64) *schema.AiCheckpoint

CreateAIInteractiveCheckpoint 创建AI交互检查点

func (*BaseCheckpointableStorage) CreateReviewCheckpoint

func (s *BaseCheckpointableStorage) CreateReviewCheckpoint(id int64) *schema.AiCheckpoint

CreateReviewCheckpoint 创建审核检查点

func (*BaseCheckpointableStorage) CreateToolCallCheckpoint

func (s *BaseCheckpointableStorage) CreateToolCallCheckpoint(id int64) *schema.AiCheckpoint

CreateToolCallCheckpoint 创建工具调用检查点

func (*BaseCheckpointableStorage) GetDB

func (s *BaseCheckpointableStorage) GetDB() *gorm.DB

GetDB 获取数据库连接

func (*BaseCheckpointableStorage) SubmitCheckpointRequest

func (s *BaseCheckpointableStorage) SubmitCheckpointRequest(checkpoint *schema.AiCheckpoint, req any) error

SubmitCheckpointRequest 提交检查点请求

func (*BaseCheckpointableStorage) SubmitCheckpointResponse

func (s *BaseCheckpointableStorage) SubmitCheckpointResponse(checkpoint *schema.AiCheckpoint, rsp any) error

SubmitCheckpointResponse 提交检查点响应

type BaseEmitter

type BaseEmitter func(e *schema.AiOutputEvent) (*schema.AiOutputEvent, error)

type BaseInteractiveHandler

type BaseInteractiveHandler struct {
	Interactivable
	// contains filtered or unexported fields
}

BaseInteractiveHandler 基础交互处理器

func NewBaseInteractiveHandler

func NewBaseInteractiveHandler() *BaseInteractiveHandler

func (*BaseInteractiveHandler) CallAfterInteractiveEventReleased

func (h *BaseInteractiveHandler) CallAfterInteractiveEventReleased(eventID string, invoke aitool.InvokeParams)

func (*BaseInteractiveHandler) CallAfterReview

func (h *BaseInteractiveHandler) CallAfterReview(seq int64, reviewQuestion string, userInput aitool.InvokeParams)

func (*BaseInteractiveHandler) DoWaitAgree

func (h *BaseInteractiveHandler) DoWaitAgree(ctx context.Context, endpoint *Endpoint)

func (*BaseInteractiveHandler) Feed

func (h *BaseInteractiveHandler) Feed(endpointId string, params aitool.InvokeParams)

func (*BaseInteractiveHandler) GetEndpointManager

func (h *BaseInteractiveHandler) GetEndpointManager() *EndpointManager

type BasicEnhanceKnowledge

type BasicEnhanceKnowledge struct {
	Content string  // 内容
	Source  string  // 来源
	Score   float64 // 相关性评分,0~1之间]
	UUID    string
}

func NewBasicEnhanceKnowledge

func NewBasicEnhanceKnowledge(content, source string, score float64) *BasicEnhanceKnowledge

func (*BasicEnhanceKnowledge) GetContent

func (e *BasicEnhanceKnowledge) GetContent() string

func (*BasicEnhanceKnowledge) GetScore

func (e *BasicEnhanceKnowledge) GetScore() float64

func (*BasicEnhanceKnowledge) GetScoreMethod

func (e *BasicEnhanceKnowledge) GetScoreMethod() string

func (*BasicEnhanceKnowledge) GetSource

func (e *BasicEnhanceKnowledge) GetSource() string

func (*BasicEnhanceKnowledge) GetTitle

func (e *BasicEnhanceKnowledge) GetTitle() string

func (*BasicEnhanceKnowledge) GetType

func (e *BasicEnhanceKnowledge) GetType() string

func (*BasicEnhanceKnowledge) GetUUID

func (e *BasicEnhanceKnowledge) GetUUID() string

type CheckpointCommitHandler

type CheckpointCommitHandler func() (*schema.AiCheckpoint, error)

type CheckpointableStorage

type CheckpointableStorage interface {
	CreateReviewCheckpoint(id int64) *schema.AiCheckpoint
	CreateToolCallCheckpoint(id int64) *schema.AiCheckpoint
	CreateAIInteractiveCheckpoint(id int64) *schema.AiCheckpoint
	SubmitCheckpointRequest(checkpoint *schema.AiCheckpoint, req any) error
	SubmitCheckpointResponse(checkpoint *schema.AiCheckpoint, rsp any) error
	GetDB() *gorm.DB
}

CheckpointableStorage 检查点存储接口

type Config

type Config struct {
	// Embedded structs
	*Emitter
	*BaseCheckpointableStorage
	*KeyValueConfig

	/*
		Basic config
	*/
	// Identity
	Id string

	// Context controller
	Ctx context.Context

	// counter
	IdSequence  int64
	IdGenerator func() int64

	// session id
	PersistentSessionId string

	// memory triage id
	MemoryTriageId string

	/*
		Event
	*/
	// Input Event Loop
	StartInputEventOnce sync.Once
	EventInputChan      *chanx.UnlimitedChan[*ypb.AIInputEvent]

	InputEventManager *AIInputEventProcessor

	// hotPatch loop
	HotPatchBroadcaster *chanx.Broadcaster[ConfigOption]
	HotPatchOptionChan  *chanx.UnlimitedChan[ConfigOption]
	StartHotPatchOnce   sync.Once

	// output Event Handle
	EventHandler           func(e *schema.AiOutputEvent)
	DisableOutputEventType []string
	SaveEvent              bool

	// asyncGuardian process special output event
	Guardian *AsyncGuardian

	/*
		AI Call
	*/
	// call back
	OriginalAICallback        AICallbackType // 原始 ai 回调, 用于 异步任务,不占用id
	QualityPriorityAICallback AICallbackType // 质量优先 ai 回调
	SpeedPriorityAICallback   AICallbackType // 速度优先 ai 回调

	//aiServiceName
	AiServerName string

	// ai call config
	AiCallTokenLimit       int64
	AiAutoRetry            int64
	AiTransactionAutoRetry int64
	PromptHook             func(string) string

	// ai consumption index
	InputConsumption  *int64
	OutputConsumption *int64

	/*
		Prompt Manager
	*/
	TopToolsCount           int // Number of top tools to display in prompt
	AiForgeManager          AIForgeFactory
	PendingContextProviders []ContextProviderEntry

	/*
		AI Tool
	*/
	// tool manager
	AiToolManager *buildinaitools.AiToolManager

	// tool config
	DisableToolUse      bool
	AiToolManagerOption []buildinaitools.ToolManagerOption
	EnableAISearch      bool
	DisallowMCPServers  bool // 禁用 MCP Servers,默认为 false(即默认启用)

	// Interactive(review/require_user/sync) features
	// endpoint manager
	Epm *EndpointManager

	// require_user and review config
	AllowRequireForUserInteract bool
	AgreePolicy                 AgreePolicyType
	AiAgreeRiskControl          RiskControl
	AgreeInterval               time.Duration
	AgreeAIScoreLow             float64 // 0 ~ low ~ mid ~ 1 ; default 0.4
	AgreeAIScoreMiddle          float64 // default 0.7
	AgreeManualCallback         func(context.Context, *Config) (aitool.InvokeParams, error)

	// sync config
	SyncMutex *sync.RWMutex
	SyncMap   map[string]func() any

	/*
		AI Memory :     General Memory = Timeline + Triage + Other Context
	*/
	// timeline
	Timeline                  *Timeline
	TimelineDiffer            *TimelineDiffer
	TimelineContentSizeLimit  int
	TimelineTotalContentLimit int

	// triage
	MemoryTriage         MemoryTriage
	MemoryPoolSize       int64
	MemoryPool           *omap.OrderedMap[string, *MemoryEntity]
	EnableSelfReflection bool

	// other context
	PersistentMemory []string

	/*
		PE Mode special config
	*/
	// Plan manager
	AllowPlanUserInteract    bool
	PlanUserInteractMaxCount int64

	// result processer
	GenerateReport  bool
	MaxTaskContinue int64

	// other
	ExtendedActionCallback map[string]func(config *Config, action *Action)
	EnableTaskAnalyze      bool

	/*
		Re-Act Mode special config
	*/
	// Call PE
	EnablePlanAndExec bool // Enable plan and execution action
	HijackPERequest   func(ctx context.Context, planPayload string) error

	// default Task for call tool directly
	DefaultTask AIStatefulTask

	// iteration limit
	MaxIterationCount int64

	// task config
	EnhanceKnowledgeManager            *EnhanceKnowledgeManager
	DisableEnhanceDirectlyAnswer       bool
	PerTaskUserInteractiveLimitedTimes int64

	/*
		Meta Info
	*/
	Keywords  []string // AI task keywords, maybe tools name, maybe task keywords ,help ai's decision
	ForgeName string   // if current config use in forge , this is the forge name
	Workdir   string
	Language  string // Response language preference

	/*
		debug config
	*/
	DebugPrompt bool
	DebugEvent  bool

	// other Options
	OtherOption []any

	// focus config
	Focus string
	// contains filtered or unexported fields
}

func NewConfig

func NewConfig(ctx context.Context, opts ...ConfigOption) *Config

NewConfig creates a new Config with options

func (*Config) AcquireId

func (c *Config) AcquireId() int64

func (*Config) Add

func (c *Config) Add(i int)

func (*Config) CallAI

func (c *Config) CallAI(request *AIRequest) (*AIResponse, error)

func (*Config) CallAIResponseConsumptionCallback

func (c *Config) CallAIResponseConsumptionCallback(i int)

func (*Config) CallAIResponseOutputFinishedCallback

func (c *Config) CallAIResponseOutputFinishedCallback(s string)

func (*Config) CallAfterInteractiveEventReleased

func (c *Config) CallAfterInteractiveEventReleased(s string, params aitool.InvokeParams)

func (*Config) CallAfterReview

func (c *Config) CallAfterReview(seq int64, reviewQuestion string, userInput aitool.InvokeParams)

func (*Config) CallAiTransaction

func (c *Config) CallAiTransaction(
	prompt string,
	callAi func(*AIRequest) (*AIResponse, error),
	postHandler func(rsp *AIResponse) error,
	requestOpts ...AIRequestOption,
) error

func (*Config) CallOriginalAI

func (c *Config) CallOriginalAI(request *AIRequest) (*AIResponse, error)

func (*Config) DoWaitAgree

func (c *Config) DoWaitAgree(ctx context.Context, endpoint *Endpoint)

func (*Config) DoWaitAgreeWithPolicy

func (c *Config) DoWaitAgreeWithPolicy(ctx context.Context, policy AgreePolicyType, endpoint *Endpoint)

func (*Config) Done

func (c *Config) Done()

func (*Config) EmitCurrentConfigInfo

func (c *Config) EmitCurrentConfigInfo()

func (*Config) Feed

func (c *Config) Feed(endpointId string, params aitool.InvokeParams)

func (*Config) GetAIForgeManager

func (c *Config) GetAIForgeManager() AIForgeFactory

func (*Config) GetAITransactionAutoRetryCount

func (c *Config) GetAITransactionAutoRetryCount() int64

func (*Config) GetAiToolManager

func (c *Config) GetAiToolManager() *buildinaitools.AiToolManager

func (*Config) GetAllowUserInteraction

func (c *Config) GetAllowUserInteraction() bool

func (*Config) GetConsumptionConfig

func (c *Config) GetConsumptionConfig() (*int64, *int64, string)

func (*Config) GetContext

func (c *Config) GetContext() context.Context

func (*Config) GetDisableEnhanceDirectlyAnswer

func (c *Config) GetDisableEnhanceDirectlyAnswer() bool

func (*Config) GetEmitter

func (c *Config) GetEmitter() *Emitter

func (*Config) GetEnablePlanAndExec

func (c *Config) GetEnablePlanAndExec() bool

func (*Config) GetEnableSelfReflection

func (c *Config) GetEnableSelfReflection() bool

func (*Config) GetEnableUserInteract

func (c *Config) GetEnableUserInteract() bool

func (*Config) GetEndpointManager

func (c *Config) GetEndpointManager() *EndpointManager

func (*Config) GetEnhanceKnowledgeManager

func (c *Config) GetEnhanceKnowledgeManager() *EnhanceKnowledgeManager

func (*Config) GetInputConsumption

func (c *Config) GetInputConsumption() int64

func (*Config) GetLanguage

func (c *Config) GetLanguage() string

func (*Config) GetMaxIterationCount

func (c *Config) GetMaxIterationCount() int64

func (*Config) GetMaxIterations

func (c *Config) GetMaxIterations() int64

func (*Config) GetOutputConsumption

func (c *Config) GetOutputConsumption() int64

func (*Config) GetRuntimeId

func (c *Config) GetRuntimeId() string

func (*Config) GetSequenceStart

func (c *Config) GetSequenceStart() int64

func (*Config) GetTimeline

func (c *Config) GetTimeline() *Timeline

func (*Config) GetTimelineContentSizeLimit

func (c *Config) GetTimelineContentSizeLimit() int64

func (*Config) GetTopToolsCount

func (c *Config) GetTopToolsCount() int

func (*Config) GetUserInteractiveLimitedTimes

func (c *Config) GetUserInteractiveLimitedTimes() int64

func (*Config) HandleSyncConsumptionEvent

func (c *Config) HandleSyncConsumptionEvent(e *ypb.AIInputEvent) error

func (*Config) HandleSyncMemoryContextEvent

func (c *Config) HandleSyncMemoryContextEvent(event *ypb.AIInputEvent) error

func (*Config) HandleSyncPongEvent

func (c *Config) HandleSyncPongEvent(e *ypb.AIInputEvent) error

func (*Config) HandleSyncTimelineEvent

func (c *Config) HandleSyncTimelineEvent(event *ypb.AIInputEvent) error

func (*Config) HandleSyncUpdataConfigEvent

func (c *Config) HandleSyncUpdataConfigEvent(event *ypb.AIInputEvent) error

func (*Config) InputConsumptionCallback

func (c *Config) InputConsumptionCallback(current int)

func (*Config) IsCtxDone

func (c *Config) IsCtxDone() bool

func (*Config) LoadAIServiceByName

func (c *Config) LoadAIServiceByName(name string) error

func (*Config) NewAIResponse

func (c *Config) NewAIResponse() *AIResponse

func (*Config) RegisterBasicSyncHandlers

func (c *Config) RegisterBasicSyncHandlers()

func (*Config) ReleaseInteractiveEvent

func (c *Config) ReleaseInteractiveEvent(eventID string, invoke aitool.InvokeParams)

func (*Config) RetryPromptBuilder

func (c *Config) RetryPromptBuilder(s string, err error) string

func (*Config) SetAICallback

func (c *Config) SetAICallback(callback AICallbackType)

func (*Config) SetContext

func (c *Config) SetContext(ctx context.Context)

func (*Config) SimpleInfoMap

func (c *Config) SimpleInfoMap() map[string]interface{}

func (*Config) StartEventLoop

func (c *Config) StartEventLoop(ctx context.Context)

func (*Config) StartEventLoopEx

func (c *Config) StartEventLoopEx(ctx context.Context, startCall func(), doneCall func())

func (*Config) StartHotPatchLoop

func (c *Config) StartHotPatchLoop(ctx context.Context)

func (*Config) Wait

func (c *Config) Wait()

type ConfigOption

type ConfigOption func(*Config) error

func ConvertConfigToOptions

func ConvertConfigToOptions(i *Config) []ConfigOption
func (c *Config) RegisterMirrorOfAIInputEvent(id string, f func(*ypb.AIInputEvent)) {
	r.mirrorMutex.Lock()
	defer r.mirrorMutex.Unlock()
	r.mirrorOfAIInputEvent[id] = f
}
func (c *Config) CallMirrorOfAIInputEvent(event *ypb.AIInputEvent) {
	r.mirrorMutex.RLock()
	defer r.mirrorMutex.RUnlock()
	for _, f := range r.mirrorOfAIInputEvent {
		f(event)
	}
}
func (c *Config) UnregisterMirrorOfAIInputEvent(id string) {
	r.mirrorMutex.Lock()
	defer r.mirrorMutex.Unlock()
	delete(r.mirrorOfAIInputEvent, id)
}

func ProcessHotPatchMessage

func ProcessHotPatchMessage(e *ypb.AIInputEvent) []ConfigOption

func WithAIAgree

func WithAIAgree() ConfigOption

func WithAIAutoRetry

func WithAIAutoRetry(n int64) ConfigOption

WithAIAutoRetry sets AiAutoRetry count.

func WithAIBlueprintManager

func WithAIBlueprintManager(factory AIForgeFactory) ConfigOption

func WithAICallback

func WithAICallback(cb AICallbackType) ConfigOption

Callback setters

func WithAIConsumptionPointers

func WithAIConsumptionPointers(input *int64, output *int64) ConfigOption

Consumption pointers

func WithAIKBPath

func WithAIKBPath(path string) ConfigOption

func WithAIKBRagPath

func WithAIKBRagPath(path string) ConfigOption

func WithAIKBResultMaxSize

func WithAIKBResultMaxSize(maxSize int64) ConfigOption

func WithAIServiceName

func WithAIServiceName(name string) ConfigOption

WithAICallback sets the AI callback for LLM interactions

func WithAITransactionAutoRetry

func WithAITransactionAutoRetry(n int64) ConfigOption

AI retry / limits

func WithAITransactionRetry

func WithAITransactionRetry(n int64) ConfigOption

WithAITransactionRetry alias to existing WithAITransactionAutoRetry for naming compatibility.

func WithAgreeAIRiskCtrlScore

func WithAgreeAIRiskCtrlScore(score float64) ConfigOption

func WithAgreeAIScoreLowMid

func WithAgreeAIScoreLowMid(low, mid float64) ConfigOption

func WithAgreeAuto

func WithAgreeAuto() ConfigOption

func WithAgreeInterval

func WithAgreeInterval(d time.Duration) ConfigOption

func WithAgreeManual

func WithAgreeManual() ConfigOption

func WithAgreeManualCallback

func WithAgreeManualCallback(cb func(context.Context, *Config) (aitool.InvokeParams, error)) ConfigOption

func WithAgreePolicy

func WithAgreePolicy(p AgreePolicyType) ConfigOption

func WithAgreeYOLO

func WithAgreeYOLO(b ...bool) ConfigOption

func WithAiAgreeRiskControl

func WithAiAgreeRiskControl(rc RiskControl) ConfigOption

func WithAiCallTokenLimit

func WithAiCallTokenLimit(limit int64) ConfigOption

func WithAiToolManagerOptions

func WithAiToolManagerOptions(opts ...buildinaitools.ToolManagerOption) ConfigOption

func WithAllowPlanUserInteract

func WithAllowPlanUserInteract(v bool) ConfigOption

func WithAllowRequireForUserInteract

func WithAllowRequireForUserInteract(v bool) ConfigOption

Interactive / review / require_user

func WithAppendOtherOption

func WithAppendOtherOption(opts any) ConfigOption

func WithAppendPersistentMemory

func WithAppendPersistentMemory(keys ...string) ConfigOption

WithAppendPersistentMemory appends keys to PersistentMemory.

func WithConsumption

func WithConsumption(input, output *int64, logUUID string) ConfigOption

func WithContext

func WithContext(ctx context.Context) ConfigOption

WithContext sets the context (and optional cancel) for the config.

func WithDebug

func WithDebug(v bool) ConfigOption

WithDebug toggles both prompt and event debug flags.

func WithDebugEvent

func WithDebugEvent(v bool) ConfigOption

func WithDebugPrompt

func WithDebugPrompt(v ...bool) ConfigOption

Debug flags

func WithDisableEnhanceDirectlyAnswer

func WithDisableEnhanceDirectlyAnswer(disable bool) ConfigOption

func WithDisableOutputEvent

func WithDisableOutputEvent(types ...string) ConfigOption

WithDisableOutputEvent is a name-compatible wrapper for disabling output event types.

func WithDisableOutputEventType

func WithDisableOutputEventType(types ...string) ConfigOption

func WithDisableToolUse

func WithDisableToolUse(disable bool) ConfigOption

func WithDisableToolsName

func WithDisableToolsName(toolsName ...string) ConfigOption

func WithDisallowMCPServers

func WithDisallowMCPServers(disallow bool) ConfigOption

func WithDisallowRequireForUserPrompt

func WithDisallowRequireForUserPrompt() ConfigOption

WithDisallowRequireForUserPrompt disables require-for-user-interact.

func WithDynamicContextProvider

func WithDynamicContextProvider(name string, provider ContextProvider) ConfigOption

func WithEnablePETaskAnalyze

func WithEnablePETaskAnalyze(v bool) ConfigOption

func WithEnablePlanAndExec

func WithEnablePlanAndExec(enable bool) ConfigOption

func WithEnableSelfReflection

func WithEnableSelfReflection(v bool) ConfigOption

func WithEnableToolManagerAISearch

func WithEnableToolManagerAISearch(enable bool) ConfigOption

func WithEnableToolsName

func WithEnableToolsName(toolsName ...string) ConfigOption

func WithEnhanceKnowledgeManager

func WithEnhanceKnowledgeManager(m *EnhanceKnowledgeManager) ConfigOption

func WithEventHandler

func WithEventHandler(handler func(e *schema.AiOutputEvent)) ConfigOption

Event / output

func WithEventInputChan

func WithEventInputChan(ch chan *ypb.AIInputEvent) ConfigOption

func WithEventInputChanx

func WithEventInputChanx(ch *chanx.UnlimitedChan[*ypb.AIInputEvent]) ConfigOption

WithEventInputChan sets a custom event input channel.

func WithExtendedActionCallback

func WithExtendedActionCallback(name string, callback func(config *Config, action *Action)) ConfigOption

WithExtendedActionCallback sets the ExtendedActionCallback map.

func WithFocus

func WithFocus(focus string) ConfigOption

func WithForgeName

func WithForgeName(name string) ConfigOption

func WithForgeParams

func WithForgeParams(i any) ConfigOption

func WithGenerateReport

func WithGenerateReport(v bool) ConfigOption

WithGenerateReport toggles GenerateReport.

func WithGuardianEventTrigger

func WithGuardianEventTrigger(eventTrigger schema.EventType, callback GuardianEventTrigger) ConfigOption

func WithGuardianMirrorStreamMirror

func WithGuardianMirrorStreamMirror(streamName string, callback GuardianMirrorStreamTrigger) ConfigOption

func WithHijackPERequest

func WithHijackPERequest(fn func(ctx context.Context, planPayload string) error) ConfigOption

func WithHotPatchOptionChan

func WithHotPatchOptionChan(ch *chanx.UnlimitedChan[ConfigOption]) ConfigOption

func WithID

func WithID(id string) ConfigOption

WithID sets the runtime id for the config.

func WithIdGenerator

func WithIdGenerator(gen func() int64) ConfigOption

WithIdGenerator sets a config option helpers that set common fields on Config (ID, context, callbacks, limits, handlers, memory/plan flags, metadata, debug flags, etc.).

func WithJarOperator

func WithJarOperator() ConfigOption

func WithKeywords

func WithKeywords(keys ...string) ConfigOption

func WithLanguage

func WithLanguage(lang string) ConfigOption

func WithManualAssistantCallback

func WithManualAssistantCallback(cb func(context.Context, *Config) (aitool.InvokeParams, error)) ConfigOption

WithManualAssistantCallback is an alias to the agree/manual callback setter.

func WithMaxIterationCount

func WithMaxIterationCount(n int64) ConfigOption

Misc / meta

func WithMaxTaskContinue

func WithMaxTaskContinue(n int64) ConfigOption

func WithMemoryLimits

func WithMemoryLimits(contentSizeLimit, totalContentLimit int) ConfigOption

Memory / timeline

func WithMemoryPoolSize

func WithMemoryPoolSize(sz int64) ConfigOption

func WithMemoryTriage

func WithMemoryTriage(mt MemoryTriage) ConfigOption

func WithMemoryTriageId

func WithMemoryTriageId(id string) ConfigOption

func WithOmniSearchTool

func WithOmniSearchTool() ConfigOption

func WithPerTaskUserInteractiveLimitedTimes

func WithPerTaskUserInteractiveLimitedTimes(n int64) ConfigOption

func WithPersistentSessionId

func WithPersistentSessionId(sid string) ConfigOption

WithPersistentSessionId sets persistentSessionId.

func WithPlanUserInteractMaxCount

func WithPlanUserInteractMaxCount(i int64) ConfigOption

func WithPromptHook

func WithPromptHook(hook func(string) string) ConfigOption

func WithQualityPriorityAICallback

func WithQualityPriorityAICallback(cb AICallbackType) ConfigOption

func WithQwenNoThink

func WithQwenNoThink() ConfigOption

func WithSaveEvent

func WithSaveEvent(v bool) ConfigOption

func WithSequence

func WithSequence(seq int64) ConfigOption

WithSequence sets the starting sequence/id and installs a simple id generator that increments it.

func WithSpeedPriorityAICallback

func WithSpeedPriorityAICallback(cb AICallbackType) ConfigOption

func WithSystemFileOperator

func WithSystemFileOperator() ConfigOption

func WithTimeline

func WithTimeline(t *Timeline) ConfigOption

func WithTimelineContentLimit

func WithTimelineContentLimit(limit int) ConfigOption

WithTimelineContentLimit sets timeline content size limit (keeps naming parity).

func WithTimelineLimit

func WithTimelineLimit(limit int) ConfigOption

WithTimelineLimit sets the timeline content size limit (deprecated name, kept for compatibility).

func WithTool

func WithTool(tool *aitool.Tool) ConfigOption

WithTool is a convenience wrapper to add a single tool (delegates to WithTools).

func WithTools

func WithTools(tool ...*aitool.Tool) ConfigOption

func WithTopToolsCount

func WithTopToolsCount(n int) ConfigOption

Prompt/tool/blueprint related

func WithTracedDynamicContextProvider

func WithTracedDynamicContextProvider(name string, provider ContextProvider) ConfigOption

WithTracedDynamicContextProvider registers a dynamic context provider with tracing capabilities It tracks changes between calls and provides diff information

func WithTracedFileContext

func WithTracedFileContext(name string, filePath string) ConfigOption

WithTracedFileContext monitors a file and provides its content as context with change tracking

func WithWorkdir

func WithWorkdir(dir string) ConfigOption

func WithWrapperedAICallback

func WithWrapperedAICallback(cb AICallbackType) ConfigOption

type ContextProvider

type ContextProvider func(config AICallerConfigIf, emitter *Emitter, key string) (string, error)

type ContextProviderEntry

type ContextProviderEntry struct {
	Name     string
	Provider ContextProvider
	Traced   bool
}

type ContextProviderManager

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

func NewContextProviderManager

func NewContextProviderManager() *ContextProviderManager

func (*ContextProviderManager) Execute

func (r *ContextProviderManager) Execute(config AICallerConfigIf, emitter *Emitter) string

func (*ContextProviderManager) Register

func (r *ContextProviderManager) Register(name string, cb ContextProvider)

func (*ContextProviderManager) RegisterTracedContent

func (r *ContextProviderManager) RegisterTracedContent(name string, cb ContextProvider)

func (*ContextProviderManager) Unregister

func (r *ContextProviderManager) Unregister(name string)

type Emitter

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

func NewDummyEmitter

func NewDummyEmitter() *Emitter

NewDummyEmitter emit sends an AI output event using the emitter's function

func NewEmitter

func NewEmitter(id string, emitter BaseEmitter) *Emitter

func (*Emitter) AssociativeAIProcess

func (i *Emitter) AssociativeAIProcess(newProcess *schema.AiProcess) *Emitter

func (*Emitter) Emit

func (*Emitter) EmitAction

func (e *Emitter) EmitAction(nodeId string, action string, actionType string) (*schema.AiOutputEvent, error)

EmitAction emits an action event for AI execution

func (*Emitter) EmitDefaultStreamEvent

func (r *Emitter) EmitDefaultStreamEvent(nodeId string, reader io.Reader, taskIndex string, finishCallback ...func()) (*schema.AiOutputEvent, error)

func (*Emitter) EmitError

func (e *Emitter) EmitError(fmtlog string, items ...any) (*schema.AiOutputEvent, error)

func (*Emitter) EmitErrorWithName

func (r *Emitter) EmitErrorWithName(name string, fmtlog string, items ...any) (*schema.AiOutputEvent, error)

func (*Emitter) EmitHTTPRequestStreamEvent

func (r *Emitter) EmitHTTPRequestStreamEvent(nodeId string, reader io.Reader, taskIndex string, finishCallback ...func()) (*schema.AiOutputEvent, error)

func (*Emitter) EmitInfo

func (e *Emitter) EmitInfo(fmtlog string, items ...any) (*schema.AiOutputEvent, error)

func (*Emitter) EmitInfoWithName

func (r *Emitter) EmitInfoWithName(name string, fmtlog string, items ...any) (*schema.AiOutputEvent, error)

func (*Emitter) EmitInteractiveJSON

func (r *Emitter) EmitInteractiveJSON(id string, typeName schema.EventType, nodeId string, i any) (*schema.AiOutputEvent, error)

func (*Emitter) EmitInteractiveRelease

func (r *Emitter) EmitInteractiveRelease(id string, invokeParams aitool.InvokeParams) (*schema.AiOutputEvent, error)

func (*Emitter) EmitIteration

func (e *Emitter) EmitIteration(nodeId string, current int, max int, description string) (*schema.AiOutputEvent, error)

EmitIteration emits an iteration event for AI reasoning loops

func (*Emitter) EmitJSON

func (r *Emitter) EmitJSON(typeName schema.EventType, id string, i any) (*schema.AiOutputEvent, error)

func (*Emitter) EmitKnowledge

func (e *Emitter) EmitKnowledge(nodeId string, enhanceID string, result EnhanceKnowledge) (*schema.AiOutputEvent, error)

EmitKnowledge emits a knowledge enhancement data for AI processes

func (*Emitter) EmitKnowledgeListAboutTask

func (e *Emitter) EmitKnowledgeListAboutTask(nodeId string, taskID string, results []EnhanceKnowledge, syncId string) (*schema.AiOutputEvent, error)

func (*Emitter) EmitLogWithLevel

func (r *Emitter) EmitLogWithLevel(level, name, fmtlog string, items ...any) (*schema.AiOutputEvent, error)

func (*Emitter) EmitObservation

func (e *Emitter) EmitObservation(nodeId string, observation string, source string) (*schema.AiOutputEvent, error)

EmitObservation emits an observation event for AI feedback

func (*Emitter) EmitPinDirectory

func (e *Emitter) EmitPinDirectory(path string) (*schema.AiOutputEvent, error)

func (*Emitter) EmitPinFilename

func (e *Emitter) EmitPinFilename(path string) (*schema.AiOutputEvent, error)

func (Emitter) EmitPlanExecFail

func (e Emitter) EmitPlanExecFail(fmtlog string, items ...any) (*schema.AiOutputEvent, error)

func (*Emitter) EmitPrompt

func (e *Emitter) EmitPrompt(step string, prompt string) (*schema.AiOutputEvent, error)

func (*Emitter) EmitReasonStreamEvent

func (r *Emitter) EmitReasonStreamEvent(nodeId string, startTime time.Time, reader io.Reader, taskIndex string, finishCallback ...func()) (*schema.AiOutputEvent, error)

func (*Emitter) EmitReferenceMaterial

func (e *Emitter) EmitReferenceMaterial(typeName string, eventId string, content any) (*schema.AiOutputEvent, error)

func (*Emitter) EmitRequirePermission

func (r *Emitter) EmitRequirePermission(title string, description ...string) (*schema.AiOutputEvent, error)

func (*Emitter) EmitResult

func (e *Emitter) EmitResult(nodeId string, result interface{}, success bool) (*schema.AiOutputEvent, error)

EmitResult emits a result event for AI final output

func (*Emitter) EmitResultAfterStream

func (e *Emitter) EmitResultAfterStream(nodeId string, result interface{}, success bool) (*schema.AiOutputEvent, error)

EmitResult emits a result event for AI final output

func (*Emitter) EmitSchema

func (r *Emitter) EmitSchema(nodeId string, i any) (*schema.AiOutputEvent, error)

func (*Emitter) EmitStatus

func (r *Emitter) EmitStatus(key string, value any) (*schema.AiOutputEvent, error)

func (*Emitter) EmitStreamEvent

func (r *Emitter) EmitStreamEvent(nodeId string, startTime time.Time, reader io.Reader, taskIndex string, finishCallback ...func()) (*schema.AiOutputEvent, error)

func (*Emitter) EmitStreamEventEx

func (r *Emitter) EmitStreamEventEx(nodeId string, startTime time.Time, reader io.Reader, taskIndex string, disableMarkdown bool, finishCallback ...func()) (*schema.AiOutputEvent, error)

func (*Emitter) EmitStreamEventWithContentType

func (r *Emitter) EmitStreamEventWithContentType(nodeId string, reader io.Reader, taskIndex string, contentType string, finishCallback ...func()) (*schema.AiOutputEvent, error)

func (*Emitter) EmitStructured

func (r *Emitter) EmitStructured(id string, i any) (*schema.AiOutputEvent, error)

func (*Emitter) EmitSyncEvent

func (r *Emitter) EmitSyncEvent(id string, i any, syncID string) (*schema.AiOutputEvent, error)

func (*Emitter) EmitSyncEventError

func (r *Emitter) EmitSyncEventError(id string, err error, syncID string) (*schema.AiOutputEvent, error)

func (*Emitter) EmitSyncJSON

func (r *Emitter) EmitSyncJSON(typeName schema.EventType, id string, i any, syncID string) (*schema.AiOutputEvent, error)

func (*Emitter) EmitSystemPrompt

func (e *Emitter) EmitSystemPrompt(step string, prompt string) (*schema.AiOutputEvent, error)

func (*Emitter) EmitSystemReasonStreamEvent

func (r *Emitter) EmitSystemReasonStreamEvent(nodeId string, startTime time.Time, reader io.Reader, taskIndex string, finishCallback ...func()) (*schema.AiOutputEvent, error)

func (*Emitter) EmitSystemStreamEvent

func (r *Emitter) EmitSystemStreamEvent(nodeId string, startTime time.Time, reader io.Reader, taskIndex string, finishCallback ...func()) (*schema.AiOutputEvent, error)

func (*Emitter) EmitTextMarkdownStreamEvent

func (r *Emitter) EmitTextMarkdownStreamEvent(
	nodeId string,
	reader io.Reader,
	taskIndex string,
	finishCallback ...func(),
) (*schema.AiOutputEvent, error)

func (*Emitter) EmitTextPlainTextStreamEvent

func (r *Emitter) EmitTextPlainTextStreamEvent(
	nodeId string,
	reader io.Reader,
	taskIndex string,
	finishCallback ...func(),
) (*schema.AiOutputEvent, error)

func (*Emitter) EmitTextReferenceMaterial

func (e *Emitter) EmitTextReferenceMaterial(eventId string, content any) (*schema.AiOutputEvent, error)

func (*Emitter) EmitTextStreamWithTaskIndex

func (r *Emitter) EmitTextStreamWithTaskIndex(nodeId string, content string, taskIndex string) (*schema.AiOutputEvent, error)

func (*Emitter) EmitThought

func (e *Emitter) EmitThought(nodeId string, thought string) (*schema.AiOutputEvent, error)

EmitThought emits a thought event for AI reasoning process

func (*Emitter) EmitThoughtStream

func (r *Emitter) EmitThoughtStream(taskId string, fmtTpl string, item ...any) (*schema.AiOutputEvent, error)

func (*Emitter) EmitThoughtStreamReader

func (r *Emitter) EmitThoughtStreamReader(taskId string, rd io.Reader, finished ...func()) (*schema.AiOutputEvent, error)

func (*Emitter) EmitThoughtTypeWriterStreamReader

func (r *Emitter) EmitThoughtTypeWriterStreamReader(taskId string, origin io.Reader, finished ...func()) (*schema.AiOutputEvent, error)

func (*Emitter) EmitToolCallDecision

func (r *Emitter) EmitToolCallDecision(callToolId string, action string, summary string) (*schema.AiOutputEvent, error)

func (*Emitter) EmitToolCallDone

func (r *Emitter) EmitToolCallDone(callToolId string) (*schema.AiOutputEvent, error)

func (*Emitter) EmitToolCallError

func (r *Emitter) EmitToolCallError(callToolId string, err any) (*schema.AiOutputEvent, error)

func (*Emitter) EmitToolCallStart

func (r *Emitter) EmitToolCallStart(callToolId string, tool *aitool.Tool) (*schema.AiOutputEvent, error)

func (*Emitter) EmitToolCallStatus

func (r *Emitter) EmitToolCallStatus(callToolId string, status string) (*schema.AiOutputEvent, error)

func (*Emitter) EmitToolCallStd

func (r *Emitter) EmitToolCallStd(toolName string, stdOut, stdErr io.Reader, taskIndex string)

func (*Emitter) EmitToolCallSummary

func (r *Emitter) EmitToolCallSummary(callToolId string, summary string) (*schema.AiOutputEvent, error)

func (*Emitter) EmitToolCallUserCancel

func (r *Emitter) EmitToolCallUserCancel(callToolId string) (*schema.AiOutputEvent, error)

func (*Emitter) EmitToolCallWatcher

func (r *Emitter) EmitToolCallWatcher(toolCallID string, id string, tool *aitool.Tool, params aitool.InvokeParams) (*schema.AiOutputEvent, error)

func (*Emitter) EmitWarning

func (e *Emitter) EmitWarning(fmtlog string, items ...any) (*schema.AiOutputEvent, error)

func (*Emitter) EmitWarningWithName

func (r *Emitter) EmitWarningWithName(name string, fmtlog string, items ...any) (*schema.AiOutputEvent, error)

func (*Emitter) EmitYakitExecResult

func (r *Emitter) EmitYakitExecResult(exec *ypb.ExecResult) (*schema.AiOutputEvent, error)

func (*Emitter) EmitYakitRisk

func (r *Emitter) EmitYakitRisk(id uint, title string) (*schema.AiOutputEvent, error)

func (*Emitter) EmitYaklangCodeStreamEvent

func (r *Emitter) EmitYaklangCodeStreamEvent(nodeId string, reader io.Reader, taskIndex string, finishCallback ...func()) (*schema.AiOutputEvent, error)

func (*Emitter) PopEventProcesser

func (i *Emitter) PopEventProcesser() *Emitter

func (*Emitter) PushEventProcesser

func (i *Emitter) PushEventProcesser(newHandler EventProcesser) *Emitter

func (*Emitter) SetInteractiveEventSaver

func (r *Emitter) SetInteractiveEventSaver(saver func(string, *schema.AiOutputEvent))

func (*Emitter) StoreInteractiveEvent

func (i *Emitter) StoreInteractiveEvent(id string, e *schema.AiOutputEvent)

func (*Emitter) WaitForStream

func (i *Emitter) WaitForStream()

type Endpoint

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

func (*Endpoint) ActiveWithParams

func (e *Endpoint) ActiveWithParams(ctx context.Context, params aitool.InvokeParams)

func (*Endpoint) GetCheckpoint

func (e *Endpoint) GetCheckpoint() *schema.AiCheckpoint

func (*Endpoint) GetId

func (e *Endpoint) GetId() string

func (*Endpoint) GetParams

func (e *Endpoint) GetParams() aitool.InvokeParams

修改后的 GetParams 方法,添加锁保护

func (*Endpoint) GetReviewMaterials

func (e *Endpoint) GetReviewMaterials() aitool.InvokeParams

func (*Endpoint) GetSeq

func (e *Endpoint) GetSeq() int64

func (*Endpoint) Release

func (e *Endpoint) Release()

func (Endpoint) ReleaseContext

func (e Endpoint) ReleaseContext(ctx context.Context)

func (*Endpoint) SetDefaultSuggestion

func (e *Endpoint) SetDefaultSuggestion(suggestion string)

func (*Endpoint) SetDefaultSuggestionContinue

func (e *Endpoint) SetDefaultSuggestionContinue()

func (*Endpoint) SetDefaultSuggestionEnd

func (e *Endpoint) SetDefaultSuggestionEnd()

func (*Endpoint) SetDefaultSuggestionNo

func (e *Endpoint) SetDefaultSuggestionNo()

func (*Endpoint) SetDefaultSuggestionYes

func (e *Endpoint) SetDefaultSuggestionYes()

func (*Endpoint) SetParams

func (e *Endpoint) SetParams(params aitool.InvokeParams)

func (*Endpoint) SetReviewMaterials

func (e *Endpoint) SetReviewMaterials(
	params aitool.InvokeParams)

func (*Endpoint) Wait

func (e *Endpoint) Wait()

func (*Endpoint) WaitContext

func (e *Endpoint) WaitContext(ctx context.Context)

func (*Endpoint) WaitTimeout

func (e *Endpoint) WaitTimeout(timeout time.Duration) bool

新增的 WaitTimeout 方法

func (*Endpoint) WaitTimeoutSeconds

func (e *Endpoint) WaitTimeoutSeconds(i float64) bool

type EndpointManager

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

func NewEndpointManager

func NewEndpointManager() *EndpointManager

func NewEndpointManagerContext

func NewEndpointManagerContext(ctx context.Context) *EndpointManager

func (*EndpointManager) CreateEndpoint

func (e *EndpointManager) CreateEndpoint() *Endpoint

func (*EndpointManager) CreateEndpointWithEventType

func (e *EndpointManager) CreateEndpointWithEventType(typeName schema.EventType) *Endpoint

func (*EndpointManager) Feed

func (e *EndpointManager) Feed(id string, params aitool.InvokeParams)

func (*EndpointManager) GetConfig

func (e *EndpointManager) GetConfig() AICallerConfigIf

func (*EndpointManager) GetContext

func (e *EndpointManager) GetContext() context.Context

func (*EndpointManager) LoadEndpoint

func (e *EndpointManager) LoadEndpoint(id string) (*Endpoint, bool)

func (*EndpointManager) SetConfig

func (e *EndpointManager) SetConfig(config AICallerConfigIf)

type EndpointSignal

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

func NewEndpointSignal

func NewEndpointSignal() *EndpointSignal

func (*EndpointSignal) ActiveAsyncContext

func (s *EndpointSignal) ActiveAsyncContext(ctx context.Context)

func (*EndpointSignal) ActiveContext

func (s *EndpointSignal) ActiveContext(ctx context.Context)

func (*EndpointSignal) Wait

func (s *EndpointSignal) Wait()

func (*EndpointSignal) WaitContext

func (s *EndpointSignal) WaitContext(ctx context.Context) error

func (*EndpointSignal) WaitTimeout

func (s *EndpointSignal) WaitTimeout(sec time.Duration) error

type EnhanceKnowledge

type EnhanceKnowledge interface {
	GetContent() string
	GetSource() string
	GetScore() float64
	GetType() string
	GetTitle() string
	GetScoreMethod() string
	GetUUID() string
}

type EnhanceKnowledgeManager

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

func NewDifferentResultEKManager

func NewDifferentResultEKManager(token, okToken string) *EnhanceKnowledgeManager

func NewEnhanceKnowledgeManager

func NewEnhanceKnowledgeManager(knowledgeGetter func(ctx context.Context, emitter *Emitter, query string) (<-chan EnhanceKnowledge, error)) *EnhanceKnowledgeManager

func NewMockEKManagerAndToken

func NewMockEKManagerAndToken() (*EnhanceKnowledgeManager, string)

func (*EnhanceKnowledgeManager) AppendKnowledge

func (m *EnhanceKnowledgeManager) AppendKnowledge(taskID string, knowledge EnhanceKnowledge)

func (*EnhanceKnowledgeManager) DumpTaskAboutKnowledge

func (m *EnhanceKnowledgeManager) DumpTaskAboutKnowledge(taskID string) string

func (*EnhanceKnowledgeManager) DumpTaskAboutKnowledgeWithTop

func (m *EnhanceKnowledgeManager) DumpTaskAboutKnowledgeWithTop(taskID string, top int) string

func (*EnhanceKnowledgeManager) FetchKnowledge

func (m *EnhanceKnowledgeManager) FetchKnowledge(ctx context.Context, query string) (<-chan EnhanceKnowledge, error)

func (*EnhanceKnowledgeManager) GetKnowledgeByTaskID

func (m *EnhanceKnowledgeManager) GetKnowledgeByTaskID(taskID string) []EnhanceKnowledge

func (*EnhanceKnowledgeManager) SetEmitter

func (m *EnhanceKnowledgeManager) SetEmitter(emitter *Emitter)

func (*EnhanceKnowledgeManager) SetKnowledgeUseless

func (m *EnhanceKnowledgeManager) SetKnowledgeUseless(taskID, uuid string)

func (*EnhanceKnowledgeManager) UnsetKnowledge

func (m *EnhanceKnowledgeManager) UnsetKnowledge(taskID, uuid string)

type EventProcesser

type EventProcesser func(e *schema.AiOutputEvent) *schema.AiOutputEvent

type FieldStreamItem

type FieldStreamItem struct {
	FieldName []string
	Handler   func(key string, reader io.Reader)
}

type ForgeQueryConfig

type ForgeQueryConfig struct {
	Filter *ypb.AIForgeFilter
	Paging *ypb.Paging
}

func NewForgeQueryConfig

func NewForgeQueryConfig(opts ...ForgeQueryOption) *ForgeQueryConfig

type ForgeQueryOption

type ForgeQueryOption func(config *ForgeQueryConfig)

func WithForgeFilter_Keyword

func WithForgeFilter_Keyword(keyword string) ForgeQueryOption

WithForgeFilter_Keyword 设置关键词搜索

func WithForgeFilter_Limit

func WithForgeFilter_Limit(limit int) ForgeQueryOption

WithForgeFilter_Limit 设置返回条数限制

func WithForgeQueryFilter

func WithForgeQueryFilter(filter *ypb.AIForgeFilter) ForgeQueryOption

func WithForgeQueryPaging

func WithForgeQueryPaging(paging *ypb.Paging) ForgeQueryOption

type GeneralKVConfig

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

func NewGeneralKVConfig

func NewGeneralKVConfig(opts ...GeneralKVConfigOption) *GeneralKVConfig

func (*GeneralKVConfig) GetStreamableFields

func (g *GeneralKVConfig) GetStreamableFields() []interface {
	AINodeId() string
	FieldKey() string
}

type GeneralKVConfigOption

type GeneralKVConfigOption func(*GeneralKVConfig)

func WithGeneralConfigStreamableField

func WithGeneralConfigStreamableField(fieldKey string) GeneralKVConfigOption

func WithGeneralConfigStreamableFieldWithNodeId

func WithGeneralConfigStreamableFieldWithNodeId(nodeId string, fieldKey string) GeneralKVConfigOption

type GuardianEmitter

type GuardianEmitter interface {
	EmitStatus(key string, value any) (*schema.AiOutputEvent, error)
	EmitStructured(nodeId string, result any) (*schema.AiOutputEvent, error)
	EmitGuardianStreamEvent(nodeId string, startTime time.Time, reader io.Reader) (*schema.AiOutputEvent, error)
	EmitJson(typeName schema.EventType, nodeId string, i any) (*schema.AiOutputEvent, error)
	WaitForStream()
}

GuardianEmitter defines the interface for emitting events in the Guardian system. it provides some restricted methods for emitting events based on an ordinary Emitter

type GuardianEventTrigger

type GuardianEventTrigger func(event *schema.AiOutputEvent, emitter GuardianEmitter, aicaller AICaller)

GuardianEventTrigger defines a function type for handling AI output events in the Guardian system.

type GuardianMirrorStreamTrigger

type GuardianMirrorStreamTrigger func(unlimitedChan *chanx.UnlimitedChan[*schema.AiOutputEvent], emitter GuardianEmitter)

GuardianMirrorStreamTrigger defines a function type for triggering a mirror stream in the Guardian system.

type HandleToolUseNext

type HandleToolUseNext string
const (
	HandleToolUseNext_Override       HandleToolUseNext = "override"
	HandleToolUseNext_DirectlyAnswer HandleToolUseNext = "directly-answer"
	HandleToolUseNext_Default        HandleToolUseNext = ""
)

type ImageData

type ImageData struct {
	Data     []byte
	IsBase64 bool
}

type Interactivable

type Interactivable interface {
	// wait and review
	Feed(endpointId string, params aitool.InvokeParams)
	GetEndpointManager() *EndpointManager
	DoWaitAgree(ctx context.Context, endpoint *Endpoint)
	CallAfterInteractiveEventReleased(string, aitool.InvokeParams)
	CallAfterReview(seq int64, reviewQuestion string, userInput aitool.InvokeParams)
}

type KeyValueConfig

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

func NewKeyValueConfig

func NewKeyValueConfig() *KeyValueConfig

func (*KeyValueConfig) GetConfig

func (r *KeyValueConfig) GetConfig(key string) (any, bool)

func (*KeyValueConfig) GetConfigBool

func (r *KeyValueConfig) GetConfigBool(key string, defaults ...bool) bool

func (*KeyValueConfig) GetConfigFloat64

func (r *KeyValueConfig) GetConfigFloat64(key string, defaults ...float64) float64

func (*KeyValueConfig) GetConfigInt

func (r *KeyValueConfig) GetConfigInt(key string, defaults ...int) int

func (*KeyValueConfig) GetConfigInt64

func (r *KeyValueConfig) GetConfigInt64(key string, defaults ...int64) int64

func (*KeyValueConfig) GetConfigString

func (r *KeyValueConfig) GetConfigString(key string, defaults ...string) string

func (*KeyValueConfig) HaveConfig

func (r *KeyValueConfig) HaveConfig(key string) bool

func (*KeyValueConfig) SetConfig

func (r *KeyValueConfig) SetConfig(key string, value any)

type KeyValueConfigIf

type KeyValueConfigIf interface {
	HaveConfig(string) bool
	GetConfig(string) (any, bool)
	GetConfigString(string, ...string) string
	GetConfigInt(string, ...int) int
	GetConfigInt64(string, ...int64) int64
	GetConfigFloat64(string, ...float64) float64
	GetConfigBool(string, ...bool) bool
	SetConfig(string, any)
}

type KnowledgeCollection

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

func NewKnowledgeCollection

func NewKnowledgeCollection() *KnowledgeCollection

func (*KnowledgeCollection) Append

func (kc *KnowledgeCollection) Append(knowledge EnhanceKnowledge)

func (*KnowledgeCollection) GetKnowledgeList

func (kc *KnowledgeCollection) GetKnowledgeList() []EnhanceKnowledge

func (*KnowledgeCollection) SetUseless

func (kc *KnowledgeCollection) SetUseless(uuid string)

func (*KnowledgeCollection) UnsetUseless

func (kc *KnowledgeCollection) UnsetUseless(uuid string)

type LazyEnhanceKnowledge

type LazyEnhanceKnowledge struct {
	BasicEnhanceKnowledge
	ContentLoader func() string
}

func (*LazyEnhanceKnowledge) GetContent

func (e *LazyEnhanceKnowledge) GetContent() string

type MemoryEntity

type MemoryEntity struct {
	Id        string
	CreatedAt time.Time
	// 尽量保留原文,适当增加一点点内容的 Content,不准超过1000字,作为记忆来说可用
	Content string
	Tags    []string // 已有 TAG,

	// 7 dims - C.O.R.E. P.A.C.T. Framework (all normalized to 0.0-1.0)
	C_Score float64 // Connectivity Score 这个记忆与其他记忆如何关联?这是一个一次性事实,几乎与其他事实没有什么关联程度
	O_Score float64 // Origin Score 记忆与信息来源确定性,这个来源从哪里来?到底有多少可信度?
	R_Score float64 // Relevance Score 这个信息对用户的目的有多关键?无关紧要?锦上添花?还是成败在此一举?
	E_Score float64 // Emotion Score 用户在表达这个信息时的情绪如何?越低越消极,消极评分时一般伴随信息源不可信
	P_Score float64 // Preference Score 个人偏好对齐评分,这个行为或者问题是否绑定了用户个人风格,品味?
	A_Score float64 // Actionability Score 可操作性评分,是否可以从学习中改进未来行为?
	T_Score float64 // Temporality Score 时效评分,核心问题:这个记忆应该如何被保留?配合时间搜索

	CorePactVector []float32

	// designed for rag searching
	PotentialQuestions []string
}

MemoryEntity 表示一个记忆条目

func (*MemoryEntity) String

func (r *MemoryEntity) String() string

type MemoryTriage

type MemoryTriage interface {
	// SetInvoker 设置AI调用运行时
	SetInvoker(invoker AIInvokeRuntime)

	// AddRawText 添加原始文本,返回提取的记忆实体
	AddRawText(text string) ([]*MemoryEntity, error)

	// SaveMemoryEntities 保存记忆条目到数据库
	SaveMemoryEntities(entities ...*MemoryEntity) error

	SearchBySemantics(query string, limit int) ([]*SearchResult, error)

	SearchByTags(tags []string, matchAll bool, limit int) ([]*MemoryEntity, error)

	// HandleMemory 智能处理输入内容,自动构造记忆、去重并保存
	HandleMemory(i any) error

	// SearchMemory 根据输入内容搜索相关记忆,限制总内容字节数
	SearchMemory(origin any, bytesLimit int) (*SearchMemoryResult, error)

	// SearchMemoryWithoutAI 不使用AI的关键词搜索,直接基于关键词匹配
	SearchMemoryWithoutAI(origin any, bytesLimit int) (*SearchMemoryResult, error)

	Close() error

	GetSessionID() string
}

type ProxyAICaller

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

func CreateProxyAICaller

func CreateProxyAICaller(
	caller AICaller,
	proxyFunc func(request *AIRequest) *AIRequest,
) *ProxyAICaller

func (ProxyAICaller) CallAI

func (p ProxyAICaller) CallAI(request *AIRequest) (*AIResponse, error)

type ReActLoopIF

type ReActLoopIF interface {
	// Core execution methods
	Execute(taskId string, ctx context.Context, userInput string) error
	ExecuteWithExistedTask(task AIStatefulTask) error

	// Task management
	GetCurrentTask() AIStatefulTask
	SetCurrentTask(t AIStatefulTask)

	// Configuration and context
	GetInvoker() AIInvokeRuntime
	GetEmitter() *Emitter
	GetConfig() AICallerConfigIf
	GetMemoryTriage() MemoryTriage
	GetEnableSelfReflection() bool

	// Variable management
	Set(key string, value any)
	Get(key string) string
	GetVariable(key string) any
	GetStringSlice(key string) []string
	GetInt(key string) int

	// Action management
	RemoveAction(actionType string)
	GetAllActionNames() []string
	NoActions() bool

	// Memory management
	PushMemory(result *SearchMemoryResult)
	GetCurrentMemoriesContent() string

	// User interaction control
	DisallowAskForClarification()
}

ReActLoopIF defines the interface for ReAct Loop operations Note: Some methods return interface{} to avoid circular dependencies with reactloops package

type RiskControl

type RiskControl func(ctx context.Context, config *Config, ep *Endpoint) (*Action, error)

type ScoreFilter

type ScoreFilter struct {
	C_Min, C_Max float64
	O_Min, O_Max float64
	R_Min, R_Max float64
	E_Min, E_Max float64
	P_Min, P_Max float64
	A_Min, A_Max float64
	T_Min, T_Max float64
}

ScoreFilter 评分过滤器,用于按C.O.R.E. P.A.C.T.评分搜索

type SearchMemoryResult

type SearchMemoryResult struct {
	Memories      []*MemoryEntity `json:"memories"`
	TotalContent  string          `json:"total_content"`
	ContentBytes  int             `json:"content_bytes"`
	SearchSummary string          `json:"search_summary"`
}

SearchMemoryResult 搜索记忆的结果

type SearchResult

type SearchResult struct {
	Entity *MemoryEntity
	Score  float64
}

SearchResult 搜索结果

type TextTimelineItem

type TextTimelineItem struct {
	ID                  int64  `json:"id"`
	Text                string `json:"text"`
	ShrinkResult        string `json:"shrink_result,omitempty"`
	ShrinkSimilarResult string `json:"shrink_similar_result,omitempty"`
}

func (*TextTimelineItem) GetID

func (t *TextTimelineItem) GetID() int64

func (*TextTimelineItem) GetShrinkResult

func (t *TextTimelineItem) GetShrinkResult() string

func (*TextTimelineItem) GetShrinkSimilarResult

func (t *TextTimelineItem) GetShrinkSimilarResult() string

func (*TextTimelineItem) SetShrinkResult

func (t *TextTimelineItem) SetShrinkResult(s string)

func (*TextTimelineItem) String

func (t *TextTimelineItem) String() string

type Timeline

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

func NewTimeline

func NewTimeline(ai AICaller, extraMetaInfo func() string) *Timeline

func UnmarshalTimeline

func UnmarshalTimeline(s string) (*Timeline, error)

func (*Timeline) BindConfig

func (m *Timeline) BindConfig(config AICallerConfigIf, aiCaller AICaller)

func (*Timeline) ClearRuntimeConfig

func (m *Timeline) ClearRuntimeConfig()

func (*Timeline) CopyReducibleTimelineWithMemory

func (m *Timeline) CopyReducibleTimelineWithMemory() *Timeline

func (*Timeline) CreateSubTimeline

func (m *Timeline) CreateSubTimeline(ids ...int64) *Timeline

func (*Timeline) Dump

func (m *Timeline) Dump() string

func (*Timeline) DumpBefore

func (m *Timeline) DumpBefore(beforeId int64) string

func (*Timeline) ExtraMetaInfo

func (m *Timeline) ExtraMetaInfo() string

func (*Timeline) GetAICaller

func (m *Timeline) GetAICaller() AICaller

func (*Timeline) GetIdToTimelineItem

func (m *Timeline) GetIdToTimelineItem() *omap.OrderedMap[int64, *TimelineItem]

func (*Timeline) GetTimelineItemIDs

func (m *Timeline) GetTimelineItemIDs() []int64

func (*Timeline) GetTimelineOutput

func (m *Timeline) GetTimelineOutput() []*TimelineItemOutput

func (*Timeline) PromptForToolCallResultsForLastN

func (m *Timeline) PromptForToolCallResultsForLastN(n int) string

func (*Timeline) PushText

func (m *Timeline) PushText(id int64, fmtText string, items ...any)

func (*Timeline) PushToolResult

func (m *Timeline) PushToolResult(toolResult *aitool.ToolResult)

func (*Timeline) PushUserInteraction

func (m *Timeline) PushUserInteraction(stage UserInteractionStage, id int64, systemPrompt string, userExtraPrompt string)

func (*Timeline) ReassignIDs

func (m *Timeline) ReassignIDs(idGenerator func() int64) int64

ReassignIDs reassigns sequential IDs to all timeline items starting from the given startID This is used when restoring from persistent session to avoid ID conflicts Returns the next available ID after reassignment

func (*Timeline) Save

func (m *Timeline) Save(db *gorm.DB, persistentId string)

func (*Timeline) SetAICaller

func (m *Timeline) SetAICaller(ai AICaller)

func (*Timeline) SetTimelineContentLimit

func (m *Timeline) SetTimelineContentLimit(contentSize int64)

func (*Timeline) SoftDelete

func (m *Timeline) SoftDelete(id ...int64)

func (*Timeline) String

func (m *Timeline) String() string

func (*Timeline) ToTimelineItemOutputLastN

func (m *Timeline) ToTimelineItemOutputLastN(n int) []*TimelineItemOutput

func (*Timeline) Valid

func (m *Timeline) Valid() bool

type TimelineDiffer

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

TimelineDiffer 用于计算 Timeline 的差异 每次 Diff 都会保存上一次的内容,下次 Diff 的结果是和上一次的对比

func NewTimelineDiffer

func NewTimelineDiffer(timeline *Timeline) *TimelineDiffer

NewTimelineDiffer 创建一个新的 TimelineDiffer 实例

func (*TimelineDiffer) Diff

func (d *TimelineDiffer) Diff() (string, error)

Diff 计算当前 Timeline 和上一次状态的差异 返回差异描述字符串,描述了 Timeline 的变化增量 第一次调用时返回当前 Timeline 和空状态的对比(即完整的当前状态) 调用后自动更新基准状态为当前状态

func (*TimelineDiffer) GetCurrentDump

func (d *TimelineDiffer) GetCurrentDump() string

GetCurrentDump 获取当前 Timeline 的转储内容(不更新状态)

func (*TimelineDiffer) GetLastDump

func (d *TimelineDiffer) GetLastDump() string

GetLastDump 获取上一次保存的 Timeline 转储内容

func (*TimelineDiffer) Reset

func (d *TimelineDiffer) Reset()

Reset 重置差异计算器,清空上一次的状态 下次调用 Diff() 将返回当前状态和空状态的对比

func (*TimelineDiffer) SetBaseline

func (d *TimelineDiffer) SetBaseline()

SetBaseline 手动设置基准状态为当前 Timeline 的状态 下次调用 Diff() 将返回当前状态和此基准状态的对比

type TimelineItem

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

func (*TimelineItem) GetID

func (item *TimelineItem) GetID() int64

func (*TimelineItem) GetShrinkResult

func (item *TimelineItem) GetShrinkResult() string

func (*TimelineItem) GetShrinkSimilarResult

func (item *TimelineItem) GetShrinkSimilarResult() string

func (*TimelineItem) GetValue

func (item *TimelineItem) GetValue() TimelineItemValue

func (*TimelineItem) IsDeleted

func (item *TimelineItem) IsDeleted() bool

func (*TimelineItem) MarshalJSON

func (item *TimelineItem) MarshalJSON() ([]byte, error)

MarshalJSON 实现自定义 JSON 序列化

func (*TimelineItem) SetShrinkResult

func (item *TimelineItem) SetShrinkResult(pers string)

func (*TimelineItem) String

func (item *TimelineItem) String() string

func (*TimelineItem) ToTimelineItemOutput

func (item *TimelineItem) ToTimelineItemOutput() *TimelineItemOutput

func (*TimelineItem) UnmarshalJSON

func (item *TimelineItem) UnmarshalJSON(data []byte) error

UnmarshalJSON 实现自定义 JSON 反序列化

type TimelineItemOutput

type TimelineItemOutput struct {
	Timestamp time.Time `json:"timestamp"`
	Type      string    `json:"type"` // "input", "thought", "action", "observation", "result"
	Content   string    `json:"content"`
}

TimelineEntry 时间线条目

func (*TimelineItemOutput) String

func (m *TimelineItemOutput) String() string

type TimelineItemValue

type TimelineItemValue interface {
	String() string
	GetID() int64
	GetShrinkResult() string
	GetShrinkSimilarResult() string
	SetShrinkResult(string)
}

type ToolCaller

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

func NewToolCaller

func NewToolCaller(ctx context.Context, opts ...ToolCallerOption) (*ToolCaller, error)

func (*ToolCaller) CallTool

func (t *ToolCaller) CallTool(tool *aitool.Tool) (result *aitool.ToolResult, directlyAnswer bool, err error)

func (*ToolCaller) CallToolWithExistedParams

func (t *ToolCaller) CallToolWithExistedParams(tool *aitool.Tool, presetParams bool, presetInvokeParams aitool.InvokeParams) (result *aitool.ToolResult, directlyAnswer bool, err error)

func (*ToolCaller) GetEmitter

func (t *ToolCaller) GetEmitter() *Emitter

func (*ToolCaller) GetParamGeneratingPrompt

func (t *ToolCaller) GetParamGeneratingPrompt(tool *aitool.Tool, toolName string) (string, error)

func (*ToolCaller) SetEmitter

func (t *ToolCaller) SetEmitter(e *Emitter)

type ToolCallerOption

type ToolCallerOption func(tc *ToolCaller)

func WithToolCaller_AICaller

func WithToolCaller_AICaller(ai AICaller) ToolCallerOption

func WithToolCaller_AICallerConfig

func WithToolCaller_AICallerConfig(config AICallerConfigIf) ToolCallerOption

func WithToolCaller_CallToolID

func WithToolCaller_CallToolID(callToolId string) ToolCallerOption

func WithToolCaller_Emitter

func WithToolCaller_Emitter(e *Emitter) ToolCallerOption

func WithToolCaller_GenerateToolParamsBuilder

func WithToolCaller_GenerateToolParamsBuilder(
	builder func(tool *aitool.Tool, toolName string) (string, error),
) ToolCallerOption

func WithToolCaller_OnEnd

func WithToolCaller_OnEnd(i func(callToolId string)) ToolCallerOption

func WithToolCaller_OnStart

func WithToolCaller_OnStart(i func(callToolId string)) ToolCallerOption

func WithToolCaller_ReviewWrongParam

func WithToolCaller_ReviewWrongParam(
	handler func(ctx context.Context, tool *aitool.Tool, oldParam aitool.InvokeParams, suggestion string) (aitool.InvokeParams, error),
) ToolCallerOption

func WithToolCaller_ReviewWrongTool

func WithToolCaller_ReviewWrongTool(
	handler func(ctx context.Context, tool *aitool.Tool, newToolName, keyword string) (*aitool.Tool, bool, error),
) ToolCallerOption

func WithToolCaller_RuntimeId

func WithToolCaller_RuntimeId(runtimeId string) ToolCallerOption

func WithToolCaller_Task

func WithToolCaller_Task(task AITask) ToolCallerOption

type ToolUseReviewSuggestion

type ToolUseReviewSuggestion struct {
	Value                   string `json:"value"`
	Prompt                  string `json:"prompt"`
	PromptEnglish           string `json:"prompt_english"`
	AllowExtraPrompt        bool   `json:"allow_extra_prompt"`
	AllowParamsModification bool   `json:"allow_params_modification"`
}

type UserInteraction

type UserInteraction struct {
	ID              int64                `json:"id"`
	SystemPrompt    string               `json:"prompt"`
	UserExtraPrompt string               `json:"extra_prompt"`
	Stage           UserInteractionStage `json:"stage"` // Stage
	ShrinkResult    string               `json:"shrink_result,omitempty"`
}

func (*UserInteraction) GetID

func (u *UserInteraction) GetID() int64

func (*UserInteraction) GetShrinkResult

func (u *UserInteraction) GetShrinkResult() string

func (*UserInteraction) GetShrinkSimilarResult

func (u *UserInteraction) GetShrinkSimilarResult() string

func (*UserInteraction) SetShrinkResult

func (u *UserInteraction) SetShrinkResult(s string)

func (*UserInteraction) String

func (u *UserInteraction) String() string

type UserInteractionStage

type UserInteractionStage string
const (
	UserInteractionStage_BeforePlan UserInteractionStage = "before_plan"
	UserInteractionStage_Review     UserInteractionStage = "review"
	UserInteractionStage_FreeInput  UserInteractionStage = "free_input"
)

type WaitableAction

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

func NewWaitableAction

func NewWaitableAction(ctx context.Context, name string) *WaitableAction

func (*WaitableAction) Name

func (w *WaitableAction) Name() string

func (*WaitableAction) Set

func (w *WaitableAction) Set(key string, value interface{})

func (*WaitableAction) SetName

func (w *WaitableAction) SetName(i string)

func (*WaitableAction) WaitAnyToString

func (w *WaitableAction) WaitAnyToString(key string) string

func (*WaitableAction) WaitBool

func (w *WaitableAction) WaitBool(key string) bool

func (*WaitableAction) WaitFloat

func (w *WaitableAction) WaitFloat(key string) float64

func (*WaitableAction) WaitInt

func (w *WaitableAction) WaitInt(key string) int64

func (*WaitableAction) WaitObject

func (w *WaitableAction) WaitObject(key string) aitool.InvokeParams

func (*WaitableAction) WaitObjectArray

func (w *WaitableAction) WaitObjectArray(key string) []aitool.InvokeParams

func (*WaitableAction) WaitString

func (w *WaitableAction) WaitString(key string) string

func (*WaitableAction) WaitStringSlice

func (w *WaitableAction) WaitStringSlice(key string) []string

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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