agentkit

package module
v1.5.0 Latest Latest
Warning

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

Go to latest
Published: Sep 5, 2026 License: MIT Imports: 39 Imported by: 0

README

AgentKit

CI

中文文档

AgentKit is a lightweight, event-stream-driven Go library for building reliable agents on top of CloudWeGo Eino ADK. It keeps the first agent small, while providing sessions, durable goals, context compaction, skills, MCP, and tool governance when an application grows.

Inspired by pi-agent-core, AgentKit focuses on a simpler public API and production-safe defaults.

Why AgentKit

  • Easy to start — create an Agent and call Ask; no graph or middleware wiring is required.
  • Easy to observe — use request-scoped streams or global events for text, reasoning, tools, compaction, goals, interrupts, and errors.
  • Easy to keep running — persist sessions, checkpoints, goals, and large tool results; reconnect by stable IDs after a client or process restart.
  • Safe by default — concurrent-run protection, panic isolation, bounded cleanup, tool-call repair, result limits, and optimistic concurrency are built in.
  • Composable when needed — add declarative subagents, skills, MCP servers, tool search, reduction, retry/failover, HITL, and multimodal input independently.

Installation

AgentKit requires Go 1.25.14 or later.

go get github.com/wsshow/agentkit@latest

Five-Minute Start

package main

import (
	"context"
	"fmt"
	"log"

	"github.com/cloudwego/eino-ext/components/model/openai"
	"github.com/wsshow/agentkit"
)

func main() {
	ctx := context.Background()

	chatModel, err := openai.NewChatModel(ctx, &openai.ChatModelConfig{
		APIKey: "your-api-key",
		Model:  "gpt-4o",
	})
	if err != nil {
		log.Fatal(err)
	}

	agent, err := agentkit.New(ctx, &agentkit.Config{
		Name:         "assistant",
		SystemPrompt: "You are a helpful assistant.",
		Model:        chatModel,
	})
	if err != nil {
		log.Fatal(err)
	}
	defer agent.Close()

	result, err := agent.Ask(ctx, "Hello!")
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println(result.Text)
}

Ask is the simplest blocking API. For real-time text and tool progress, use Stream:

stream, err := agent.Stream(ctx, "Explain MCP")
if err != nil {
	log.Fatal(err)
}
defer stream.Close()

for event := range stream.Events() {
	if event.Type == agentkit.EventMessageDelta {
		fmt.Print(event.Delta)
	}
}
result, err := stream.Wait()

See Runtime and events for the complete run API, lifecycle rules, HITL, queues, and multimodal input.

Choose the Capabilities You Need

Need Start here
Run methods, events, cancellation, HITL, queues, multimodal input Runtime and events
Manage many isolated conversations for users or tenants Multi-session management
Restore conversations and checkpoints after restart Sessions and persistence
Run a multi-step objective for hours or days and reconnect safely Durable goals
Wake goals from cron, queues, or cloud schedulers Scheduling and wakeups
Delegate focused work to isolated specialist agents Subagents
Keep long conversations inside the model context window Context management
Load reusable SKILL.md instructions on demand Skills
Connect stdio, SSE, or Streamable HTTP MCP servers MCP
Govern tools, repair calls, reduce large results, or search a catalog Tool management
Test without a live model or external tools Testing

The documentation index includes recommended reading paths and links between related topics.

A Practical Production Baseline

Most stateful agents should begin with a durable session and automatic compaction. Enable result reduction when tools may return large payloads:

store, err := agentkit.NewFileSessionStore("./data/agent")
if err != nil {
	log.Fatal(err)
}

agent, err := agentkit.New(ctx, &agentkit.Config{
	Name:  "assistant",
	Model: chatModel,
	Session: &agentkit.SessionConfig{
		ID:    "user-123",
		Store: store,
	},
	Compaction: &agentkit.CompactionConfig{
		MaxTokens:       80_000,
		KeepRecentTurns: 2,
	},
	ToolReduction: &agentkit.ToolReductionConfig{},
})

The file store is designed for a local single-process worker. Multi-replica services should implement the persistence interfaces with transactional database semantics; see Sessions and persistence and Durable goals.

Built-In Tool Middleware Decisions

AgentKit includes the three capabilities that remove recurring application work without exposing Eino middleware plumbing:

  • Dangling tool-call repair is always on because valid history is a correctness requirement.
  • Large-result reduction is one opt-in zero-value configuration because it changes storage and model-visible content.
  • On-demand tool search is opt-in because it is useful for large catalogs but adds an extra model decision for small ones.

See Tool management for defaults, ordering, and extension points.

Examples

Example What it demonstrates
simple Minimal multi-turn conversation
tools Tool calls and progress events
history Manual history export and restore
session Multi-session management and cross-process restore
goal Durable objective execution and reconnect
subagents Declarative specialist delegation and correlated events
compaction Automatic context compaction
skills Local SKILL.md discovery and loading
mcp Streamable HTTP MCP integration
queues Steering and follow-up queues
hitl Human interrupt and resume
multimodal Text and image input

Project

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 and goals, delegate to isolated subagents, 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. Applications serving multiple conversations can use SessionManager to create, reconnect, isolate, archive, fork, observe, and close session-bound Agents.

Index

Constants

