Documentation
¶
Overview ¶
Package agentkit provides a small, event-stream-driven runtime for building tool-using agents on CloudWeGo Eino ADK.
An Agent can run text or multimodal prompts, expose Eino-compatible tools, persist sessions, compact long contexts, load reusable skills, and manage MCP connections. Prompt, Send, Continue, and Resume block until a run completes and are mutually exclusive for each Agent. Subscribe delivers ordered, synchronous event snapshots for streaming output and lifecycle observation.
Call Close when an Agent is no longer needed. Use Cancel for non-blocking cancellation from an event subscriber, or Abort outside a subscriber when the caller must wait for the active run to finish.
Index ¶
- Constants
- Variables
- func EmitToolUpdate(ctx context.Context, content string)
- func GetInterruptState[T any](ctx context.Context) (wasInterrupted bool, hasState bool, state T)
- func GetResumeContext[T any](ctx context.Context) (isResumeTarget bool, hasData bool, data T)
- func GoalOperationKey(ctx context.Context, operation string) (string, bool)
- func Interrupt(ctx context.Context, info any) error
- func RunValue[T any](ctx context.Context, key string) (T, bool)
- func RunValues(ctx context.Context) map[string]any
- func SetRunValue(ctx context.Context, key string, value any)
- func StatefulInterrupt(ctx context.Context, info any, state any) error
- func WithRunConfig(ctx context.Context, config RunConfig) context.Context
- type Agent
- func (a *Agent) Abort()
- func (a *Agent) AbortContext(ctx context.Context) error
- func (a *Agent) Ask(ctx context.Context, input string) (*RunResult, error)
- func (a *Agent) AskParts(ctx context.Context, parts ...ContentPart) (*RunResult, error)
- func (a *Agent) Cancel()
- func (a *Agent) ClearAllQueues()
- func (a *Agent) ClearCheckpoint(ctx context.Context) error
- func (a *Agent) ClearFollowUpQueue()
- func (a *Agent) ClearSteeringQueue()
- func (a *Agent) Close() error
- func (a *Agent) CloseContext(ctx context.Context) error
- func (a *Agent) ContextHistory() []*schema.Message
- func (a *Agent) Continue(ctx context.Context) error
- func (a *Agent) ContinueWithResult(ctx context.Context) (*RunResult, error)
- func (a *Agent) FollowUp(content string)
- func (a *Agent) History() []*schema.Message
- func (a *Agent) Name() string
- func (a *Agent) PendingInterrupts() []InterruptPoint
- func (a *Agent) Prompt(ctx context.Context, input string) error
- func (a *Agent) Reset()
- func (a *Agent) Resume(ctx context.Context, targets map[string]any) error
- func (a *Agent) ResumeWithResult(ctx context.Context, targets map[string]any) (*RunResult, error)
- func (a *Agent) SaveSession(ctx context.Context) error
- func (a *Agent) Send(ctx context.Context, parts ...ContentPart) error
- func (a *Agent) Session() *Session
- func (a *Agent) SetFollowUpMode(mode QueueMode)
- func (a *Agent) SetHistory(history []*schema.Message)
- func (a *Agent) SetSteeringMode(mode QueueMode)
- func (a *Agent) State() *State
- func (a *Agent) Steer(content string)
- func (a *Agent) Stream(ctx context.Context, input string) (*RunStream, error)
- func (a *Agent) StreamParts(ctx context.Context, parts ...ContentPart) (*RunStream, error)
- func (a *Agent) Subscribe(fn Subscriber) func()
- func (a *Agent) ToolResultStore() ToolResultStore
- type BaseChatModelAgentMiddleware
- type ChatModel
- type ChatModelAgentMiddleware
- type CheckpointDeleter
- type CheckpointStore
- type CheckpointStoreProvider
- type CompactionConfig
- type CompactionInfo
- type Config
- type ContentPart
- func AudioBase64(data, mimeType string) ContentPart
- func AudioURL(url string) ContentPart
- func FileBase64(data, mimeType string, name ...string) ContentPart
- func FileURL(url string) ContentPart
- func ImageBase64(data, mimeType string, detail ...ImageURLDetail) ContentPart
- func ImageURL(url string, detail ...ImageURLDetail) ContentPart
- func Text(s string) ContentPart
- func VideoBase64(data, mimeType string) ContentPart
- func VideoURL(url string) ContentPart
- type EnhancedInvokableToolEndpoint
- type EnhancedInvokableToolMiddleware
- type EnhancedInvokableToolOutput
- type EnhancedStreamableToolEndpoint
- type EnhancedStreamableToolMiddleware
- type EnhancedStreamableToolOutput
- type Event
- type EventType
- type FileCheckpointStore
- type FileGoalStore
- func (s *FileGoalStore) AcquireGoalLease(ctx context.Context, goalID, workerID string, duration time.Duration) (*GoalLease, error)
- func (s *FileGoalStore) Delete(ctx context.Context, id string) error
- func (s *FileGoalStore) DeleteGoalWithLease(ctx context.Context, goalID string, lease *GoalLease) error
- func (s *FileGoalStore) List(ctx context.Context) ([]GoalInfo, error)
- func (s *FileGoalStore) Load(ctx context.Context, id string) (*Goal, error)
- func (s *FileGoalStore) ReleaseGoalLease(ctx context.Context, lease *GoalLease) error
- func (s *FileGoalStore) RenewGoalLease(ctx context.Context, lease *GoalLease, duration time.Duration) (*GoalLease, error)
- func (s *FileGoalStore) Save(ctx context.Context, goal *Goal) error
- func (s *FileGoalStore) SaveGoalWithLease(ctx context.Context, goal *Goal, lease *GoalLease) error
- type FileSessionStore
- func (s *FileSessionStore) CheckpointStore() CheckpointStore
- func (s *FileSessionStore) Delete(ctx context.Context, id string) error
- func (s *FileSessionStore) GoalStore() GoalStore
- func (s *FileSessionStore) List(ctx context.Context) ([]SessionInfo, error)
- func (s *FileSessionStore) Load(ctx context.Context, id string) (*Session, error)
- func (s *FileSessionStore) Save(ctx context.Context, session *Session) error
- func (s *FileSessionStore) ToolResultStore() ToolResultStore
- type FileSkillBackend
- type FileToolResultStore
- func (s *FileToolResultStore) Delete(ctx context.Context, id string) error
- func (s *FileToolResultStore) List(ctx context.Context) ([]ToolResultInfo, error)
- func (s *FileToolResultStore) Load(ctx context.Context, id string) (*StoredToolResult, error)
- func (s *FileToolResultStore) Save(ctx context.Context, result *StoredToolResult) error
- type Goal
- type GoalDecision
- type GoalEvaluation
- type GoalEvaluator
- type GoalEvaluatorFunc
- type GoalInfo
- type GoalLease
- type GoalLeaseHeldError
- type GoalLeaseStore
- type GoalRequest
- type GoalRun
- type GoalRunInfo
- type GoalRunResult
- type GoalRunner
- func (r *GoalRunner) Clear(ctx context.Context, id string) (retErr error)
- func (r *GoalRunner) Get(ctx context.Context, id string) (*Goal, error)
- func (r *GoalRunner) List(ctx context.Context) ([]GoalInfo, error)
- func (r *GoalRunner) Pause(ctx context.Context, id string) (retErr error)
- func (r *GoalRunner) Resume(ctx context.Context, id string) (out *GoalRunResult, retErr error)
- func (r *GoalRunner) ResumeAsync(ctx context.Context, id string) (*GoalRun, error)
- func (r *GoalRunner) ResumeInterrupt(ctx context.Context, id string, targets map[string]any) (out *GoalRunResult, retErr error)
- func (r *GoalRunner) ResumeInterruptAsync(ctx context.Context, id string, targets map[string]any) (*GoalRun, error)
- func (r *GoalRunner) ResumePending(ctx context.Context) (*GoalRunResult, error)
- func (r *GoalRunner) ResumePendingAsync(ctx context.Context) (*GoalRun, error)
- func (r *GoalRunner) Retry(ctx context.Context, id string) (out *GoalRunResult, retErr error)
- func (r *GoalRunner) RetryAsync(ctx context.Context, id string) (*GoalRun, error)
- func (r *GoalRunner) Start(ctx context.Context, request GoalRequest) (out *GoalRunResult, retErr error)
- func (r *GoalRunner) StartAsync(ctx context.Context, request GoalRequest) (*GoalRun, error)
- type GoalRunnerConfig
- type GoalStatus
- type GoalStore
- type GoalStoreProvider
- type ImageURLDetail
- type InterruptPoint
- type InvokableToolEndpoint
- type InvokableToolMiddleware
- type MCPClientSession
- type MCPConfig
- type MCPServerConfig
- type MCPTransport
- type MemoryCheckpointStore
- type MemoryGoalStore
- func (s *MemoryGoalStore) AcquireGoalLease(ctx context.Context, goalID, workerID string, duration time.Duration) (*GoalLease, error)
- func (s *MemoryGoalStore) Delete(ctx context.Context, id string) error
- func (s *MemoryGoalStore) DeleteGoalWithLease(ctx context.Context, goalID string, lease *GoalLease) error
- func (s *MemoryGoalStore) List(ctx context.Context) ([]GoalInfo, error)
- func (s *MemoryGoalStore) Load(ctx context.Context, id string) (*Goal, error)
- func (s *MemoryGoalStore) ReleaseGoalLease(ctx context.Context, lease *GoalLease) error
- func (s *MemoryGoalStore) RenewGoalLease(ctx context.Context, lease *GoalLease, duration time.Duration) (*GoalLease, error)
- func (s *MemoryGoalStore) Save(ctx context.Context, goal *Goal) error
- func (s *MemoryGoalStore) SaveGoalWithLease(ctx context.Context, goal *Goal, lease *GoalLease) error
- type MemorySessionStore
- func (s *MemorySessionStore) CheckpointStore() CheckpointStore
- func (s *MemorySessionStore) Delete(ctx context.Context, id string) error
- func (s *MemorySessionStore) GoalStore() GoalStore
- func (s *MemorySessionStore) List(ctx context.Context) ([]SessionInfo, error)
- func (s *MemorySessionStore) Load(ctx context.Context, id string) (*Session, error)
- func (s *MemorySessionStore) Save(ctx context.Context, session *Session) error
- func (s *MemorySessionStore) ToolResultStore() ToolResultStore
- type MemorySkillBackend
- type MemoryToolResultStore
- func (s *MemoryToolResultStore) Delete(ctx context.Context, id string) error
- func (s *MemoryToolResultStore) List(ctx context.Context) ([]ToolResultInfo, error)
- func (s *MemoryToolResultStore) Load(ctx context.Context, id string) (*StoredToolResult, error)
- func (s *MemoryToolResultStore) Save(ctx context.Context, result *StoredToolResult) error
- type Message
- type MockChatModel
- func (m *MockChatModel) AddResponses(responses ...MockModelResponse)
- func (m *MockChatModel) Calls() []MockModelCall
- func (m *MockChatModel) Generate(ctx context.Context, input []*schema.Message, opts ...model.Option) (*schema.Message, error)
- func (m *MockChatModel) LastCall() (MockModelCall, bool)
- func (m *MockChatModel) RemainingResponses() int
- func (m *MockChatModel) Stream(ctx context.Context, input []*schema.Message, opts ...model.Option) (*schema.StreamReader[*schema.Message], error)
- type MockModelCall
- type MockModelExpectation
- type MockModelResponse
- func MockExpect(response MockModelResponse, expect MockModelExpectation) MockModelResponse
- func MockModelAfterToolResult(callID string, response MockModelResponse) MockModelResponse
- func MockModelAfterToolResults(response MockModelResponse, callIDs ...string) MockModelResponse
- func MockModelCalls(invocations ...MockToolCallProvider) MockModelResponse
- func MockModelCallsAfter(wait MockToolCallProvider, calls ...MockToolCallProvider) MockModelResponse
- func MockModelCallsAfterAll(wait []MockToolCallProvider, calls ...MockToolCallProvider) MockModelResponse
- func MockModelError(err error) MockModelResponse
- func MockModelMessage(message *schema.Message) MockModelResponse
- func MockModelReasoning(content, reasoning string) MockModelResponse
- func MockModelRespondsAfter[D any](call *MockToolInvocation[D], reply func(D) MockModelResponse) MockModelResponse
- func MockModelRespondsAfterToolResult(callID string, reply func(result string) MockModelResponse) MockModelResponse
- func MockModelRespondsAfterToolResultAs[D any](callID string, reply func(D) MockModelResponse) MockModelResponse
- func MockModelStream(chunks ...string) MockModelResponse
- func MockModelStreamError(err error, chunks ...string) MockModelResponse
- func MockModelText(content string) MockModelResponse
- func MockModelTextAfter[D any](call *MockToolInvocation[D], reply func(D) string) MockModelResponse
- func MockModelTextAfterAll(content string, calls ...MockToolCallProvider) MockModelResponse
- func MockModelTextAfterToolResult(callID string) MockModelResponse
- func MockModelToolCall(name, arguments string) MockModelResponse
- func MockModelToolCallWithID(id, name, arguments string) MockModelResponse
- func MockModelToolCalls(calls ...schema.ToolCall) MockModelResponse
- type MockTool
- type MockToolCallProvider
- type MockToolInvocation
- type MockToolProvider
- type ModelFailoverConfig
- type ModelGoalEvaluator
- type ModelOption
- type ModelRetryConfig
- type QueueMode
- type ResponseMeta
- type RetentionPolicy
- type RetentionReport
- type RoleType
- type RunConfig
- type RunResult
- type RunStream
- type Session
- type SessionConfig
- type SessionInfo
- type SessionStore
- type Skill
- type SkillBackend
- type SkillInfo
- type SkillsConfig
- type State
- type StoredToolResult
- type StreamToolOutput
- type StreamableToolEndpoint
- type StreamableToolMiddleware
- type Subscriber
- type TokenUsage
- type Tool
- type ToolAlias
- type ToolCall
- type ToolInput
- type ToolInvocation
- type ToolMiddleware
- type ToolOption
- type ToolOutcome
- type ToolOutput
- type ToolPolicy
- type ToolReductionConfig
- type ToolResultInfo
- type ToolResultStore
- type ToolResultStoreProvider
- type ToolSearchConfig
Constants ¶
const ( // DefaultMCPMaxResultChars 是单次 MCP 工具结果默认保留的最大字符数。 DefaultMCPMaxResultChars = 100_000 // DefaultMCPMaxDescriptionChars 是单个 MCP 工具描述默认保留的最大字符数。 DefaultMCPMaxDescriptionChars = 4_000 // DefaultMCPInitializationTimeout 是每个 MCP 服务器连接与工具发现的默认总时限。 DefaultMCPInitializationTimeout = 30 * time.Second )
const ( // ToolResultReadToolName 是启用工具结果压缩后自动注册的只读回取工具名。 ToolResultReadToolName = "read_tool_result" // DefaultToolReductionMaxResultBytes 是单个工具结果触发持久化卸载的默认字节数。 DefaultToolReductionMaxResultBytes = 50_000 // DefaultToolReductionMaxContextTokens 是清理旧工具轮次的默认上下文 token 阈值。 DefaultToolReductionMaxContextTokens int64 = 160_000 // DefaultToolReductionKeepRecentRounds 是清理时原样保留的最近工具调用轮数。 DefaultToolReductionKeepRecentRounds = 1 // DefaultToolResultReadMaxChars 是一次回取最多返回给模型的 Unicode 字符数。 DefaultToolResultReadMaxChars = 20_000 )
const DefaultCompactionMaxTokens = 100_000
DefaultCompactionMaxTokens 是未指定触发条件时使用的默认上下文 token 上限。
const DefaultGoalLeaseDuration = time.Minute
DefaultGoalLeaseDuration 是 GoalRunner 自动续期的默认 worker 租约时长。
const DefaultPersistenceTimeout = 30 * time.Second
DefaultPersistenceTimeout 是取消后的内部持久化收尾 context 默认时限。 自定义存储必须及时响应 context,时限才能按预期生效。
const DefaultToolResultMaxChars = 100_000
DefaultToolResultMaxChars 是工具文本结果的默认字符上限。
Variables ¶
var ( // ErrAgentClosed 表示 Agent 已关闭,不能再执行新的请求。 ErrAgentClosed = errors.New("agentkit: agent is closed") // ErrAgentRunning 表示 Agent 正在执行另一个请求。 ErrAgentRunning = errors.New("agent is already running") // ErrNoMessagesToContinue 表示 Agent 没有可继续执行的历史消息。 ErrNoMessagesToContinue = errors.New("no messages in state to continue from") // ErrCannotContinue 表示最后一条消息已由助手完成,不能继续执行。 ErrCannotContinue = errors.New("cannot continue from assistant message, last message must be user or tool result") // ErrResumeRequired 表示存在未处理的检查点,必须先 Resume 或 ClearCheckpoint。 ErrResumeRequired = errors.New("agentkit: pending checkpoint must be resumed or cleared before starting a new run") )
var ( // ErrGoalNotFound 表示目标存储中不存在指定目标。 ErrGoalNotFound = errors.New("agentkit: goal not found") // ErrGoalConflict 表示目标已被其他调用方更新,当前快照不能覆盖新状态。 ErrGoalConflict = errors.New("agentkit: goal revision conflict") )
var ( // ErrGoalLeaseHeld 表示目标正由另一个 worker 的有效租约持有。 ErrGoalLeaseHeld = errors.New("agentkit: goal lease is held") // ErrGoalLeaseLost 表示租约已过期、被接管或令牌不再匹配。 ErrGoalLeaseLost = errors.New("agentkit: goal lease is lost") )
var ( // ErrGoalExists 表示相同 ID 的目标已经存在,应改用 Resume。 ErrGoalExists = errors.New("agentkit: goal already exists") // ErrGoalRunning 表示 GoalRunner 正在运行另一个目标。 ErrGoalRunning = errors.New("agentkit: goal runner is already running") // ErrGoalBlocked 表示目标需要调用方处理后才能继续。 ErrGoalBlocked = errors.New("agentkit: goal is blocked") // ErrGoalInterruptRequired 表示目标正在等待 HITL 数据。 ErrGoalInterruptRequired = errors.New("agentkit: goal requires interrupt data") // ErrGoalRecoveryRequired 表示上次进程可能在未保存工具结果时退出,自动重试可能重复副作用。 ErrGoalRecoveryRequired = errors.New("agentkit: goal recovery requires an explicit retry") // ErrGoalResumeAmbiguous 表示当前会话有多个未完成目标,调用方必须明确指定目标 ID。 ErrGoalResumeAmbiguous = errors.New("agentkit: multiple unfinished goals require an explicit goal ID") // ErrGoalEvaluatorPanic 表示自定义 GoalEvaluator 发生 panic。 ErrGoalEvaluatorPanic = errors.New("agentkit: goal evaluator panicked") )
var ( // ErrMCPInitializationPanic 表示 MCP 会话在初始工具发现时发生 panic。 ErrMCPInitializationPanic = errors.New("agentkit: MCP initialization panicked") // ErrMCPClosePanic 表示 MCP 会话在关闭时发生 panic。 ErrMCPClosePanic = errors.New("agentkit: MCP session close panicked") )
var ( // ErrSessionNotFound 表示会话存储中不存在指定会话。 ErrSessionNotFound = errors.New("agentkit: session not found") // ErrSessionConflict 表示会话已被其他调用方更新,当前快照不能覆盖新状态。 ErrSessionConflict = errors.New("agentkit: session revision conflict") // ErrSessionDisabled 表示 Agent 未配置会话存储。 ErrSessionDisabled = errors.New("agentkit: session persistence is not configured") )
var ( // ErrSkillNotFound 表示指定技能不存在。 ErrSkillNotFound = errors.New("agentkit: skill not found") // ErrSkillBackendPanic 表示自定义 SkillBackend 发生 panic。 ErrSkillBackendPanic = errors.New("agentkit: skill backend panicked") )
var ( // ErrToolResultNotFound 表示存储中不存在指定的大型工具结果。 ErrToolResultNotFound = errors.New("agentkit: tool result not found") // ErrToolResultExists 表示相同 ID 的不可变工具结果已经存在。 ErrToolResultExists = errors.New("agentkit: tool result already exists") )
var ErrMiddlewarePanic = errors.New("agentkit: agent middleware panicked")
ErrMiddlewarePanic 表示自定义 ChatModelAgentMiddleware 发生 panic。
var ErrMockModelNoResponse = errors.New("mock chat model has no response configured")
ErrMockModelNoResponse 表示没有可消费的预设响应。
var ErrModelPanic = errors.New("agentkit: model panicked")
ErrModelPanic 表示第三方模型实现在生成或读取流时发生 panic。
var ErrModelPolicyPanic = errors.New("agentkit: model policy callback panicked")
ErrModelPolicyPanic 表示模型重试或故障切换的用户回调发生 panic。
var ErrPersistencePanic = errors.New("agentkit: persistence backend panicked")
ErrPersistencePanic 表示自定义持久化后端在执行操作时发生 panic。
var ErrSubscriberPanic = errors.New("agentkit: event subscriber panicked")
ErrSubscriberPanic 表示事件订阅回调发生 panic;其他订阅者会通过 EventError 收到该错误。
var ErrToolExecutionPanic = errors.New("agentkit: tool execution panicked")
ErrToolExecutionPanic 表示用户工具实现发生 panic。
var ErrToolMetadataPanic = errors.New("agentkit: tool metadata panicked")
ErrToolMetadataPanic 表示第三方工具在返回元数据时发生 panic。
var ErrToolPolicyPanic = errors.New("agentkit: tool policy callback panicked")
ErrToolPolicyPanic 表示 ToolPolicy 的用户回调发生 panic。
Functions ¶
func EmitToolUpdate ¶
EmitToolUpdate 在工具执行中发送进度更新事件。 工具通过 context 获取 Emitter 并发送 tool_update 事件:
func myTool(ctx context.Context, input string) (string, error) {
agentkit.EmitToolUpdate(ctx, "正在处理...")
return "done", nil
}
func GetInterruptState ¶
GetInterruptState 在工具中检查是否从中断恢复,并获取之前保存的状态。
返回值:
- wasInterrupted: 此工具是否曾被中断
- hasState: 是否有保存的状态且成功转换为类型 T
- state: 保存的状态(hasState 为 false 时为零值)
func GetResumeContext ¶
GetResumeContext 在工具中检查是否是 Resume 的显式目标,并获取恢复数据。
返回值:
- isResumeTarget: 此工具是否被显式指定为恢复目标
- hasData: 是否提供了恢复数据
- data: 恢复数据(hasData 为 false 时为零值)
用于区分:
- 作为恢复目标被调用(应继续执行)
- 因兄弟工具被恢复而重新执行(应再次中断)
用法:
func myTool(ctx context.Context, input string) (string, error) {
wasInterrupted, _, _ := agentkit.GetInterruptState[any](ctx)
if !wasInterrupted {
return "", agentkit.Interrupt(ctx, "需要用户输入")
}
isTarget, hasData, data := agentkit.GetResumeContext[string](ctx)
if !isTarget {
return "", agentkit.Interrupt(ctx, nil) // 非目标,重新中断
}
if hasData {
return "用户输入: " + data, nil
}
return "已确认", nil
}
func GoalOperationKey ¶ added in v1.4.0
GoalOperationKey 为当前目标尝试和业务操作名生成稳定、不透明的幂等键。 同一目标尝试在进程恢复或显式 Retry 后会得到相同结果;operation 必须稳定且非空。
func Interrupt ¶
Interrupt 在工具执行中触发 HITL 中断。 调用后工具应立即返回,Agent 将暂停执行并发出 EventInterrupted 事件。 用户可通过 Agent.Resume 恢复执行。
info 是面向用户的中断原因描述,会通过 InterruptPoint.Info 传递给订阅者。
用法:
func myTool(ctx context.Context, input string) (string, error) {
if needsConfirmation(input) {
return "", agentkit.Interrupt(ctx, "请确认是否继续")
}
return doWork(input), nil
}
func SetRunValue ¶ added in v1.4.0
SetRunValue 在工具或中间件执行期间更新当前请求值。 该值可被同一次底层运行中的后续工具和中间件读取。
func StatefulInterrupt ¶
StatefulInterrupt 在工具执行中触发带状态保存的 HITL 中断。 恢复时可通过 GetInterruptState 取回保存的状态。
state 必须是可通过 gob 序列化的类型。
用法:
type MyState struct { Step int }
func myTool(ctx context.Context, input string) (string, error) {
wasInterrupted, hasState, state := agentkit.GetInterruptState[MyState](ctx)
if !wasInterrupted {
return "", agentkit.StatefulInterrupt(ctx, "处理中", MyState{Step: 1})
}
if hasState {
return fmt.Sprintf("从步骤 %d 恢复", state.Step), nil
}
return "已恢复", nil
}
Types ¶
type Agent ¶
type Agent struct {
// contains filtered or unexported fields
}
Agent 提供事件流驱动的交互能力。
func (*Agent) Abort ¶
func (a *Agent) Abort()
Abort 取消当前执行并等待完成。 Subscribe 回调与执行处于同一 goroutine,回调内请使用 Cancel 以避免等待自身。
func (*Agent) AbortContext ¶ added in v1.4.0
AbortContext 取消当前执行,并等待它退出或 ctx 结束。 返回 context.Canceled 或 context.DeadlineExceeded 只表示等待提前结束;取消请求仍已发出。
func (*Agent) Cancel ¶ added in v1.3.0
func (a *Agent) Cancel()
Cancel 请求取消当前执行且不等待完成。 可在 Subscribe 回调中安全调用;需要等待执行退出时请在回调外使用 Abort。
func (*Agent) ClearCheckpoint ¶ added in v1.4.0
ClearCheckpoint 放弃当前中断并使已有检查点失效。 配置了 Session 时,清理后的状态会立即持久化。
func (*Agent) CloseContext ¶ added in v1.4.0
CloseContext 关闭 Agent,并等待当前执行和 MCP 连接释放完成或 ctx 结束。 超时后关闭仍会在后台继续;重复调用只会等待同一次 MCP 关闭。
func (*Agent) ContextHistory ¶ added in v1.3.0
ContextHistory 获取当前发送给模型的上下文副本。 未发生压缩时,它与 History 相同;压缩后 History 仍保留完整对话。
func (*Agent) ContinueWithResult ¶ added in v1.4.0
ContinueWithResult 从当前状态继续执行并返回本次新增的结果。
func (*Agent) PendingInterrupts ¶ added in v1.4.0
func (a *Agent) PendingInterrupts() []InterruptPoint
PendingInterrupts 返回当前等待 Resume 的中断点副本。
func (*Agent) Resume ¶
Resume 从 HITL 中断恢复执行。 targets 格式为 map[interruptID]data,interruptID 来自 Event.Interrupt[].ID。 如果 Agent 已在执行中,返回错误。
func (*Agent) ResumeWithResult ¶ added in v1.4.0
ResumeWithResult 从 HITL 中断恢复并返回本次恢复执行新增的结果。
func (*Agent) SaveSession ¶ added in v1.3.0
SaveSession 立即保存当前会话快照。 Prompt、Send、Continue 和 Resume 结束时会自动调用它。
func (*Agent) Send ¶ added in v1.1.0
func (a *Agent) Send(ctx context.Context, parts ...ContentPart) error
Send 发送多模态内容并驱动 Agent 执行。 使用 Text、ImageURL、AudioURL 等构造函数创建 ContentPart。 如果 Agent 已在执行中,返回错误。
func (*Agent) SetFollowUpMode ¶
SetFollowUpMode 设置后续消息处理模式
func (*Agent) SetHistory ¶ added in v1.2.0
SetHistory 替换完整对话历史,并同步展示状态。
func (*Agent) SetSteeringMode ¶
SetSteeringMode 设置转向消息处理模式
func (*Agent) StreamParts ¶ added in v1.4.0
StreamParts 发送多模态内容并立即返回本次请求专属的事件流。
func (*Agent) Subscribe ¶
func (a *Agent) Subscribe(fn Subscriber) func()
Subscribe 订阅事件流,返回取消订阅函数。 回调按订阅顺序同步执行,每个回调收到独立的事件快照;nil 回调会被忽略。
func (*Agent) ToolResultStore ¶ added in v1.4.0
func (a *Agent) ToolResultStore() ToolResultStore
ToolResultStore 返回工具结果压缩使用的存储;未启用 ToolReduction 时返回 nil。
type BaseChatModelAgentMiddleware ¶ added in v1.2.0
type BaseChatModelAgentMiddleware = adk.BaseChatModelAgentMiddleware
BaseChatModelAgentMiddleware 提供 ChatModelAgentMiddleware 的默认空实现。
type ChatModelAgentMiddleware ¶ added in v1.2.0
type ChatModelAgentMiddleware = adk.ChatModelAgentMiddleware
ChatModelAgentMiddleware 是 ChatModelAgent 扩展接口。
type CheckpointDeleter ¶ added in v1.4.0
CheckpointDeleter 是支持显式删除检查点的可选接口。 内置存储均实现该接口;自定义存储也应实现它,以便 Reset、SetHistory 和成功恢复后能够及时清理失效检查点。Delete 必须及时响应 context 取消与截止时间。
type CheckpointStore ¶ added in v1.4.0
type CheckpointStore = compose.CheckPointStore
CheckpointStore 保存可恢复执行所需的检查点。 实现必须及时响应每个方法的 context 取消与截止时间;Set 不得保留调用方传入的可变字节切片。
type CheckpointStoreProvider ¶ added in v1.4.0
type CheckpointStoreProvider interface {
CheckpointStore() CheckpointStore
}
CheckpointStoreProvider 可由 SessionStore 选择性实现,为会话提供配套的检查点存储。 Config.CheckPointStore 未设置时,Agent 会优先使用该存储。
type CompactionConfig ¶ added in v1.3.0
type CompactionConfig struct {
// Model 用于生成摘要。为空时复用 Agent 的主模型。
Model ChatModel
// MaxTokens 在估算的上下文 token 数超过该值时压缩。
// MaxTokens 和 MaxMessages 都为 0 时默认使用 DefaultCompactionMaxTokens。
MaxTokens int
// MaxMessages 在模型上下文消息数超过该值时压缩。
MaxMessages int
// KeepRecentTurns 原样保留最近的用户轮次,默认 1。
KeepRecentTurns int
// SummaryPrompt 是可选的自定义摘要指令。
SummaryPrompt string
}
CompactionConfig 配置基于摘要的自动上下文压缩。
type CompactionInfo ¶ added in v1.3.0
CompactionInfo 描述一次上下文压缩前后的消息数量。
type Config ¶
type Config struct {
Name string
Description string
SystemPrompt string
Model ChatModel // 聊天模型(可直接使用 agentkit.ChatModel 别名)
Tools []Tool // 工具列表(可直接使用 agentkit.Tool 别名)
ToolPolicy *ToolPolicy // 工具别名、分发、执行保护与中间件(可选)
History []*schema.Message // 完整对话历史(可选)
Handlers []ChatModelAgentMiddleware // ChatModelAgent 扩展处理器
ModelRetryConfig *ModelRetryConfig // 模型调用重试配置(可选)
ModelFailoverConfig *ModelFailoverConfig // 模型失败转移配置(可选)
MaxIterations int // 默认 20
PersistenceTimeout time.Duration // 取消后的内部持久化收尾 context 超时;默认 30 秒
CheckPointStore compose.CheckPointStore // 自定义 CheckPoint 存储;默认使用 Session 配套存储或内存存储
Session *SessionConfig // 自动恢复并保存完整对话(可选)
Compaction *CompactionConfig // 自动上下文压缩(可选)
Skills *SkillsConfig // 按需加载 SKILL.md(可选)
MCP *MCPConfig // 自动连接并管理 MCP 服务器(可选)
ToolSearch *ToolSearchConfig // 大型工具集按需搜索(可选)
ToolReduction *ToolReductionConfig // 大型工具结果持久化卸载与按需回取(可选)
}
Config Agent 配置
type ContentPart ¶ added in v1.1.0
type ContentPart = schema.MessageInputPart
ContentPart 表示用户输入的一个内容片段(文本、图片、音频、视频、文件)。 通过 Text、ImageURL 等构造函数创建,用于 Agent.Send 多模态输入。
func AudioBase64 ¶ added in v1.1.0
func AudioBase64(data, mimeType string) ContentPart
AudioBase64 创建 Base64 编码音频内容片段。
func FileBase64 ¶ added in v1.1.0
func FileBase64(data, mimeType string, name ...string) ContentPart
FileBase64 创建 Base64 编码文件内容片段。name 为文件名(可选)。
func ImageBase64 ¶ added in v1.1.0
func ImageBase64(data, mimeType string, detail ...ImageURLDetail) ContentPart
ImageBase64 创建 Base64 编码图片内容片段。
func ImageURL ¶ added in v1.1.0
func ImageURL(url string, detail ...ImageURLDetail) ContentPart
ImageURL 创建图片 URL 内容片段。 detail 可选,控制图片识别质量(默认由模型决定)。
func VideoBase64 ¶ added in v1.1.0
func VideoBase64(data, mimeType string) ContentPart
VideoBase64 创建 Base64 编码视频内容片段。
type EnhancedInvokableToolEndpoint ¶ added in v1.4.0
type EnhancedInvokableToolEndpoint = compose.EnhancedInvokableToolEndpoint
EnhancedInvokableToolEndpoint 是非流式多模态工具调用端点。
type EnhancedInvokableToolMiddleware ¶ added in v1.4.0
type EnhancedInvokableToolMiddleware = compose.EnhancedInvokableToolMiddleware
EnhancedInvokableToolMiddleware 包装非流式多模态工具调用。
type EnhancedInvokableToolOutput ¶ added in v1.4.0
type EnhancedInvokableToolOutput = compose.EnhancedInvokableToolOutput
EnhancedInvokableToolOutput 描述一次非流式多模态工具调用输出。
type EnhancedStreamableToolEndpoint ¶ added in v1.4.0
type EnhancedStreamableToolEndpoint = compose.EnhancedStreamableToolEndpoint
EnhancedStreamableToolEndpoint 是流式多模态工具调用端点。
type EnhancedStreamableToolMiddleware ¶ added in v1.4.0
type EnhancedStreamableToolMiddleware = compose.EnhancedStreamableToolMiddleware
EnhancedStreamableToolMiddleware 包装流式多模态工具调用。
type EnhancedStreamableToolOutput ¶ added in v1.4.0
type EnhancedStreamableToolOutput = compose.EnhancedStreamableToolOutput
EnhancedStreamableToolOutput 描述一次流式多模态工具调用输出。
type Event ¶
type Event struct {
Type EventType
Agent string // 产生事件的 Agent 名称
Role RoleType // 消息角色(message_start / message_end)
Content string // 文本内容(message_end / tool_end)
Delta string // 流式增量内容(message_delta / reasoning_delta)
ReasoningContent string // 完整推理内容(message_end,仅推理模型)
ResponseMeta *ResponseMeta // 响应元数据:token 用量、完成原因(message_end)
ToolCalls []ToolCall // 工具调用列表(tool_start)
ToolCallID string // 工具调用 ID(tool_update / tool_end)
ToolName string // 工具名称(tool_update / tool_end)
ToolArguments string // 工具调用参数(tool_update / tool_end)
Interrupt []InterruptPoint // 中断点列表(interrupted)
Compaction *CompactionInfo // 上下文压缩信息(compaction_start / compaction_end)
Goal *Goal // 已持久化的目标快照(goal_update)
Error error // 错误信息(error)
}
Event 统一事件
type EventType ¶
type EventType string
EventType 事件类型
const ( EventAgentStart EventType = "agent_start" // Agent 开始处理 EventTurnStart EventType = "turn_start" // 新一轮开始,发生在模型请求前 EventMessageStart EventType = "message_start" // 消息开始(流式或非流式) EventReasoningDelta EventType = "reasoning_delta" // 推理模型思考过程增量(如 DeepSeek-R1、o1) EventMessageDelta EventType = "message_delta" // 流式增量文本 EventMessageEnd EventType = "message_end" // 消息结束 EventToolStart EventType = "tool_start" // 工具调用请求 EventToolUpdate EventType = "tool_update" // 工具执行进度更新 EventToolEnd EventType = "tool_end" // 工具调用结果 EventTurnEnd EventType = "turn_end" // 助手消息和工具结果处理完成 EventTransfer EventType = "transfer" // Agent 转移 EventInterrupted EventType = "interrupted" // HITL 中断(等待用户输入) EventCompactionStart EventType = "compaction_start" // 上下文压缩开始 EventCompactionEnd EventType = "compaction_end" // 上下文压缩完成 EventGoalUpdate EventType = "goal_update" // Goal 状态已持久化 EventAgentEnd EventType = "agent_end" // Agent 处理完成 EventError EventType = "error" // 错误 )
type FileCheckpointStore ¶ added in v1.4.0
type FileCheckpointStore struct {
// contains filtered or unexported fields
}
FileCheckpointStore 将每个检查点原子地保存为一个二进制文件。 它适合本地应用和单进程服务;多进程写入请实现数据库型 CheckpointStore。
func NewFileCheckpointStore ¶ added in v1.4.0
func NewFileCheckpointStore(dir string) (*FileCheckpointStore, error)
NewFileCheckpointStore 创建文件检查点存储。目录不存在时会自动创建。
func (*FileCheckpointStore) Delete ¶ added in v1.4.0
func (s *FileCheckpointStore) Delete(ctx context.Context, id string) error
Delete 删除检查点。检查点不存在时也返回 nil。
type FileGoalStore ¶ added in v1.4.0
type FileGoalStore struct {
// contains filtered or unexported fields
}
FileGoalStore 将每个目标原子地保存为一个 JSON 文件。 它适合本地应用和单进程服务;多进程写入请实现数据库型 GoalStore。
func NewFileGoalStore ¶ added in v1.4.0
func NewFileGoalStore(dir string) (*FileGoalStore, error)
NewFileGoalStore 创建文件目标存储。目录不存在时会自动创建。
func (*FileGoalStore) AcquireGoalLease ¶ added in v1.4.0
func (s *FileGoalStore) AcquireGoalLease( ctx context.Context, goalID, workerID string, duration time.Duration, ) (*GoalLease, error)
AcquireGoalLease 原子地取得文件目标存储中的租约。
func (*FileGoalStore) Delete ¶ added in v1.4.0
func (s *FileGoalStore) Delete(ctx context.Context, id string) error
Delete 删除目标文件。目标不存在时也返回 nil。
func (*FileGoalStore) DeleteGoalWithLease ¶ added in v1.4.0
func (s *FileGoalStore) DeleteGoalWithLease(ctx context.Context, goalID string, lease *GoalLease) error
DeleteGoalWithLease 在租约仍有效时删除目标;目标不存在时也返回 nil。
func (*FileGoalStore) List ¶ added in v1.4.0
func (s *FileGoalStore) List(ctx context.Context) ([]GoalInfo, error)
List 按更新时间从新到旧列出目标。
func (*FileGoalStore) ReleaseGoalLease ¶ added in v1.4.0
func (s *FileGoalStore) ReleaseGoalLease(ctx context.Context, lease *GoalLease) error
ReleaseGoalLease 释放自己持有的文件目标租约;同一令牌重复释放是幂等的。
func (*FileGoalStore) RenewGoalLease ¶ added in v1.4.0
func (s *FileGoalStore) RenewGoalLease( ctx context.Context, lease *GoalLease, duration time.Duration, ) (*GoalLease, error)
RenewGoalLease 延长仍然有效的文件目标租约。
func (*FileGoalStore) Save ¶ added in v1.4.0
func (s *FileGoalStore) Save(ctx context.Context, goal *Goal) error
Save 通过原子文件替换保存目标快照。
func (*FileGoalStore) SaveGoalWithLease ¶ added in v1.4.0
SaveGoalWithLease 在同一临界区校验租约、目标版本并保存目标。
type FileSessionStore ¶ added in v1.3.0
type FileSessionStore struct {
// contains filtered or unexported fields
}
FileSessionStore 将每个会话原子地保存为一个 JSON 文件。 它适合本地应用和单进程服务;多进程写入请实现数据库型 SessionStore。
func NewFileSessionStore ¶ added in v1.3.0
func NewFileSessionStore(dir string) (*FileSessionStore, error)
NewFileSessionStore 创建文件会话存储。目录不存在时会自动创建。
func (*FileSessionStore) CheckpointStore ¶ added in v1.4.0
func (s *FileSessionStore) CheckpointStore() CheckpointStore
CheckpointStore 返回与会话目录配套的文件检查点存储。
func (*FileSessionStore) Delete ¶ added in v1.3.0
func (s *FileSessionStore) Delete(ctx context.Context, id string) error
Delete 删除会话及其配套的检查点、目标和工具结果。会话不存在时也会清理可识别的孤儿资源。
func (*FileSessionStore) GoalStore ¶ added in v1.4.0
func (s *FileSessionStore) GoalStore() GoalStore
GoalStore 返回与会话目录配套的文件目标存储。
func (*FileSessionStore) List ¶ added in v1.3.0
func (s *FileSessionStore) List(ctx context.Context) ([]SessionInfo, error)
List 按更新时间从新到旧列出会话。
func (*FileSessionStore) Save ¶ added in v1.3.0
func (s *FileSessionStore) Save(ctx context.Context, session *Session) error
Save 通过原子文件替换保存会话快照,并拒绝覆盖更新版本。
func (*FileSessionStore) ToolResultStore ¶ added in v1.4.0
func (s *FileSessionStore) ToolResultStore() ToolResultStore
ToolResultStore 返回与会话目录配套的文件大型工具结果存储。
type FileSkillBackend ¶ added in v1.3.0
type FileSkillBackend struct {
// contains filtered or unexported fields
}
FileSkillBackend 从本地 SKILL.md 文件动态加载技能。 每次 List/Get 都重新读取文件,因此开发时修改技能无需重建 Agent。
func NewFileSkillBackend ¶ added in v1.3.0
func NewFileSkillBackend(paths ...string) (*FileSkillBackend, error)
NewFileSkillBackend 创建本地技能后端。 每个路径可以是 SKILL.md、包含该文件的目录,或包含多个技能子目录的目录。
type FileToolResultStore ¶ added in v1.4.0
type FileToolResultStore struct {
// contains filtered or unexported fields
}
FileToolResultStore 将大型工具结果原子地保存为 JSON 文件。 它适合本地应用和单进程服务;多进程写入请实现数据库型 ToolResultStore。
func NewFileToolResultStore ¶ added in v1.4.0
func NewFileToolResultStore(dir string) (*FileToolResultStore, error)
NewFileToolResultStore 创建文件结果存储。目录不存在时会自动创建。
func (*FileToolResultStore) Delete ¶ added in v1.4.0
func (s *FileToolResultStore) Delete(ctx context.Context, id string) error
Delete 删除结果文件;结果不存在时也返回 nil。
func (*FileToolResultStore) List ¶ added in v1.4.0
func (s *FileToolResultStore) List(ctx context.Context) ([]ToolResultInfo, error)
List 按创建时间从新到旧列出结果。
func (*FileToolResultStore) Load ¶ added in v1.4.0
func (s *FileToolResultStore) Load(ctx context.Context, id string) (*StoredToolResult, error)
Load 从文件加载完整工具结果。
func (*FileToolResultStore) Save ¶ added in v1.4.0
func (s *FileToolResultStore) Save(ctx context.Context, result *StoredToolResult) error
Save 原子地创建一个不可变工具结果文件。
type Goal ¶ added in v1.4.0
type Goal struct {
ID string `json:"id"`
SessionID string `json:"session_id"`
Objective string `json:"objective"`
SuccessCriteria string `json:"success_criteria,omitempty"`
Status GoalStatus `json:"status"`
Iteration int `json:"iteration"`
MaxIterations int `json:"max_iterations"`
LastResponse string `json:"last_response,omitempty"`
LastReason string `json:"last_reason,omitempty"`
NextPrompt string `json:"next_prompt,omitempty"`
LastError string `json:"last_error,omitempty"`
InProgress bool `json:"in_progress,omitempty"`
AwaitingInterrupt bool `json:"awaiting_interrupt,omitempty"`
PendingEvaluation bool `json:"pending_evaluation,omitempty"`
AttemptIteration int `json:"attempt_iteration,omitempty"`
HistoryMessageCount int `json:"history_message_count,omitempty"`
PendingPrompt string `json:"pending_prompt,omitempty"`
Revision uint64 `json:"revision"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
}
Goal 是一个可跨进程重启恢复的目标快照。 LastResponse、LastReason 和 NextPrompt 用于在每个执行步骤之间恢复自动推进状态。
type GoalDecision ¶ added in v1.4.0
type GoalDecision struct {
Complete bool `json:"complete"`
Reason string `json:"reason"`
NextPrompt string `json:"next_prompt"`
}
GoalDecision 表示一次目标完成度判断。
type GoalEvaluation ¶ added in v1.4.0
type GoalEvaluation struct {
Objective string
SuccessCriteria string
Iteration int
LastResponse string
}
GoalEvaluation 是交给 GoalEvaluator 的最小判断上下文。
type GoalEvaluator ¶ added in v1.4.0
type GoalEvaluator interface {
Evaluate(ctx context.Context, evaluation GoalEvaluation) (GoalDecision, error)
}
GoalEvaluator 判断最新一次执行是否已经满足目标,并给出下一步提示。
type GoalEvaluatorFunc ¶ added in v1.4.0
type GoalEvaluatorFunc func(context.Context, GoalEvaluation) (GoalDecision, error)
GoalEvaluatorFunc 将函数适配为 GoalEvaluator。
func (GoalEvaluatorFunc) Evaluate ¶ added in v1.4.0
func (f GoalEvaluatorFunc) Evaluate(ctx context.Context, evaluation GoalEvaluation) (GoalDecision, error)
Evaluate 调用目标判断函数。
type GoalInfo ¶ added in v1.4.0
type GoalInfo struct {
ID string `json:"id"`
SessionID string `json:"session_id"`
Objective string `json:"objective"`
Status GoalStatus `json:"status"`
Iteration int `json:"iteration"`
MaxIterations int `json:"max_iterations"`
AttemptIteration int `json:"attempt_iteration,omitempty"`
InProgress bool `json:"in_progress,omitempty"`
AwaitingInterrupt bool `json:"awaiting_interrupt,omitempty"`
PendingEvaluation bool `json:"pending_evaluation,omitempty"`
LastReason string `json:"last_reason,omitempty"`
LastError string `json:"last_error,omitempty"`
Revision uint64 `json:"revision"`
UpdatedAt time.Time `json:"updated_at"`
}
GoalInfo 是用于目标列表展示的轻量元数据。
type GoalLease ¶ added in v1.4.0
type GoalLease struct {
GoalID string `json:"goal_id"`
WorkerID string `json:"worker_id"`
Token string `json:"token"`
ExpiresAt time.Time `json:"expires_at"`
}
GoalLease 是一次有期限的目标执行所有权。Token 是不可猜测的 fencing 令牌。
type GoalLeaseHeldError ¶ added in v1.4.0
type GoalLeaseHeldError struct {
Lease GoalLease
}
GoalLeaseHeldError 提供当前持有者和到期时间,便于调度器安全安排重试。 可同时通过 errors.Is(err, ErrGoalLeaseHeld) 和 errors.As 使用。
func (*GoalLeaseHeldError) Error ¶ added in v1.4.0
func (e *GoalLeaseHeldError) Error() string
Error 返回包含持有者和到期时间的租约冲突信息。
func (*GoalLeaseHeldError) Unwrap ¶ added in v1.4.0
func (e *GoalLeaseHeldError) Unwrap() error
Unwrap 支持 errors.Is(err, ErrGoalLeaseHeld)。
type GoalLeaseStore ¶ added in v1.4.0
type GoalLeaseStore interface {
AcquireGoalLease(ctx context.Context, goalID, workerID string, duration time.Duration) (*GoalLease, error)
RenewGoalLease(ctx context.Context, lease *GoalLease, duration time.Duration) (*GoalLease, error)
ReleaseGoalLease(ctx context.Context, lease *GoalLease) error
SaveGoalWithLease(ctx context.Context, goal *Goal, lease *GoalLease) error
DeleteGoalWithLease(ctx context.Context, goalID string, lease *GoalLease) error
}
GoalLeaseStore 为 GoalStore 增加原子 worker 所有权和防陈旧写入能力。 AcquireGoalLease 对未过期租约必须返回包装 ErrGoalLeaseHeld 的错误;过期租约可被接管。 RenewGoalLease、SaveGoalWithLease 和 DeleteGoalWithLease 必须校验有效 Token, 不匹配或已过期时返回包装 ErrGoalLeaseLost 的错误。ReleaseGoalLease 不得释放其他 Token。 所有方法必须可以安全地被多个 goroutine 调用,并及时响应 context 取消与截止时间。
type GoalRequest ¶ added in v1.4.0
type GoalRequest struct {
ID string // 可选;为空时自动生成 UUID
Objective string
SuccessCriteria string
MaxIterations int
}
GoalRequest 创建一个新的自动推进目标。
type GoalRun ¶ added in v1.4.0
type GoalRun struct {
// contains filtered or unexported fields
}
GoalRun 表示一次正在后台推进的持久化目标。 目标在 StartAsync 返回前已经创建并落盘,可立即通过 ID、Get 或 List 对外提供状态。
func (*GoalRun) Wait ¶ added in v1.4.0
func (r *GoalRun) Wait() (*GoalRunResult, error)
Wait 等待本次后台推进停止并返回隔离的结果副本。
func (*GoalRun) WaitContext ¶ added in v1.4.0
func (r *GoalRun) WaitContext(ctx context.Context) (*GoalRunResult, error)
WaitContext 等待本次后台推进停止或 ctx 结束;等待超时不会取消目标。 可在超时后再次调用 Wait 或 WaitContext。
type GoalRunInfo ¶ added in v1.4.0
GoalRunInfo 描述当前工具调用所属的持久化目标尝试。
func CurrentGoalRun ¶ added in v1.4.0
func CurrentGoalRun(ctx context.Context) (GoalRunInfo, bool)
CurrentGoalRun 返回当前工具调用所属的 Goal 信息。 普通 Agent 运行或没有 GoalRunner 上下文时返回 false。
type GoalRunResult ¶ added in v1.4.0
GoalRunResult 汇总一次 Start 或 Resume 调用。
type GoalRunner ¶ added in v1.4.0
type GoalRunner struct {
// contains filtered or unexported fields
}
GoalRunner 将长目标拆为可持久化的普通 Agent 步骤,并在每步后判断是否继续。 它要求 Agent 启用 Session,确保会话与目标状态可以一起恢复。
func NewGoalRunner ¶ added in v1.4.0
func NewGoalRunner(agent *Agent, cfg *GoalRunnerConfig) (*GoalRunner, error)
NewGoalRunner 创建目标执行器。Store 和 Evaluator 默认复用 Agent 的 SessionStore 与模型。
func (*GoalRunner) Clear ¶ added in v1.4.0
func (r *GoalRunner) Clear(ctx context.Context, id string) (retErr error)
Clear 删除已停止的目标状态,但保留 Agent 会话历史。
func (*GoalRunner) List ¶ added in v1.4.0
func (r *GoalRunner) List(ctx context.Context) ([]GoalInfo, error)
List 按更新时间从新到旧列出属于当前 Agent 会话的目标。
func (*GoalRunner) Pause ¶ added in v1.4.0
func (r *GoalRunner) Pause(ctx context.Context, id string) (retErr error)
Pause 持久化暂停状态,并取消由当前 GoalRunner 发起的同一目标执行。
func (*GoalRunner) Resume ¶ added in v1.4.0
func (r *GoalRunner) Resume(ctx context.Context, id string) (out *GoalRunResult, retErr error)
Resume 从持久化状态继续自动推进目标。
func (*GoalRunner) ResumeAsync ¶ added in v1.4.0
ResumeAsync 校验持久化状态并取得执行所有权后,在后台继续指定目标。
func (*GoalRunner) ResumeInterrupt ¶ added in v1.4.0
func (r *GoalRunner) ResumeInterrupt(ctx context.Context, id string, targets map[string]any) (out *GoalRunResult, retErr error)
ResumeInterrupt 提交 HITL 数据后继续当前目标。
func (*GoalRunner) ResumeInterruptAsync ¶ added in v1.4.0
func (r *GoalRunner) ResumeInterruptAsync(ctx context.Context, id string, targets map[string]any) (*GoalRun, error)
ResumeInterruptAsync 提交 HITL 数据、持久化恢复状态后,在后台继续当前目标。 返回前会复制 targets 的 map 容器;其中的引用类值仍应由调用方视为不可变。
func (*GoalRunner) ResumePending ¶ added in v1.4.0
func (r *GoalRunner) ResumePending(ctx context.Context) (*GoalRunResult, error)
ResumePending 自动恢复当前会话唯一的未完成目标。 没有未完成目标时返回 ErrGoalNotFound;存在多个时返回 ErrGoalResumeAmbiguous, 调用方可先使用 List 查看并通过 Resume 明确选择。
func (*GoalRunner) ResumePendingAsync ¶ added in v1.4.0
func (r *GoalRunner) ResumePendingAsync(ctx context.Context) (*GoalRun, error)
ResumePendingAsync 在后台恢复当前会话唯一的未完成目标。
func (*GoalRunner) Retry ¶ added in v1.4.0
func (r *GoalRunner) Retry(ctx context.Context, id string) (out *GoalRunResult, retErr error)
Retry 明确允许重新执行一个无法确认是否产生副作用的未完成步骤。
func (*GoalRunner) RetryAsync ¶ added in v1.4.0
RetryAsync 持久化显式重试状态后,在后台重新执行无法确认是否产生副作用的步骤。
func (*GoalRunner) Start ¶ added in v1.4.0
func (r *GoalRunner) Start(ctx context.Context, request GoalRequest) (out *GoalRunResult, retErr error)
Start 创建并执行一个新目标。相同 ID 已存在时返回 ErrGoalExists,避免覆盖恢复点。
func (*GoalRunner) StartAsync ¶ added in v1.4.0
func (r *GoalRunner) StartAsync(ctx context.Context, request GoalRequest) (*GoalRun, error)
StartAsync 创建并持久化新目标后立即返回后台运行句柄。 ctx 控制后台执行生命周期;服务端应传入应用或 worker 生命周期的 context。
type GoalRunnerConfig ¶ added in v1.4.0
type GoalRunnerConfig struct {
Store GoalStore
Evaluator GoalEvaluator
MaxIterations int
// WorkerID 用于租约诊断;为空时自动生成当前 GoalRunner 实例的唯一 ID。
WorkerID string
// LeaseDuration 是 worker 租约时长,默认一分钟;续期频率约为其三分之一。
LeaseDuration time.Duration
// RequireLease 要求 Store 实现 GoalLeaseStore,避免生产环境意外退化为单 worker 模式。
RequireLease bool
}
GoalRunnerConfig 配置目标的持久化、判断器与默认执行上限。
type GoalStatus ¶ added in v1.4.0
type GoalStatus string
GoalStatus 描述持久化目标的生命周期状态。
const ( GoalStatusActive GoalStatus = "active" GoalStatusPaused GoalStatus = "paused" GoalStatusCompleted GoalStatus = "completed" GoalStatusBlocked GoalStatus = "blocked" )
type GoalStore ¶ added in v1.4.0
type GoalStore interface {
Load(ctx context.Context, id string) (*Goal, error)
Save(ctx context.Context, goal *Goal) error
Delete(ctx context.Context, id string) error
List(ctx context.Context) ([]GoalInfo, error)
}
GoalStore 管理持久化目标。 Load 在目标不存在时必须返回包装 ErrGoalNotFound 的错误;Delete 必须是幂等的。 实现还必须可以安全地被多个 goroutine 调用,并且不得保留调用方传入的可变数据。 所有方法必须及时响应 context 取消与截止时间。 Save 使用 Goal.Revision 进行乐观并发控制:新目标必须为 0,已有目标必须等于当前版本; 存储成功后持久化版本加一,但不修改调用方传入的 Goal。
type GoalStoreProvider ¶ added in v1.4.0
type GoalStoreProvider interface {
GoalStore() GoalStore
}
GoalStoreProvider 允许会话存储提供共享生命周期的目标存储。
type ImageURLDetail ¶ added in v1.1.0
type ImageURLDetail = schema.ImageURLDetail
ImageURLDetail 控制图片识别质量。
const ( ImageDetailHigh ImageURLDetail = schema.ImageURLDetailHigh ImageDetailLow ImageURLDetail = schema.ImageURLDetailLow ImageDetailAuto ImageURLDetail = schema.ImageURLDetailAuto )
type InterruptPoint ¶
InterruptPoint HITL 中断点信息
type InvokableToolEndpoint ¶ added in v1.4.0
type InvokableToolEndpoint = compose.InvokableToolEndpoint
InvokableToolEndpoint 是非流式工具调用端点。
type InvokableToolMiddleware ¶ added in v1.4.0
type InvokableToolMiddleware = compose.InvokableToolMiddleware
InvokableToolMiddleware 包装非流式工具调用。
type MCPClientSession ¶ added in v1.3.0
type MCPClientSession interface {
officialmcp.ClientSession
Close() error
}
MCPClientSession 是已连接的 MCP 会话。 AgentKit 会取得传入会话的所有权,并在 Agent.Close 时关闭它。
type MCPConfig ¶ added in v1.3.0
type MCPConfig struct {
Servers []MCPServerConfig
ClientName string // MCP 客户端名称,默认 "agentkit"
ClientVersion string // MCP 客户端版本,默认 "dev"
KeepAlive time.Duration // 大于 0 时定期 ping 服务器
// InitializationTimeout 限制每个服务器的连接与初始工具发现;零值使用 30 秒默认值。
InitializationTimeout time.Duration
// 0 使用安全默认值,-1 关闭限制,正数使用指定限制。
MaxResultChars int
MaxDescriptionChars int
}
MCPConfig 配置 Agent 使用的 MCP 服务器。
type MCPServerConfig ¶ added in v1.3.0
type MCPServerConfig struct {
Name string
Transport MCPTransport
URL string
Command string
Args []string
Env map[string]string
WorkingDir string
Headers map[string]string
HTTPClient *http.Client
Session MCPClientSession
ToolNames []string // 为空时加载服务器的全部工具
ToolPrefix string // 暴露给模型的工具名前缀,用于避免多服务器重名
}
MCPServerConfig 配置一个 MCP 服务器。 Session 与 Transport 二选一;Session 适合已连接的自定义或进程内会话。
type MCPTransport ¶ added in v1.3.0
type MCPTransport string
MCPTransport 表示 MCP 服务器传输方式。
const ( MCPTransportStdio MCPTransport = mcpsession.TransportStdio MCPTransportSSE MCPTransport = mcpsession.TransportSSE MCPTransportStreamableHTTP MCPTransport = mcpsession.TransportStreamableHTTP )
type MemoryCheckpointStore ¶ added in v1.4.0
type MemoryCheckpointStore struct {
// contains filtered or unexported fields
}
MemoryCheckpointStore 是并发安全的内存检查点存储,适合测试和单进程服务。
func NewMemoryCheckpointStore ¶ added in v1.4.0
func NewMemoryCheckpointStore() *MemoryCheckpointStore
NewMemoryCheckpointStore 创建内存检查点存储。
func (*MemoryCheckpointStore) Delete ¶ added in v1.4.0
func (s *MemoryCheckpointStore) Delete(ctx context.Context, id string) error
Delete 删除检查点。检查点不存在时也返回 nil。
type MemoryGoalStore ¶ added in v1.4.0
type MemoryGoalStore struct {
// contains filtered or unexported fields
}
MemoryGoalStore 是并发安全的内存目标存储,适合测试和单进程服务。
func NewMemoryGoalStore ¶ added in v1.4.0
func NewMemoryGoalStore() *MemoryGoalStore
NewMemoryGoalStore 创建内存目标存储。
func (*MemoryGoalStore) AcquireGoalLease ¶ added in v1.4.0
func (s *MemoryGoalStore) AcquireGoalLease( ctx context.Context, goalID, workerID string, duration time.Duration, ) (*GoalLease, error)
AcquireGoalLease 原子地取得目标租约。
func (*MemoryGoalStore) Delete ¶ added in v1.4.0
func (s *MemoryGoalStore) Delete(ctx context.Context, id string) error
Delete 删除目标。目标不存在时也返回 nil。
func (*MemoryGoalStore) DeleteGoalWithLease ¶ added in v1.4.0
func (s *MemoryGoalStore) DeleteGoalWithLease(ctx context.Context, goalID string, lease *GoalLease) error
DeleteGoalWithLease 在租约仍有效时删除目标;目标不存在时也返回 nil。
func (*MemoryGoalStore) List ¶ added in v1.4.0
func (s *MemoryGoalStore) List(ctx context.Context) ([]GoalInfo, error)
List 按更新时间从新到旧列出目标。
func (*MemoryGoalStore) ReleaseGoalLease ¶ added in v1.4.0
func (s *MemoryGoalStore) ReleaseGoalLease(ctx context.Context, lease *GoalLease) error
ReleaseGoalLease 释放自己持有的目标租约;同一令牌重复释放是幂等的。
func (*MemoryGoalStore) RenewGoalLease ¶ added in v1.4.0
func (s *MemoryGoalStore) RenewGoalLease( ctx context.Context, lease *GoalLease, duration time.Duration, ) (*GoalLease, error)
RenewGoalLease 延长仍然有效的目标租约。
func (*MemoryGoalStore) Save ¶ added in v1.4.0
func (s *MemoryGoalStore) Save(ctx context.Context, goal *Goal) error
Save 保存并完全替换目标快照。
func (*MemoryGoalStore) SaveGoalWithLease ¶ added in v1.4.0
func (s *MemoryGoalStore) SaveGoalWithLease(ctx context.Context, goal *Goal, lease *GoalLease) error
SaveGoalWithLease 在同一临界区校验租约、目标版本并保存目标。
type MemorySessionStore ¶ added in v1.3.0
type MemorySessionStore struct {
// contains filtered or unexported fields
}
MemorySessionStore 是并发安全的内存会话存储,适合测试和单进程服务。
func NewMemorySessionStore ¶ added in v1.3.0
func NewMemorySessionStore() *MemorySessionStore
NewMemorySessionStore 创建内存会话存储。
func (*MemorySessionStore) CheckpointStore ¶ added in v1.4.0
func (s *MemorySessionStore) CheckpointStore() CheckpointStore
CheckpointStore 返回与会话共享生命周期的内存检查点存储。
func (*MemorySessionStore) Delete ¶ added in v1.3.0
func (s *MemorySessionStore) Delete(ctx context.Context, id string) error
Delete 删除会话及其配套的检查点、目标和工具结果。会话不存在时也会清理可识别的孤儿资源。
func (*MemorySessionStore) GoalStore ¶ added in v1.4.0
func (s *MemorySessionStore) GoalStore() GoalStore
GoalStore 返回与会话共享生命周期的内存目标存储。
func (*MemorySessionStore) List ¶ added in v1.3.0
func (s *MemorySessionStore) List(ctx context.Context) ([]SessionInfo, error)
List 按更新时间从新到旧列出会话。
func (*MemorySessionStore) Save ¶ added in v1.3.0
func (s *MemorySessionStore) Save(ctx context.Context, session *Session) error
Save 保存并完全替换会话快照,拒绝覆盖更新版本。
func (*MemorySessionStore) ToolResultStore ¶ added in v1.4.0
func (s *MemorySessionStore) ToolResultStore() ToolResultStore
ToolResultStore 返回与会话配套的内存大型工具结果存储。
type MemorySkillBackend ¶ added in v1.3.0
type MemorySkillBackend struct {
// contains filtered or unexported fields
}
MemorySkillBackend 是可动态增删技能的并发安全内存后端。
func NewMemorySkillBackend ¶ added in v1.3.0
func NewMemorySkillBackend(skills ...Skill) (*MemorySkillBackend, error)
NewMemorySkillBackend 创建内存技能后端。
func (*MemorySkillBackend) Delete ¶ added in v1.3.0
func (b *MemorySkillBackend) Delete(name string) error
Delete 删除技能。技能不存在时也返回 nil。
func (*MemorySkillBackend) List ¶ added in v1.3.0
func (b *MemorySkillBackend) List(ctx context.Context) ([]SkillInfo, error)
List 列出所有技能元数据,结果按名称排序。
func (*MemorySkillBackend) Set ¶ added in v1.3.0
func (b *MemorySkillBackend) Set(item Skill) error
Set 新增或替换一个技能。
type MemoryToolResultStore ¶ added in v1.4.0
type MemoryToolResultStore struct {
// contains filtered or unexported fields
}
MemoryToolResultStore 是并发安全的内存结果存储。
func NewMemoryToolResultStore ¶ added in v1.4.0
func NewMemoryToolResultStore() *MemoryToolResultStore
NewMemoryToolResultStore 创建内存结果存储。
func (*MemoryToolResultStore) Delete ¶ added in v1.4.0
func (s *MemoryToolResultStore) Delete(ctx context.Context, id string) error
Delete 删除结果;结果不存在时也返回 nil。
func (*MemoryToolResultStore) List ¶ added in v1.4.0
func (s *MemoryToolResultStore) List(ctx context.Context) ([]ToolResultInfo, error)
List 按创建时间从新到旧列出结果。
func (*MemoryToolResultStore) Load ¶ added in v1.4.0
func (s *MemoryToolResultStore) Load(ctx context.Context, id string) (*StoredToolResult, error)
Load 加载完整工具结果。
func (*MemoryToolResultStore) Save ¶ added in v1.4.0
func (s *MemoryToolResultStore) Save(ctx context.Context, result *StoredToolResult) error
Save 创建一个不可变工具结果。
type Message ¶
type Message struct {
Role RoleType
Agent string // 产生消息的 Agent 名称
Content string
ReasoningContent string // 推理模型的思考内容(如 DeepSeek-R1、o1),非推理模型为空
}
Message 消息记录
type MockChatModel ¶ added in v1.2.0
type MockChatModel struct {
// contains filtered or unexported fields
}
MockChatModel 按顺序返回预设响应,并记录每次调用。
func NewMockChatModel ¶ added in v1.2.0
func NewMockChatModel(responses ...MockModelResponse) *MockChatModel
NewMockChatModel 创建按顺序返回响应的模型。
func (*MockChatModel) AddResponses ¶ added in v1.2.0
func (m *MockChatModel) AddResponses(responses ...MockModelResponse)
AddResponses 追加后续响应。
func (*MockChatModel) Calls ¶ added in v1.2.0
func (m *MockChatModel) Calls() []MockModelCall
Calls 返回模型调用记录。
func (*MockChatModel) Generate ¶ added in v1.2.0
func (m *MockChatModel) Generate(ctx context.Context, input []*schema.Message, opts ...model.Option) (*schema.Message, error)
Generate 返回下一条完整响应。
func (*MockChatModel) LastCall ¶ added in v1.2.0
func (m *MockChatModel) LastCall() (MockModelCall, bool)
LastCall 返回最近一次模型调用记录。
func (*MockChatModel) RemainingResponses ¶ added in v1.2.0
func (m *MockChatModel) RemainingResponses() int
RemainingResponses 返回还未消费的响应数量。
type MockModelCall ¶ added in v1.2.0
MockModelCall 记录一次模型调用。
type MockModelExpectation ¶ added in v1.2.0
type MockModelExpectation func(call MockModelCall) error
MockModelExpectation 校验一次模型调用。
func MockExpectToolResults ¶ added in v1.2.0
func MockExpectToolResults(callIDs ...string) MockModelExpectation
MockExpectToolResults 校验输入中存在指定工具结果。
type MockModelResponse ¶ added in v1.2.0
type MockModelResponse struct {
Message *schema.Message
Chunks []*schema.Message
Err error
StreamErr error
Expect MockModelExpectation
Build func(call MockModelCall) MockModelResponse
}
MockModelResponse 描述一次模型返回。
func MockExpect ¶ added in v1.2.0
func MockExpect(response MockModelResponse, expect MockModelExpectation) MockModelResponse
MockExpect 为响应追加调用校验。
func MockModelAfterToolResult ¶ added in v1.2.0
func MockModelAfterToolResult(callID string, response MockModelResponse) MockModelResponse
MockModelAfterToolResult 要求输入中包含指定工具结果后再返回响应。
func MockModelAfterToolResults ¶ added in v1.2.0
func MockModelAfterToolResults(response MockModelResponse, callIDs ...string) MockModelResponse
MockModelAfterToolResults 要求输入中包含指定工具结果后再返回响应。
func MockModelCalls ¶ added in v1.2.0
func MockModelCalls(invocations ...MockToolCallProvider) MockModelResponse
MockModelCalls 创建一组工具调用回复。
func MockModelCallsAfter ¶ added in v1.2.0
func MockModelCallsAfter(wait MockToolCallProvider, calls ...MockToolCallProvider) MockModelResponse
MockModelCallsAfter 在指定工具结果返回后创建下一组工具调用回复。
func MockModelCallsAfterAll ¶ added in v1.2.0
func MockModelCallsAfterAll(wait []MockToolCallProvider, calls ...MockToolCallProvider) MockModelResponse
MockModelCallsAfterAll 在指定工具结果全部返回后创建下一组工具调用回复。
func MockModelError ¶ added in v1.2.0
func MockModelError(err error) MockModelResponse
MockModelError 创建调用错误。
func MockModelMessage ¶ added in v1.2.0
func MockModelMessage(message *schema.Message) MockModelResponse
MockModelMessage 创建完整消息回复。
func MockModelReasoning ¶ added in v1.2.0
func MockModelReasoning(content, reasoning string) MockModelResponse
MockModelReasoning 创建带推理内容的文本回复。
func MockModelRespondsAfter ¶ added in v1.2.0
func MockModelRespondsAfter[D any](call *MockToolInvocation[D], reply func(D) MockModelResponse) MockModelResponse
MockModelRespondsAfter 根据工具结果生成回复。
func MockModelRespondsAfterToolResult ¶ added in v1.2.0
func MockModelRespondsAfterToolResult(callID string, reply func(result string) MockModelResponse) MockModelResponse
MockModelRespondsAfterToolResult 根据工具结果生成响应。
func MockModelRespondsAfterToolResultAs ¶ added in v1.2.0
func MockModelRespondsAfterToolResultAs[D any](callID string, reply func(D) MockModelResponse) MockModelResponse
MockModelRespondsAfterToolResultAs 根据工具结果生成回复。
func MockModelStream ¶ added in v1.2.0
func MockModelStream(chunks ...string) MockModelResponse
MockModelStream 创建文本分片回复。
func MockModelStreamError ¶ added in v1.2.0
func MockModelStreamError(err error, chunks ...string) MockModelResponse
MockModelStreamError 创建分片后的流式错误。
func MockModelText ¶ added in v1.2.0
func MockModelText(content string) MockModelResponse
MockModelText 创建文本回复。
func MockModelTextAfter ¶ added in v1.2.0
func MockModelTextAfter[D any](call *MockToolInvocation[D], reply func(D) string) MockModelResponse
MockModelTextAfter 根据工具结果生成文本回复。
func MockModelTextAfterAll ¶ added in v1.2.0
func MockModelTextAfterAll(content string, calls ...MockToolCallProvider) MockModelResponse
MockModelTextAfterAll 在指定工具结果全部返回后创建文本回复。
func MockModelTextAfterToolResult ¶ added in v1.2.0
func MockModelTextAfterToolResult(callID string) MockModelResponse
MockModelTextAfterToolResult 使用工具结果作为文本回复。
func MockModelToolCall ¶ added in v1.2.0
func MockModelToolCall(name, arguments string) MockModelResponse
MockModelToolCall 创建单个工具调用回复。
func MockModelToolCallWithID ¶ added in v1.2.0
func MockModelToolCallWithID(id, name, arguments string) MockModelResponse
MockModelToolCallWithID 创建指定调用 ID 的工具调用回复。
func MockModelToolCalls ¶ added in v1.2.0
func MockModelToolCalls(calls ...schema.ToolCall) MockModelResponse
MockModelToolCalls 创建多个工具调用回复。
type MockTool ¶ added in v1.2.0
MockTool 描述一个可在测试中执行的工具。
func MustMockTool ¶ added in v1.2.0
func MustMockTool[T, D any](name, desc string, fn func(context.Context, T) (D, error)) *MockTool[T, D]
MustMockTool 创建可复用的工具。
func NewMockTool ¶ added in v1.2.0
func NewMockTool[T, D any](name, desc string, fn func(context.Context, T) (D, error)) (*MockTool[T, D], error)
NewMockTool 创建可复用的工具。
func (*MockTool[T, D]) Call ¶ added in v1.2.0
func (f *MockTool[T, D]) Call(callID string, input T) *MockToolInvocation[D]
Call 创建一次工具调用。
func (*MockTool[T, D]) Invocation ¶ added in v1.2.0
func (f *MockTool[T, D]) Invocation(callID string, input T) (*MockToolInvocation[D], error)
Invocation 创建一次工具调用。
func (*MockTool[T, D]) MustInvocation ¶ added in v1.2.0
func (f *MockTool[T, D]) MustInvocation(callID string, input T) *MockToolInvocation[D]
MustInvocation 创建一次工具调用。
type MockToolCallProvider ¶ added in v1.2.0
MockToolCallProvider 提供模型发起的工具调用。
type MockToolInvocation ¶ added in v1.2.0
MockToolInvocation 描述一次由模型发起并由工具执行的调用。
func MockToolCallFunc ¶ added in v1.2.0
func MockToolCallFunc[T, D any](name, desc string, input T, fn func(context.Context, T) (D, error)) (*MockToolInvocation[D], error)
MockToolCallFunc 创建带实际执行函数的工具调用。
func MustMockToolCallFunc ¶ added in v1.2.0
func MustMockToolCallFunc[T, D any](name, desc string, input T, fn func(context.Context, T) (D, error)) *MockToolInvocation[D]
MustMockToolCallFunc 创建带实际执行函数的工具调用。
func (*MockToolInvocation[D]) MockTool ¶ added in v1.2.0
func (i *MockToolInvocation[D]) MockTool() Tool
MockTool 返回工具调用对应的工具。
func (*MockToolInvocation[D]) MockToolCall ¶ added in v1.2.0
func (i *MockToolInvocation[D]) MockToolCall() schema.ToolCall
MockToolCall 返回模型发起的工具调用。
type MockToolProvider ¶ added in v1.2.0
type MockToolProvider interface {
MockTool() Tool
}
MockToolProvider 提供可加入 Agent 配置的工具。
type ModelFailoverConfig ¶ added in v1.2.0
type ModelFailoverConfig = adk.ModelFailoverConfig[*schema.Message]
ModelFailoverConfig 配置 ChatModel 失败转移策略。
type ModelGoalEvaluator ¶ added in v1.4.0
type ModelGoalEvaluator struct {
// contains filtered or unexported fields
}
ModelGoalEvaluator 使用聊天模型判断目标是否完成。
func NewModelGoalEvaluator ¶ added in v1.4.0
func NewModelGoalEvaluator(model ChatModel) (*ModelGoalEvaluator, error)
NewModelGoalEvaluator 创建模型目标判断器。
func (*ModelGoalEvaluator) Evaluate ¶ added in v1.4.0
func (e *ModelGoalEvaluator) Evaluate(ctx context.Context, evaluation GoalEvaluation) (GoalDecision, error)
Evaluate 要求模型仅返回结构化的目标判断结果。
type ModelOption ¶ added in v1.4.0
ModelOption 是单次模型调用选项,可通过 RunConfig 按请求传入。
type ModelRetryConfig ¶ added in v1.2.0
type ModelRetryConfig = adk.ModelRetryConfig
ModelRetryConfig 配置 ChatModel 调用重试策略。
type ResponseMeta ¶
type ResponseMeta = schema.ResponseMeta
ResponseMeta 聊天响应元数据,包含 token 用量、完成原因、log probabilities 等。 通常附着于 EventMessageEnd 事件,在流式场景下来自最后一个 chunk。
type RetentionPolicy ¶ added in v1.4.0
type RetentionPolicy struct {
// SessionIdleTime 删除超过该时长未更新的会话;删除内置会话时会级联清理关联资源。
SessionIdleTime time.Duration
// CompletedGoalAge 删除超过该时长未更新的已完成目标;不会删除 active、paused 或 blocked 目标。
CompletedGoalAge time.Duration
// DetachedToolResultAge 删除超过该时长且 SessionID 为空的工具结果。
DetachedToolResultAge time.Duration
}
RetentionPolicy 配置一次显式资源清扫。零值不删除任何数据。
type RetentionReport ¶ added in v1.4.0
type RetentionReport struct {
SessionsDeleted int
CompletedGoalsDeleted int
DetachedToolResultsDeleted int
}
RetentionReport 汇总一次资源清扫直接删除的条目数。 SessionStore.Delete 内部级联删除的资源不重复计入其他字段。
func PruneResources ¶ added in v1.4.0
func PruneResources( ctx context.Context, sessions SessionStore, policy RetentionPolicy, ) (RetentionReport, error)
PruneResources 按保留策略显式清扫资源。 它不会启动后台任务;调用方应确保待删除会话已没有运行中的 worker。
type RunConfig ¶ added in v1.4.0
type RunConfig struct {
// ModelOptions 会传给本次请求中的每次模型调用。
ModelOptions []ModelOption
// ToolOptions 会传给本次请求中的每次工具调用。
ToolOptions []ToolOption
// Values 可用于 SystemPrompt 的 {name} 占位符,也可在工具和中间件中通过 RunValue 读取。
Values map[string]any
}
RunConfig 配置一次请求;它只影响携带它的 context,不会修改 Agent 的全局配置。
type RunResult ¶ added in v1.4.0
type RunResult struct {
Response *schema.Message // 本次执行最后一条 assistant 消息;可能为 nil
Messages []*schema.Message // 本次执行新增的完整消息
Text string // Response.Content 的便捷访问
ReasoningContent string // Response.ReasoningContent 的便捷访问
FinishReason string // Response.ResponseMeta.FinishReason 的便捷访问
Usage *TokenUsage // 本次执行所有模型调用的累计 token 用量
ToolCalls []ToolCall // 本次执行请求的全部工具调用
Interrupts []InterruptPoint // 当前等待 Resume 的中断点
}
RunResult 汇总一次 Agent 执行新增的消息与最终响应。 即使执行返回错误,Result 仍会保留错误发生前已经产生的消息和用量。
func (*RunResult) IsInterrupted ¶ added in v1.4.0
IsInterrupted 报告本次执行是否正在等待 Resume。
type RunStream ¶ added in v1.4.0
type RunStream struct {
// contains filtered or unexported fields
}
RunStream 表示一次正在执行的流式请求。 Events 会按 Agent 的事件顺序输出并在队列排空后关闭;Wait 不依赖事件消费进度。
func (*RunStream) Done ¶ added in v1.4.0
func (s *RunStream) Done() <-chan struct{}
Done 在本次请求完成时关闭,不要求调用方先消费完 Events。
type Session ¶ added in v1.3.0
type Session struct {
ID string `json:"id"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
Messages []*schema.Message `json:"messages"` // 未删减的完整对话
Context []*schema.Message `json:"context,omitempty"` // 压缩后的模型上下文;nil 表示与 Messages 相同
CheckpointID string `json:"checkpoint_id,omitempty"` // 当前可恢复执行的检查点标识
PendingInterrupts []InterruptPoint `json:"pending_interrupts,omitempty"` // 等待 Resume 的中断点
Revision uint64 `json:"revision"` // 乐观并发控制版本
}
Session 是可持久化的完整对话快照。
type SessionConfig ¶ added in v1.3.0
type SessionConfig struct {
ID string // 在存储中唯一且稳定的会话标识
Store SessionStore // 会话存储
}
SessionConfig 配置 Agent 的自动会话恢复与持久化。
type SessionInfo ¶ added in v1.3.0
type SessionInfo struct {
ID string `json:"id"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
MessageCount int `json:"message_count"`
ContextMessageCount int `json:"context_message_count"`
PendingInterruptCount int `json:"pending_interrupt_count"`
Revision uint64 `json:"revision"`
}
SessionInfo 是用于会话列表展示的轻量元数据。
type SessionStore ¶ added in v1.3.0
type SessionStore interface {
Load(ctx context.Context, id string) (*Session, error)
Save(ctx context.Context, session *Session) error
Delete(ctx context.Context, id string) error
List(ctx context.Context) ([]SessionInfo, error)
}
SessionStore 管理多个持久化会话。 Load 在会话不存在时必须返回包装 ErrSessionNotFound 的错误;Delete 必须是幂等的。 实现还必须可以安全地被多个 goroutine 调用,并且不得保留调用方传入的可变切片。 所有方法必须及时响应 context 取消与截止时间。 Save 使用 Session.Revision 进行乐观并发控制:新会话必须为 0,已有会话必须等于当前版本; 存储成功后持久化版本加一,但不修改调用方传入的 Session。
type SkillBackend ¶ added in v1.3.0
SkillBackend 提供技能列表和按名称加载能力。
type SkillInfo ¶ added in v1.3.0
type SkillInfo = einoskill.FrontMatter
SkillInfo 是技能 YAML frontmatter 中的名称和描述等元数据。
type SkillsConfig ¶ added in v1.3.0
type SkillsConfig struct {
Paths []string
Backend SkillBackend
ToolName string // 模型用于加载技能的工具名称,默认 "skill"
}
SkillsConfig 配置 Agent 可按需加载的技能。 Paths 与 Backend 二选一;Paths 可指向 SKILL.md、单个技能目录或技能集合目录。
type StoredToolResult ¶ added in v1.4.0
type StoredToolResult struct {
ID string `json:"id"`
SessionID string `json:"session_id,omitempty"` // 为空表示不随会话自动删除
Content string `json:"content"`
CreatedAt time.Time `json:"created_at"`
}
StoredToolResult 是从模型上下文卸载的完整文本工具结果。
type StreamToolOutput ¶ added in v1.4.0
type StreamToolOutput = compose.StreamToolOutput
StreamToolOutput 描述一次流式文本工具调用输出。
type StreamableToolEndpoint ¶ added in v1.4.0
type StreamableToolEndpoint = compose.StreamableToolEndpoint
StreamableToolEndpoint 是流式文本工具调用端点。
type StreamableToolMiddleware ¶ added in v1.4.0
type StreamableToolMiddleware = compose.StreamableToolMiddleware
StreamableToolMiddleware 包装流式文本工具调用。
type Tool ¶
Tool 基础工具接口
func MockTools ¶ added in v1.2.0
func MockTools(items ...MockToolProvider) []Tool
MockTools 提取工具调用中的工具列表。
type ToolAlias ¶ added in v1.4.0
type ToolAlias struct {
Names []string // 工具名称别名
Arguments map[string][]string // canonical argument -> aliases
}
ToolAlias 配置一个工具可接受的名称和顶层 JSON 参数别名。
type ToolInvocation ¶ added in v1.4.0
type ToolInvocation struct {
// Name 是解析别名后的正式工具名。
Name string
// Arguments 是传给工具的 JSON 参数。
Arguments string
// CallID 是模型生成的工具调用 ID。
CallID string
}
ToolInvocation 描述一次即将执行的工具调用。
type ToolMiddleware ¶ added in v1.4.0
type ToolMiddleware = compose.ToolMiddleware
ToolMiddleware 为工具调用添加自定义执行逻辑。
type ToolOption ¶ added in v1.4.0
ToolOption 是单次工具调用选项,可通过 RunConfig 按请求传入。
type ToolOutcome ¶ added in v1.4.0
type ToolOutcome struct {
// Err 是工具或保护策略返回的错误。
Err error
// Truncated 表示文本结果是否因超过上限而被截断。
Truncated bool
// OutputChars 是最终保留的原始文本字符数,不包含截断提示。
OutputChars int
// Duration 是从前置钩子开始到工具结果处理完成的耗时。
Duration time.Duration
}
ToolOutcome 描述一次工具调用的执行结果,适合用于审计和指标记录。
type ToolPolicy ¶ added in v1.4.0
type ToolPolicy struct {
Aliases map[string]ToolAlias
UnknownTool func(ctx context.Context, name, arguments string) (string, error)
RewriteArguments func(ctx context.Context, name, arguments string) (string, error)
Sequential bool
// Timeout 限制单次工具调用(含钩子)的最长执行时间。零值表示不限制。
Timeout time.Duration
// MaxResultChars 限制返回给模型的文本字符数。零值使用 DefaultToolResultMaxChars,-1 表示不限制。
MaxResultChars int
// BeforeTool 在工具执行前调用;返回错误可拒绝本次调用。
BeforeTool func(ctx context.Context, call ToolInvocation) error
// AfterTool 在工具结束后调用,可用于审计和指标记录。
AfterTool func(ctx context.Context, call ToolInvocation, outcome ToolOutcome)
Middlewares []ToolMiddleware
}
ToolPolicy 集中配置工具分发与执行行为。
type ToolReductionConfig ¶ added in v1.4.0
type ToolReductionConfig struct {
Store ToolResultStore
// MaxResultBytes 是单个工具结果触发卸载的字节数,默认 50,000。
MaxResultBytes int
// MaxContextTokens 是开始清理旧工具轮次的上下文 token 估算值,默认 160,000。
MaxContextTokens int64
// KeepRecentToolRounds 是清理时原样保留的最近工具调用轮数,默认 1。
KeepRecentToolRounds int
}
ToolReductionConfig 配置大型工具结果卸载和旧工具轮次清理。 零值使用安全默认值;Store 为空时优先复用 Session 配套存储,否则使用内存存储。
type ToolResultInfo ¶ added in v1.4.0
type ToolResultInfo struct {
ID string `json:"id"`
SessionID string `json:"session_id,omitempty"`
Size int `json:"size"` // Content 的字节数
CreatedAt time.Time `json:"created_at"`
}
ToolResultInfo 是用于结果清理和监控的轻量元数据。
type ToolResultStore ¶ added in v1.4.0
type ToolResultStore interface {
Load(ctx context.Context, id string) (*StoredToolResult, error)
Save(ctx context.Context, result *StoredToolResult) error
Delete(ctx context.Context, id string) error
List(ctx context.Context) ([]ToolResultInfo, error)
}
ToolResultStore 管理从上下文卸载的不可变工具结果。 Load 在结果不存在时必须返回包装 ErrToolResultNotFound 的错误。 Save 只允许创建新 ID,重复 ID 必须返回包装 ErrToolResultExists 的错误。 Delete 必须幂等;所有方法必须可以安全地被多个 goroutine 调用,并及时响应 context 取消与截止时间。
type ToolResultStoreProvider ¶ added in v1.4.0
type ToolResultStoreProvider interface {
ToolResultStore() ToolResultStore
}
ToolResultStoreProvider 允许会话存储提供配套的大型工具结果存储。
type ToolSearchConfig ¶ added in v1.4.0
type ToolSearchConfig struct {
Tools []Tool
// UseModelNative 使用模型提供商原生的工具搜索协议。大多数模型保持 false 即可。
UseModelNative bool
}
ToolSearchConfig 配置按需发现的大型工具集。 Tools 中的工具默认不进入模型上下文;模型先调用 tool_search,匹配的工具才会变为可见。
Source Files
¶
- agent.go
- checkpoint.go
- checkpoint_file.go
- checkpoint_lifecycle.go
- compaction.go
- content.go
- doc.go
- event.go
- file_store.go
- goal.go
- goal_context.go
- goal_file.go
- goal_lease.go
- goal_lease_file.go
- goal_run.go
- goal_runner.go
- goal_runner_lease.go
- history.go
- interrupt.go
- lifecycle.go
- mcp.go
- middleware_guard.go
- mock_model.go
- model_failover.go
- model_guard.go
- model_policy.go
- model_retry.go
- persistence.go
- persistence_guard.go
- result.go
- retention.go
- run.go
- run_options.go
- session.go
- session_cleanup.go
- session_file.go
- skills.go
- state.go
- stream.go
- tool_guard.go
- tool_policy.go
- tool_reduction.go
- tool_result_store.go
- tool_result_store_file.go
- tool_search.go
- types.go