View Source
const (
	// DefaultMCPMaxResultChars 是单次 MCP 工具结果默认保留的最大字符数。
	DefaultMCPMaxResultChars = 100_000
	// DefaultMCPMaxDescriptionChars 是单个 MCP 工具描述默认保留的最大字符数。
	DefaultMCPMaxDescriptionChars = 4_000
	// DefaultMCPInitializationTimeout 是每个 MCP 服务器连接与工具发现的默认总时限。
	DefaultMCPInitializationTimeout = 30 * time.Second
)
View Source
const (
	// DefaultSessionPageSize 是未指定分页大小时返回的会话数量。
	DefaultSessionPageSize = 50
	// MaxSessionPageSize 防止一次查询意外加载过多会话元数据。
	MaxSessionPageSize = 200
)
View Source
const (
	// DefaultSubAgentMaxDelegations 限制一次顶层运行最多启动的子 Agent 调用数。
	DefaultSubAgentMaxDelegations = 8
	// DefaultSubAgentMaxParallel 限制不同子 Agent 的并行调用数。
	DefaultSubAgentMaxParallel = 4
	// DefaultSubAgentTimeout 限制一次子 Agent 调用的最长时间。
	DefaultSubAgentTimeout = 10 * time.Minute
)
View Source
const (
	// ToolResultReadToolName 是启用工具结果压缩后自动注册的只读回取工具名。
	ToolResultReadToolName = "read_tool_result"
	// DefaultToolReductionMaxResultBytes 是单个工具结果触发持久化卸载的默认字节数。
	DefaultToolReductionMaxResultBytes = 50_000
	// DefaultToolReductionMaxContextTokens 是清理旧工具轮次的默认上下文 token 阈值。
	DefaultToolReductionMaxContextTokens int64 = 160_000
	// DefaultToolReductionKeepRecentRounds 是清理时原样保留的最近工具调用轮数。
	DefaultToolReductionKeepRecentRounds = 1
	// DefaultToolResultReadMaxChars 是一次回取最多返回给模型的 Unicode 字符数。
	DefaultToolResultReadMaxChars = 20_000
)
View Source
const DefaultCompactionMaxTokens = 100_000

DefaultCompactionMaxTokens 是未指定触发条件时使用的默认上下文 token 上限。

View Source
const DefaultGoalLeaseDuration = time.Minute

DefaultGoalLeaseDuration 是 GoalRunner 自动续期的默认 worker 租约时长。

View Source
const DefaultPersistenceTimeout = 30 * time.Second

DefaultPersistenceTimeout 是取消后的内部持久化收尾 context 默认时限。 自定义存储必须及时响应 context,时限才能按预期生效。

View Source
const DefaultToolResultMaxChars = 100_000

DefaultToolResultMaxChars 是工具文本结果的默认字符上限。

Variables

View Source
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")
)
View Source
var (
	// ErrGoalNotFound 表示目标存储中不存在指定目标。
	ErrGoalNotFound = errors.New("agentkit: goal not found")
	// ErrGoalConflict 表示目标已被其他调用方更新,当前快照不能覆盖新状态。
	ErrGoalConflict = errors.New("agentkit: goal revision conflict")
)
View Source
var (
	// ErrGoalLeaseHeld 表示目标正由另一个 worker 的有效租约持有。
	ErrGoalLeaseHeld = errors.New("agentkit: goal lease is held")
	// ErrGoalLeaseLost 表示租约已过期、被接管或令牌不再匹配。
	ErrGoalLeaseLost = errors.New("agentkit: goal lease is lost")
)
View Source
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")
)
View Source
var (
	// ErrMCPInitializationPanic 表示 MCP 会话在初始工具发现时发生 panic。
	ErrMCPInitializationPanic = errors.New("agentkit: MCP initialization panicked")
	// ErrMCPClosePanic 表示 MCP 会话在关闭时发生 panic。
	ErrMCPClosePanic = errors.New("agentkit: MCP session close panicked")
)
View Source
var (
	// ErrPersistencePanic 表示自定义持久化后端在执行操作时发生 panic。
	ErrPersistencePanic = errors.New("agentkit: persistence backend panicked")
	// ErrInvalidPersistenceData 表示自定义持久化后端返回 nil、错误 ID 或无效快照。
	ErrInvalidPersistenceData = errors.New("agentkit: persistence backend returned invalid data")
)
View Source
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")
	// ErrSessionArchived 表示会话已经归档,不能再创建运行实例。
	ErrSessionArchived = errors.New("agentkit: session is archived")
	// ErrSessionStale 表示 Agent 的会话快照已发生并发冲突,必须重新打开。
	ErrSessionStale = errors.New("agentkit: session snapshot is stale; reopen the session")
)
View Source
var (
	// ErrSessionManagerClosed 表示会话管理器已经关闭。
	ErrSessionManagerClosed = errors.New("agentkit: session manager is closed")
	// ErrSessionAlreadyExists 表示创建会话时指定的 ID 已经存在。
	ErrSessionAlreadyExists = errors.New("agentkit: session already exists")
	// ErrSessionAccessDenied 表示会话不属于当前管理器配置的 OwnerID。
	ErrSessionAccessDenied = errors.New("agentkit: session access denied")
	// ErrSessionFactoryPanic 表示自定义会话 Agent 工厂发生 panic。
	ErrSessionFactoryPanic = errors.New("agentkit: session agent factory panicked")
	// ErrSessionFactoryMismatch 表示自定义工厂返回的 Agent 未绑定到管理器提供的会话或存储。
	ErrSessionFactoryMismatch = errors.New("agentkit: session agent factory binding mismatch")
	// ErrSessionIDGeneratorPanic 表示自定义会话 ID 生成器发生 panic。
	ErrSessionIDGeneratorPanic = errors.New("agentkit: session ID generator panicked")
)
View Source
var (
	// ErrInvalidSessionQuery 表示会话查询参数无效。
	ErrInvalidSessionQuery = errors.New("agentkit: invalid session query")
	// ErrInvalidSessionCursor 表示分页游标无效或已损坏。
	ErrInvalidSessionCursor = errors.New("agentkit: invalid session cursor")
)
View Source
var (
	// ErrSkillNotFound 表示指定技能不存在。
	ErrSkillNotFound = errors.New("agentkit: skill not found")
	// ErrSkillBackendPanic 表示自定义 SkillBackend 发生 panic。
	ErrSkillBackendPanic = errors.New("agentkit: skill backend panicked")
)
View Source
var (
	// ErrSubAgentBusy 表示同一个子 Agent 已有调用正在执行或等待结果入账。
	ErrSubAgentBusy = errors.New("agentkit: sub-agent is busy")
	// ErrSubAgentBudgetExceeded 表示本次顶层运行已达到子 Agent 委派次数上限。
	ErrSubAgentBudgetExceeded = errors.New("agentkit: sub-agent delegation budget exceeded")
)
View Source
var (
	// ErrToolResultNotFound 表示存储中不存在指定的大型工具结果。
	ErrToolResultNotFound = errors.New("agentkit: tool result not found")
	// ErrToolResultExists 表示相同 ID 的不可变工具结果已经存在。
	ErrToolResultExists = errors.New("agentkit: tool result already exists")
	// ErrToolResultAccessDenied 表示结果不属于当前 Agent 会话。
	ErrToolResultAccessDenied = errors.New("agentkit: tool result access denied")
)
View Source
var ErrMiddlewarePanic = errors.New("agentkit: agent middleware panicked")

ErrMiddlewarePanic 表示自定义 ChatModelAgentMiddleware 发生 panic。

View Source
var ErrMockModelNoResponse = errors.New("mock chat model has no response configured")

ErrMockModelNoResponse 表示没有可消费的预设响应。

View Source
var ErrModelPanic = errors.New("agentkit: model panicked")

ErrModelPanic 表示第三方模型实现在生成或读取流时发生 panic。

View Source
var ErrModelPolicyPanic = errors.New("agentkit: model policy callback panicked")

ErrModelPolicyPanic 表示模型重试或故障切换的用户回调发生 panic。

View Source
var ErrSubscriberPanic = errors.New("agentkit: event subscriber panicked")

ErrSubscriberPanic 表示事件订阅回调发生 panic;其他订阅者会通过 EventError 收到该错误。

View Source
var ErrToolExecutionPanic = errors.New("agentkit: tool execution panicked")

ErrToolExecutionPanic 表示用户工具实现发生 panic。

View Source
var ErrToolMetadataPanic = errors.New("agentkit: tool metadata panicked")

ErrToolMetadataPanic 表示第三方工具在返回元数据时发生 panic。

View Source
var ErrToolPolicyPanic = errors.New("agentkit: tool policy callback panicked")

ErrToolPolicyPanic 表示 ToolPolicy 的用户回调发生 panic。

Functions

func EmitToolUpdate

func EmitToolUpdate(ctx context.Context, content string)

EmitToolUpdate 在工具执行中发送进度更新事件。 工具通过 context 获取 Emitter 并发送 tool_update 事件:

func myTool(ctx context.Context, input string) (string, error) {
    agentkit.EmitToolUpdate(ctx, "正在处理...")
    return "done", nil
}

func GetInterruptState

func GetInterruptState[T any](ctx context.Context) (wasInterrupted bool, hasState bool, state T)

GetInterruptState 在工具中检查是否从中断恢复,并获取之前保存的状态。

返回值:

  • wasInterrupted: 此工具是否曾被中断
  • hasState: 是否有保存的状态且成功转换为类型 T
  • state: 保存的状态(hasState 为 false 时为零值)

func GetResumeContext

func GetResumeContext[T any](ctx context.Context) (isResumeTarget bool, hasData bool, data T)

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

func GoalOperationKey(ctx context.Context, operation string) (string, bool)

GoalOperationKey 为当前目标尝试和业务操作名生成稳定、不透明的幂等键。 同一目标尝试在进程恢复或显式 Retry 后会得到相同结果;operation 必须稳定且非空。

func Interrupt

func Interrupt(ctx context.Context, info any) error

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 RunValue added in v1.4.0

func RunValue[T any](ctx context.Context, key string) (T, bool)

RunValue 读取当前请求中的一个类型匹配的值。

func RunValues added in v1.4.0

func RunValues(ctx context.Context) map[string]any

RunValues 返回当前请求值的副本。

func SetRunValue added in v1.4.0

func SetRunValue(ctx context.Context, key string, value any)

SetRunValue 在工具或中间件执行期间更新当前请求值。 该值可被同一次底层运行中的后续工具和中间件读取。

func StatefulInterrupt

func StatefulInterrupt(ctx context.Context, info any, state any) error

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
}

func WithRunConfig added in v1.4.0

func WithRunConfig(ctx context.Context, config RunConfig) context.Context

WithRunConfig 返回携带请求级配置的 context。 配置的切片、map 和常见嵌套值会被复制,调用方可在返回后安全复用原始容器。

Types

type Agent

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

Agent 提供事件流驱动的交互能力。

func New

func New(ctx context.Context, cfg *Config) (*Agent, error)

New 创建 Agent

func (*Agent) Abort

func (a *Agent) Abort()

Abort 取消当前执行并等待完成。 Subscribe 或 GoalEvaluator 回调与执行处于同一 goroutine,回调内请使用 Cancel 以避免等待自身。

func (*Agent) AbortContext added in v1.4.0

func (a *Agent) AbortContext(ctx context.Context) error

AbortContext 取消当前执行,并等待它退出或 ctx 结束。 返回 context.Canceled 或 context.DeadlineExceeded 只表示等待提前结束;取消请求仍已发出。

func (*Agent) Ask added in v1.4.0

func (a *Agent) Ask(ctx context.Context, input string) (*RunResult, error)

Ask 发送用户文本并返回本次执行的完整结果。

func (*Agent) AskParts added in v1.4.0

func (a *Agent) AskParts(ctx context.Context, parts ...ContentPart) (*RunResult, error)

AskParts 发送多模态内容并返回本次执行的完整结果。

func (*Agent) Cancel added in v1.3.0

func (a *Agent) Cancel()

Cancel 请求取消当前执行且不等待完成。 可在 Subscribe 回调中安全调用;需要等待执行退出时请在回调外使用 Abort。

func (*Agent) ClearAllQueues

func (a *Agent) ClearAllQueues()

ClearAllQueues 清空所有消息队列

func (*Agent) ClearCheckpoint added in v1.4.0

func (a *Agent) ClearCheckpoint(ctx context.Context) error

ClearCheckpoint 放弃当前中断并使已有检查点失效。 配置了 Session 时,清理后的状态会立即持久化。

func (*Agent) ClearFollowUpQueue

func (a *Agent) ClearFollowUpQueue()

ClearFollowUpQueue 清空后续消息队列

func (*Agent) ClearSteeringQueue

func (a *Agent) ClearSteeringQueue()

ClearSteeringQueue 清空转向消息队列

func (*Agent) Close

func (a *Agent) Close() error

Close 关闭 Agent,释放资源。实现 io.Closer 接口。

func (*Agent) CloseContext added in v1.4.0

func (a *Agent) CloseContext(ctx context.Context) error

CloseContext 关闭 Agent,并等待当前执行和 MCP 连接释放完成或 ctx 结束。 超时后关闭仍会在后台继续;重复调用只会等待同一次 MCP 关闭。

func (*Agent) ContextHistory added in v1.3.0

func (a *Agent) ContextHistory() []*schema.Message

ContextHistory 获取当前发送给模型的上下文副本。 未发生压缩时,它与 History 相同;压缩后 History 仍保留完整对话。

func (*Agent) Continue

func (a *Agent) Continue(ctx context.Context) error

Continue 从当前状态恢复执行(不添加新消息),用于错误后重试。 如果 Agent 已在执行中,返回错误。

func (*Agent) ContinueWithResult added in v1.4.0

func (a *Agent) ContinueWithResult(ctx context.Context) (*RunResult, error)

ContinueWithResult 从当前状态继续执行并返回本次新增的结果。

func (*Agent) FollowUp

func (a *Agent) FollowUp(content string)

FollowUp 在 Agent 完成当前工作后追加后续消息。 只有在没有转向消息时才会被处理。

func (*Agent) History

func (a *Agent) History() []*schema.Message

History 获取完整对话历史(含 assistant/tool 的 schema.Message),用于调试或持久化。

func (*Agent) Name

func (a *Agent) Name() string

Name 获取 Agent 名称

func (*Agent) PendingInterrupts added in v1.4.0

func (a *Agent) PendingInterrupts() []InterruptPoint

PendingInterrupts 返回当前等待 Resume 的中断点副本。

func (*Agent) Prompt

func (a *Agent) Prompt(ctx context.Context, input string) error

Prompt 发送用户输入并驱动 Agent 执行,事件通过 Subscribe 订阅。 如果 Agent 已在执行中,返回错误。

func (*Agent) Reset

func (a *Agent) Reset()

Reset 重置 Agent 状态(清空消息历史和队列)。 如果 Agent 正在执行,先等待执行完成。

func (*Agent) Resume

func (a *Agent) Resume(ctx context.Context, targets map[string]any) error

Resume 从 HITL 中断恢复执行。 targets 格式为 map[interruptID]data,interruptID 来自 Event.Interrupt[].ID。 如果 Agent 已在执行中,返回错误。

func (*Agent) ResumeWithResult added in v1.4.0

func (a *Agent) ResumeWithResult(ctx context.Context, targets map[string]any) (*RunResult, error)

ResumeWithResult 从 HITL 中断恢复并返回本次恢复执行新增的结果。

func (*Agent) SaveSession added in v1.3.0

func (a *Agent) SaveSession(ctx context.Context) error

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) Session added in v1.3.0

func (a *Agent) Session() *Session

Session 获取当前会话快照。未配置会话持久化时返回 nil。

func (*Agent) SetFollowUpMode

func (a *Agent) SetFollowUpMode(mode QueueMode)

SetFollowUpMode 设置后续消息处理模式

func (*Agent) SetHistory added in v1.2.0

func (a *Agent) SetHistory(history []*schema.Message)

SetHistory 替换完整对话历史,并同步展示状态。

func (*Agent) SetSteeringMode

func (a *Agent) SetSteeringMode(mode QueueMode)

SetSteeringMode 设置转向消息处理模式

func (*Agent) State

func (a *Agent) State() *State

State 获取当前状态

func (*Agent) Steer

func (a *Agent) Steer(content string)

Steer 在 Agent 执行期间插入转向消息。 当前工具批次完成后检查队列,若有消息则中断当前执行并注入新消息。

func (*Agent) Stream added in v1.4.0

func (a *Agent) Stream(ctx context.Context, input string) (*RunStream, error)

Stream 发送文本并立即返回本次请求专属的事件流。

func (*Agent) StreamParts added in v1.4.0

func (a *Agent) StreamParts(ctx context.Context, parts ...ContentPart) (*RunStream, error)

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 ChatModel

type ChatModel = model.BaseChatModel

ChatModel 基础聊天模型接口

type ChatModelAgentMiddleware added in v1.2.0

type ChatModelAgentMiddleware = adk.ChatModelAgentMiddleware

ChatModelAgentMiddleware 是 ChatModelAgent 扩展接口。

type CheckpointDeleter added in v1.4.0

type CheckpointDeleter interface {
	Delete(ctx context.Context, id string) error
}

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

type CompactionInfo struct {
	MessagesBefore int
	MessagesAfter  int
}

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       // 大型工具结果持久化卸载与按需回取(可选)
	SubAgents           []SubAgentConfig           // 独立上下文的声明式子 Agent(可选)
	SubAgentPolicy      *SubAgentPolicy            // 子 Agent 委派次数、并发与超时策略(可选)
}

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 AudioURL added in v1.1.0

func AudioURL(url string) ContentPart

AudioURL 创建音频 URL 内容片段。

func FileBase64 added in v1.1.0

func FileBase64(data, mimeType string, name ...string) ContentPart

FileBase64 创建 Base64 编码文件内容片段。name 为文件名(可选)。

func FileURL added in v1.1.0

func FileURL(url string) ContentPart

FileURL 创建文件 URL 内容片段。

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 Text added in v1.1.0

func Text(s string) ContentPart

Text 创建文本内容片段。

func VideoBase64 added in v1.1.0

func VideoBase64(data, mimeType string) ContentPart

VideoBase64 创建 Base64 编码视频内容片段。

func VideoURL added in v1.1.0

func VideoURL(url string) ContentPart

VideoURL 创建视频 URL 内容片段。

type CreateSessionOptions added in v1.5.0

type CreateSessionOptions struct {
	ID      string
	Title   string
	OwnerID string
	Tags    []string
}

CreateSessionOptions 配置一个新会话。ID 为空时自动生成 UUID。

type DelegationInfo added in v1.5.0

type DelegationInfo struct {
	ID          string
	ParentAgent string
	Agent       string
	Path        []string
}

DelegationInfo 标识一次父 Agent 到子 Agent 的委派。

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 名称
	SessionID        string           // 产生事件的会话 ID;未启用会话时为空
	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)
	Delegation       *DelegationInfo  // 子 Agent 委派信息(delegation_start / delegation_end 及子 Agent 事件)
	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 状态已持久化
	EventDelegationStart EventType = "delegation_start" // 子 Agent 委派开始
	EventDelegationEnd   EventType = "delegation_end"   // 子 Agent 委派结束
	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。

func (*FileCheckpointStore) Get added in v1.4.0

func (s *FileCheckpointStore) Get(ctx context.Context, id string) ([]byte, bool, error)

Get 加载检查点。检查点不存在时 existed 为 false。

func (*FileCheckpointStore) Set added in v1.4.0

func (s *FileCheckpointStore) Set(ctx context.Context, id string, value []byte) error

Set 通过原子文件替换保存检查点。

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) Load added in v1.4.0

func (s *FileGoalStore) Load(ctx context.Context, id string) (*Goal, error)

Load 从文件加载目标快照。

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

func (s *FileGoalStore) SaveGoalWithLease(ctx context.Context, goal *Goal, lease *GoalLease) error

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) Load added in v1.3.0

func (s *FileSessionStore) Load(ctx context.Context, id string) (*Session, error)

Load 从文件加载会话快照。

func (*FileSessionStore) QuerySessions added in v1.5.0

func (s *FileSessionStore) QuerySessions(ctx context.Context, query SessionQuery) (SessionPage, error)

QuerySessions 查询文件存储中的会话。文件存储面向本地规模,会先读取元数据再分页。

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、包含该文件的目录,或包含多个技能子目录的目录。

func (*FileSkillBackend) Get added in v1.3.0

func (b *FileSkillBackend) Get(ctx context.Context, name string) (Skill, error)

Get 按 frontmatter 中的 name 加载技能。

func (*FileSkillBackend) List added in v1.3.0

func (b *FileSkillBackend) List(ctx context.Context) ([]SkillInfo, error)

List 列出所有技能元数据,结果按名称排序。

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

List 按创建时间从新到旧列出结果。

func (*FileToolResultStore) Load added in v1.4.0

Load 从文件加载完整工具结果。

func (*FileToolResultStore) Save added in v1.4.0

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) Done added in v1.4.0

func (r *GoalRun) Done() <-chan struct{}

Done 在本次后台推进停止时关闭。

func (*GoalRun) ID added in v1.4.0

func (r *GoalRun) ID() string

ID 返回持久化目标 ID。

func (*GoalRun) Pause added in v1.4.0

func (r *GoalRun) Pause(ctx context.Context) error

Pause 持久化暂停目标并取消本次后台推进。

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

type GoalRunInfo struct {
	GoalID    string
	SessionID string
	Attempt   int
}

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

type GoalRunResult struct {
	Goal    *Goal
	LastRun *RunResult
}

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) Get added in v1.4.0

func (r *GoalRunner) Get(ctx context.Context, id string) (*Goal, error)

Get 返回最新目标状态。

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

func (r *GoalRunner) ResumeAsync(ctx context.Context, id string) (*GoalRun, error)

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

func (r *GoalRunner) RetryAsync(ctx context.Context, id string) (*GoalRun, error)

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 控制图片识别质量。

type InterruptPoint

type InterruptPoint struct {
	ID   string // 中断点唯一标识,Resume 时传入此 ID
	Info any    // 中断原因/上下文信息
}

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。

func (*MemoryCheckpointStore) Get added in v1.4.0

func (s *MemoryCheckpointStore) Get(ctx context.Context, id string) (value []byte, existed bool, err error)

Get 加载检查点。检查点不存在时 existed 为 false。

func (*MemoryCheckpointStore) Set added in v1.4.0

func (s *MemoryCheckpointStore) Set(ctx context.Context, id string, value []byte) error

Set 保存并完全替换检查点。

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) Load added in v1.4.0

func (s *MemoryGoalStore) Load(ctx context.Context, id string) (*Goal, error)

Load 加载目标快照。

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

List 按更新时间从新到旧列出会话。

func (*MemorySessionStore) Load added in v1.3.0

func (s *MemorySessionStore) Load(ctx context.Context, id string) (*Session, error)

Load 加载会话快照。

func (*MemorySessionStore) QuerySessions added in v1.5.0

func (s *MemorySessionStore) QuerySessions(ctx context.Context, query SessionQuery) (SessionPage, error)

QuerySessions 在内存快照上完成筛选和分页。

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) Get added in v1.3.0

func (b *MemorySkillBackend) Get(ctx context.Context, name string) (Skill, error)

Get 按名称加载技能。

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

List 按创建时间从新到旧列出结果。

func (*MemoryToolResultStore) Load added in v1.4.0

Load 加载完整工具结果。

func (*MemoryToolResultStore) Save added in v1.4.0

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 返回还未消费的响应数量。

func (*MockChatModel) Stream added in v1.2.0

func (m *MockChatModel) Stream(ctx context.Context, input []*schema.Message, opts ...model.Option) (*schema.StreamReader[*schema.Message], error)

Stream 返回下一条流式响应。

type MockModelCall added in v1.2.0

type MockModelCall struct {
	Input     []*schema.Message
	Options   []model.Option
	Streaming bool
}

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

type MockTool[T, D any] struct {
	Tool Tool
	Name string
}

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]) MockTool added in v1.2.0

func (f *MockTool[T, D]) MockTool() Tool

MockTool 返回工具函数对应的工具。

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

type MockToolCallProvider interface {
	MockToolCall() schema.ToolCall
}

MockToolCallProvider 提供模型发起的工具调用。

type MockToolInvocation added in v1.2.0

type MockToolInvocation[D any] struct {
	Tool      Tool
	CallID    string
	Name      string
	Arguments string
}

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

type ModelOption = model.Option

ModelOption 是单次模型调用选项,可通过 RunConfig 按请求传入。

type ModelRetryConfig added in v1.2.0

type ModelRetryConfig = adk.ModelRetryConfig

ModelRetryConfig 配置 ChatModel 调用重试策略。

type QueueMode

type QueueMode string

QueueMode 消息队列处理模式

const (
	QueueModeOneAtATime QueueMode = "one-at-a-time" // 每次处理一条
	QueueModeAll        QueueMode = "all"           // 一次性处理全部
)

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 RoleType

type RoleType string

RoleType 消息角色类型

const (
	RoleUser      RoleType = "user"
	RoleAssistant RoleType = "assistant"
	RoleTool      RoleType = "tool"
)

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

func (r *RunResult) IsInterrupted() bool

IsInterrupted 报告本次执行是否正在等待 Resume。

type RunStream added in v1.4.0

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

RunStream 表示一次正在执行的流式请求。 Events 会按 Agent 的事件顺序输出并在队列排空后关闭;Wait 不依赖事件消费进度。

func (*RunStream) Cancel added in v1.4.0

func (s *RunStream) Cancel()

Cancel 请求取消本次执行且不等待退出。

func (*RunStream) Close added in v1.4.0

func (s *RunStream) Close() error

Close 取消本次执行并放弃尚未消费的事件。 Wait 仍可用于等待底层执行结束并取得部分结果。

func (*RunStream) Done added in v1.4.0

func (s *RunStream) Done() <-chan struct{}

Done 在本次请求完成时关闭,不要求调用方先消费完 Events。

func (*RunStream) Events added in v1.4.0

func (s *RunStream) Events() <-chan Event

Events 返回本次请求专属的事件流。

func (*RunStream) Wait added in v1.4.0

func (s *RunStream) Wait() (*RunResult, error)

Wait 等待请求完成并返回隔离的运行结果。 Wait 可安全地重复调用;它不负责消费 Events。

func (*RunStream) WaitContext added in v1.4.0

func (s *RunStream) WaitContext(ctx context.Context) (*RunResult, error)

WaitContext 等待请求完成或 ctx 结束;等待超时不会取消底层执行。 可在超时后再次调用 Wait 或 WaitContext 获取最终结果。

type Session added in v1.3.0

type Session struct {
	SessionMetadata
	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 的中断点
	Archived          bool              `json:"archived,omitempty"`           // 归档后不可再运行,但仍可查询和恢复
	Revision          uint64            `json:"revision"`                     // 乐观并发控制版本
}

Session 是可持久化的完整对话快照。

type SessionAgentFactory added in v1.5.0

type SessionAgentFactory func(ctx context.Context, session SessionConfig) (*Agent, error)

SessionAgentFactory 为一个已存在的会话创建 Agent。 实现必须使用传入的 SessionConfig,返回的 Agent 必须绑定相同的会话 ID。

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 {
	SessionMetadata
	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"`
	Archived              bool      `json:"archived,omitempty"`
	Revision              uint64    `json:"revision"`
}

SessionInfo 是用于会话列表展示的轻量元数据。

type SessionManager added in v1.5.0

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

SessionManager 管理多个相互隔离的会话 Agent。 同一管理器内,一个会话 ID 最多只有一个活动 Agent;不同会话可并发运行。

func NewSessionManager added in v1.5.0

func NewSessionManager(cfg *SessionManagerConfig) (*SessionManager, error)

NewSessionManager 创建多会话管理器,不会连接模型或打开会话。

func (*SessionManager) ActiveSessionIDs added in v1.5.0

func (m *SessionManager) ActiveSessionIDs() []string

ActiveSessionIDs 返回当前打开的会话 ID,按字典序排列。

func (*SessionManager) Archive added in v1.5.0

func (m *SessionManager) Archive(ctx context.Context, id string) error

Archive 关闭活动 Agent 并归档会话。归档会话在 Unarchive 前不能 Open。

func (*SessionManager) Close added in v1.5.0

func (m *SessionManager) Close() error

Close 关闭管理器和全部活动 Agent。实现 io.Closer 接口。

func (*SessionManager) CloseContext added in v1.5.0

func (m *SessionManager) CloseContext(ctx context.Context) error

CloseContext 关闭管理器和全部活动 Agent,并等待资源释放或 ctx 结束。 等待超时后,关闭仍会在后台继续。关闭管理器不会删除任何持久化会话。

func (*SessionManager) CloseSession added in v1.5.0

func (m *SessionManager) CloseSession(ctx context.Context, id string) error

CloseSession 关闭并移除一个活动 Agent,但保留持久化会话。重复调用是安全的。

func (*SessionManager) Create added in v1.5.0

func (m *SessionManager) Create(ctx context.Context) (*Agent, error)

Create 创建并打开一个使用自动 ID 的会话。

func (*SessionManager) CreateWithOptions added in v1.5.0

func (m *SessionManager) CreateWithOptions(ctx context.Context, options CreateSessionOptions) (*Agent, error)

CreateWithOptions 创建、持久化并打开一个会话。 Agent 初始化失败时会话仍会保留,调用方可修复外部依赖后通过 Open 重试。

func (*SessionManager) Delete added in v1.5.0

func (m *SessionManager) Delete(ctx context.Context, id string) error

Delete 先关闭活动 Agent,再删除持久化会话及其配套资源。删除不存在的会话成功。

func (*SessionManager) Fork added in v1.5.0

func (m *SessionManager) Fork(ctx context.Context, sourceID string, options CreateSessionOptions) (*Agent, error)

Fork 复制一个会话的对话历史和压缩上下文,并创建独立的新 Agent。 检查点、待处理中断、目标和大型工具结果不会复制。

func (*SessionManager) Get added in v1.5.0

func (m *SessionManager) Get(ctx context.Context, id string) (*Session, error)

Get 返回活动 Agent 的最新内存快照,或加载未打开会话的持久化快照。

func (*SessionManager) List added in v1.5.0

List 按条件分页列出会话。配置 OwnerID 后,查询会被强制限制在该 Owner 内。

func (*SessionManager) Open added in v1.5.0

func (m *SessionManager) Open(ctx context.Context, id string) (*Agent, error)

Open 打开已存在的会话。同一管理器重复打开相同 ID 会返回同一个活动 Agent。

func (*SessionManager) OpenOrCreate added in v1.5.0

func (m *SessionManager) OpenOrCreate(ctx context.Context, options CreateSessionOptions) (agent *Agent, created bool, err error)

OpenOrCreate 打开指定会话;不存在时使用 options 创建它。 created 仅在本次调用成功持久化新会话时为 true。ID 为空时总是生成新 ID。

func (*SessionManager) Subscribe added in v1.5.0

func (m *SessionManager) Subscribe(fn Subscriber) func()

Subscribe 订阅当前管理器内所有会话的事件。 每个事件都携带 SessionID;不同会话并发运行时回调也可能并发执行。

func (*SessionManager) Unarchive added in v1.5.0

func (m *SessionManager) Unarchive(ctx context.Context, id string) error

Unarchive 恢复归档会话,使其可以再次 Open。

func (*SessionManager) UpdateMetadata added in v1.5.0

func (m *SessionManager) UpdateMetadata(ctx context.Context, id string, metadata SessionMetadata) (*Session, error)

UpdateMetadata 原子替换会话标题、OwnerID 和标签,并保留对话与运行状态。

type SessionManagerConfig added in v1.5.0

type SessionManagerConfig struct {
	Store        SessionStore
	AgentConfig  *Config
	AgentFactory SessionAgentFactory
	OwnerID      string
	IDGenerator  func() string
}

SessionManagerConfig 配置多会话管理器。 AgentConfig 适合共享同一套 Agent 配置的常见场景;AgentFactory 用于按会话创建模型等高级场景,二者必须且只能配置一个。

type SessionMetadata added in v1.5.0

type SessionMetadata struct {
	Title   string   `json:"title,omitempty"`
	OwnerID string   `json:"owner_id,omitempty"`
	Tags    []string `json:"tags,omitempty"`
}

SessionMetadata 是用于组织和检索会话的应用级元数据。 OwnerID 可表示用户、租户或应用自己的隔离命名空间。

type SessionPage added in v1.5.0

type SessionPage struct {
	Sessions   []SessionInfo `json:"sessions"`
	NextCursor string        `json:"next_cursor,omitempty"`
}

SessionPage 是按更新时间从新到旧排列的一页会话。 NextCursor 为空表示没有下一页;游标是不透明值,调用方不应解析或修改。

func QuerySessions added in v1.5.0

func QuerySessions(ctx context.Context, store SessionStore, query SessionQuery) (SessionPage, error)

QuerySessions 查询任意 SessionStore。 支持 SessionQueryStore 的后端会直接执行查询,旧后端自动通过 List 兼容回退。

type SessionQuery added in v1.5.0

type SessionQuery struct {
	OwnerID  string
	Tags     []string
	Archived *bool
	Limit    int
	Cursor   string
}

SessionQuery 描述一次会话目录查询。 Tags 使用 AND 语义;Archived 为 nil 时同时返回归档和未归档会话。

type SessionQueryStore added in v1.5.0

type SessionQueryStore interface {
	QuerySessions(ctx context.Context, query SessionQuery) (SessionPage, error)
}

SessionQueryStore 是 SessionStore 的可选高效查询扩展。 数据库实现应在存储端完成筛选和分页;未实现时 QuerySessions 会通过 List 兼容回退。

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 Skill added in v1.3.0

type Skill = einoskill.Skill

Skill 是从 SKILL.md 加载的技能。

type SkillBackend added in v1.3.0

type SkillBackend = einoskill.Backend

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 State

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

State Agent 状态管理(线程安全)

func (*State) AddMessage

func (s *State) AddMessage(msg Message)

AddMessage 添加消息

func (*State) Clear

func (s *State) Clear()

Clear 清空状态

func (*State) IsStreaming

func (s *State) IsStreaming() bool

IsStreaming 是否正在流式输出

func (*State) Messages

func (s *State) Messages() []Message

Messages 获取所有消息的副本

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 SubAgentConfig added in v1.5.0

type SubAgentConfig struct {
	Name         string
	Description  string
	SystemPrompt string

	// Model 为空时继承父 Agent 的模型。
	Model ChatModel
	// Tools 只属于当前子 Agent;父 Agent 的工具不会自动继承。
	Tools      []Tool
	ToolPolicy *ToolPolicy
	Handlers   []ChatModelAgentMiddleware

	// ModelRetryConfig 与 ModelFailoverConfig 为空时继承父 Agent 的策略。
	ModelRetryConfig    *ModelRetryConfig
	ModelFailoverConfig *ModelFailoverConfig
	MaxIterations       int

	Skills     *SkillsConfig
	MCP        *MCPConfig
	ToolSearch *ToolSearchConfig

	// IncludeHistory 显式允许把父 Agent 的聊天历史改写后交给子 Agent。
	// 默认 false,只传递本次委派请求以保持上下文隔离。
	IncludeHistory bool
}

SubAgentConfig 声明一个由主 Agent 按需调用的专业子 Agent。 子 Agent 使用独立对话上下文,默认只接收委派请求并向父 Agent 返回最终文本。

type SubAgentPolicy added in v1.5.0

type SubAgentPolicy struct {
	MaxDelegations int
	MaxParallel    int
	Timeout        time.Duration
}

SubAgentPolicy 为全部子 Agent 配置有界执行默认值。 零值使用 DefaultSubAgentMaxDelegations、DefaultSubAgentMaxParallel 和 DefaultSubAgentTimeout。

type Subscriber

type Subscriber func(Event)

Subscriber 事件订阅函数

type TokenUsage

type TokenUsage = schema.TokenUsage

TokenUsage 表示一次聊天请求的 token 用量统计。

type Tool

type Tool = tool.BaseTool

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 ToolCall

type ToolCall = schema.ToolCall

ToolCall 工具调用信息

type ToolInput added in v1.4.0

type ToolInput = compose.ToolInput

ToolInput 描述一次工具调用输入。

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

type ToolOption = tool.Option

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 ToolOutput added in v1.4.0

type ToolOutput = compose.ToolOutput

ToolOutput 描述一次非流式工具调用输出。

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,匹配的工具才会变为可见。

Jump to

Keyboard shortcuts

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